Skip to content
pi-c Artifact [c4b9e5ed52]
Login

Artifact [c4b9e5ed52]

Artifact c4b9e5ed5279e3910e878dc264bbe43b3daf827d6e3116c20ee362d79c17d04a:


/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This file is automatically generated. Edit at your own risk. */
#if !defined(_FILE_OFFSET_BITS)
#  define _FILE_OFFSET_BITS 64 /* 64-bit off_t on 32-bit targets */
#endif
#if !defined(_TIME_BITS)
#  define _TIME_BITS 64 /* 64-bit time_t on 32-bit targets */
#endif
#define FSL_EXPOSE_INTERNAL_APIS
/* start of libfossil.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This file is automatically generated. Edit at your own risk. */
#if !defined(ORG_FOSSIL_SCM_LIBFOSSIL_AMAL_H_INCLUDED)
#define ORG_FOSSIL_SCM_LIBFOSSIL_AMAL_H_INCLUDED
#undef FSL_AMALGAMATION_BUILD
#define FSL_AMALGAMATION_BUILD 1
#define FSL_PACKAGE_NAME "libfossil"
#define FSL_LIBRARY_VERSION "0.6.1"
#define FSL_LIB_VERSION_HASH "8aa1823ae1d0ad08c0408cada7c77035220b187e23aa713a69f24278f1da528b"
#define FSL_LIB_VERSION_TIMESTAMP "2026-11-22 11:49:10.526 UTC"
#define FSL_LIB_CONFIG_TIMESTAMP "2026-11-22 12:02 GMT"
#define FSL_AUX_SCHEMA "2015-01-24"
#define FSL_CONTENT_SCHEMA "2"
#define FOSSIL_RELEASE_VERSION_NUMBER 22700
#define FOSSIL_MANIFEST_NUMERIC_DATE 20250727
#define FOSSIL_MANIFEST_NUMERIC_TIME 110738

#if defined(HAVE_CONFIG_H)
#  include "config.h"
#endif
#if defined(HAVE_LIBFOSSIL_CONFIG_H)
#  include "libfossil-config.h"
#endif
#include "sqlite3.h"
/* start of file include/fossil-scm/config.h */
#if !defined (ORG_FOSSIL_SCM_FSL_CONFIG_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_CONFIG_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).

*/


#if !defined(_ISOC99_SOURCE)
/* glibc apparently guards snprintf() on this #define, even though
   snprintf() is part of C99 and we're building in C99 mode. */
#  define _ISOC99_SOURCE
#endif
#if !defined(_C99_SOURCE)
/* Some Mac enviorments guard snprintf() on this #define but do not
   #define it when building in C99 mode. */
#  define _C99_SOURCE
#endif

#if !defined(FSL_AUX_SCHEMA)
#  error "Expecting FSL_AUX_SCHEMA to be defined by the configuration bits."
#endif
#if !defined(FSL_LIBRARY_VERSION)
#  error "Expecting FSL_LIBRARY_VERSION to be defined by the configuration bits."
#endif

/**
   FSL_API_ARMOR is a not-yet-widely-implemented feature adopted from
   SQLite, in which many APIs will perform more argument validation
   against NULL pointers or values which might, if unchecked, lead to
   illegal memory access. Without this flag, such APIs have undefined
   behavior with such illegal arguments but use fewer CPU cycles.
*/
#if !defined(FSL_API_ARMOR)
#  define FSL_API_ARMOR 1
#endif


#ifdef _WIN32
# if defined(BUILD_libfossil_static) || defined(FSL_AMALGAMATION_BUILD)
#  define FSL_EXPORT extern
# elif defined(BUILD_libfossil)
#  define FSL_EXPORT extern __declspec(dllexport)
# else
#  define FSL_EXPORT extern __declspec(dllimport)
# endif
#else
# define FSL_EXPORT extern
#endif

#if !defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L)
#  if defined(__cplusplus) && !defined(__STDC_FORMAT_MACROS)
/* inttypes.h needs this for the PRI* and SCN* macros in C++ mode. */
#    define __STDC_FORMAT_MACROS
#  else
#    error "This tree requires a standards-compliant C99-capable compiler."
#  endif
#endif

#if defined(_MSC_VER)
#  define FSL_PLATFORM_IS_WINDOWS 1
#  define FSL_PLATFORM_IS_UNIX 0
#  define FSL_PLATFORM_PLATFORM "windows"
/* define a __func__ compatibility macro */
#  if _MSC_VER < 1500    /* (vc9.0; dev studio 2008) */
/* sorry; cant do much better than nothing at all on those earlier ones */
#    define __func__ "(func)"
#  else
#    define __func__ __FUNCTION__
#  endif
/* for the time being at least, don't complain about there being secure crt alternatives: */
#  ifndef _CRT_SECURE_NO_WARNINGS
#    define _CRT_SECURE_NO_WARNINGS
#  endif
/* for the time being at least, don't complain about using POSIX names instead of ISO C++: */
#  pragma warning ( disable : 4996 )
/* for the time being at least, suppresss some int conversion warnings */
#  pragma warning ( disable : 4244 )     /*'fsl_size_t' to 'int'; this masks other problems that should be fixed*/
#  pragma warning ( disable : 4761 )     /*'integral size mismatch in argument'; more size_t problems*/
#  pragma warning ( disable : 4267 )     /*'size_t' to 'int'; crops up especially in 64-bit builds*/
/* these were extracted from fossil's unistd.h */
#  define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#  include <io.h>
#elif defined(__MINGW32__)
#  define FSL_PLATFORM_IS_WINDOWS 1
#  define FSL_PLATFORM_IS_UNIX 0
#  define FSL_PLATFORM_PLATFORM "windows"
#elif defined(__CYGWIN__)
#  define FSL_PLATFORM_IS_WINDOWS 0
#  define FSL_PLATFORM_IS_UNIX 1
#  define FSL_PLATFORM_PLATFORM "unix"
#else
#  define FSL_PLATFORM_IS_WINDOWS 0
#  define FSL_PLATFORM_IS_UNIX 1
#  define FSL_PLATFORM_PLATFORM "unix"
#endif

#if !defined(HAVE_SIGACTION)
#  if defined(FSL_PLATFORM_IS_UNIX)
#    define HAVE_SIGACTION 1
#  else
#    define HAVE_SIGACTION 0
#  endif
#endif

#include <stdint.h>
#include <inttypes.h>


/** @typedef some_int_type fsl_int_t

    fsl_int_t is a signed integer type used to denote "relative"
    ranges and lengths, or to tell a routine that it should try to
    figure out the length of some byte array itself (e.g.  by using
    fsl_strlen() on it). It is provided primarily for
    documentation/readability purposes, to avoid confusion with the
    widely varying integer semantics used by various APIs. This type
    is never used as a return type for functions which use "result
    code semantics". Those always use an unadorned integer type or
    some API-specific enum type.

    The library typedefs this to a 64-bit type if possible, else
    a 32-bit type.

    @see fsl_strlen_t
*/
typedef int64_t fsl_int_t;
/**
    The unsigned counterpart of fsl_int_t.
*/
typedef uint64_t fsl_uint_t;

/**
   A 32-bit unsigned int type. This typedef is primarily to
   improve documentation of the intent of function arguments
   and struct members.
*/
typedef uint32_t fsl_flag32_t;
typedef uint16_t fsl_flag16_t;

/**
   A signed integer type intended for use with APIs which allow a
   negative value as a length, where a negative value means to use
   strlen(), or an equivalent, to calculate the value.

   This type is limited to 31 length bits because it is most
   frequently used with data intended for sqlite3 APIs which have that
   limitation.
*/
typedef int32_t fsl_strlen_t;

/** @def FSL_INT_T_PFMT
    Fossil's fsl_int_t equivalent of C99's PRIi32 and friends.
 */
#define FSL_INT_T_PFMT PRIi64
/** @def FSL_INT_T_SFMT

    Fossil's fsl_int_t equivalent of C99's SCNi32 and friends.
 */
#define FSL_INT_T_SFMT SCNi64
/** @def FSL_UINT_T_PFMT

    Fossil's fsl_uint_t equivalent of C99's PRIu32 and friends.
 */
#define FSL_UINT_T_PFMT PRIu64
/** @def FSL_UINT_T_SFMT

    Fossil's fsl_uint_t equivalent of C99's SCNu32 and friends.
 */
#define FSL_UINT_T_SFMT SCNu64

/** @def FSL_JULIAN_T_PFMT

    An output format specifier for Julian-format doubles.
 */
#define FSL_JULIAN_T_PFMT ".17g"

/**
    fsl_size_t is an unsigned integer type used to denote absolute
    ranges and lengths. It is provided primarily for
    documentation/readability purposes, to avoid confusion with the
    widely varying integer semantics used by various APIs. While a
    32-bit type is legal, a 64-bit type is required for "unusually
    large" repos and for some metrics reporting even for mid-sized
    repos.
 */
typedef uint64_t fsl_size_t;

/** @def FSL_SIZE_T_PFMT

    Fossil's fsl_size_t equivalent of C99's PRIu32 and friends.

    ACHTUNG: when passing arguments of this type of fsl_appendf(), or
    any function which uses it for formatting purposes, it is very
    important if if you pass _literal integers_ OR enum values, that
    they be cast to fsl_size_t, or the va_list handling might extract
    the wrong number of bytes from the argument list, leading to
    really weird side-effects via what is effectively memory
    corruption.

    That warning applies primarily to the following typedefs and their
    format specifiers: fsl_size_t, fsl_int_t, fsl_uint_t, fsl_id_t.

    The warning does not apply to strongly-typed arguments,
    e.g. variables of the proper type, so long as the format specifier
    string matches the argument type.

    For example:

    ```
    fsl_size_t sz = 3;
    fsl_fprintf( stdout, "%"FSL_SIZE_T_PFMT" %"FSL_SIZE_T_PFMT\n",
                 sz, // OK!
                 3 // BAD! See below...
                 );
    ```

    The "fix" is to cast the literal 3 to a fsl_size_t resp. the type
    appropriate for the format specifier. That ensures that there is
    no (or much less ;) confusion when va_arg() extracts arguments
    from the variadic array.

    Reminders to self:

    ```
    int i = 0;
    f_out(("#%d: %"FSL_ID_T_PFMT" %"FSL_ID_T_PFMT" %"FSL_ID_T_PFMT"\n",
            ++i, 1, 2, 3));
    f_out(("#%d: %"FSL_SIZE_T_PFMT" %"FSL_ID_T_PFMT" %"FSL_SIZE_T_PFMT"\n",
           ++i, (fsl_size_t)1, (fsl_id_t)2, (fsl_size_t)3));
    // This one is the (generally) problematic case:
    f_out(("#%d: %"FSL_SIZE_T_PFMT" %"FSL_ID_T_PFMT" %"FSL_SIZE_T_PFMT"\n",
           ++i, 1, 2, 3));
    ```

    The above was Tested with gcc, clang, tcc on a 32-bit linux
    platform (it has not been problematic on 64-bit builds!). The
    above problem was reproduced on all compiler combinations i
    tricored. Current code (20130824) seems to be behaving well as long
    as callers always cast to help variadic arg handling DTRT.
 */
#define FSL_SIZE_T_PFMT FSL_UINT_T_PFMT

/** @def FSL_SIZE_T_SFMT

    Fossil's fsl_int_t equivalent of C99's SCNu32 and friends.
 */
#define FSL_SIZE_T_SFMT FSL_UINT_T_SFMT

/**
    fsl_id_t is a signed integer type used to store database record
    IDs. It is provided primarily for documentation/readability purposes,
    to avoid confusion with the widely varying integer semantics used
    by various APIs.

    This type "could" be 32-bit (instead of 64) because the
    oldest/largest Fossil repo (the TCL tree, with 15 years of
    history) currently (August 2013) has only 131k RIDs. HOWEVER,
    changing this type can have side-effects vis-a-vis va_arg() deep
    in the fsl_appendf() implementation if FSL_ID_T_PFMT is not 100%
    correct for this typedef. After changing this, _make sure_ to do a
    full clean rebuild and test thoroughly because changing a sizeof
    can produce weird side-effects (effectively memory corruption) on
    unclean rebuilds.
 */
typedef int32_t fsl_id_t;

/** @def FSL_ID_T_PFMT

    Fossil's fsl_id_t equivalent of C99's PRIi32 and friends.

    ACHTUNG: see FSL_SIZE_T_PFMT for important details.
 */
#define FSL_ID_T_PFMT PRIi32

/** @def FSL_ID_T_SFMT

    Fossil's fsl_id_t equivalent of C99's SCNi32 and friends.
 */
#define FSL_ID_T_SFMT SCNi32

/**
    The type used to represent type values. Unless noted otherwise,
    the general convention is Unix Epoch. That said, Fossil internally
    uses Julian Date for times, so this typedef is clearly the result
    of over-specification/over-thinking the problem. THAT said,
    application-level code more commonly works with Unix timestamps,
    so... here it is. Over-specified, perhaps, but not 100%
    unjustifiable.
 */
typedef int64_t fsl_time_t;

/** @def FSL_TIME_T_PFMT

    Fossil's fsl_time_t equivalent of C99's PRIi32 and friends.
 */
#define FSL_TIME_T_PFMT PRIi64

/** @def FSL_TIME_T_SFMT

    Fossil's fsl_time_t equivalent of C99's SCNi32 and friends.
 */
#define FSL_TIME_T_SFMT SCNi64

/**
   If true, the fsl_timer_xxx() family of functions might do something useful,
   otherwise they do not.
 */
#define FSL_CONFIG_ENABLE_TIMER 1

#if !defined(FSL_ENABLE_SQLITE_REGEXP)
#  define FSL_ENABLE_SQLITE_REGEXP 0
#endif

/**
   fossil(1)'s internal buffer size upper limit, which is also its
   blob.content size limit. Changing this has no magic ability to push
   past this limit, as pushing past them would create content
   incompatible with fossil(1), and going past just shy of 2gb would
   exceed sqlite3's limits.
*/
#define FSL_BLOB_MAX_SIZE 0x7fff0000

#if !defined(FSL_SWITCH_FALL_THROUGH)
#  if defined(__GNUC__) && !defined(__clang__) && (__GNUC__ >= 7)
/*
  #define FSL_USING_GCC

  gcc v7+ treats implicit 'switch' fallthrough as a warning
  (i.e. error because we always build with -Wall -Werror -Wextra
  -pedantic).

  Similarly braindead, clang #defines __GNUC__.

  _Sigh_.
*/
#    define FSL_SWITCH_FALL_THROUGH __attribute__ ((fallthrough))
#  else
#    define FSL_SWITCH_FALL_THROUGH
#  endif
#endif
/* /FSL_SWITCH_FALL_THROUGH

   TODO: add support for the C++ attributes for doing this.
*/

#if !defined(fsl__unused)
#define fsl__unused
#endif


#endif
/* ORG_FOSSIL_SCM_FSL_CONFIG_H_INCLUDED */
/* end of file include/fossil-scm/config.h */
/* start of file include/fossil-scm/util.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_UTIL_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_UTIL_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).

*/

/** @file util.h

    This file declares a number of utility classes and routines used by
    libfossil. All of them considered "public", suitable for direct use
    by client code.
*/

#include <stdio.h> /* FILE type */
#include <stdarg.h> /* va_list */
#include <time.h> /* tm struct */
#include <stdbool.h>
#if defined(__cplusplus)
extern "C" {
#endif
typedef struct fsl_allocator fsl_allocator;
typedef struct fsl_b fsl_b;
typedef struct fsl_error fsl_error;
typedef struct fsl_finalizer fsl_finalizer;
typedef struct fsl_fstat fsl_fstat;
typedef struct fsl_list fsl_list;
typedef struct fsl_outputer fsl_outputer;
typedef struct fsl_state fsl_state;
typedef struct fsl_id_bag fsl_id_bag;

/**
   fsl_uuid_str and fsl_uuid_cstr are "for documentation and
   readability purposes" typedefs used to denote strings which the API
   requires to be in the form of Fossil UUID strings. Such strings are
   exactly FSL_STRLEN_SHA1 or FSL_STRLEN_K256 bytes long plus a
   terminating NUL byte and contain only lower-case hexadecimal
   bytes. Where this typedef is used, the library requires, enforces,
   and/or assumes (at different times) that fsl_is_uuid() returns true
   for such strings (if they are not NULL, though not all contexts
   allow a NULL UUID). These typedef are _not_ used to denote
   arguments which may refer to partial UUIDs or symbolic names, only
   100% bonafide Fossil UUIDs (which are different from RFC4122
   UUIDs).

   The API guarantees that this typedef will always be (char *) and
   that fsl_uuid_cstr will always ben (char const *), and thus it
   is safe/portable to use those type instead of these. These
   typedefs serve only to improve the readability of certain APIs
   by implying (through the use of this typedef) the preconditions
   defined for UUID strings.

   Sidebar: fossil historically used the term UUID for blob IDs, and
   still uses that term in the DB schema, but it has fallen out of
   favor in documentation and discussions, with "hash" being the
   preferred term. Much of the libfossil code was developed before
   that happened, though, so "UUID" is still prevalent in its API and
   documentation.

   @see fsl_is_uuid()
   @see fsl_uuid_cstr
*/
typedef char * fsl_uuid_str;

/**
   The const counterpart of fsl_uuid_str.

   @see fsl_is_uuid()
   @see fsl_uuid_str
*/
typedef char const * fsl_uuid_cstr;

/**
   A typedef for comparison function used by standard C routines such
   as qsort(). It is provided here primarily to simplify documentation
   of other APIs. Concrete implementations must compare lhs and rhs,
   returning negative, 0, or positive depending on whether lhs is less
   than, equal to, or greater than rhs.

   Implementations might need to be able to deal with NULL
   arguments. That depends on the routine which uses the comparison
   function.
*/
typedef int (*fsl_generic_cmp_f)( void const * lhs, void const * rhs );

/**
   If the NUL-terminated input str is exactly FSL_STRLEN_SHA1 or
   FSL_STRLEN_K256 bytes long and contains only lower-case
   hexadecimal characters, returns the length of the string, else
   returns 0.

   Note that Fossil UUIDs are not RFC4122 UUIDs, but are SHA1 or
   SHA3-256 hash strings. Don't let that disturb you. As Tim
   Berners-Lee writes:

   > The assertion that the space of URIs is a universal space
   sometimes encounters opposition from those who feel there should
   not be one universal space. These people need not oppose the
   concept because it is not of a single universal space: Indeed,
   the fact that URIs form universal space does not prevent anyone
   else from forming their own universal space, which of course by
   definition would be able to envelop within it as a subset the
   universal URI space. Therefore the web meets the "independent
   design" test, that if a similar system had been concurrently and
   independently invented elsewhere, in such a way that the
   arbitrary design decisions were made differently, when they met
   later, the two systems could be made to interoperate.

   Source: https://www.w3.org/DesignIssues/Axioms.html

   (Just mentally translate URI as UUID.)
*/
FSL_EXPORT int fsl_is_uuid(char const * str);

/**
   If x is a valid fossil UUID length, it is returned, else 0 is returned.
*/
FSL_EXPORT int fsl_is_uuid_len(int x);

/**
   Expects str to be a string containing an unsigned decimal
   value. Returns its decoded value, or -1 on error.
*/
FSL_EXPORT fsl_size_t fsl_str_to_size(char const * str);

/**
   Expects str to be a string containing a decimal value,
   optionally with a leading sign. Returns its decoded value, or
   dflt if !str or on error.
*/
FSL_EXPORT fsl_int_t fsl_str_to_int(char const * str, fsl_int_t dflt);


/**
   Generic list container type. This is used heavily by the Fossil
   API for storing arrays of dynamically-allocated objects. It is
   not useful as a non-pointer-array replacement.

   It is up to the APIs using this type to manage the entry count
   member and use fsl_list_reserve() to manage the "capacity"
   member.

   @see fsl_list_reserve()
   @see fsl_list_append()
   @see fsl_list_visit()
*/
struct fsl_list {
  /**
     Array of entries. It contains this->capacity entries,
     this->used of which are "valid" (in use).
  */
  void ** list;
  /**
     Number of "used" entries in the list.
  */
  fsl_size_t used;
  /**
     Number of slots allocated in this->list. Use fsl_list_reserve()
     to modify this. Doing so might move the this->list pointer but
     the values it points to will stay stable.
  */
  fsl_size_t capacity;
};

/**
   Empty-initialized fsl_list structure, intended for const-copy
   initialization.
*/
#define fsl_list_empty_m { .list=NULL, .used=0, .capacity=0 }

/**
   Empty-initialized fsl_list structure, intended for copy
   initialization.
*/
FSL_EXPORT const fsl_list fsl_list_empty;

/**
   Generic interface for finalizing/freeing memory. Intended
   primarily for use as a destructor/finalizer for high-level
   structs. Implementations must semantically behave like free(mem),
   regardless of whether or not they actually free the memory. At
   the very least, they generally should clean up any memory owned by
   mem (e.g. db resources or buffers), even if they do not free() mem.
   some implementations assume that mem is stack-allocated
   and they only clean up resources owned by mem.

   The state parameter is any state needed by the finalizer
   (e.g. a memory allocation context) and mem is the memory which is
   being finalized.

   The exact interpretaion of the state and mem are of course
   implementation-specific.
*/
typedef void (*fsl_finalizer_f)( void * state, void * mem );

/**
   Generic interface for memory finalizers.
*/
struct fsl_finalizer {
  /**
     State to be passed as the first argument to f().
  */
  void * state;
  /**
     Finalizer function. Should be called like this->f( this->state, ... ).
  */
  fsl_finalizer_f f;
};

/** Empty-initialized fsl_finalizer struct. */
#define fsl_finalizer_empty_m {NULL,NULL}

/**
   fsl_finalizer_f() impl which requires that mem be-a
   (fsl_b*).  This function frees all memory associated with
   that buffer and zeroes out the structure, but does not free mem
   (because it is rare that fsl_bs are created on the
   heap). The state parameter is ignored.
*/
FSL_EXPORT int fsl_finalizer_f_buffer( void * state, void * mem );


/**
   Generic state-with-finalizer holder. Used for binding
   client-specified state to another object, such that a
   client-specified finalizer is called with the other object is
   cleaned up.
*/
struct fsl_state {
  /**
     Arbitrary context-dependent state.
  */
  void * state;
  /**
     Finalizer for this->state. If used, it should be called like:

     ```
     this->finalize.f( this->finalize.state, this->state );
     ```

     After which this->state must be treated as if it has been
     free(3)'d. See fsl_state_finalize().
  */
  fsl_finalizer finalize;
};

/** Empty-initialized fsl_state struct. */
#define fsl_state_empty_m {NULL,fsl_finalizer_empty_m}

/**
   Empty-initialized fsl_state struct, intended for
   copy-initializing.
*/
FSL_EXPORT const fsl_state fsl_state_empty;

/**
   If fst is not NULL then:

   - If fst->finalize.f is not null, then it is called and
     passed (fst->finalize.f, fst->state).

   - *fst is cleared out. fst is not freed.

   This is a no-op if fst is NULL.
*/
void fsl_state_finalize(fsl_state * fst);

/**
   Generic interface for streaming out data. Implementations must
   write n bytes from src to their destination channel and return 0
   on success, non-0 on error (assumed to be a value from the fsl_rc_e
   enum). The state parameter is the implementation-specified output
   channel.

   Potential TODO: change the final argument to a pointer, with
   semantics similar to fsl_input_f(): at call-time n is the number
   of bytes to output, and on returning n is the number of bytes
   actually written. This would allow, e.g. the fsl_zip_writer APIs
   to be able to stream a ZIP file (they have to know the real size
   of the output, and this interface doesn't support that
   operation).
*/
typedef int (*fsl_output_f)( void * state, void const * src, fsl_size_t n );


/**
   Generic interface for flushing arbitrary output streams.  Must
   return 0 on success, non-0 on error, but the result code
   "should" (to avoid downstream confusion) be one of the fsl_rc_e
   values. When in doubt, return FSL_RC_IO on error. The
   interpretation of the state parameter is
   implementation-specific.
*/
typedef int (*fsl_flush_f)(void * state);

/**
   Generic interface for streaming in data. Implementations must
   read (at most) *n bytes from their input, copy it to dest, assign
   *n to the number of bytes actually read, return 0 on success, and
   return non-0 on error (assumed to be a value from the fsl_rc_e
   enum). When called, *n is the max length to read. On return, *n
   is the actual amount read. The state parameter is the
   implementation-specified input file/buffer/whatever channel.

   Implementations may need to distinguish a short read due to EOF
   from a short read due to an I/O error, e.g. using feof() and/or
   ferror().
*/
typedef int (*fsl_input_f)( void * state, void * dest, fsl_size_t * n );

/**
   fsl_output_f() implementation which requires state to be a
   (fsl_cx*) to which this routine simply redirects the output via
   fsl_output().  Is a no-op (returning 0) if !n. Returns
   FSL_RC_MISUSE if !state or !src.
*/
FSL_EXPORT int fsl_output_f_fsl_cx(void * state, void const * src, fsl_size_t n );

/**
   An interface which encapsulates data for managing an output
   destination, primarily intended for use with fsl_output(). Why
   abstract it to this level? So that we can do interesting things
   like output to buffers, files, sockets, etc., using the core
   output mechanism. e.g. so script bindings can send their output
   to the same channel used by the library and other library
   clients.
*/
struct fsl_outputer {
  /**
     Output channel.
  */
  fsl_output_f out;
  /**
     flush() implementation. This may be NULL for most uses of this
     class. Cases which specifically require it must document that
     requirement so.
  */
  fsl_flush_f flush;
  /**
     State to be used when calling this->out(), namely:
     this->out( this->state, ... ) and this->flush(this->state).
  */
  void * state;
};
/** Empty-initialized fsl_outputer instance. */
#define fsl_outputer_empty_m {NULL,NULL,NULL}
/**
   Empty-initialized fsl_outputer instance, intended for
   copy-initializing.
*/
FSL_EXPORT const fsl_outputer fsl_outputer_empty;

/**
   A fsl_outputer instance which is initialized to output to a
   (FILE*). To use it, this value then set the copy's state
   member to an opened-for-write (FILE*) handle. By default it will
   use stdout.
*/
FSL_EXPORT const fsl_outputer fsl_outputer_FILE;

/**
   fsl_outputer initializer which uses fsl_flush_f_FILE() and
   fsl_output_f_FILE(). After copying, the state member must be
   pointed to an opened-for-writing (FILE*).
*/
#define fsl_outputer_FILE_m { \
  .out = fsl_output_f_FILE,   \
  .flush = fsl_flush_f_FILE,  \
  .state = NULL               \
}

/**
   Generic stateful alloc/free/realloc() interface.

   Implementations must behave as follows:

   - If 0==n then semantically behave like free(3) and return
   NULL.

   - If 0!=n and !mem then semantically behave like malloc(3), returning
   newly-allocated memory on success and NULL on error.

   - If 0!=n and NULL!=mem then semantically behave like
   realloc(3). Note that realloc specifies: "If n was equal to 0,
   either NULL or a pointer suitable to be passed to free() is
   returned." Which is kind of useless, and thus implementations
   MUST return NULL when n==0.
*/
typedef void *(*fsl_realloc_f)(void * state, void * mem, fsl_size_t n);

/**
   Holds an allocator function and its related state.
*/
struct fsl_allocator {
  /**
     Base allocator function. It must be passed this->state as its
     first argument.
  */
  fsl_realloc_f f;
  /**
     State intended to be passed as the first argument to this->f().
  */
  void * state;
};

/** Empty-initialized fsl_allocator instance. */
#define fsl_allocator_empty_m {NULL,NULL}


/**
   A fsl_realloc_f() implementation which uses the standard
   malloc()/free()/realloc(). The state parameter is ignored.
*/
FSL_EXPORT void * fsl_realloc_f_stdalloc(void * state, void * mem, fsl_size_t n);

/**
   Semantically behaves like malloc(3), but may introduce instrumentation,
   error checking, or similar.
*/
FSL_EXPORT void * fsl_malloc( fsl_size_t n )
#ifdef __GNUC__
  __attribute__ ((malloc))
#endif
  ;

/**
   Semantically behaves like free(3), but may introduce instrumentation,
   error checking, or similar.
*/
FSL_EXPORT void fsl_free( void * mem );

/**
   Behaves like realloc(3). Clarifications on the behaviour (because
   the standard has one case of unfortunate wording involving what
   it returns when n==0):

   - If passed (NULL, n>0) then it semantically behaves like
   fsl_malloc(f, n).

   - If 0==n then it semantically behaves like free(2) and returns
   NULL (clarifying the aforementioned wording problem).

   - If passed (non-NULL, n) then it semantically behaves like
   realloc(mem,n).

   - If n is larger than SIZE_MAX, as it can be on 32-bit targets,
   it returns NULL without calling the allocator, leaving mem
   unchanged, as for any failed allocation.

*/
FSL_EXPORT void * fsl_realloc( void * mem, fsl_size_t n );

/**
   A fsl_flush_f() impl which expects _FILE to be-a (FILE*) opened
   for writing, which this function passes the call on to
   fflush(). If fflush() returns 0, so does this function, else it
   returns non-0.
*/
FSL_EXPORT int fsl_flush_f_FILE(void * _FILE);

/**
   A fsl_finalizer_f() impl which requires that mem be-a (FILE*).
   This function passes that FILE to fsl_fclose(). The state
   parameter is ignored.
*/
FSL_EXPORT void fsl_finalizer_f_FILE( void * state, void * mem );

/**
   A fsl_output_f() impl which requires state to be-a (FILE*), which
   this function passes the call on to fwrite(). Returns 0 on
   success. On error it returns the counterpart of fwrite()'s errno
   value, as per fsl_errno_to_rc(), falling back to FSL_RC_IO.
*/
FSL_EXPORT int fsl_output_f_FILE( void * state, void const * src, fsl_size_t n );

/**
   A fsl_output_f() impl which requires state to be-a (fsl_b*),
   which this function passes to fsl_b_append(). Returns 0 on
   success, FSL_RC_OOM (probably) on error.
*/
FSL_EXPORT int fsl_output_f_b( void * state, void const * src, fsl_size_t n );


/**
   A fsl_output_f() impl which requires state to be-a (int*) referring
   to a writable file descriptor, which this function passes to
   write(2). Returns 0 after writing all n bytes. It retries a write
   interrupted by a signal and continues after a partial write. On
   error it returns the counterpart of write()'s errno value, as per
   fsl_errno_to_rc(), falling back to FSL_RC_IO.
*/
FSL_EXPORT int fsl_output_f_fd( void * state, void const * src, fsl_size_t n );

/**
   A fsl_input_f() implementation which requires that state be
   a readable (FILE*) handle. Returns 0 on success, including a short
   read at end of file. On a read error it returns the counterpart of
   fread()'s errno value, as per fsl_errno_to_rc(), falling back to
   FSL_RC_IO; reading a directory, for example, returns FSL_RC_TYPE.
*/
FSL_EXPORT int fsl_input_f_FILE( void * state, void * dest, fsl_size_t * n );

/**
   A fsl_input_f() implementation which requires that state be a
   readable file descriptor, in the form of an ([const] int*).  This
   function will not modify that value.

   Like fsl_input_f_FILE(), it reads all *n bytes unless the input
   ends first, so a short read means the end of the input, as
   fsl_stream() and fsl_b_fill_from() assume. On a pipe or socket it
   therefore blocks until *n bytes arrive or the writer closes its
   end. A read interrupted by a signal is retried.
*/
FSL_EXPORT int fsl_input_f_fd( void * state, void * dest, fsl_size_t * n );

/**
   A fsl_input_f() implementation which requires that state be a
   readable (fsl_b*) handle. The buffer's cursor member is
   updated to track input postion, but that is the only modification
   made by this routine. Thus the user may need to reset the cursor to
   0 if he wishes to start consuming the buffer at its starting point
   (e.g. call fsl_b_rewind()). Subsequent calls to this function
   will increment the cursor by the number of bytes returned via *n.
   The buffer's "used" member is used to determine the logical end of
   input.

   If fsl_b_err() is non-zero for the state argument, that code
   is returned without other side effects.

   Returns 0 on success and has no error conditions except for invalid
   arguments, which result in undefined beavhiour, or fsl_b_err()
   being true for the state argument. Results are undefined if any
   argument is NULL.

   Tip (and warning): sometimes a routine might have a const buffer
   handle which it would like to use in conjunction with this
   routine but cannot without violating constness. Here's a crude
   workaround:

   ```
   fsl_b kludge = fsl_b_empty;
   fsl_b_external(&kludge, theConstBuffer->mem, theConstBuffer->used);
   rc = some_func( fsl_input_f_buffer, &kludge, ... );
   assert( kludge.mem == theConstBuffer->mem );// not reallocated
   assert( 0==kludge.capacity );// b/c it's an external buffer
   ```

   That is legal because this routine modifies only
   fsl_b::cursor. It is not useful as a constness workaround if
   there is ANY CHANCE WHATSOEVER that the buffer's memory will be
   modified. If such tricks are used for APIs which may modify their
   buffer, the "kludge" buffer (above), because it's an "external"
   buffer, will create a new copy of theConstBuffer's memory before
   making any changes, which will lead a leak if that object is not
   cleaned up.

   [Much later:] a cleaner approach is to use fsl_b_external().
*/
FSL_EXPORT int fsl_input_f_buffer( void * state, void * dest, fsl_size_t * n );


/**
   A generic streaming routine which copies data from an
   fsl_input_f() to an fsl_outpuf_f().

   Reads all data from inF() in chunks of an unspecified size and
   passes them on to outF(). It reads until inF() returns fewer bytes
   than requested. Returns the result of the last call to outF() or
   (only if reading fails) inF(). Results are undefined if either of
   the callback function arguments are NULL.  (This function cannot
   know whether a NULL state argument is legal.)

   Here is an example which basically does the same thing as the
   cat(1) command on Unix systems:

   ```
   fsl_stream( fsl_input_f_FILE, stdin, fsl_output_f_FILE, stdout );
   ```

   Or copy a FILE to a buffer:

   ```
   FILE * f = fopen(...);
   fsl_b myBuf = fsl_b_empty;
   rc = fsl_stream( fsl_input_f_FILE, f, fsl_output_f_b, &myBuf );
   // Note that on error myBuf might be partially populated.
   // Eventually clean up the buffer:
   fsl_b_clear(&myBuf);
   ```
*/
FSL_EXPORT int fsl_stream( fsl_input_f inF, void * inState,
                           fsl_output_f outF, void * outState );

/**
   Consumes two input streams looking for differences.  It stops
   reading as soon as either or both streams run out of input or a
   byte-level difference is found.  It consumes input in chunks of
   an unspecified size, and after this returns the input cursor of
   the streams is not well-defined.  i.e. the cursor probably does
   not point to the exact position of the difference because this
   level of abstraction does not allow that unless we read byte by
   byte.

   Returns 0 if both streams emit the same amount of output and
   that ouput is bitwise identical, otherwise it returns non-0.
*/
FSL_EXPORT int fsl_stream_compare( fsl_input_f in1, void * in1State,
                                   fsl_input_f in2, void * in2State );


/**
   A general-purpose buffer class, analog to Fossil's Blob
   class, but it is not called fsl_blob to avoid confusion with
   DB-side blobs. Buffers are used extensively in fossil to do
   everything from reading files to compressing artifacts to
   creating dynamically-formatted strings. Because they are such a
   pervasive low-level type, and have such a simple structure,
   their members (unlike most other structs in this API) may be
   considered public and used directly by client code (as long as
   they do not mangle their state, e.g. by setting this->capacity
   smaller than this->used!).

   General conventions of this class:

   - ALWAYS initialize them by copying fsl_b_empty or
   (depending on the context) fsl_b_empty_m. Failing to
   initialize them properly leads to undefined behaviour.

   - ALWAYS fsl_b_clear() buffers when done with
   them. Remember that failed routines which output to buffers
   might partially populate the buffer, so be sure to clean up in
   error cases.

   - The `capacity` member specifies how much memory the buffer
   currently holds in its `mem` member. If `capacity` is 0 and `mem`
   is not then the memory is expected to refer to `used` bytes of
   memory which are owned elsewhere. See fsl_b_external() and
   fsl_b_materialize() for details.

   - The `used` member specifies how much of the memory is actually
   "in use" by the buffer. The exact meaning of "used" is
   context-dependent but it's typically equivalent to the strlen() of
   the buffer's contents.

   - As a rule, the public APIs keep (`used`<`capacity`) and always
   (unless documented otherwise) tries to keep the memory buffer
   NUL-terminated (if it has any memory at all). The notable
   potential exception to that is that "external" buffers
   may not be NUL-terminated (see fsl_b_external()).

   - Use fsl_b_reuse() to keep memory around and reset the `used`
   amount to 0. Most library-wide routines which write to buffers will
   re-use that memory if they can, rather than re-allocating.

   This example demonstrates the difference between `used` and
   `capacity` (error checking reduced to assert()ions for clarity):

   ```
   fsl_b b = fsl_b_empty;
   // ALWAYS init via copying fsl_b_empty or (depending on
   // the context) fsl_b_empty_m. The latter is used for
   // in-struct initialization of struct members.
   int rc = fsl_b_reserve(&b, 20);
   assert(0==rc);
   assert(b.capacity>=20); // it may reserve more!
   assert(0==b.used);
   rc = fsl_b_append(&b, "abc", 3);
   assert(0==rc);
   assert(3==b.used);
   assert(0==b.mem[b.used]); // API always NUL-terminates
   fsl_b_reuse(&b);
   assert(0==b.used); // Resets the buffer but...
   assert(b.capacity>=20);  // ... keeps the memory.
   fsl_b_clear(&b); // ALWAYS clean up
   ```

   @see fsl_b_reserve()
   @see fsl_b_resize()
   @see fsl_b_external()
   @see fsl_b_materialize()
   @see fsl_b_append()
   @see fsl_b_appendf()
   @see fsl_b_cstr()
   @see fsl_b_size()
   @see fsl_b_capacity()
   @see fsl_b_clear()
   @see fsl_b_reuse()
   @see fsl_b_err()
   @see fsl_b_err_clear()
*/
struct fsl_b {
  /**
     The raw memory pointed to by this buffer. There are two ways of
     using this member:

     - If `this->capacity` is non-0 then the first `this->capacity`
     bytes of `this->mem` are owned by this buffer instance. The API
     docs call this state "managed" buffers.

     - `If this->capacity` is 0 and this->mem is not NULL then the
     memory is owned by "somewhere else" and this API will treat it as
     _immutable_ (so it may safely point to const data). Its lifetime
     must exceed this object's and any attempt made via this API to
     write to it will cause the memory to be copied (effectively a
     copy-on-write op). The API calls this state "external" buffers
     and refers to the copy-on-write of such buffers as
     "materializing" them. See fsl_b_external() and
     fsl_b_materialize() for details.

     `this->used` bytes are treated as the "used" part of the buffer
     (as opposed to its capacity). When `this->capacity>0` the
     difference beween (`this->capacity - this->used`) represents
     space the buffer has available for use before it will require
     another expansion/reallocation.
  */
  unsigned char * mem;
  /**
     Number of bytes allocated for this buffer. If capacity is 0
     and `this->mem` is not NULL then this buffer's memory is assumed
     to be owned "elsewhere" and will be considered immutable by the
     API. Any attempt to modify it will result in a copy-on-write
     operation
  */
  fsl_size_t capacity;

  /**
     Number of "used" bytes in the buffer. This is generally
     interpreted as the string length of this->mem, and the buffer
     APIs which add data to a buffer always ensure that
     this->capacity is large enough to account for a trailing NUL
     byte in this->mem.

     Library routines which manipulate buffers must ensure that
     (this->used<this->capacity) is always true, expanding the buffer
     if necessary. Much of the API assumes that precondition is always
     met, and any violation of it opens the code to undefined
     behaviour (which is okay, just don't ever break that
     precondition). Most APIs ensure that (used<capacity) is always
     true (as opposed to used<=capacity) because they add a trailing
     NUL byte which is not counted in the "used" length.
  */
  fsl_size_t used;
  /**
     Used by some routines to keep a cursor into this->mem. Note that
     a pointer-based cursor is not valid for some uses because mem can
     be reallocated (and thus moved).
  */
  fsl_size_t cursor;

  /**
     When any buffer-related routines encounter an error, they set
     this flag so that the error can be propagated. Many APIs also
     become no-ops when this is set, the intention being to simplify
     many common uses of this class, e.g.:

     ```
     fsl_b_append(b, ... );
     fsl_b_append(b, ... );
     fsl_b_append(b, ... );
     if(fsl_b_err(b)) ...
     ```

     The alternative (without this member) being to check for an OOM
     error after every append operation.
  */
  int errCode;
};

/** Empty-initialized fsl_b instance, intended for const-copy
    initialization. */
#define fsl_b_empty_m \
  {.mem=NULL,.capacity=0U,.used=0U,.cursor=0U,.errCode=0}

/** Empty-initialized fsl_b instance, intended for copy
    initialization. */
FSL_EXPORT const fsl_b fsl_b_empty;

/**
   A container for storing generic error state. It is used to
   propagate error state between layers of the API back to the
   client. i.e. they act as basic exception containers.

   @see fsl_error_set()
   @see fsl_error_get()
   @see fsl_error_propagate()
   @see fsl_error_clear()
*/
struct fsl_error {
  /**
     Error message text is stored in this->msg.mem. The usable text
     part is this->msg.used bytes long.
  */
  fsl_b msg;
  /**
     Error code, generally assumed to be a fsl_rc_e value. The
     "non-error" code is 0.
  */
  int code;
};

/** Empty-initialized fsl_error instance, intended for const-copy
    initialization. */
#define fsl_error_empty_m {.msg = fsl_b_empty_m, .code = 0}

/** Empty-initialized fsl_error instance, intended for copy
    initialization. */
FSL_EXPORT const fsl_error fsl_error_empty;

/**
   If err is not NULL, populates err with the given code and formatted
   string, replacing any existing state. If fmt==NULL then
   fsl_rc_cstr(rc) is used to get the error string.

   If err is NULL this is a no-op and returns code.

   Returns code on success, some other non-0 code on error.

   As a special case, if 0==code then fmt is ignored and the error
   state is cleared. This will not free any memory held by err but
   will re-set its string to start with a NUL byte, ready for
   re-use later on.

   As a special case, if code==FSL_RC_OOM then fmt is ignored
   to avoid a memory allocation (which would presumably fail).

   @see fsl_error_get()
   @see fsl_error_clear()
   @see fsl_error_propagate()
*/
FSL_EXPORT int fsl_error_set( fsl_error *  err, int code,
                              char const * fmt, ... );

/**
   va_list counterpart to fsl_error_set().
*/
FSL_EXPORT int fsl_error_setv( fsl_error *  err, int code,
                               char const * fmt, va_list args );

/**
   Fetches the error state from err. Returns err's current error code.

   If str is not NULL then *str will be assigned to the raw
   (NUL-terminated) error string (which might be empty or even
   NULL). The memory for the string is owned by err and may be
   invalidated by any calls which take err as a non-const parameter OR
   which might modify it indirectly through a container object, so the
   client is required to copy it if it is needed for later
   reference. As a special case, if the error object has no message
   then the returned string is set to NULL, as opposed to an empty
   string.

   If len is not NULL then *len will be assigned to the length of
   the (*str) string (in bytes).

   @see fsl_error_set()
   @see fsl_error_clear()
   @see fsl_error_propagate()
*/
FSL_EXPORT int fsl_error_get( fsl_error const * err,
                              char const ** str, fsl_size_t *  len );

/**
   If err is not NULL, frees up any resources owned by err and sets
   its error code to 0, but does not free err. This is harmless no-op
   if err is NULL or holds no dynamically allocated no memory.

   @see fsl_error_set()
   @see fsl_error_get()
   @see fsl_error_propagate()
   @see fsl_error_reset()
*/
FSL_EXPORT void fsl_error_clear( fsl_error *  err );

/**
   Sets err->code to 0 and resets its buffer, but keeps any err->msg
   memory around for later re-use. This is a no-op if err is NULL.

   @see fsl_error_clear()
*/
FSL_EXPORT void fsl_error_reset( fsl_error *  err );

/**
   Copies the error state from src to dest. If dest contains state, it is
   cleared/recycled by this operation.

   Returns 0 on success, FSL_RC_MISUSE if either argument is NULL
   or if (src==dest), and FSL_RC_OOM if allocation of the message
   string fails.

   As a special case, if src->code==FSL_RC_OOM, then the code is
   copied but the message bytes (if any) are not (under the
   assumption that we have no more memory).
*/
FSL_EXPORT int fsl_error_copy( fsl_error const * src,
                               fsl_error *  dest );

/**
   Swaps the state between two fsl_error objects and then resets the
   error state on the `from` object. Intended as an allocation
   optimization when propagating error state up the API.

   This is a no-op if from==to.

   Because this modifies one argument differently from the other, it's
   not exactly like a swap, but it has the effect of moving an error
   from the `from` object to the `to` object, while keeping `to`'s
   former memory intact for re-use (now inside the `from` object).

   Results are undefined if either parameter is NULL or either is not
   properly initialized. i.e. neither may refer to uninitialized
   memory. Copying fsl_error_empty at declaration-time is a simple way
   to ensure that instances are cleanly initialized.
*/
FSL_EXPORT void fsl_error_propagate( fsl_error *  from, fsl_error *  to );

/** Old name for fsl_error_propagate() */
#define fsl_error_move fsl_error_propagate
///** Old, misleading name for fsl_error_propagate() */
//#define fsl_error_swap fsl_error_propagate

/**
   Returns the given Unix Epoch timestamp value as its approximate
   Julian Day value. Note that the calculation does not account for
   leap seconds.
*/
FSL_EXPORT double fsl_unix_to_julian( fsl_time_t unixEpoch );

/**
   Returns the current Unix Epoch time converted to its approximate
   Julian form. Equivalent to fsl_unix_to_julian(time(0)). See
   fsl_unix_to_julian() for details. Note that the returned time
   has seconds, not milliseconds, precision.
*/
FSL_EXPORT double fsl_julian_now(void);

#if 0
/** UNTESTED, possibly broken vis-a-vis timezone conversion.

    Returns the given Unix Epoch time value formatted as an ISO8601
    string.  Returns NULL on allocation error, else a string 19
    bytes long plus a terminating NUL
    (e.g. "2013-08-19T20:35:49"). The returned memory must
    eventually be freed using fsl_free().
*/
FSL_EXPORT char * fsl_unix_to_iso8601( fsl_time_t j );
#endif

/**
   Returns true if the first 10 digits of z _appear_ to form the start
   of an ISO date string (YYYY-MM-DD). Whether or not the string is
   really a valid date is left for downstream code to
   determine. Returns false in all other cases, including if z is
   NULL.
*/
FSL_EXPORT bool fsl_str_is_date(const char *z);


/**
   Checks if z is syntactically a time-format string in the format:

   [Y]YYYY-MM-DD

   (Yes, the year may be five-digits, left-padded with a zero for
   years less than 9999.)

   Returns a positive value if the YYYYY part has five digits, a
   negative value if it has four. It returns 0 (false) if z does not
   match that pattern.

   If it returns a negative value, the MM part of z starts at byte offset
   (z+5), and a positive value means the MM part starts at (z+6).

   z need not be NUL terminated - this function does not read past
   the first invalid byte. Thus is can be used on, e.g., full
   ISO8601-format strings. If z is NULL, 0 is returned.
*/
FSL_EXPORT int fsl_str_is_date2(const char *z);


/**
   Returns the current error code of the given buffer. Many buffer
   APIs become noops when this function returns non-0.
*/
FSL_EXPORT int fsl_b_err(fsl_b const * b);

/**
   Resets the error code of the given buffer to 0.
*/
FSL_EXPORT void fsl_b_err_clear(fsl_b *  b);

/**
   Reserves at least n bytes of capacity in buf. Returns 0 on
   success, FSL_RC_OOM if allocation fails. Results are undefined
   if !buf.

   If fsl_b_err() is true and n is not 0 then this function
   returns its value without other side effects. If n is 0 then the
   error state is cleared.

   If b is an external buffer then:

   - If n is 0, this disassociates b->mem from b, effectively clearing
     the buffer's state. Else...

   - The buffer is materialized, transformed into a managed buffer.
     This happens even if n is less than b->used because this routine
     is always used in preparation for writing to the buffer.

   - If n>0 then the greater of (n, b->used) bytes of memory are
     allocated, b->used bytes are copied from b->mem (its external
     memory) to the new block, and b->mem is replaced with the new
     block. Afterwards, b->capacity will be non-0.

   This does not change b->used, nor will it shrink the buffer
   (reduce buf->capacity) unless n is 0, in which case it immediately:

   - frees b->mem (if b is a managed buffer)
   - sets b->capacity, buf->used, and b->cursor to 0
   - sets b->errCode to 0

   @see fsl_b_resize()
   @see fsl_b_materialize()
   @see fsl_b_clear()
*/
FSL_EXPORT int fsl_b_reserve( fsl_b *  b, fsl_size_t n );

/**
   If b is a "managed" buffer or b->errCode is non-0 then this is a
   no-op and returns b->errCode, else b is an "external" buffer and
   it...

   - Allocates enough memory to store b->used bytes plus a NUL
     terminator.

   - Copies b->mem to the new block.

   - NUL-terminates the new block.

   - Assigns b->mem to the new block.

   b is thereby transformed to a managed buffer, i.e. b owns b->mem.

   If fsl_b_err() is non-0 before this call, this call is a no-op
   and that value is returned.

   Returns 0 on success, FSL_RC_OOM on allocation error.

   This materialization happens automatically on demand by fsl_b
   APIs which write to the buffer but clients should use this to
   ensure that it is managed memory before they manipulate b->mem
   directly. (Editing b->mem for an external buffer specifically
   results in Undefined Behavior.)

   @see fsl_b_external()
*/
FSL_EXPORT int fsl_b_materialize( fsl_b *  b );

/**
   Initializes b to be an "external" buffer pointing to n bytes of the
   given memory. If n is negative, the equivalent of fsl_strlen() is
   used to count its length. The buffer API treats external buffers as
   immutable. If asked to write to one, the API will first
   "materialize" the buffer, as documented for
   fsl_b_materialize().

   Either mem must be guaranteed to outlive b or b must be
   materialized before mem goes out of scope.

   ACHTUNG: it is NEVER legal to pass a pointer which may get
   reallocated, as doing so may change its address, invaliding the
   resulting `b->mem` pointer. Similarly, it is never legal to pass it
   scope-local memory unless b's lifetime is limited to that scope.

   If b->mem is not NULL, this function first passes the buffer to
   fsl_b_clear() to ensure that this routine does not leak any
   dynamic memory it may already own.

   Results are undefined if mem is NULL, but n may be 0.

   Results are undefined if passed a completely uninitialized buffer
   object. _Always_ initialize new buffer objects by copying
   fsl_b_empty or (when appropriate) fsl_b_empty_m.

   This function resets b->errCode.

   @see fsl_b_materialize()
*/
FSL_EXPORT void fsl_b_external( fsl_b *  b, void const * mem, fsl_int_t n );

/**
   Convenience equivalent of fsl_b_reserve(b,0).
*/
FSL_EXPORT void fsl_b_clear( fsl_b *  b );

/**
   If b is a managed buffer, this resets b->used, b->cursor, and
   b->mem[0] (if b->mem is not NULL) to 0. If b is an external buffer,
   this clears all state from the buffer, behaving like
   fsl_b_clear() (making it available for reuse as a managed or
   external buffer).

   This does not (de)allocate memory, only changes the logical "used"
   size of the buffer. Returns its argument.

   This function resets b->errCode.

   Returns b.

   Achtung for fossil(1) porters: this function's semantics are much
   different from the fossil's blob_reset(). To get those semantics,
   use fsl_b_reserve(buf, 0) or its convenience form
   fsl_b_clear(). (This function _used_ to be called
   fsl_b_reset(), but it was renamed in the hope of avoiding
   related confusion.)
*/
FSL_EXPORT fsl_b * fsl_b_reuse( fsl_b *  b );

/**
   Similar to fsl_b_reserve() except that...

   - If fsl_b_err() is true, that result is returned with no other
     side effects.

   For managed buffers:

   - It does not free all memory when n==0. Instead it essentially
     makes the memory a length-0, NUL-terminated string.

   - It will try to shrink (realloc) buf's memory if (n<buf->capacity).

   - It sets buf->capacity to (n+1) and buf->used to n. This routine
     allocates one extra byte to ensure that buf is always
     NUL-terminated.

   - On success it always NUL-terminates the buffer at
   offset buf->used.

   For external buffers it behaves slightly differently:

   - If n==buf->used, this is a no-op and returns 0.

   - If n==0 then it behaves like fsl_b_external(buf,"",0)
     and returns 0.

   - Else it materializes the buffer, as per fsl_b_materialize(),
     copies the lesser of (n, buf->used) bytes from buf->mem to that
     memory, NUL-terminates the new block, replaces buf->mem with the
     new block, sets buf->used to n and buf->capacity to n+1.

   Returns 0 on success or FSL_RC_OOM if a (re)allocation fails. On
   allocation error, the buffer's memory state is unchanged.

   @see fsl_b_reserve()
   @see fsl_b_materialize()
   @see fsl_b_clear()
*/
FSL_EXPORT int fsl_b_resize( fsl_b *  buf, fsl_size_t n );

/**
   Swaps the entire state of the left and right arguments. Results are
   undefined if either argument is NULL or points to uninitialized
   memory.
*/
FSL_EXPORT void fsl_b_swap( fsl_b *  left, fsl_b *  right );

/**
   Similar fsl_b_swap() but it also optionally frees one of
   the buffer's memories after swapping them. If clearWhich is
   negative then the left buffer (1st arg) is cleared _after_
   swapping (i.e., the NEW left hand side gets cleared). If
   clearWhich is greater than 0 then the right buffer (2nd arg) is
   cleared _after_ swapping (i.e. the NEW right hand side gets
   cleared). If clearWhich is 0, this function behaves identically
   to fsl_b_swap().

   A couple examples should clear this up:

   ```
   fsl_b_swap_free( &b1, &b2, -1 );
   ```

   Swaps the contents of b1 and b2, then frees the contents
   of the left-side buffer (b1).

   ```
   fsl_b_swap_free( &b1, &b2, 1 );
   ```

   Swaps the contents of b1 and b2, then frees the contents
   of the right-side buffer (b2).
*/
FSL_EXPORT void fsl_b_swap_free( fsl_b *  left,
                                      fsl_b *  right,
                                      int clearWhich );

/**
   Appends the first n bytes of src, plus a NUL byte, to b,
   expanding b as necessary and incrementing b->used by n. If n is
   less than 0 then the equivalent of fsl_strlen((char const*)src)
   is used to calculate the length.

   If fsl_b_err() is true, its result is returned without further
   side effects.

   If b is an external buffer, it is first transformed into a
   managed buffer.

   Results are undefined if b or src are NULL.

   If n is 0 (or negative and !*src), this function ensures that
   b->mem is not NULL and is NUL-terminated, so it may allocate
   to have space for that NUL byte.

   Returns 0 on success, FSL_RC_OOM if allocation of memory fails.

   If this function succeeds, it guarantees that it NUL-terminates the
   buffer (but that the NUL terminator is not counted in b->used).

   This function does not modify b's cursor.

   @see fsl_b_appendf()
   @see fsl_b_reserve()
*/
FSL_EXPORT int fsl_b_append( fsl_b * b, void const * src, fsl_int_t n );

/**
   Convenience form of fsl_b_append() which requires a literal
   C-string and appends it all to (fsl_b*) B.
*/
#define fsl_b_append_literal(B,LITERAL) \
  fsl_b_append(B, "" LITERAL, sizeof(LITERAL)-1)

/**
   Uses fsl_appendf() to append formatted output to the given buffer.
   Returns 0 on success, FSL_RC_OOM if an allocation fails while
   expanding dest, or the non-0 code fsl_appendf() returns, such as
   FSL_RC_RANGE for a string length it cannot format. Results are
   undefined if either of the first two arguments are NULL.

   If fsl_b_err() is true, its result is returned without further
   side effects.

   @see fsl_b_append()
   @see fsl_b_reserve()
*/
FSL_EXPORT int fsl_b_appendf( fsl_b *  dest,
                                   char const * fmt, ... );

/** va_list counterpart to fsl_b_appendf(). */
FSL_EXPORT int fsl_b_appendfv( fsl_b *  dest,
                                    char const * fmt, va_list args );

/**
   Appends the given byte to b. This is slightly more efficient than
   fsl_b_append() for the common case where b has slack memory to
   fill.

   If b->errCode is non-0, this is a no-op and returns that code.

   On success this routine always NUL-terminates b. On error,
   b->errCode is returned.
*/
FSL_EXPORT int fsl_b_appendch(fsl_b *  b, char c);

/**
   Add an EOL to b if it has content (i.e. b->used is not 0) but does
   not end on one, else do nothing. It does not modify empty buffers.
   b is materialized if needed.

   Returns b->errCode and is a no-op if b->errCode is non-0 when this
   is called.
*/
FSL_EXPORT int fsl_b_ensure_eol(fsl_b *  b);

/**
   If b ends with a `\n` character or a pair of `\r\n`, the `\n` or
   `\r\n` pair are "chomped" (to use Perl's term for it), reducing
   b->used by 1 or 2, else this function has no side-effects.

   For external buffers, the b->used is adjusted but the memory is
   otherwise not modified (as external buffers are never guaranteed to
   be NUL-terminated). For non-external buffers b is NUL-terminated at
   its new length. If you really need to chomp an external buffer,
   pass it to fsl_b_materialize() first.

   This is a no-op if b->errCode is non-0. (We don't strictly need to
   do so, but we do for consistency - b's state should not change when
   errCode is non-0.)
*/
FSL_EXPORT void fsl_b_chomp(fsl_b *  b);

/**
   Expects z to be a single argument intended for future call to
   system()-like function. It is quoted/escaped appropriately and
   appended to b, adding a space between any previous contents of
   b. It will fail, returning FSL_RC_SYNTAX, if the input contains
   what it believes to be malicious characters or if z contains any
   non-UTF-8 characters. It does not permit control characters of any
   kind, for example.

   If isFilename is true and z starts with a '-' character then the
   result gets prefixed with `./` (or `.\` on Windows) to (A)
   differentiate it from a flag argument and (B) avoid passing an
   unintended, but valid, flag to a command. isFilename has no further
   effect.

   The intent is that this function be called once per argument for a
   pending system()-style call, and b's contents eventually be used as
   the argument for that system()-style call.

   If b->errCode is non-0 when this is called, this function is a no-op
   and that value is returned.

   If err is not NULL then any validation-time error state are set in
   err and err->code is returned, It may fail for a number of reasons,
   as it performs checks on the input to avoid certain types of
   malicious uses. If initial validation of b->errCode and
   materialization of b (if needed) both pass, err is passed to
   fsl_error_reset() before this function starts its work.

   If err is NULL then this function still returns non-0 on error but
   the caller will not know exactl which validation failed.

   If this function returns FSL_RC_SYNTAX and err is not NULL, err
   will contain more info about the problem. If it returns any other
   error code, it's an allocation error and err will not have been
   updated.

   On error it always updates b->errCode so that subsequent calls
   will not mask the error.
*/
FSL_EXPORT int fsl_b_esc_arg_v2(fsl_b *  b,
                                     fsl_error *  err,
                                     char const *z,
                                     bool isFilename);
/**
   Equivalent to fsl_b_esc_arg_v2() with NULL as its second
   argument.
*/

FSL_EXPORT int fsl_b_esc_arg(fsl_b *  b,
                                  char const *z,
                                  bool isFilename);

/**
   Hex-encodes n bytes of src into n*2 hex-digit bytes appended to
   b. On error, b->errCode will be set to non-0 and that value is
   returned. If the final argument is true, upper-case hex digits are
   used, else lower-case are used.

   If fsl_b_err() is non-0 when this is called, this function has
   no side effects and that value is returned.
*/
FSL_EXPORT int fsl_b_append_hex( fsl_b *  b,
                                      void const * src, fsl_uint_t n,
                                      bool upperCase);


/**
   Compresses the first pIn->used bytes of pIn to pOut. It is ok for
   pIn and pOut to be the same blob.

   If fsl_b_err() is true for pIn buffer, its result is
   returned without further side effects. pOut's error state is ignored
   because it will be replaced.

   pOut must either be the same as pIn or else a properly
   initialized buffer. Any prior contents will be freed or their
   memory reused.

   Results are undefined if either argument is NULL.

   If is pIn!=pOut and pOut has enough memory to hold the compressed
   result then that memory is reused, but on error then pOut->errCode
   may (depending on the source of the error) be non-0 and the
   contents of pOut->mem are effectively undefined.

   Returns 0 on success, FSL_RC_OOM on allocation error (including
   one inside zlib), FSL_RC_RANGE if pIn->used is FSL_BLOB_MAX_SIZE
   or more, a size which fsl_b_uncompress() does not recognise as
   compressed, and FSL_RC_ERROR if the lower-level compression
   routines fail.

   Use fsl_b_uncompress() to uncompress the data. The data are
   encoded with a big-endian, unsigned 32-bit length as the first four
   bytes (holding its uncomressed size), and then the data as
   compressed by zlib.

   @see fsl_b_compress2()
   @see fsl_b_uncompress()
   @see fsl_b_is_compressed()
*/
FSL_EXPORT int fsl_b_compress(fsl_b const *pIn, fsl_b * pOut);

/**
   Compress the concatenation of a blobs pIn1 and pIn2 into pOut.

   pOut must be either empty (cleanly initialized or newly
   recycled) or must be the same as either pIn1 or pIn2.

   Results are undefined if any argument is NULL.

   If fsl_b_err() is true for any buffer, its result is
   returned without further side effects. The buffers are checked in
   the order of their parameter declaration.

   Returns 0 on success, FSL_RC_OOM on allocation error (including
   one inside zlib), FSL_RC_RANGE if the combined size is
   FSL_BLOB_MAX_SIZE or more, as for fsl_b_compress(), and
   FSL_RC_ERROR if the lower-level compression routines fail.

   TODO: if pOut!=(pIn1 or pIn2) then re-use its memory, if it has any.

   @see fsl_b_compress()
   @see fsl_b_uncompress()
   @see fsl_b_is_compressed()
*/
FSL_EXPORT int fsl_b_compress2(fsl_b const *pIn1,
                                    fsl_b const *pIn2,
                                    fsl_b *  pOut);

/**
   Uncompress buffer pIn and store the result in pOut. It is ok for
   pIn and pOut to be the same buffer. Returns 0 on success. If
   pIn!=pOut then on error, depending on the type of error, pOut may
   have been partially written so the state of its contents are
   unspecified (but its state as a buffer object is still valid).

   If fsl_b_err() is true for either buffer, its result is
   returned without further side effects. The buffers are checked in
   the order of their parameter declaration.

   pOut must be either cleanly initialized/empty or the same object as
   pIn. If it has any current memory, it will be reused if it's
   large enough and it is not the same pointer as pIn.

   Results are undefined if any argument is NULL.

   Returns 0 on success, FSL_RC_OOM on allocation error (including
   one inside zlib), FSL_RC_CONSISTENCY if pIn's zlib stream is
   corrupt, truncated, or decodes to more bytes than its 4-byte size
   prefix records, and FSL_RC_ERROR for any other failure of the
   lower-level decompression routines. On error, pOut->errCode is
   updated.

   Note that the decompression process, though computationally costly,
   is a no-op if pIn is not actually compressed.

   As a special case, if pIn==pOut and fsl_b_is_compressed() returns
   false for pIn then this is a no-op.

   @see fsl_b_compress()
   @see fsl_b_compress2()
   @see fsl_b_is_compressed()
*/
FSL_EXPORT int fsl_b_uncompress(fsl_b const * pIn,
                                     fsl_b *  pOut);

/**
   Returns true if this function believes that mem (which must be
   at least len bytes of valid memory long) appears to have been
   compressed by fsl_b_compress() or equivalent. This is not a
   100% reliable check - it could potentially have false positives
   on certain inputs, but that is thought to be unlikely (at least
   for text data).

   Returns 0 if mem is NULL.

   As of 2026-10-15, it is this developer's hope to eliminate all use
   of this in the library. A single false-positive is all it takes to
   break a repo rebuild.
*/
FSL_EXPORT bool fsl_data_is_compressed(unsigned char const * mem, fsl_size_t len);

/**
   Equivalent to fsl_data_is_compressed(buf->mem, buf->used).
*/
FSL_EXPORT bool fsl_b_is_compressed(fsl_b const * buf);

/**
   If fsl_data_is_compressed(mem,len) returns true then this function
   returns the uncompressed size of the data, else it returns a negative
   value.
*/
FSL_EXPORT fsl_int_t fsl_data_uncompressed_size(unsigned char const *mem, fsl_size_t len);

/**
   The fsl_b counterpart of fsl_data_uncompressed_size().
*/
FSL_EXPORT fsl_int_t fsl_b_uncompressed_size(fsl_b const * b);

/**
   Equivalent to ((char const *)b->mem) except that if b->errCode is
   non-0, this returns NULL. The returned string is effectively
   b->used bytes long unless the user decides to apply his own
   conventions. Note that the buffer APIs generally assure that
   buffers are NUL-terminated, meaning that strings returned from this
   function can (for the vast majority of cases) assume that the
   returned string is NUL-terminated (with a string length of b->used
   _bytes_). It is, however, possible for client code to violate that
   convention via direct manipulation of the buffer or using
   non-NUL-terminated extranal buffers.

   Results are undefined if b is NULL.

   @see fsl_b_str()
   @see fsl_b_cstr2()
*/
FSL_EXPORT char const * fsl_b_cstr(fsl_b const * b);

/**
   If b has any memory allocated to it and b->errCode is non-0, that
   memory is returned. If len is not NULL then *len is set to
   b->used. If b has no memory or b->errCode is non-0 then NULL is
   returned and *len (if len is not NULL) is set to 0.

   Results are undefined if b is NULL.

   @see fsl_b_str()
   @see fsl_b_cstr()
*/
FSL_EXPORT char const * fsl_b_cstr2(fsl_b const * b, fsl_size_t *  len);

/**
   Equivalent to ((char *)b->mem) except that if b->errCode is non-0
   then NULL is returned. The returned memory is effectively b->used
   bytes long unless the user decides to apply their own conventions.

   Care must be taken to only write to the returned pointer for memory
   owned or write-proxied by this buffer. More specifically, results
   are undefined if b is an external buffer proxying const bytes. When
   in doubt about whether b is external, use fsl_b_materialize()
   to transform it to a managed buffer before using this routine,
   noting that any of the public fsl_b APIs which write to a
   buffer will materialize it on demand if needed.

   @see fsl_b_take()
*/
FSL_EXPORT char * fsl_b_str(fsl_b const * b);

/**
   "Takes" the memory refered to by the given buffer, transfering
   ownership to the caller. After calling this, b's state will be
   empty. If b is an external buffer, this will materialize it
   first and return NULL if that fails.

   @see fsl_b_materialize()
   @see fsl_b_str()
   @see fsl_b_cstr()
   @see fsl_b_cstr2()
*/
FSL_EXPORT char * fsl_b_take(fsl_b *  b);

/**
   Returns the "used" size of b, or 0 if !b.
*/
#define fsl_b_size(b) (b)->used
#if 0
FSL_EXPORT fsl_size_t fsl_b_size(fsl_b const * b);
#endif

/**
   Returns the current capacity of b, or 0 if !b.
*/
#define fsl_b_capacity(b) (b)->capacity
#if 0
FSL_EXPORT fsl_size_t fsl_b_capacity(fsl_b const * b);
#endif
/**
   Compares the contents of buffers lhs and rhs using memcmp(3)
   semantics. Returns negative, zero, or positive if the first buffer
   is less then, equal to, or greater than the second.  Results are
   undefined if either argument is NULL.

   When buffers of different length match on the first N bytes,
   where N is the shorter of the two buffers' lengths, it treats the
   shorter buffer as being "less than" the longer one.
*/
FSL_EXPORT int fsl_b_compare(fsl_b const * lhs,
                                  fsl_b const * rhs);

/**
   Compares b and the first nStr bytes of the given string. If nStr is
   negative, fsl_strlen() is used to calculate it. Returns true if the
   buffer and the string match, as per the rules of
   fsl_b_compare(), else returns false.
*/
FSL_EXPORT bool fsl_b_eq(fsl_b const * b, char const * str,
                              fsl_int_t nStr);

/**
   Bitwise-compares the contents of b against the file named by
   zFile.  Returns 0 if they have the same size and contents, else
   non-zero.  This function has no way to report if zFile cannot be
   opened, and any error results in a non-0 return value. No
   interpretation/canonicalization of zFile is performed - it is
   used as-is.

   This resolves symlinks and returns non-0 if zFile refers (after
   symlink resolution) to a non-file.

   If zFile does not exist, is not readable, or has a different
   size than b->used, non-0 is returned without opening/reading the
   file contents. If a content comparison is performed, it is
   streamed in chunks of an unspecified (but relatively small)
   size, so it does not need to read the whole file into memory
   (unless it is smaller than the chunk size).
*/
FSL_EXPORT int fsl_b_compare_file( fsl_b const * b, char const * zFile );

/**
   Compare two buffers in constant (a.k.a. O(1)) time and return
   zero if they are equal.  Constant time comparison only applies
   for buffers of the same length.  If lengths are different,
   immediately returns 1. This operation is provided for cases
   where the timing/duration of fsl_b_compare() (or an
   equivalent memcmp()) might inadvertently leak security-relevant
   information.  Specifically, it address the concern that
   attackers can use timing differences to check for password
   misses, to narrow down an attack to passwords of a specific
   length or content properties.
*/
FSL_EXPORT int fsl_b_compare_O1(fsl_b const * lhs, fsl_b const * rhs);

/**
   Overwrites dest's contents with a copy of those from src
   (reusing dest's memory if it has any). Results are undefined if
   either pointer is NULL or invalid. Returns 0 on success,
   FSL_RC_OOM on allocation error.
*/
FSL_EXPORT int fsl_b_copy( fsl_b *  dest,
                                fsl_b const * src );

/**
   Apply the delta in pDelta to the original content pOriginal to
   generate the target content pTarget. All three pointers must point
   to properly initialized memory.

   If pTarget==pOriginal then this is a destructive operation,
   replacing the original's content with its new form.

   If fsl_b_err() is true for any buffer, its result is
   returned without further side effects. The buffers are checked in
   the order of their parameter declaration.

   Return 0 on success, FSL_RC_OOM on allocation error, or one of the
   codes fsl_delta_applied_size() and fsl_delta_apply() return for a
   malformed delta or one which does not belong to pOriginal, such
   as FSL_RC_DELTA_INVALID_TERMINATOR or FSL_RC_CHECKSUM_MISMATCH.
   Use fsl_b_delta_apply2() to get a description of a delta error.

   @see fsl_b_delta_apply()
   @see fsl_delta_apply()
   @see fsl_delta_apply2()
*/
FSL_EXPORT int fsl_b_delta_apply( fsl_b const * pOriginal,
                                       fsl_b const * pDelta,
                                       fsl_b *  pTarget);

/**
   Identical to fsl_b_delta_apply() except that if delta
   application fails then any error messages/codes are written to
   pErr if it is not NULL. It is rare that delta application fails
   (only if the inputs are invalid, e.g. do not belong together or
   are corrupt), but when it does, having error information can be
   useful.

   If fsl_b_err() is true for any buffer, its result is
   returned without further side effects. The buffers are checked in
   the order of their parameter declaration.

   @see fsl_b_delta_apply()
   @see fsl_delta_apply()
   @see fsl_delta_apply2()
*/
FSL_EXPORT int fsl_b_delta_apply2( fsl_b const * pOriginal,
                                        fsl_b const * pDelta,
                                        fsl_b *  pTarget,
                                        fsl_error *  pErr);


/**
   Uses a fsl_input_f() function to buffer input into a fsl_b.

   dest must be a non-NULL, initialized (though possibly empty)
   fsl_b object. Its contents, if any, will be overwritten by
   this function, and any memory it holds might be re-used.

   If fsl_b_err() is true then this function returns its value
   without other side effects.

   The src function is called, and passed the state parameter, to
   fetch the input. If it returns non-0, this function returns that
   error code. src() is called, possibly repeatedly, until it
   reports that there is no more data.

   Whether or not this function succeeds, dest still owns any memory
   pointed to by dest->mem, and the client must eventually free it
   by calling fsl_b_reserve(dest,0).

   dest->mem might (and possibly will) be (re)allocated by this
   function, so any pointers to it held from before this call might
   be invalidated by this call.

   On error non-0 is returned and dest may be partially populated.

   Errors include:

   - Allocation error (FSL_RC_OOM), in which case dest->errCode is
     updated.

   - src() returns an error code, in which case dest->errCode is _not_
     modified.

   - The total input size overflows fsl_size_t (FSL_RC_RANGE), in
     which case dest->errCode is _not_ modified.

   Whether or not the state parameter may be NULL depends on the src
   implementation requirements.

   On success dest will contain the contents read from the input
   source. dest->used will be the length of the read-in data, and
   dest->mem will point to the memory. dest->mem is automatically
   NUL-terminated if this function succeeds, but dest->used does not
   count that terminator. On error the state of dest->mem must be
   considered incomplete, and is not guaranteed to be NUL-terminated.

   Example usage:

   ```
   fsl_b buf = fsl_b_empty;
   int rc = fsl_b_fill_from( &buf,
     fsl_input_f_FILE,
      stdin );
   if( rc ){
   fprintf(stderr,"Error %d (%s) while filling buffer.\n",
   rc, fsl_rc_cstr(rc));
   fsl_b_reserve( &buf, 0 );
     return ...;
   }
   ... use the buf->mem ...
   ... clean up the buffer ...
   fsl_b_reserve( &buf, 0 );
   ```

   To take over ownership of the buffer's memory, do:

   ```
   void * mem = buf.mem;
   buf = fsl_b_empty;
   ```

   In which case the memory must eventually be passed to fsl_free()
   to free it.
*/
FSL_EXPORT int fsl_b_fill_from( fsl_b *  dest,
                                fsl_input_f src, void *  state );

/**
   A fsl_b_fill_from() proxy which overwrite's dest->mem with
   the contents of the given FILE handler (which must be opened for
   read access).  Returns 0 on success, after which dest->mem
   contains dest->used bytes of content from the input source. On
   error dest may be partially filled.
*/
FSL_EXPORT int fsl_b_fill_from_FILE( fsl_b *  dest,
                                     FILE *  src );

/**
   A wrapper for fsl_b_fill_from_FILE() which gets its input
   from the given file name.

   If fsl_b_err() is true then this function returns its value
   without other side effects.

   It uses fsl_fopen() to open the file, so it supports the name '-'
   as an alias for stdin.

   Returns 0 on success and FSL_RC_OOM on allocation error. If the
   file cannot be opened it returns fsl_errno_to_rc() of the
   resulting errno, with FSL_RC_IO as the default, so a missing file
   gives FSL_RC_NOT_FOUND and a permissions failure FSL_RC_ACCESS. A
   read error, including reading a directory, gives FSL_RC_IO. This
   function has no error object, so callers which report the failure
   must name the file themselves.
*/
FSL_EXPORT int fsl_b_fill_from_filename( fsl_b *  dest,
                                         char const * filename );

/**
   Writes the given buffer to the given filename. Returns 0 on success,
   FSL_RC_MISUSE if !b or !fname. If opening, writing, flushing, or
   closing the file fails, it returns fsl_errno_to_rc() of the resulting errno,
   with FSL_RC_IO as the default (so a missing directory gives
   FSL_RC_NOT_FOUND, a permissions failure FSL_RC_ACCESS, and a full
   disk FSL_RC_IO). This function has no error object, so callers
   which report the failure must name the file themselves.

   If fsl_b_err() is true, that result is returned with no other
   side effects.

   Uses fsl_fopen() to open the file, so it supports the name '-'
   as an alias for stdout.
*/
FSL_EXPORT int fsl_b_to_filename( fsl_b const * b,
                                  char const * fname );

/**
   Copy N lines of text from pFrom into pTo. The copy begins at the
   current pFrom->cursor position. On success, pFrom->cursor is left
   pointing at the first character past the last `\n` copied.
   (Modification of the cursor is why pFrom is not const.) The copy is
   made in a single go, not line-by-line.

   If fsl_b_err() is true for either buffer (checked in parameter
   order), that result is returned with no other side effects.

   If pTo==NULL then this routine simply skips over N lines.

   Returns 0 if it copies lines or does nothing (because N is 0 or
   pFrom's contents have been exhausted). Copying fewer lines than
   requested (because of EOF) is not an error. Returns non-0 only on
   allocation error. Results are undefined if pFrom is NULL or not
   properly initialized. Whether or not it copies anything can be
   checked by copying pTo->used before calling this and comparing
   pTo->used to that value afterwards. The difference is the number of
   bytes added.

   @see fsl_b_stream_lines()
*/
FSL_EXPORT int fsl_b_copy_lines(fsl_b *  pTo,
                                     fsl_b *  pFrom,
                                     fsl_size_t N);

/**
   Works identically to fsl_b_copy_lines() except that it sends
   its output to the fTo output function. If fTo is NULL then it
   simply skips over N lines. The callback is called a single time,
   not once per line.

   If fsl_b_err() is true, that result is returned with no other
   side effects.

   @see fsl_b_copy_lines()
*/
FSL_EXPORT int fsl_b_stream_lines(fsl_output_f fTo, void *  toState,
                                       fsl_b *  pFrom,
                                       fsl_size_t N);


/**
   Works like fsl_appendfv(), but appends all output to a
   dynamically-allocated string, expanding the string as necessary
   to collect all formatted data. The returned NUL-terminated string
   is owned by the caller and it must be cleaned up using
   fsl_free(...). If !fmt, NULL is returned. It is conceivable that
   it returns NULL on a zero-length formatted string, e.g.  (%.*s)
   with (0,"...") as arguments, but it will only do that if the
   whole format string resolves to empty.

   It also returns NULL on any error fsl_appendfv() reports, which
   is FSL_RC_OOM in practice but is FSL_RC_RANGE for an unsupported
   conversion character or an over-long argument. The result code
   is not available to the caller; use fsl_b_appendf() where it
   matters.
*/
FSL_EXPORT char * fsl_mprintf( char const * fmt, ... );

/**
   va_list counterpart to fsl_mprintf().
*/
FSL_EXPORT char * fsl_mprintfv(char const * fmt, va_list vargs );

/**
   An sprintf(3) clone which uses fsl_appendf() for the formatting.
   Outputs at most n bytes to dest. Returns 0 on success, non-0
   on error. Returns 0 without side-effects if !n. If !*fmt it sets
   dest to an empty string and returns 0. Returns FSL_RC_MISUSE if
   !dest or !fmt, else a formatting error as documented for
   fsl_appendfv(). Truncating the output to n bytes is not an
   error.

   If the destination buffer is long enough, this function
   NUL-terminates it.
*/
FSL_EXPORT int fsl_snprintf( char * dest, fsl_size_t n, char const * fmt, ... );

/**
   va_list counterpart to fsl_snprintf()
*/
FSL_EXPORT int fsl_snprintfv( char * dest, fsl_size_t n, char const * fmt, va_list args );

/**
   Equivalent to fsl_strndup(src,-1).
*/
FSL_EXPORT char * fsl_strdup( char const * src );

/**
   Similar to strndup(3) but returns NULL if !src.  The returned
   memory must eventually be passed to fsl_free(). Returns NULL on
   allocation error. If len is less than 0 and src is not NULL then
   fsl_strlen() is used to calculate its length.

   If src is not NULL but len is 0 then it will return an empty
   (length-0) string, as opposed to NULL.
*/
FSL_EXPORT char * fsl_strndup( char const * src, fsl_int_t len );

/**
   Equivalent to strlen(3) but returns 0 if src is NULL.  It counts
   bytes, not UTF characters.
*/
FSL_EXPORT fsl_size_t fsl_strlen( char const * src );

/**
   Convenience helper for use with fsl_strlen_t-type string semantics.
*/
static inline fsl_size_t fsl_nstrlen(char const * z, fsl_strlen_t n){
  return n<0 ? fsl_strlen(z) : (fsl_size_t)n;
}

/**
   Returns the number of UTF8 characters which begin within the first
   n bytes of str (noting that it's possible that a multi-byte
   character starts 1-3 bytes away from the end and overlaps past the
   end of (str+len)). If len is negative then fsl_strlen() is used to
   calculate it.

   Results are undefined if str is not UTF8 input or if str contains a
   BOM marker.
*/
FSL_EXPORT fsl_size_t fsl_strlen_utf8( char const * str, fsl_strlen_t n );

/**
   Like strcmp(3) except that it accepts NULL pointers.  NULL sorts
   before all non-NULL string pointers.  Also, this routine
   performs a binary comparison that does not consider locale.
*/
FSL_EXPORT int fsl_strcmp( char const * lhs, char const * rhs );

/**
   Equivalent to fsl_strcmp(), but with a signature suitable
   for use as a generic comparison function (e.g. for use with
   qsort() and search algorithms).
*/
FSL_EXPORT int fsl_strcmp_cmp( void const * lhs, void const * rhs );

/**
   Case-insensitive form of fsl_strcmp().

   @implements fsl_generic_cmp_f()
*/
FSL_EXPORT int fsl_stricmp(const char *zA, const char *zB);

/**
   Equivalent to fsl_stricmp(), but with a signature suitable
   for use as a generic comparison function (e.g. for use with
   qsort() and search algorithms).

   @implements fsl_generic_cmp_f()
*/
FSL_EXPORT int fsl_stricmp_cmp( void const * lhs, void const * rhs );

/**
   fsl_strcmp() variant which compares at most nByte bytes of the
   given strings, case-insensitively.  If nByte is less than 0 then
   fsl_strlen(zB) is used to obtain the length for comparision
   purposes.
*/
FSL_EXPORT int fsl_strnicmp(const char *zA, const char *zB, fsl_int_t nByte);

/**
   fsl_strcmp() variant which compares at most nByte bytes of the
   given strings, case-sensitively. Returns 0 if nByte is 0.
*/
FSL_EXPORT int fsl_strncmp(const char *zA, const char *zB, fsl_size_t nByte);

/**
   BSD strlcpy() variant which is less error prone than strncpy. Copy up to
   dstsz - 1 characters from src to dst and NUL-terminate the resulting string
   if dstsz is not 0.

   Returns the length of the string it writes to dst. If it returns a value
   equal to or greater than its 3rd argument then the output was truncated.
*/
FSL_EXPORT fsl_size_t fsl_strlcpy(char *dst, const char *src, fsl_size_t dstsz);

/**
   BSD strlcat() variant which is less error prone than strncat. Append src to
   the end of dst. Append at most dstsz - strlen(dst - 1) characters, and
   NUL-terminate unless dstsize is 0 or the passed in dst string was longer
   than dstsz to begin with.

   Returns the initial string-length of dest plus the length src. If
   it returns a value equal to or greater than its 3rd argument then
   the output was truncated.
*/
FSL_EXPORT fsl_size_t fsl_strlcat(char *dst, const char *src, fsl_size_t dstsz);

/**
   Equivalent to fsl_strncmp(lhs, rhs, X), where X is either
   FSL_STRLEN_SHA1 or FSL_STRLEN_K256: if both lhs and rhs are
   longer than FSL_STRLEN_SHA1 then they are assumed to be
   FSL_STRLEN_K256 bytes long and are compared as such, else they
   are assumed to be FSL_STRLEN_SHA1 bytes long and compared as
   such.

   Potential FIXME/TODO: if their lengths differ, i.e. one is v1 and
   one is v2, compare them up to their common length then, if they
   still compare equivalent, treat the shorter one as less-than the
   longer.
*/
FSL_EXPORT int fsl_uuidcmp( fsl_uuid_cstr lhs, fsl_uuid_cstr rhs );

/**
   Returns false if s is NULL or starts with any of (0 (NUL), '0'
   (ASCII character zero), 'f', 'n', "off"), case-insensitively,
   else it returns true.
*/
FSL_EXPORT bool fsl_str_bool( char const * s );

/**
   _Almost_ equivalent to fopen(3) but:

   - expects name to be UTF8-encoded.

   - If name=="-", it returns one of stdin or stdout, depending on
   the mode string: stdout is returned if 'w' or '+' appear,
   otherwise stdin.

   If it returns NULL, the global errno "should" contain a description
   of the problem unless the problem was argument validation. Pass it
   to fsl_errno_to_rc() to convert that into an API-conventional error
   code.

   If at all possible, use fsl_fclose() (as opposed to fclose()) to
   close these handles, as it has logic to skip closing the
   standard streams.

   Potential TODOs:

   - extend mode string to support 'x', meaning "exclusive", analog
   to open(2)'s O_EXCL flag. Barring race conditions, we have
   enough infrastructure to implement that. (It turns out that
   glibc's fopen() supports an 'x' with exactly this meaning.)

   - extend mode to support a 't', meaning "temporary". The idea
   would be that we delete the file from the FS right after
   opening, except that Windows can't do that.
*/
FSL_EXPORT FILE * fsl_fopen(char const * name, char const *mode);

/**
   Passes f to fclose(3) unless f is NULL or one of the C-standard
   (stdin, stdout, stderr) handles, in which cases it does nothing
   at all.
*/
FSL_EXPORT void fsl_fclose(FILE * f);

/**
   This function works similarly to classical printf
   implementations, but instead of outputing somewhere specific, it
   uses a callback function to push its output somewhere. This
   allows it to be used for arbitrary external representations. It
   can be used, for example, to output to an external string, a UI
   widget, or file handle (it can also emulate printf by outputing
   to stdout this way).

   INPUTS:

   pfAppend: The is a fsl_output_f function which is responsible
   for accumulating the output. If pfAppend returns a negative
   value then processing stops immediately.

   pfAppendArg: is ignored by this function but passed as the first
   argument to pfAppend. pfAppend will presumably use it as a data
   store for accumulating its string.

   fmt: This is the format string, as in the usual printf(3), except
   that it supports more options (detailed below).

   ap: This is a pointer to a list of arguments.  Same as in
   vprintf() and friends.


   OUTPUTS:

   ACHTUNG: this interface changed significantly in 2021-09:

   - The output function was changed from a type specific to this
   interface to fsl_output_f().

   - The return semantics where changed from printf()-like to
   0 on success, non-0 on error.

   Most printf-style specifiers work as they do in standard printf()
   implementations. There might be some very minor differences, but
   the more common format specifiers work as most developers expect
   them to. In addition...

   Current (documented) printf extensions:

   `%s` works like conventional printf `%s` except that any precision
   value can be modified via the '#' flag to count in UTF8 characters
   instead of bytes. That is, if an `%#.10s` argument has a byte
   length of 20, a precision of 10, and contains only 8 UTF8, its
   precision will allow it to output all 8 characters, even though
   they total 20 bytes. The '#' flag works this way for both width and
   precision.

   `%z` works exactly like `%s`, but takes a non-const (char *) and
   deletes the string (using fsl_free()) after appending it to the
   output.

   `%h` (HTML) works like `%s` but (A) does not support the '#' flag and
   (B) converts certain characters (namely '<' and '&') to their HTML
   escaped equivalents.

   `%t` (URL encode) works like `%h` but converts certain characters
   into a representation suitable for use in an HTTP URL. (e.g. ' '
   gets converted to `%20`)

   `%T` (URL decode) does the opposite of `%t` - it decodes
   URL-encoded strings and outputs their decoded form. ACHTUNG:
   fossil(1) interprets this the same as `%t` except that it leaves
   '/' characters unescaped (did that change at some point? This code
   originally derived from that one some years ago!). It is still to
   be determined whether we "really need" that behaviour (we don't
   really need either one, seeing as the library is not CGI-centric
   like fossil(1) is).

   `%r` requires an int and renders it in "ordinal form". That is,
   the number 1 converts to "1st" and 398 converts to "398th".

   `%q` quotes a string as required for SQL. That is, '\''
   characters get doubled. It does NOT included the outer quotes
   and NULL values get replaced by the string "(NULL)" (without
   quotes). See `%Q`...

   `%Q` works like `%q`, but includes the outer '\'' characters and
   NULL pointers get output as the string literal "NULL" (without
   quotes), i.e. an SQL NULL. If modified with `%!Q` then it instead
   uses double quotes, the intent being for use with identifiers.
   In that form it still emits `NULL` without quotes, but it is not
   intended to be used with `NULL` values.

   `%S` works like `%.16s`. It is intended for fossil hashes. The '!'
   modifier removes the length limit, resulting in the whole hash
   (making this formatting option equivalent to `%s`).  (Sidebar: in
   fossil(1) this length is runtime configurable but that requires
   storing that option in global state, which is not an option for
   this implementation.)

   `%/`: works mostly like `%s` but normalizes path-like strings by
   replacing backslashes with the One True Slash.

   `%b`: works like `%s` but takes its input from a (fsl_b
   const*) argument. It does not support the '#' flag.

   `%B`: works like `%Q` but takes its input from a (fsl_b
   const*) argument.

   `%F`: works like `%s` but runs the output through
   fsl_bytes_fossilize().  This requires dynamic memory allocation, so
   is less efficient than re-using a client-provided buffer with
   fsl_bytes_fossilize() if the client needs to fossilize more than
   one element. Does not support the '#' flag.

   `%j`: works like `%s` but JSON-encodes the string. It does not
   include the outer quotation marks by default, but using the '!'
   flag, i.e. `%!j`, causes those to be added. The length and precision
   flags are NOT supported for this format. Results are undefined if
   given input which is not legal UTF8. By default non-ASCII
   characters with values less than 0xffff are emitted as as literal
   characters (no escaping), but the '#' modifier flag will cause it
   to emit such characters in the `\u####` form. It always encodes
   characters above 0xFFFF as UTF16 surrogate pairs (as JSON
   requires). Invalid UTF8 characters may get converted to '?' or may
   produce invalid JSON output. As a special case, if the value is NULL
   pointer, it resolves to "null" without quotes (regardless of the '!'
   modifier).

   `%R`: requires an integer argument and renders it like fsl_rc_cstr()
   would. If that function result is NULL then "#n" is used, where n
   is the integer argument.

   Some of these extensions may be disabled by setting certain macros
   when compiling appendf.c (see that file for details).

   Returns 0 on success. On error it stops, having emitted any output
   up to that point, and returns:

   - FSL_RC_RANGE if fmt contains a conversion character this
     function does not support, or if a string or buffer argument is
     longer than INT_MAX bytes.

   - FSL_RC_OOM if `%F` or a long `%/` argument cannot allocate its
     working memory.

   - FSL_RC_MISUSE if a `%F` argument is NULL.

   - The first non-0 value returned by pfAppend(), unchanged.

   This function has no error object, so it sets no error message.

   Potential TODO: add fsl_bytes_fossilize_out() which works like
   fsl_bytes_fossilize() but sends its output to an fsl_output_f(), so
   that this routine doesn't need to alloc for that case.
*/
FSL_EXPORT int fsl_appendfv(fsl_output_f pfAppend, void * pfAppendArg,
                            const char *fmt, va_list ap );

/**
   Identical to fsl_appendfv() but takes an ellipses list (...)
   instead of a va_list.
*/
FSL_EXPORT int fsl_appendf(fsl_output_f pfAppend,
                           void * pfAppendArg,
                           const char *fmt,
                           ... )
#if 0
/* Would be nice, but complains about our custom format options: */
  __attribute__ ((__format__ (__printf__, 3, 4)))
#endif
  ;

/**
   Works like fsl_appendf() except that it sends the first n bytes of
   str as-is to pfAppend(). If n is negative, fsl_strlen() is used to
   calculate its lenght.
*/
FSL_EXPORT int fsl_appendn(fsl_output_f pfAppend, void * pfAppendArg,
                           const char *str, fsl_int_t n);


/**
   A fsl_output_f() impl which requires that state be an opened,
   writable (FILE*) handle.
*/
FSL_EXPORT int fsl_output_f_FILE( void * state, void const * s,
                                  fsl_size_t n );


/**
   Emulates fprintf() using fsl_appendf(). Returns the result of
   passing the data through fsl_appendf() to the given file handle:
   0 on success, FSL_RC_IO if writing fails, or a formatting error
   as documented for fsl_appendfv(). Returns FSL_RC_MISUSE if !fp or
   !fmt.
*/
FSL_EXPORT int fsl_fprintf( FILE * fp, char const * fmt, ... );

/**
   The va_list counterpart of fsl_fprintf().
*/
FSL_EXPORT int fsl_fprintfv( FILE * fp, char const * fmt, va_list args );


/**
   Possibly reallocates self->list, changing its size. This function
   ensures that self->list has at least n entries. If n is 0 then
   the list is deallocated (but the self object is not), BUT THIS
   DOES NOT DO ANY TYPE-SPECIFIC CLEANUP of the items. If n is less
   than or equal to self->capacity then there are no side effects. If
   n is greater than self->capacity, self->list is reallocated and
   self->capacity is adjusted to be at least n (it might be bigger -
   this function may pre-allocate a larger value).

   Passing an n of 0 when self->capacity is 0 is a no-op.

   Newly-allocated slots will be initialized with NULL pointers.

   Returns 0 on success, FSL_RC_MISUSE if !self, FSL_RC_OOM if
   reservation of new elements fails.

   The return value should be used like this:

   ```
   fsl_size_t const n = number of bytes to allocate;
   int const rc = fsl_list_reserve( myList, n );
   if( rc ) { ... error ... }
   ```

   @see fsl_list_clear()
   @see fsl_list_visit_free()
*/
FSL_EXPORT int fsl_list_reserve( fsl_list *  self, fsl_size_t n );

/**
   Appends a bitwise copy of cp to self->list, expanding the list as
   necessary and adjusting self->used.

   Returns 0 on success, FSL_RC_OOM on allocation error, FSL_RC_MISUSE
   if !self.

   Ownership of cp is unchanged by this call. cp may not be NULL.
*/
FSL_EXPORT int fsl_list_append( fsl_list *  self, void * cp );

/**
   Swaps all contents of both lhs and rhs. Results are undefined if
   lhs or rhs are NULL or not properly initialized (via initial copy
   initialization from fsl_list_empty resp. fsl_list_empty_m).
*/
FSL_EXPORT void fsl_list_swap( fsl_list *  lhs, fsl_list *  rhs );

/** @typedef typedef int (*fsl_list_visitor_f)(void * p, void * visitorState )

    Generic visitor interface for fsl_list lists.  Used by
    fsl_list_visit(). p is the pointer held by that list entry and
    visitorState is the 4th argument passed to fsl_list_visit().

    Implementations must return 0 on success. Any other value causes
    looping to stop and that value to be returned, but interpretation
    of the value is up to the caller (it might or might not be an
    error, depending on the context). Note that client code may use
    custom values, and is not strictly required to use FSL_RC_xxx
    values. HOWEVER...  all of the libfossil APIs which take these
    as arguments may respond differently to some codes (most notable
    FSL_RC_BREAK, which they tend to treat as a
    stop-iteration-without-error result), so clients are strongly
    encourage to return an FSL_RC_xxx value on error.
*/
typedef int (*fsl_list_visitor_f)(void * obj, void * visitorState );

/**
   A fsl_list_visitor_f() implementation which requires that obj be
   arbitrary memory which can legally be passed to fsl_free()
   (which this function does). The visitorState parameter is
   ignored.
*/
FSL_EXPORT int fsl_list_v_fsl_free(void * obj, void * visitorState );


/**
   For each item in self->list, visitor(item,visitorState) is
   called.  The item is owned by self. The visitor function MUST
   NOT free the item (unless the visitor is a finalizer!), but may
   manipulate its contents if application rules do not specify
   otherwise.

   If order is 0 or greater then the list is traversed from start
   to finish, else it is traverse from end to begin.

   Returns 0 on success, non-0 on error.

   If visitor() returns non-0 then looping stops and that code is
   returned.
*/
FSL_EXPORT int fsl_list_visit( fsl_list const * self, int order,
                               fsl_list_visitor_f visitor, void * visitorState );

/**
   A list clean-up routine which takes a callback to clean up its
   contents.

   Passes each element in the given list to
   childFinalizer(item,finalizerState). If that returns non-0,
   processing stops and that value is returned, otherwise
   fsl_list_reserve(list,0) is called and 0 is returned.

   WARNING: if cleanup fails because childFinalizer() returns non-0,
   the returned object is effectively left in an undefined state and
   the client has no way (unless the finalizer somehow accounts for it)
   to know which entries in the list were cleaned up. Thus it is highly
   recommended that finalizer functions follow the conventional wisdom
   of "destructors do not throw."

   @see fsl_list_visit_free()
*/
FSL_EXPORT int fsl_list_clear( fsl_list *  list,
                               fsl_list_visitor_f childFinalizer,
                               void * finalizerState );
/**
   Similar to fsl_list_clear(list, fsl_list_v_fsl_free, NULL), but
   only frees list->list if the second argument is true, otherwise
   it sets the list's length to 0 but keep the list->list memory
   intact for later use.

   Be sure only to use this on lists of types for which fsl_free()
   is legal. i.e. don't use it on a list of fsl_deck objects or
   other types which have their own finalizers.

   Results are undefined if list is NULL.

   @see fsl_list_clear()
*/
FSL_EXPORT void fsl_list_visit_free( fsl_list *  list, bool freeListMem );

/**
   Works similarly to the visit operation without the _p suffix
   except that the pointer the visitor function gets is a (**)
   pointing back to the entry within this list. That means that
   callers can assign the entry in the list to another value during
   the traversal process (e.g. set it to 0). If shiftIfNulled is
   true then if the callback sets the list's value to 0 then it is
   removed from the list and self->used is adjusted (self->capacity
   is not changed).
*/
FSL_EXPORT int fsl_list_visit_p( fsl_list *  self, int order,
                                 bool shiftIfNulled,
                                 fsl_list_visitor_f visitor, void * visitorState );


/**
   Sorts the given list using the given comparison function. Neither
   argument may be NULL. The arugments passed to the comparison function
   will be pointers to pointers to the original entries, and may (depending
   on how the list is used) point to NULL.
*/
FSL_EXPORT void fsl_list_sort( fsl_list *  li, fsl_generic_cmp_f cmp);

/**
   Searches for a value in the given list, using the given
   comparison function to determine equivalence. The comparison
   function will never be passed a NULL value by this function - if
   value is NULL then only a NULL entry will compare equal to it.
   Results are undefined if li or cmpf are NULL.

   Returns the index in li of the entry, or a negative value if no
   match is found.
*/
FSL_EXPORT fsl_int_t fsl_list_index_of( fsl_list const * li,
                                        void const * value,
                                        fsl_generic_cmp_f cmpf);

/**
   Equivalent to fsl_list_index_of(li, key, fsl_strcmp_cmp).
*/
FSL_EXPORT fsl_int_t fsl_list_index_of_cstr( fsl_list const * li,
                                             char const * key );


/**
   Returns 0 if the given file is readable. Flags may be any values
   accepted by the access(2) resp. _waccess() system calls.
*/
FSL_EXPORT int fsl_file_access(const char *zFilename, int flags);

/**
   Computes a canonical pathname for a file or directory. Makes the
   name absolute if it is relative. Removes redundant / characters.
   Removes all /./ path elements. Converts /A/../ to just /. If the
   slash parameter is non-zero, the trailing slash, if any, is
   retained.

   If zRoot is not NULL then it is used for transforming a relative
   zOrigName into an absolute path. If zRoot is NULL fsl_getcwd()
   is used to determine the virtual root directory. If zRoot is
   empty (starts with a NUL byte) then this function effectively
   just sends zOrigName through fsl_file_simplify_name().

   Returns 0 on success, FSL_RC_MISUSE if !zOrigName or !pOut,
   FSL_RC_OOM if an allocation fails.

   pOut, if not NULL, is _appended_ to, so be sure to set pOut->used=0
   (or pass it to fsl_b_reuse()) before calling this to start
   writing at the beginning of a re-used buffer. On error pOut might
   conceivably be partially populated, but that is highly
   unlikely. Nonetheless, be sure to fsl_b_clear() it at some
   point regardless of success or failure.

   This function does no actual filesystem-level processing unless
   zRoot is NULL or empty (and then only to get the current
   directory). This does not confirm whether the resulting file
   exists, nor that it is strictly a valid filename for the current
   filesystem. It simply transforms a potentially relative path
   into an absolute one.

   Example:

   ```
   int rc;
   char const * zRoot = "/a/b/c";
   char const * zName = "../foo.bar";
   fsl_b buf = fsl_b_empty;
   rc = fsl_file_canonical_name2(zRoot, zName, &buf, 0);
   if(rc){
     fsl_b_clear(&buf);
     return rc;
   }
   assert(0 == fsl_strcmp( "/a/b/foo.bar, fsl_b_cstr(&buf)));
   fsl_b_clear(&buf);
   ```
*/
FSL_EXPORT int fsl_file_canonical_name2(const char *zRoot,
                                        const char *zOrigName,
                                        fsl_b *  pOut,
                                        bool slash);

/**
   Equivalent to fsl_file_canonical_name2(NULL, zOrigName, pOut, slash).

   @see fsl_file_canonical_name2()
*/

FSL_EXPORT int fsl_file_canonical_name(const char *zOrigName,
                                       fsl_b *  pOut, bool slash);

/**
   Calculates the "directory part" of zFilename and _appends_ it to
   pOut. The directory part is all parts up to the final path
   separator ('\\' or '/'). If leaveSlash is true then the separator
   part is appended to pOut, otherwise it is not. This function only
   examines the first nLen bytes of zFilename.  If nLen is negative
   then fsl_strlen() is used to determine the number of bytes to
   examine.

   If zFilename ends with a slash then it is considered to be its
   own directory part. i.e.  the dirpart of "foo/" evaluates to
   "foo" (or "foo/" if leaveSlash is true), whereas the dirpart of
   "foo" resolves to nothing (empty - no output except a NUL
   terminator sent to pOut).

   Returns 0 on success, FSL_RC_MISUSE if !zFilename or !pOut,
   FSL_RC_RANGE if 0==nLen or !*zFilename, and FSL_RC_OOM if
   appending to pOut fails. If zFilename contains only a path
   separator and leaveSlash is false then only a NUL terminator is
   appended to pOut if it is not already NUL-terminated.

   This function does no filesystem-level validation of the the
   given path - only string evaluation.
*/
FSL_EXPORT int fsl_file_dirpart(char const * zFilename, fsl_int_t nLen,
                                fsl_b * pOut, bool leaveSlash);

/**
   Return the tail of a NUL-terminated file pathname. The tail is the
   last component of the path.  For example, the tail of "/a/b/c.d" is
   "c.d". If the name ends in a slash, a pointer to its NUL terminator
   is returned.
*/
FSL_EXPORT const char *fsl_file_tail(const char *z);

/**
   Writes the absolute path name of the current directory to zBuf,
   which must be at least nBuf bytes long (nBuf includes the space
   for a trailing NUL terminator).

   Returns FSL_RC_RANGE if the name would be too long for nBuf,
   FSL_RC_IO if it cannot determine the current directory (e.g. a
   side effect of having removed the directory at runtime or similar
   things), and 0 on success.

   On success, if outLen is not NULL then the length of the string
   written to zBuf is assigned to *outLen. The output string is
   always NUL-terminated.

   On Windows, the name is converted from unicode to UTF8 and all '\\'
   characters are converted to '/'.  No conversions are needed on
   Unix.
*/
FSL_EXPORT int fsl_getcwd(char *zBuf, fsl_size_t nBuf, fsl_size_t * outLen);


/**
   Return true if the filename given is a valid filename
   for a file in a repository. Valid filenames follow all of the
   following rules:

   -  Does not begin with "/"
   -  Does not contain any path element named "." or ".."
   -  Does not contain any of these characters in the path: "\"
   -  Does not end with "/".
   -  Does not contain two or more "/" characters in a row.
   -  Contains at least one character

   Invalid UTF8 characters result in a false return if bStrictUtf8 is
   true.  If bStrictUtf8 is false, invalid UTF8 characters are
   silently ignored. See
   https://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences and
   https://en.wikipedia.org/wiki/Unicode (for the non-characters).

   Fossil compatibility note: the bStrictUtf8 flag must be true
   when parsing new manifests but is false when parsing legacy
   manifests, for backwards compatibility.

   z must be NUL terminated. Results are undefined if !z.

   Note that periods in and of themselves are valid filename
   components, with the special exceptions of "." and "..", one
   implication being that "...." is, for purposes of this function,
   a valid simple filename.
*/
FSL_EXPORT bool fsl_is_simple_pathname(const char *z, bool bStrictUtf8);

/**
   Return the size of a file in bytes. Returns -1 if the file does
   not exist or is not stat(2)able.
*/
FSL_EXPORT fsl_int_t fsl_file_size(const char *zFilename);

/**
   Return the modification time for a file.  Return -1 if the file
   does not exist or is not stat(2)able.
*/
FSL_EXPORT fsl_time_t fsl_file_mtime(const char *zFilename);

#if 0
/**
   Don't use this. The wd (working directory) family of functions
   might or might-not be necessary and in any case they require
   a fsl_cx context argument because they require repo-specific
   "allow-symlinks" setting.

   Return TRUE if the named file is an ordinary file or symlink
   and symlinks are allowed.

   Return false for directories, devices, fifos, etc.
*/
FSL_EXPORT bool fsl_wd_isfile_or_link(const char *zFilename);
#endif

/**
   Returns true if the named file is an ordinary file. Returns false
   for directories, devices, fifos, symlinks, etc. The name
   may be absolute or relative to the current working dir.
*/
FSL_EXPORT bool fsl_is_file(const char *zFilename);

/**
   Returns true if the given file is a symlink, else false. The name
   may be absolute or relative to the current working dir. On Windows
   platforms this always returns false.
*/
FSL_EXPORT bool fsl_is_symlink(const char *zFilename);

/**
   Returns true if the given filename refers to a plain file or
   symlink, else returns false. The name may be absolute or relative
   to the current working dir.
*/
FSL_EXPORT bool fsl_is_file_or_link(const char *zFilename);

/**
   Returns true if the given path appears to be absolute, else
   false. On Unix a path is absolute if it starts with a '/'.  On
   Windows a path is also absolute if it starts with a letter, a
   colon, and either a backslash or forward slash.
*/
FSL_EXPORT bool fsl_is_absolute_path(const char *zPath);

/**
   Simplify a filename by:

   * converting all \ into / on windows and cygwin
   * removing any trailing and duplicate /
   * removing /./
   * removing /A/../

   Changes are made in-place.  Return the new name length.

   If n is <0 then fsl_strlen() is used to calculate the length.

   If the slash parameter is true, the trailing slash, if any, is
   retained, else any trailing slash is removed.

   As a special case, if the input string (simplified) is "/" then the
   output string will be "/", regardless of the value of the final
   argument. That behavior is debatable but this API is really
   intended to be used for paths deeper than the root directory.
*/
FSL_EXPORT fsl_size_t fsl_file_simplify_name(char *z, fsl_int_t n_, bool slash);

/**
   Return true if string z matches glob pattern zGlob and false if the
   pattern does not match. Always returns false if either argument is
   NULL. Supports all globbing rules supported by sqlite3_strglob().
*/
FSL_EXPORT bool fsl_str_glob(const char *zGlob, const char *z);

/**
   Parses zPatternList as a comma-and/or-fsl_isspace()-delimited
   list of glob patterns (as supported by fsl_str_glob()). Each
   pattern in that list is copied and appended to tgt in the form
   of a new (char *) owned by that list.

   Returns 0 on success, FSL_RC_OOM if copying a pattern to tgt
   fails, FSL_RC_MISUSE if !tgt or !zPatternList. An empty
   zPatternList is not considered an error (to simplify usage) and
   has no side-effects. On allocation error, tgt might be partially
   populated.

   Elements of the glob list may be optionally enclosed in single
   or double-quotes.  This allows a comma to be part of a glob
   pattern.

   Leading and trailing spaces on unquoted glob patterns are
   ignored.

   Note that there is no separate "glob list" class. A "glob list"
   is simply a fsl_list whose list entries are glob-pattern strings
   owned by that list.

   Calling this does not reset tgt's list, so it may be called
   multiple times to prepare a given list.

   Examples of a legal value for zPatternList:

   ```
   "*.c *.h, *.sh, '*.in'"
   ```

   @see fsl_glob_list_append()
   @see fsl_glob_list_matches()
   @see fsl_glob_list_clear()
*/
FSL_EXPORT int fsl_glob_list_parse( fsl_list *  tgt, char const * zPatternList );

/**
   Appends a single blob pattern to tgt, in the form of a new (char *)
   owned by tgt. This function copies zGlob and appends that copy
   to tgt.

   Returns 0 on success, FSL_RC_MISUSE if !tgt or !zGlob or
   !*zGlob, FSL_RC_OOM if appending to the list fails.

   @see fsl_glob_list_parse()
   @see fsl_glob_list_matches()
   @see fsl_glob_list_clear()
*/
FSL_EXPORT int fsl_glob_list_append( fsl_list *  tgt, char const * zGlob );

/**
   Assumes globList is a list of (char [const] *) glob values and
   tries to match each one against zNeedle using
   fsl_str_glob(). If any glob matches, it returns a pointer to the
   matched globList->list entry. If no matches are found, or if any
   argument is invalid, NULL is returned.

   The returned bytes are owned by globList and may be invalidated at
   its leisure. It is primarily intended to be used as a boolean,
   for example:

   ```
   if( fsl_glob_list_matches(myGlobs, someFilename) ) { ... }
   ```

   @see fsl_glob_list_parse()
   @see fsl_glob_list_append()
   @see fsl_glob_list_clear()
*/
FSL_EXPORT char const * fsl_glob_list_matches( fsl_list const * globList,
                                               char const * zNeedle );

/**
   If globList is not NULL this is equivalent to
   fsl_list_visit_free(globList, 1), otherwise it is a no-op.

   Note that this does not free the globList object itself, just
   its underlying list entries and list memory. (In practice, lists
   are either allocated on the stack or as part of a higher-level
   structure, and not on the heap.)

   @see fsl_glob_list_parse()
   @see fsl_glob_list_append()
   @see fsl_glob_list_matches()
*/
FSL_EXPORT void fsl_glob_list_clear( fsl_list *  globList );


/**
   Returns true if the given letter is an ASCII alphabet character.
*/
FSL_EXPORT bool fsl_isalpha(int c);

/**
   Returns true if c is a lower-case ASCII alphabet character.
*/
FSL_EXPORT bool fsl_islower(int c);

/**
   Returns true if c is an upper-case ASCII alphabet character.
*/
FSL_EXPORT bool fsl_isupper(int c);

/**
   Returns true if c is ' ', '\\r' (ASCII 13dec), or '\\t' (ASCII 9
   dec).
*/
FSL_EXPORT bool fsl_isspace(int c);

/**
   Returns true if c is an ASCII digit in the range '0' to '9'.
*/
FSL_EXPORT bool fsl_isdigit(int c);

/**
   Equivalent to fsl_isdigit(c) || fsl_isalpha().
*/
FSL_EXPORT bool fsl_isalnum(int c);

/**
   Returns the upper-case form of c if c is an ASCII alphabet
   letter, else returns c.
*/
FSL_EXPORT int fsl_tolower(int c);

/**
   Returns the lower-case form of c if c is an ASCII alphabet
   letter, else returns c.
*/
FSL_EXPORT int fsl_toupper(int c);

#ifdef _WIN32
/**
   Translate MBCS to UTF-8.  Return a pointer to the translated
   text. ACHTUNG: Call fsl_mbcs_free() (not fsl_free()) to
   deallocate any memory used to store the returned pointer when
   done.
*/
FSL_EXPORT char * fsl_mbcs_to_utf8(char const * mbcs);

/**
   Frees a string allocated from fsl_mbcs_to_utf8(). Results are undefined
   if mbcs was allocated using any other mechanism.
*/
FSL_EXPORT void fsl_mbcs_free(char * mbcs);
#endif
/* _WIN32 */

/**
   Deallocates the given memory, which must have been allocated
   from fsl_unicode_to_utf8(), fsl_utf8_to_unicode(), or any
   function which explicitly documents this function as being the
   proper finalizer for its returned memory.
*/
FSL_EXPORT void fsl_unicode_free(void *);

/**
   Translate UTF-8 to Unicode for use in system calls. Returns a
   pointer to the translated text. The returned value must
   eventually be passed to fsl_unicode_free() to deallocate any
   memory used to store the returned pointer when done.

   This function exists only for Windows. On other platforms
   it behaves like fsl_strdup().

   The returned type is (wchar_t*) on Windows and (char*)
   everywhere else.
*/
FSL_EXPORT void *fsl_utf8_to_unicode(const char *zUtf8);

/**
   Translates Unicode text into UTF-8.  Return a pointer to the
   translated text. Call fsl_unicode_free() to deallocate any
   memory used to store the returned pointer when done.

   This function exists only for Windows. On other platforms it
   behaves like fsl_strdup().
*/
FSL_EXPORT char *fsl_unicode_to_utf8(const void *zUnicode);

/**
   Translate text from the OS's character set into UTF-8. Return a
   pointer to the translated text. Call fsl_os_str_free() to
   deallocate any memory used to store the returned pointer when
   done.

   This function must not convert '\' to '/' on Windows/Cygwin, as
   it is used in places where we are not sure it's really filenames
   we are handling, e.g. fsl_getenv() or handling the argv
   arguments from main().

   On Windows, translate some characters in the in the range
   U+F001 - U+F07F (private use area) to ASCII. Cygwin sometimes
   generates such filenames. See:
   <https://cygwin.com/cygwin-ug-net/using-specialnames.html>
*/
FSL_EXPORT char *fsl_filename_to_utf8(const void *zFilename);

/**
   Attempts to ensure that the name of a file in the filesystem matches
   the same case as one provided by the user. This distinction can be
   significant for users on case-insensitive filesystems.

   `zDir` must be the name of the target directory and `zPath` must be
   a relative path rooted at `zDir`.  If `zPath` does not exist, it is
   assumed to be a _potential_ name and `*zOut` will be set to an
   as-is copy of `zPath`.

   If `isCaseSensitive` is true then this function is essentially a
   dummy stub which returns a copy of `zPath`, made using
   fsl_strdup(), via `*zOut`.

   If isCaseSensitive is false, then it behaves rather differently:

   Uses opendir() on the given directory and scans it for a name
   matching `zPath`, case-insensitvely and recursively. On success,
   the result is a case-correct copy of `zPath`.

   On error, non-zero is returned and `*zOut` is not modified. On
   success, `*zOut` is modified as described above and ownership of it
   is transfered to the caller, who must eventually pass it to
   fsl_free().

   Non-0 error codes include:

   - FSL_RC_OOM on allocation error.
   - If opendir() fails on `zDir` or on a matching subdirectory, the
     counterpart of its errno value, as per fsl_errno_to_rc(),
     falling back to FSL_RC_IO: for example FSL_RC_NOT_FOUND for a
     missing directory and FSL_RC_ACCESS for an unreadable one.

   Design note: `isCaseSensitive` is provided as a bool, rather than a
   fsl_cx instance (which has a setting for that flag), so that this
   routine can be used in cases where a fsl_cx is not readily
   available and in cases where this validation is desired on
   case-sensitive filesystems. When a fsl_cx is available,
   fsl_cx_is_case_sensitive() may optionally be used to as the value
   for the first argument. Depending on _how_ filenames are collected,
   however, this case-check may or may not be entirely superfluous.
*/
FSL_EXPORT int fsl_filename_preferred_case(bool isCaseSensitive, const char *zDir,
                                           const char *zPath, char **zOut);

/**
   Translate text from UTF-8 to the OS's filename character set.
   Return a pointer to the translated text. Call
   fsl_os_str_free() to deallocate any memory used to store the
   returned pointer when done.

   On Windows, characters in the range U+0001 to U+0031 and the
   characters '"', '*', ':', '<', '>', '?' and '|' are invalid in
   filenames. Therefore, translate those to characters in the in the
   range U+F001 - U+F07F (private use area), so those characters
   never arrive in any Windows API. The filenames might look
   strange in Windows explorer, but in the cygwin shell everything
   looks as expected.

   See: <https://cygwin.com/cygwin-ug-net/using-specialnames.html>

   The returned type is (wchar_t*) on Windows and (char*)
   everywhere else.
*/
FSL_EXPORT void *fsl_utf8_to_filename(const char *zUtf8);


/**
   Deallocate pOld, which must be NULL or must have been allocated by
   fsl_filename_to_utf8(), fsl_utf8_to_filename(), fsl_getenv(), or
   another routine which explicitly documents this function as being
   the proper finalizer for its returned memory.
*/
FSL_EXPORT void fsl_os_str_free(void *pOld);

/**
   Returns a (possible) copy of the environment variable with the
   given key, or NULL if no entry is found. The returned value must
   be passed to fsl_os_str_free() to free it. ACHTUNG: DO NOT
   MODIFY the returned value - on Unix systems it is _not_ a
   copy. That interal API inconsistency "should" be resolved
   (==return a copy from here, but that means doing it everywhere)
   to avoid memory ownership problems later on.

   Why return a copy? Because native strings from at least one of
   the more widespread OSes often have to be converted to something
   portable and this requires allocation on such platforms, but
   not on Unix. For API transparency, that means all platforms get
   the copy(-like) behaviour.
*/
FSL_EXPORT char *fsl_getenv(const char *zName);

/**
   Collects a list of directories intended to use as temp dirs in the
   current environment. The returned array ends with a NULL element to
   mark its end.  The memory's ownership is a bit awkward and
   therefore it must be eventually freed by passing it to
   fsl_temp_dirs_free().

   No entries in the returned list contain a trailing slash unless the
   entry is itself a reference to a Unix-style root directory (which
   would be highly unusual).

   The list of directories varies by platform:

   Windows:

   - `GetTempPath()`, `$TEMP`, `$TMP`, "."

   Non-Windows:

   - `$TMPDIR`, "/var/tmp", "/usr/tmp", "/tmp", "/temp",
   "."

   (`$X` refers to the value of environment variable `X`.)

   Noting that only directories in those lists which actually exist
   (at the time this is called) are added to the list (also noting
   that "." always exists unless CWD is deleted while the app is
   active). If no suitable directories are found, an empty array (with
   a leading `NULL` element) is returned, but this would indicate
   that, e.g., even CWD does not exist (so the app has bigger
   problems).

   `NULL` is only returned if allocation of the containing array
   fails. Failure to allocate memory for a given directory name (as
   those require conversion on some platforms) is ignored and such
   entries are simply skipped over.

   @see fsl_temp_dirs_free()
   @see fsl_file_tempname()
*/
FSL_EXPORT char ** fsl_temp_dirs_get(void);

/**
   If aDirs is not NULL then it is expected to be an array created by
   fsl_temp_dirs_get() and it frees the list's entries and the list
   itself. After calling this, the argument's memory is invalidated
   and any use of it leads to undefined results.

   This is a harmless no-op if the argument is NULL.

   @see fsl_temp_dirs_get()
   @see fsl_file_tempname()
*/
FSL_EXPORT void fsl_temp_dirs_free(char **aDirs);

/**
   Creates a semi-random temp filename and appends it to the given
   buffer. The second argument is an optional string to prefix
   each filename with. If it is NULL then a library-wide default is
   used. If it is empty then no prefix is used. The final argument is
   expected to be NULL or a list of directories in the format
   constructed by fsl_temp_dirs_get(). If it is not NULL, this
   function uses the first entry in dirs which refers to an existing
   directory. If it is NULL then the buffer is filled with the new
   name with no directory prefix.

   Returns...

   - 0 on success, in which case tgt is populated with the new name.

   - If tgt->errCode is not 0 when this is called, that is returned
     and this function has no further side effects.

   - FSL_RC_NOT_FOUND if dirs is empty or refers only to non-existent
     directories.

   - FSL_RC_OOM if allocating memory for the target buffer fails.

   - FSL_RC_RANGE if, after some hard-coded number of attempts, it is
     unable to construct a unique filename due to name collisions in
     the target directory. That "shouldn't ever happen."

   Sidebars:

   - This function does no translation or validation of the 2nd
     argument other than to check if it is NULL. It "should" be either
     a file base name, with no path component, or a relative path
     component for which the caller has already created the directory.
     e.g. use the base name of the application, e.g. "my-app".

   - This function does not actually write to the filesystem, it just
     constructs a name. There is hypothetically a window of
     opportunity for another file with the same name to be created
     before the caller has a chance to create the file, but the
     chances of that actually happening are close enough to zero to
     rule them out for all practical purposes.

   - The RNG is officially unspecified. (That said:
     sqlite3_randomness().)

   @see fsl_temp_dirs_get()
   @see fsl_temp_dirs_free()
*/
FSL_EXPORT int fsl_file_tempname(fsl_b *  tgt, char const *zPrefix,
                                 char * const * dirs);

/**
   Returns a positive value if zFilename is a directory, 0 if
   zFilename does not exist, or a negative value if zFilename
   exists but is something other than a directory. Results are
   undefined if zFilename is NULL.

   This function expects zFilename to be a well-formed path -
   it performs no normalization on it.
*/
FSL_EXPORT int fsl_dir_check(const char *zFilename);

/**
   Check the given path to determine whether it is an empty directory.
   Returns 0 on success (i.e., directory exists and is empty), <0 if
   the provided path is not a directory or cannot be opened, and >0 if
   the directory is not empty.
*/
FSL_EXPORT int fsl_dir_is_empty(const char *path);

/**
   Deletes the given file from the filesystem. Returns 0 on
   success. If the component is a directory, this operation will
   fail. If zFilename refers to a symlink, the link (not its target)
   is removed.

   Results are undefined if zFilename is NULL.

   Potential TODO: if it refers to a dir, forward the call to
   fsl_rmdir().
*/
FSL_EXPORT int fsl_file_unlink(const char *zFilename);

/**
   Renames file zFrom to zTo using the OS's equivalent of
   `rename(2)`. Both files must be in the same filesystem and any
   directory parts of zTo must already exist. Returns 0 on success,
   FSL_RC_OOM if a filename conversion allocation fails (on platforms
   which do that), or a FSL_RC_xxx counterpart of an `errno` value if
   the `rename(2)` call fails (as per fsl_errno_to_rc()).
*/
FSL_EXPORT int fsl_file_rename(const char *zFrom, const char *zTo);

/**
   Deletes an empty directory from the filesystem. Returns 0
   on success. There are any number of reasons why deletion
   of a directory can fail, some of which include:

   - It is not empty or permission denied (FSL_RC_ACCESS).

   - Not found (FSL_RC_NOT_FOUND).

   - Is not a directory or (on Windows) is a weird pseudo-dir type for
     which rmdir() does not work (FSL_RC_TYPE).

   - I/O error (FSL_RC_IO).

   @see fsl_dir_is_empty()
*/
FSL_EXPORT int fsl_rmdir(const char *zFilename);

/**
   Sets the mtime (Unix epoch) for a file. Returns 0 on success,
   non-0 on error. If newMTime is less than 0 then the current
   time(2) is used. This routine does not create non-existent files
   (e.g. like a Unix "touch" command).
*/
FSL_EXPORT int fsl_file_mtime_set(const char *zFilename, fsl_time_t newMTime);

/**
   On non-Windows platforms, this function sets or unsets the
   executable bits on the given filename. All other permissions are
   retained as-is. Returns 0 on success. On Windows this is a no-op,
   returning 0.

   If the target is a directory or a symlink, this is a no-op and
   returns 0.
*/
FSL_EXPORT int fsl_file_exec_set(const char *zFilename, bool isExec);

/**
   Returns true if the argument is fsl_stat()'able and has the
   executable bit set, else false.
*/
FSL_EXPORT bool fsl_file_isexec(const char *zFilename);

/**
   Makes a bitwise copy of the file zFrom to file zTo, creating any
   directories needed for the target file's if they do not already
   exist. If the source file is executable then the target file will
   also be made so, but any failure to do so (e.g. because the target
   filesystem does not support it) is silently ignored.

   Returns 0 on success. On error it may return any number of result
   codes if opening a file fails, if a mkdir fails (see
   fsl_mkdir_for_file()), or if any I/O fails.

   Results are undefined if the source and target refer to the
   same file.
*/
FSL_EXPORT int fsl_file_copy(char const *zFrom, char const *zTo);

/**
   Create the directory with the given name if it does not already
   exist. If forceFlag is true, delete any prior non-directory
   object with the same name.

   Return 0 on success, non-0 on error.

   If the directory already exists then 0 is returned, not an error
   (FSL_RC_ALREADY_EXISTS), because that simplifies usage. If
   another filesystem entry with this name exists and forceFlag is
   true then that entry is deleted before creating the directory,
   and this operation fails if deletion fails. If forceFlag is
   false and a non-directory entry already exists, FSL_RC_TYPE is
   returned.

   For recursively creating directories, use fsl_mkdir_for_file().

   Bug/corner case: if zFilename refers to a symlink to a
   non-existent directory, this function gets slightly confused,
   tries to make a dir with the symlink's name, and returns
   FSL_RC_ALREADY_EXISTS. How best to resolve that is not yet
   clear. The problem is that stat(2)ing the symlink says "nothing
   is there" (because the link points to a non-existing thing), so
   we move on to the underlying mkdir(), which then fails because
   the link exists with that name.
*/
FSL_EXPORT int fsl_mkdir(const char *zName, bool forceFlag);

/**
   A convenience form of fsl_mkdir() which can recursively create
   directories. If zName has a trailing slash then the last
   component is assumed to be a directory part, otherwise it is
   assumed to be a file part (and no directory is created for that
   part). zName may be either an absolute or relative path.

   Returns 0 on success (including if all directories already exist).
   Returns FSL_RC_OOM if there is an allocation error. Returns
   FSL_RC_TYPE if one of the path components already exists and is not
   a directory. Returns FSL_RC_RANGE if zName is NULL or empty. If
   zName is only 1 byte long, this is a no-op.

   On systems which support symlinks, a link to a directory is
   considered to be a directory for purposes of this function.

   If forceFlag is true and a non-directory component is found in
   the filesystem where zName calls for a directory, that component
   is removed (and this function fails if removal fails).

   Examples:

   "/foo/bar" creates (if needed) /foo, but assumes "bar" is a file
   component. "/foo/bar/" creates /foo/bar. However "foo" will not
   create a directory - because the string has no path component,
   it is assumed to be a filename.

   Both "/foo/bar/my.doc" and "/foo/bar/" result in the directories
   "/foo/bar".
*/
FSL_EXPORT int fsl_mkdir_for_file(char const *zName, bool forceFlag);

/**
   This function expects its second argument to refer to a symlink
   (and that the caller has already validated that it is one). The
   `readlink(2)` system call is used to fetch the contents of that
   link and the target buffer is populated with those contents
   (reusing any memory the buffer may already own).

   Returns 0 on success, FSL_RC_OOM if copying to the target buffer
   fails due to an allocation error, or an error propagated from
   `readlink()` in the form of a fsl_errno_to_rc() result.

   Caveat: on Windows platforms this function simply passes the buffer
   to fsl_b_reuse() and returns 0. It should arguably read the
   contents of zFilename into the buffer in that case, on the
   assumption that the file is a pseudo-symlink. That decision may be
   re-evaluated if/when the library claims to have fossil-compatible
   symlink support.

   Bugs:

   - This function has a limited internal buffer as a target for
     `readlink()`. It "should be" long enough for any "reasonable"
     uses in the scope of this library, but there's bound to be some
     user out there who wants to use it for other contexts.
*/
FSL_EXPORT int fsl_symlink_read(fsl_b *  tgt, char const * zFilename);

/**
   Creates a symlink or pseudo-symlink named zLinkFile linking to
   zTargetFile. If realLink is true and this is a non-Windows platform
   then:

   - fsl_file_simplify_name() is used to normalize zLinkFile.

   - `symlink(2)` is used to link zTargetFile to a new link named the
      simplified form of zLinkFile. If zLinkFile already exists, this
      will fail.

   If realLink is false or this is a Windows platform, a file is
   created named zLinkFile containing the string zTargetFile as its
   contents. If a file or symlink named zLinkFile already exists, it
   is removed before writing the new contents.

   In both cases the parent directories for zLinkFile are created, if
   needed, but that process will fail with FSL_RC_TYPE if any
   non-directory components with conflicting names are found in the
   to-be-mkdir'd path.

   Returns 0 on success or some lower-level result code if
   creation/writing of a directory, a symlink, or pseudo-symlink
   fails.
*/
FSL_EXPORT int fsl_symlink_create(char const *zTargetFile, char const * zLinkFile,
                                  bool realLink);

/**
   Reads symlink zFrom, as per fsl_symlink_read(), then creates a copy
   named zTo, as per fsl_symlink_create(). The first argument for the
   latter call is the contents of the result of fsl_symlink_read().
   The 2nd and 3rd arguments to fsl_symlink_create() are the 2nd and
   3rd arguments to this function.

   Returns 0 on success, FSL_RC_OOM on OOM, or any of various
   filesystem-related non-0 codes if reading or saving the link fails.
*/
FSL_EXPORT int fsl_symlink_copy(char const *zFrom, char const *zTo, bool realLink);

/**
   Uses fsl_getenv() to look for the environment variables
   (FOSSIL_USER, (Windows: USERNAME), (Unix: USER, LOGNAME)). If
   it finds one it returns a copy of that value, which must
   eventually be passed to fsl_free() to free it (NOT
   fsl_os_str_free(), though fsl_getenv() requires that one). If
   it finds no match, or if copying the entry fails, it returns
   NULL.

   @see fsl_cx_user_set()
   @see fsl_cx_user_get()
*/
FSL_EXPORT char * fsl_user_name_guess(void);

/**
   Tries to find the user's home directory. If found, 0 is
   returned, tgt's memory is _overwritten_ (not appended) with the
   path, and tgt->used is set to the path's string length.  (Design
   note: the overwrite behaviour is inconsistent with most of the
   API, but the implementation currently requires this.)

   On Unix platforms the home directory is taken from the HOME
   environment variable. On Windows it is the first of LOCALAPPDATA,
   APPDATA, and HOMEPATH (prefixed by HOMEDRIVE when that is set)
   which is set. FOSSIL_HOME and XDG_CONFIG_HOME are not consulted
   here: they apply only to locating the global config database,
   which fsl_config_global_preferred_name() does before or after
   calling this function.

   If requireWriteAccess is true then the directory is checked for
   write access, and FSL_RC_ACCESS is returned if that check
   fails. For historical (possibly techinical?) reasons, this check
   is only performed on Unix platforms. On others this argument is
   ignored. When writing code on Windows, it may be necessary to
   assume that write access is necessary on non-Windows platform,
   and to pass 1 for the second argument even though it is ignored
   on Windows.

   On error non-0 is returned and tgt is updated with an error
   string OR (if the error was an allocation error while appending
   to the path or allocating MBCS strings for Windows), it returns
   FSL_RC_OOM and tgt "might" be updated with a partial path (up to
   the allocation error), and "might" be empty (if the allocation
   error happens early on).

   This routine does not canonicalize/transform the home directory
   path provided by the environment, other than to convert the
   string byte encoding on some platforms. i.e. if the environment
   says that the home directory is "../" then this function will
   return that value, possibly to the eventual disappointment of
   the caller.

   Result codes include:

   - FSL_RC_OK (0) means a home directory was found and tgt is
   populated with its path.

   - FSL_RC_NOT_FOUND means the home directory (platform-specific)
   could not be found.

   - FSL_RC_ACCESS if the home directory is not writable and
   requireWriteAccess is true. Unix platforms only -
   requireWriteAccess is ignored on others.

   - FSL_RC_TYPE if the home (as determined via inspection of the
   environment) is not a directory.

   - FSL_RC_OOM if a memory (re)allocation fails.
*/
FSL_EXPORT int fsl_find_home_dir( fsl_b *  tgt, bool requireWriteAccess );

/**
   Values for use with the fsl_fstat::type field.
*/
enum fsl_fstat_type_e {
/** Sentinel value for unknown/invalid filesystem entry types. */
FSL_FSTAT_TYPE_UNKNOWN = 0,
/** Indicates a directory filesystem entry. */
FSL_FSTAT_TYPE_DIR,
/** Indicates a non-directory, non-symlink filesystem entry.
    Because fossil's scope is limited to SCM work, it assumes that
    "special files" (sockets, etc.) are just files, and makes no
    special effort to handle them.
*/
FSL_FSTAT_TYPE_FILE,
/** Indicates a symlink filesystem entry. */
FSL_FSTAT_TYPE_LINK
};
typedef enum fsl_fstat_type_e fsl_fstat_type_e;

/**
   Bitmask values for use with the fsl_fstat::perms field.

   Only permissions which are relevant for fossil are listed here.
   e.g. read-vs-write modes are irrelevant for fossil as it does not
   track them. It manages only the is-executable bit. In in the
   contexts of fossil manifests, it also treats "is a symlink" as a
   permission flag.
*/
enum fsl_fstat_perm_e {
/**
   Sentinel value.
*/
FSL_FSTAT_PERM_UNKNOWN = 0,
/**
   The executable bit, as understood by Fossil. Fossil does not
   differentiate between different +x values for user/group/other.
*/
FSL_FSTAT_PERM_EXE = 0x01
};
typedef enum fsl_fstat_perm_e fsl_fstat_perm_e;

/**
   A simple wrapper around the stat(2) structure resp. _stat/_wstat
   (on Windows). It exposes only the aspects of stat(2) info which
   Fossil works with, and not any platform-/filesystem-specific
   details except the executable bit for the permissions mode and some
   handling of symlinks.
*/
struct fsl_fstat {
  /**
     Indicates the type of filesystem object.
  */
  fsl_fstat_type_e type;
  /**
     The time of the last file metadata change (owner, permissions,
     etc.). The man pages (neither for Linux nor Windows) do not
     specify exactly what unit this is. Let's assume seconds since the
     start of the Unix Epoch.
  */
  fsl_time_t ctime;
  /**
     Last modification time.
  */
  fsl_time_t mtime;
  /**
     The size of the stat'd file, in bytes.
  */
  fsl_size_t size;
  /**
     Contains the filesystem entry's permissions as a bitmask of
     fsl_fstat_perm_e values. Note that only the executable bit for
     _files_ (not directories) is exposed here.
  */
  int perm;
};

/** Empty-initialized fsl_fstat structure, intended for const-copy
    construction. */
#define fsl_fstat_empty_m {FSL_FSTAT_TYPE_UNKNOWN,0,0,-1,0}

/** Empty-initialized fsl_fstat instance, intended for non-const copy
    construction. */
FSL_EXPORT const fsl_fstat fsl_fstat_empty;

/**
   Runs the OS's stat(2) equivalent to populate fst (if not NULL) with
   information about the given file.

   The second argument may be NULL.

   Returns 0 on success. Results are undefined if zFilename is NULL or
   invalid. Returns FSL_RC_NOT_FOUND if no filesystem entry is found
   for the given name and FSL_RC_OOM if converting the name to the
   platform's filename encoding fails. Any other failure of the
   underlying stat()/lstat()/_wstati64() call returns the counterpart
   of its errno value, as per fsl_errno_to_rc(), falling back to
   FSL_RC_IO. Note that the fst parameter may be NULL,
   in which case the return value will be 0 if the name is stat-able,
   but will return no other information about it.

   The derefSymlinks argument is ignored on non-Unix platforms.  On
   Unix platforms, if derefSymlinks is true then stat(2) is used, else
   lstat(2) (if available on the platform) is used. For most cases
   clients should pass true. They should only pass false if they need
   to differentiate between symlinks and files.

   The fsl_fstat_type_e family of flags can be used to determine the
   type of the filesystem object being stat()'d (file, directory, or
   symlink). It does not apply any special logic for platform-specific
   oddities other than symlinks (e.g. character devices and such).
*/
FSL_EXPORT int fsl_stat(const char *zFilename, fsl_fstat *  fst,
                        bool derefSymlinks);

/**
   Create a new fossil-format delta between the memory zIn and zOut.

   The delta is written into a preallocated buffer, zDelta, which
   must be at least 60 bytes longer than the target memory, zOut.
   The delta string will be NUL-terminated, but it might also
   contain embedded NUL characters if either the zSrc or zOut files
   are binary.

   On success this function returns 0 and the length of the delta
   string, in bytes, excluding the final NUL terminator character,
   is written to *deltaSize.

   Returns FSL_RC_OOM if memory allocation fails during generation of
   the delta. Returns FSL_RC_RANGE if lenSrc or lenOut are "too
   big" (if they cause an overflow in the math).

   Results are undefined if any pointer is NULL.

   Output Format:

   The delta begins with a base64 number followed by a newline.
   This number is the number of bytes in the TARGET file.  Thus,
   given a delta file z, a program can compute the size of the
   output file simply by reading the first line and decoding the
   base-64 number found there.  The fsl_delta_applied_size()
   routine does exactly this.

   After the initial size number, the delta consists of a series of
   literal text segments and commands to copy from the SOURCE file.
   A copy command looks like this:

   (Achtung: extra backslashes are for Doxygen's benefit - not
   visible in the processsed docs.)

   NNN\@MMM,

   where NNN is the number of bytes to be copied and MMM is the
   offset into the source file of the first byte (both base-64).
   If NNN is 0 it means copy the rest of the input file.  Literal
   text is like this:

   NNN:TTTTT

   where NNN is the number of bytes of text (base-64) and TTTTT is
   the text.

   The last term is of the form

   NNN;

   In this case, NNN is a 32-bit bigendian checksum of the output
   file that can be used to verify that the delta applied
   correctly.  All numbers are in base-64.

   Pure text files generate a pure text delta.  Binary files
   generate a delta that may contain some binary data.

   Algorithm:

   The encoder first builds a hash table to help it find matching
   patterns in the source file.  16-byte chunks of the source file
   sampled at evenly spaced intervals are used to populate the hash
   table.

   Next we begin scanning the target file using a sliding 16-byte
   window.  The hash of the 16-byte window in the target is used to
   search for a matching section in the source file.  When a match
   is found, a copy command is added to the delta.  An effort is
   made to extend the matching section to regions that come before
   and after the 16-byte hash window.  A copy command is only
   issued if the result would use less space that just quoting the
   text literally. Literal text is added to the delta for sections
   that do not match or which can not be encoded efficiently using
   copy commands.

   @see fsl_delta_applied_size()
   @see fsl_delta_apply()
*/
FSL_EXPORT int fsl_delta_create( unsigned char const *zSrc, fsl_size_t lenSrc,
                      unsigned char const *zOut, fsl_size_t lenOut,
                      unsigned char *zDelta, fsl_size_t * deltaSize);

/**
   Works identically to fsl_delta_create() but sends its output to
   the given output function. out(outState,...) may be called any
   number of times to emit delta output. Each time it is called it
   should append the new bytes to its output channel.

   The semantics of the return value and the first four arguments
   are identical to fsl_delta_create(), with these ammendments
   regarding the return value:

   - Returns FSL_RC_MISUSE if any of (zV1, zV2, out) are NULL.

   - If out() returns non-0 at any time, delta generation is
     aborted and that code is returned.

   Example usage:

   ```
   int rc = fsl_delta_create( v1, v1len, v2, v2len,
                              fsl_output_f_FILE, stdout);
   ```
*/
FSL_EXPORT int fsl_delta_create2( unsigned char const *zV1, fsl_size_t lenV1,
                                  unsigned char const *zV2, fsl_size_t lenV2,
                                  fsl_output_f out, void * outState);

/**
   A fsl_delta_create() wrapper which uses the first two arguments
   as the original and "new" content versions to delta, and outputs
   the delta to the 3rd argument (overwriting any existing contents
   and re-using any memory it had allocated).

   If any of the buffers have the same address, FSL_RC_MISUSE is
   returned. If fsl_b_err() is true for the 3rd argument, that
   value is returned without side effects. If allocation of memory for
   the delta fails, FSL_RC_OOM is returned and delta's errCode is
   updated with that value. If either input is larger than
   UINT32_MAX bytes, which the delta format cannot encode,
   FSL_RC_RANGE is returned.

   Results are undefined if any argument is NULL.

   Returns 0 on success.
*/
FSL_EXPORT int fsl_b_delta_create( fsl_b const * src,
                                        fsl_b const * newVers,
                                        fsl_b *  delta);

/**
   Apply a delta created using fsl_delta_create().

   The output buffer must be big enough to hold the whole output
   file and a NUL terminator at the end. The
   fsl_delta_applied_size() routine can be used to determine that
   size.

   zSrc represents the original sources to apply the delta to.
   It must be at least lenSrc bytes of valid memory.

   zDelta holds the delta (created using fsl_delta_create()),
   and it must be lenDelta bytes long.

   On success this function returns 0 and writes the applied delta
   to zOut.

   Returns FSL_RC_MISUSE if any pointer argument is NULL. Returns
   FSL_RC_RANGE if lenSrc or lenDelta are "too big" (if they cause an
   overflow in the math) or lenDelta is 0. Invalid delta input can
   cause any of FSL_RC_RANGE, FSL_RC_DELTA_INVALID_TERMINATOR,
   FSL_RC_CHECKSUM_MISMATCH, FSL_RC_SIZE_MISMATCH, or
   FSL_RC_DELTA_INVALID_OPERATOR to be returned.

   Refer to the fsl_delta_create() documentation above for a
   description of the delta file format.

   @see fsl_delta_applied_size()
   @see fsl_delta_create()
   @see fsl_delta_apply2()
*/
FSL_EXPORT int fsl_delta_apply( unsigned char const *zSrc, fsl_size_t lenSrc,
                     unsigned char const *zDelta, fsl_size_t lenDelta,
                     unsigned char *zOut );

/**
   Functionally identical to fsl_delta_apply() but any errors
   generated during application of the delta (as distinct from
   argument validation) are described in more detail in pErr. If pErr
   is NULL this behaves exactly as documented for fsl_delta_apply().
*/
FSL_EXPORT int fsl_delta_apply2( unsigned char const *zSrc,
                                 fsl_size_t lenSrc,
                                 unsigned char const *zDelta,
                                 fsl_size_t lenDelta,
                                 unsigned char *zOut,
                                 fsl_error * pErr);
/**
  Calculates the size (in bytes) of the output from applying a the
  given delta. On success 0 is returned and *appliedSize will be
  updated with the amount of memory required for applying the
  delta. zDelta must point to lenDelta bytes of memory in the
  format emitted by fsl_delta_create(). It is legal for appliedSize
  to point to the same memory as the 2nd argument.

  Returns FSL_RC_RANGE if lenDelta is too short to be a delta. Returns
  FSL_RC_DELTA_INVALID_TERMINATOR if the delta's encoded length is not
  properly terminated.

  Results are undefined if any pointer argument is NULL.

  This routine is provided so that an procedure that is able to call
  fsl_delta_apply() can learn how much space is required for the
  output and hence allocate no more space that is really needed.

  TODO?: consolidate 2nd and 3rd parameters into one i/o parameter?

  @see fsl_delta_apply()
  @see fsl_delta_create()
*/
FSL_EXPORT int fsl_delta_applied_size(unsigned char const *zDelta,
                                      fsl_size_t lenDelta,
                                      fsl_size_t * appliedSize);

/**
   "Fossilizes" the first len bytes of the given input string. If
   (len<0) then fsl_strlen(inp) is used to calculate its length.
   The output replaces the contents of out (it sets out->used to 0
   before writing), which is expanded as needed and out->used is
   updated accordingly.  Returns 0 on success, FSL_RC_MISUSE if !inp
   or !out. If 0==len or (!*inp && len<0), it sets out->used to 0 and
   returns 0. Returns FSL_RC_OOM if reservation of the output buffer
   fails (it is expanded, at most, one time by this function), or
   fsl_b_err() of out if that is non-0.

   Fossilization replaces the following bytes/sequences with the
   listed replacements:

   (Achtung: usage of doubled backslashes here it just to please
   doxygen - they will show up as single slashes in the processed
   output.)

   - Backslashes are doubled.

   - (\\n, \\r, \\v, \\t, \\f) are replaced with \\\\X, where X is the
   conventional encoding letter for that escape sequence.

   - Spaces are replaced with \\s.

   - Embedded NULs are replaced by \\0 (numeric 0, not character
   '0').
*/
FSL_EXPORT int fsl_bytes_fossilize( unsigned char const * inp, fsl_int_t len,
                         fsl_b * out );
/**
   "Defossilizes" bytes encoded by fsl_bytes_fossilize() in-place.
   inp must be a string encoded by fsl_bytes_fossilize(), and the
   decoding processes stops at the first unescaped NUL terminator.
   It has no error conditions except for !inp or if inp is not
   NUL-terminated, both of which invoke in undefined behaviour.

   If resultLen is not NULL then *resultLen is set to the resulting string
   length.

*/
FSL_EXPORT void fsl_bytes_defossilize( unsigned char * inp, fsl_size_t * resultLen );

/**
   Defossilizes the contents of b. Equivalent to:
   fsl_bytes_defossilize( b->mem, &b->used );
*/
FSL_EXPORT void fsl_b_defossilize( fsl_b *  b );

/**
   Returns true if the input string contains only valid lower-case
   base-16 digits. If any invalid characters appear in the string,
   false is returned.
*/
FSL_EXPORT bool fsl_validate16(const char *zIn, fsl_size_t nIn);

/**
   The input string is a base16 value.  Convert it into its canonical
   form.  This means that digits are all lower case and that conversions
   like "l"->"1" and "O"->"0" occur.
*/
FSL_EXPORT void fsl_canonical16(char *z, fsl_size_t n);

/**
   Decode a N-character base-16 number into base-256.  N must be a
   multiple of 2. The output buffer must be at least N/2 characters
   in length. Returns 0 on success, FSL_RC_RANGE if N is odd or if
   any of the first N bytes of zIn is not a hexadecimal digit. On
   error, pOut may have been partly written.
*/
FSL_EXPORT int fsl_decode16(const unsigned char *zIn, unsigned char *pOut, fsl_size_t N);

/**
   Encode a N-digit base-256 in base-16. N is the byte length of pIn
   and zOut must be at least (N*2+1) bytes long (the extra is for a
   terminating NUL). Returns zero on success, FSL_RC_MISUSE if !pIn
   or !zOut.
*/
FSL_EXPORT int fsl_encode16(const unsigned char *pIn, unsigned char *zOut, fsl_size_t N);

/*
   Undo the obscuring of text performed by obscure().  Or, if the input is
   not hexadecimal (meaning the input is not the output of obscure()) then
   do the equivalent of strdup().
  
   The result is memory obtained from malloc that should be freed by the caller.
*/
FSL_EXPORT char * fsl_unobscure(const char *zIn);

/**
   Tries to convert the value of errNo, which is assumed to come
   from the global errno, to a fsl_rc_e code. If it can, it returns
   something approximating the errno value, else it returns dflt.

   Example usage:

   ```
   FILE * f = fsl_fopen("...", "...");
   int rc = f ? 0 : fsl_errno_to_rc(errno, FSL_RC_IO);
   ...
   ```

   Why require the caller to pass in errno, instead of accessing it
   directly from this function? To avoid the the off-chance that
   something changes errno between the call and the conversion
   (whether or not that's possible is as yet undetermined). It can
   also be used by clients to map to explicit errno values to
   fsl_rc_e values, e.g. fsl_errno_to_rc(EROFS,-1) returns
   FSL_RC_ACCESS.

   A list of the errno-to-fossil conversions:

   - 0: FSL_RC_OK (0)

   - EINVAL: FSL_RC_MISUSE (could arguably be FSL_RC_RANGE, though)

   - ENOMEM: FSL_RC_OOM

   - EACCES, EBUSY, EPERM, EROFS, EDQUOT, EAGAIN: FSL_RC_ACCESS

   - EISDIR, ENOTDIR: FSL_RC_TYPE

   - ENAMETOOLONG, ELOOP, ERANGE: FSL_RC_RANGE

   - ENOENT: FSL_RC_NOT_FOUND

   - EEXIST: FSL_RC_ALREADY_EXISTS

   - EIO: FSL_RC_IO

   Any other value for errNo causes dflt to be returned.
*/
FSL_EXPORT int fsl_errno_to_rc(int errNo, int dflt);

/**
   Make the given string safe for HTML by converting every "<" into
   "&lt;", every ">" into "&gt;", every "&" into "&amp;", and
   encode '"' as &quot; so that it can appear as an argument to
   markup.

   The escaped output is send to out(oState,...).

   Returns 0 on success or if there is nothing to do (input has a
   length of 0, in which case out() is not called). Returns
   FSL_RC_MISUSE if !out or !zIn. If out() returns a non-0 code
   then that value is returned to the caller.

   If n is negative, fsl_strlen() is used to calculate zIn's length.
*/
FSL_EXPORT int fsl_htmlize(fsl_output_f out, void * oState,
                const char *zIn, fsl_int_t n);

/**
   Functionally equivalent to fsl_htmlize() but optimized to perform
   only a single allocation.

   Returns 0 on success or if there is nothing to do (input has a
   length of 0). Returns FSL_RC_MISUSE if !p or !zIn, and
   FSL_RC_OOM on allocation error.

   If n is negative, fsl_strlen() is used to calculate zIn's length.
*/
FSL_EXPORT int fsl_htmlize_to_buffer(fsl_b *p, const char *zIn, fsl_int_t n);

/**
   Equivalent to fsl_htmlize_to_buffer() but returns the result as a
   new string which must eventually be fsl_free()d by the caller.

   Returns NULL for invalid arguments or allocation error.
*/
FSL_EXPORT char *fsl_htmlize_str(const char *zIn, fsl_int_t n);

/**
   If c is a character Fossil likes to HTML-escape, assigns *xlate
   to its transformed form, else set it to NULL. Returns 1 for
   untransformed characters and the strlen of *xlate for others.
   Bytes returned via xlate are static and immutable.

   Results are undefined if xlate is NULL.
*/
FSL_EXPORT fsl_size_t fsl_htmlize_xlate(int c, char const ** xlate);


/** @enum fsl_diff2_flag_e

   Flags for use with the 2021-era text-diff generation APIs
   (fsl_dibu and friends). This set of flags may still change
   considerably.

   Maintenance reminders:

   - Some of these values are holy and must not be changed without
     also changing the corresponding code in diff2.c.

   - Where these entries semantically overlap with their
     older/deprecated fsl_diff_flag_e counterparts, they MUST (for the
     sake of avoiding client-side Grief) have the same values because
     some internal APIs are used by both of the diff APIs.

  @see fsl_dibu_impl_flags_e

   TODO?:

   - Move the diff-builder-specific flags from here to, possibly, the
     fsl_dibu::implFlags member or a new flag member dedicated to this
     type of flag.
*/
enum fsl_diff2_flag_e {
/** Ignore end-of-line whitespace. Applies to all diff builders. */
FSL_DIFF2_IGNORE_EOLWS = 0x01,
/** Ignore all whitespace. Applies to all diff builders.  */
FSL_DIFF2_IGNORE_ALLWS = 0x03,
/** Suppress optimizations (debug). Applies to
    all diff builders. */
FSL_DIFF2_NOOPT =        0x0100,
/** Invert the diff. Applies to all diff builders. */
FSL_DIFF2_INVERT =       0x0200,
/** Use context line count even if it's zero. Applies to all diff
    builders. Normally a value of 0 is treated as the built-in
    default. */
FSL_DIFF2_CONTEXT_ZERO =  0x0400,
/**
   Only calculate diff if it's not "too big", meaning more than 10000
   lines inserted or deleted, as in fossil(1). Applies to all diff
   builders and will cause the public APIs which hit this to return
   FSL_RC_RANGE.
*/
FSL_DIFF2_NOTTOOBIG =    0x0800,
/**
   Strip trailing CR before diffing. Applies to all diff builders.
*/
FSL_DIFF2_STRIP_EOLCR =    0x1000,
/*
  ACHTUNG: do not use 0x2000 because it would semantically collide
  with FSL_DIFF_ANSI_COLOR.
*/
/**
   More precise but slower side-by-side diff algorithm, for diffs
   which use that.
*/
FSL_DIFF2_SLOW_SBS =       0x4000,
/**
   Tells diff builders which support it to include line numbers in
   their output.
*/
FSL_DIFF2_LINE_NUMBERS = 0x10000,
/**
   Tells diff builders which optionally support an "index" line
   to NOT include it in their output.
*/
FSL_DIFF2_NOINDEX = 0x20000,

/**
   Reserved for client-defined diff builder use.
*/
FSL_DIFF2_CLIENT1 = 0x01000000,
/**
   Reserved for client-defined diff builder use.
*/
FSL_DIFF2_CLIENT2 = 0x02000000,
/**
   Reserved for client-defined diff builder use.
*/
FSL_DIFF2_CLIENT3 = 0x04000000,
/**
   Reserved for client-defined diff builder use.
*/
FSL_DIFF2_CLIENT4 = 0x08000000
};

/**
   Flags for use with various concrete fsl_dibu implementations.
   Specifically, these are flags for fsl_dibu::implFlags (as opposed
   to fsl_dibu::pimplFlags, which must not be modified by clients).

   Note that it is perfectly legitimate for different entries to have
   the same values, but different semantics, so long as the different
   entries are specific to different fsl_dibu types.
*/
enum fsl_dibu_impl_flags_e {
/**
   Tells the TCL diff builder that the complete output and each line
   should be wrapped in {...}.
*/
FSL_DIBU_TCL_BRACES = 0x01,
/**
   Tells the TCL diff builder that the squiggly braces embedded in any
   output (as opposed to the braces added by FSL_DIBU_TCL_BRACES)
   need to be backslash-escaped. Whether this is required depends on
   how the output will be used.
*/
FSL_DIBU_TCL_BRACES_ESC = 0x02,
/**
   Tells the TCL diff builder to generate a complete TCL/TK app as output.
   The resulting script can (if tcl and tk are installed) be run with
   tclsh to get a graphical diff.

   Note that this flag includes both FSL_DIBU_TCL_BRACES and
   FSL_DIBU_TCL_BRACES_ESC.
*/
FSL_DIBU_TCL_TK = 0x07

};

/**
   An instance of this class is used to convey certain state to
   fsl_dibu objects. Some of this state is configuration
   provided by the client and some is volatile, used for communicating
   common state to diff builder instances during the diff rendering
   process.

   Certain fsl_dibu implementations may require that some
   ostensibly optional fields be filled out. Documenting that is TODO,
   as the builders get developed.
*/
struct fsl_dibu_opt {
  /**
     Flags from the fsl_diff2_flag_e enum.
  */
  uint32_t diffFlags;
  /**
     Number of lines of diff context (number of lines common to the
     LHS and RHS of the diff). Library-wide default is 5.
  */
  unsigned short contextLines;
  /**
     Maximum column width hint for side-by-side, a.k.a. split, diffs.

     FSL_DIBU_SPLIT_TEXT truncates its content columns (as
     opposed to line numbers and its modification marker) to, at most,
     this width. By default it uses as much width as is necessary to
     render whole lines. It treats this limit as UTF8 characters, not
     bytes.

     This is a hint, not a rule. A given diff builder is free to
     ignore it or to ignore values which are arbitrarily deemed "too
     small" or "too large."
  */
  unsigned short columnWidth;
  /**
     The filename of the object represented by the LHS of the
     diff. This is intentended for, e.g., generating header-style
     output. This may be NULL.
  */
  const char * nameLHS;
  /**
     The hash of the object represented by the LHS of the diff. This
     is intentended for, e.g., generating header-style output. This
     may be NULL.
  */
  const char * hashLHS;
  /**
     The filename of the object represented by the LHS of the
     diff. This is intentended for, e.g., generating header-style
     output. If this is NULL but nameLHS is not then they are assumed
     to have the same name.
  */
  const char * nameRHS;
  /**
     The hash of the object represented by the RHS of the diff. This
     is intentended for, e.g., generating header-style output. This
     may be NULL.
  */
  const char * hashRHS;
  /**
     Output destination. Any given builder might, depending on how it
     actually constructs the diff, buffer output and delay calling
     this until its finish() method is called.

     Note that not all diff builders use this. e.g. a diff builder
     which outputs to an ncurses widget cannot do so via this method
     and instead has to use the drawing methods of that API. Thus is
     is legal for this method to be NULL for some builders.
  */
  fsl_output_f out;
  /**
     State for this->out(). Ownership is unspecified by this
     interface: it is for use by this->out() but what is supposed to
     happen to it after this object is done with it depends on
     higher-level code.
  */
  void * outState;
  /**
     EXPERIMENTAL AND SUBJECT TO CHANGE.

     Optional ANSI color control sequences to be injected into
     text-mode diff output by diff builders which support them. All
     members of this struct must either be NULL, an empty string, or a
     valid ANSI escape sequence. The reset option must be the escape
     sequence to reset either just the color or to reset all ANSI
     control attributes, depending on how the other members are
     set. If any member other than reset is set, all must be set.

     The diff driver will treat any members of this which are NULL as
     empty strings to simplify diff builder color integration. The
     exception is the reset member - see its docs for details.
  */
  struct fsl_dibu_opt_ansi {
    /**
       Color escape sequence for inserted lines.
    */
    char const * insertion;
    /**
       Color escape sequence for edited or replaced lines. This option
       might be ignored, depending on how the renderer works. Some
       will render edits as a deletion/insertion pair.
    */
    char const * edit;
    /**
       Color escape sequence for inserted lines.
    */
    char const * deletion;
    /**
       Escape sequence to reset colors. If reset is empty or NULL and
       any others are not then reset is automatically treated as if it
       were the ANSI code to reset all color attributes.
    */
    char const * reset;
  } ansiColor;
};

/** Convenience typedef. */
typedef struct fsl_dibu_opt fsl_dibu_opt;

/** Initialized-with-defaults fsl_dibu_opt structure, intended for
    const-copy initialization. */
#define fsl_dibu_opt_empty_m {\
  0/*diffFlags*/, 5/*contextLines*/, 0/*columnWidth*/,\
  NULL/*nameLHS*/,NULL/*hashLHS*/,                       \
  NULL/*nameRHS*/, NULL/*hashRHS*/,                      \
  NULL/*out*/, NULL/*outState*/,                          \
  {/*ansiColor*/ ""/*insertion*/,""/*edit*/,""/*deletion*/,\
    ""/*reset*/}                                                \
}

/** Initialized-with-defaults fsl_dibu_opt structure, intended for
    non-const copy initialization. */
extern const fsl_dibu_opt fsl_dibu_opt_empty;

/**
   Information about each line of a file being diffed.

   This type is only in the public API for use by the fsl_dibu
   interface, specifically for use with fsl_dline_change_spans(). It
   is not otherwise intended for public use. None of its members are
   considered even remotely public except for this->z and this->n.
*/
struct fsl_dline {
  /**
      The text of the line. Owned by higher-level code.  Not
      necessarily NUL-terminated: this->n holds its length.
  */
  const char *z;
  /** Number of bytes of z which belong to this line. */
  unsigned short n;
  // All members after this point are strictly for internal use only.
  /** Index of first non-space char. */
  unsigned short indent;
  /** Number of bytes without leading/trailing space. */
  unsigned short nw;
  /** Hash of the line. Lower X bits are the length. */
  uint64_t h;
  /** 1+(Index of next line with same the same hash) */
  unsigned int iNext;
  /**
     An array of fsl_dline elements serves two purposes.  The fields
     above are one per line of input text.  But each entry is also
     a bucket in a hash table, as follows:
  */
  unsigned int iHash;   /* 1+(first entry in the hash chain) */
};

/**
   Convenience typedef.
*/
typedef struct fsl_dline fsl_dline;
/** Initialized-with-defaults fsl_dline structure, intended for
    const-copy initialization. */
#define fsl_dline_empty_m {NULL,0U,0U,0U,0U,0U,0U}
/** Initialized-with-defaults fsl_dline structure, intended for
    non-const copy initialization. */
extern const fsl_dline fsl_dline_empty;

/**
   Maximum number of change spans for fsl_dline_change.
*/
#define fsl_dline_change_max_spans 8

/**
   This "mostly-internal" type describes zero or more (up to
   fsl_dline_change_max_spans) areas of difference between two lines
   of text. This type is only in the public API for use with concrete
   fsl_dibu implementations.
*/
struct fsl_dline_change {
  /** Number of change spans (number of used elements in this->a). */
  unsigned char n;
  /** Array of change spans, in left-to-right order */
  struct fsl_dline_change_span {
    /* Reminder: int instead of uint b/c some ported-in algos use
       negatives. */
    /** Byte offset to start of a change on the left */
    int iStart1;
    /** Length of the left change in bytes */
    int iLen1;
    /** Byte offset to start of a change on the right */
    int iStart2;
    /** Length of the change on the right in bytes */
    int iLen2;
    /** True if this change is known to have no useful subdivs */
    int isMin;
  } a[fsl_dline_change_max_spans];
};

/**
   Convenience typedef.
*/
typedef struct fsl_dline_change fsl_dline_change;

/** Initialized-with-defaults fsl_dline_change structure, intended for
    const-copy initialization. */
#define fsl_dline_change_empty_m { \
  0, {                                                \
    {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}, \
    {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0} \
  } \
}

/** Initialized-with-defaults fsl_dline_change structure, intended for
    non-const copy initialization. */
extern const fsl_dline_change fsl_dline_change_empty;

/**
   Given two lines of a diff, this routine computes a set of changes
   between those lines for display purposes and writes a description
   of those changes into the 3rd argument. After returning, p->n
   contains the number of elements in p->a which were populated by
   this routine.

   This function is only in the public API for use with
   fsl_dibu objects. It is not a requirement for such objects
   but can be used to provide more detailed diff changes than marking
   whole lines as simply changed or not.
*/
FSL_EXPORT void fsl_dline_change_spans(const fsl_dline *pLeft,
                                       const fsl_dline *pRight,
                                       fsl_dline_change *  p);

/**
   Compares two fsl_dline instances using memcmp() semantics,
   returning 0 if they are equivalent.

   @see fsl_dline_cmp_ignore_ws()
*/
FSL_EXPORT int fsl_dline_cmp(const fsl_dline *  pA,
                             const fsl_dline *  pB);

/**
   Counterpart of fsl_dline_cmp() but ignores all whitespace
   when comparing for equivalence.
*/
FSL_EXPORT int fsl_dline_cmp_ignore_ws(const fsl_dline *  pA,
                                       const fsl_dline *  pB);

/**
   Breaks the first n bytes of z into an array of fsl_dline records,
   each of which refers back to z (so it must remain valid for their
   lifetime). If n is negative, fsl_strlen() is used to calculate
   z's length.

   The final argument may be any flags from the fsl_diff2_flag_e
   enum, but only the following flags are honored:

   - FSL_DIFF2_STRIP_EOLCR
   - FSL_DIFF2_IGNORE_EOLWS
   - FSL_DIFF2_IGNORE_ALLWS

   On success, returns 0, assigns *pnLine to the number of lines, and
   sets *pOut to the array of fsl_dline objects, transfering ownership
   to the caller, who must eventually pass it to fsl_free() to free
   it.

   If z is NULL or n is 0, the input is assumed to be empty, 0 is returned,
   (*pOut) will be set to NULL, and (*pnLine) will be set to 0.

   On error, neither (*pnLine) nor (*pOut) are modified and returns one
   of:

   - FSL_RC_DIFF_BINARY if the input appears to be non-text.
   - FSL_RC_OOM on allocation error.
*/
FSL_EXPORT int fsl_break_into_dlines(const char *z, fsl_int_t n,
                                     uint32_t *pnLine,
                                     fsl_dline **pOut, uint64_t diff2Flags);

/** Convenience typedef. */
typedef struct fsl_dibu fsl_dibu;

/**
   This class is the basis of libfossil's port of the diff engine
   added to fossil(1) in 2021-09, colloquially known as the "diff
   builder."

   A diff builder is an object responsible for formatting low-level
   diff info another form, typically for human readability but also
   for machine readability (patches). The library generates a
   low-level diff then feeds that through an algorithm which
   determines which methods of this class to call, delegating all
   rendering of the diff to an instance of this class.

   The internal APIs which drive each instance of this class guaranty
   that if any method of this class returns non-0 (an error code) then
   no futher methods will be called except for finalize().
*/
struct fsl_dibu {
  /**
     Config info, owned by higher-level routines. Every diff builder
     requires one of these but not all options are relevant for all
     builders.

     Note that the diff driver may make a bitwise copy of this object
     and use _that_ one for the actual diff generation. That is,
     methods of this class must never assume that this member's
     pointer refers to a specific object. (This leeway is necessary in
     order to implement diff inversion (swapping the LHS/RHS of a
     diff).)
  */
  fsl_dibu_opt const * opt;
  /**
     Can optionally be set by factory functions to some internal
     opaque value, so that non-member routines specific to that type can determine
     whether any given builder is of the proper type.
  */
  void const * typeID;
  /**
     If not NULL, this is called once per pass per diff to give the
     builder a chance to perform any bootstrapping initialization or
     header output. At the point this is called, this->cfg is assumed
     to have been filled out properly. Diff builder implementations
     which require dynamic resource allocation may perform it here or
     in their factory routine(s).

     b->lnLHS and b->lnRHS will be set to 0 before each call.

     This method should also reset any dynamic state of a builder so
     that it may be reused for subsequent diffs. This enables the API
     to use a single builder for a collection of logically grouped
     files without having to destroy and reallocate the builder.

     Must return 0 on success, non-0 on error. If it returns non-0,
     the only other method of the instance which may be legally called
     is finalize().

     The diff driver sets this->lnLHS and this->lnRHS to 0 before
     calling this.
  */
  int (*start)(fsl_dibu *  b);

  /**
     If this is not NULL, it is called one time at the start of each
     chunk of diff for a given file and is passed the line number of
     each half of the diff and the number of lines in that chunk for
     that half (including insertions and deletions). This is primarily
     intended for generating conventional unified diff chunk headers
     in the form:

     ```
     @@ -A,B +C,D @@
     ```

     The inclusion of this method in an object might preclude certain
     other diff formatting changes which might otherwise apply.
     Notably, if the span between two diff chunks is smaller than the
     context lines count, the diff builder driver prefers to merge
     those two chunks together. That "readability optimization" is
     skipped when this method is set because this method may otherwise
     report that lines are being skipped which then subsequently get
     output by the driver.

     Must return 0 on success, non-0 on error.
  */
  int (*chunkHeader)(fsl_dibu* ,
                     uint32_t A, uint32_t B,
                     uint32_t C, uint32_t D);

  /**
     Tells the builder that n lines of common output are to be
     skipped. How it represents this is up to the impl. Must return 0
     on success, non-0 on error.

     Typical common implementation details:

     - Increment both this->lnLHS and this->lnRHS by n.
  */
  int (*skip)(fsl_dibu* , uint32_t n);
  /**
     Tells the builder that the given line represents one line of
     common output. Must return 0 on success, non-0 on error.

     Typical common implementation details:

     - Increment both this->lnLHS and this->lnRHS by 1.
  */
  int (*common)(fsl_dibu* , fsl_dline const * line);
  /**
     Tells the builder that the given line represents an "insert" into
     the RHS. Must return 0 on success, non-0 on error.

     Typical common implementation details:

     - Increment this->lnRHS by 1.
  */
  int (*insertion)(fsl_dibu* , fsl_dline const * line);
  /**
     Tells the builder that the given line represents a "deletion" - a
     line removed from the LHS. Must return 0 on success, non-0 on
     error.

     Typical common implementation details:

     - Increment this->lnLHS by 1.
  */
  int (*deletion)(fsl_dibu* , fsl_dline const * line);
  /**
     Tells the builder that the given line represents a replacement
     from the LHS to the RHS. Must return 0 on success, non-0 on
     error. This differs from an "edit" in that the line being
     replaced seems to have on relationship to the replacement. Even
     so, builders are free to represent replacements and edits
     identically, and are free to represent either or both as a pair
     of deletion/insertion operations.

     Typical common implementation details:

     - Increment both this->lnLHS and this->lnRHS by 1.
  */
  int (*replacement)(fsl_dibu* , fsl_dline const * lineLhs,
                     fsl_dline const * lineRhs);
  /**
     Tells the builder that the given line represents an "edit" from
     the LHS to the RHS. Must return 0 on success, non-0 on
     error. Builders are free, syntax permitting, to use the
     fsl_dline_change_spans() API to elaborate on edits for display
     purposes, to treat it identically to this->replacement(), or to
     treat this as a single pair of calls to this->deletion() and
     this->insertion(). In the latter case they simply need to pass
     lineLhs to this->deletion() and lineRhs to this->insertion().

     Typical common implementation details:

     - Increment both this->lnLHS and this->lnRHS by 1.
  */
  int (*edit)(fsl_dibu* , fsl_dline const * lineLhs,
              fsl_dline const * lineRhs);
  /**
     Must "finish" the diff process. Depending on the diff impl, this
     might flush any pending output or may be a no-op. This is only
     called if the rest of the diff was generated without producing an
     error result.

     This member may be NULL.

     Implementations are free to collect all of their output in an
     internal representation and delay flushing it until this routine
     is called.

     Must return 0 on success, non-0 on error (e.g. output flushing
     fails).

     Minor achtung: for a multi-file diff run, this gets called after
     each file. The library does not have enough information to know
     when a builder is "done for good" and if a custom builder
     requires, e.g., extra post-diff-loop processing, the client will
     have to take care of that themselves.
  */
  int (*finish)(fsl_dibu*  b);
  /**
     This optional method is similar to this->finish() but it is not
     called by the library. It is intended to be called, if it's not
     NULL, by the client after they are done, e.g., looping over a
     series of diffs with the same builder. Some builders can use this
     to flush any final state, e.g. dumping out change count totals or
     some such.

     As an example, the TCL/TK-based builder, when the FSL_DIBU_TCL_TK
     flag is set on this->implFlag, embeds a TK script in the output
     from this method.
  */
  int (*finally)(fsl_dibu*  b);
  /**
     Must free any state owned by this builder, including the builder
     object. It must not generate any output.
  */
  void (*finalize)(fsl_dibu* );
  /**
     If true, this builder gets passed through the diff generation
     process twice. See this->passNumber for details.
  */
  bool twoPass;
  /**
     Gets set to the "pass number" immediately before this->start() is
     called, starting with pass number 1. This value is only relevant
     for two-pass builders, which can use this to control their mode
     of operation, e.g. data collection in pass 1 and actual work in
     pass 2. Note that all of the diff-building API methods are called
     for both passes, including start() and finish().  Only finalize()
     and finally() are not affected by this.
  */
  unsigned short passNumber;
  /**
     Impl-specific diff-generation state. If it is owned by this
     instance then this->finalize() must clean it up.
  */
  void * pimpl;
  /**
     Space for private, implementation-specific flags, e.g. for
     tracking basic output state, e.g. of opening/closing tags. This
     must not be modified by clients.
  */
  unsigned int pimplFlags;
  /**
     Space for implementation-specific flags which clients may set to
     modify the dibu's behaviour. This is different from
     fsl_dibu_opt::diffFlags in that these flags are specific to a
     given dibu type. See the fsl_dibu_impl_flags_e enum for the list
     of flags for the library-provided diff builders.
  */
  unsigned int implFlags;
  /**
     A place to store the number of files seen by this builder so far,
     for builders which need to distinguish that somehow (e.g. adding
     a separator before each file after the first). Implementations
     which use this should increment it in their start() method.

     Maintenance reminder/TODO: we can't increment this from the main
     diff driver because... we possibly could, but we'd need to patch
     the various diff builders which currently do this themselves.
     The main diff driver doesn't have enough info to know when to set
     it, though. That "could" be done in this->finally() but that
     method is optional.
  */
  uint32_t fileCount;
  /**
     Number of lines seen of the LHS content. It is up to the concrete
     builder impl to update this if it's needed. The core diff driver
     sets this to 0 before calling this->start().
  */
  uint32_t lnLHS;
  /**
     Number of lines seen of the RHS content. It is up to the concrete
     builder impl to update this if it's needed. The core diff driver
     sets this to 0 before calling this->start().
  */
  uint32_t lnRHS;

  /**
     Metrics maintained by the core diff algorithm. These are updated
     during the first pass through a given fsl_diff_v2() run. They are
     NEVER reset by the builder algo because it cannot know if the
     user wants a running total or a per-file total. Clients running
     diffs in a loop may want to reset them on each loop. The simplest
     way is to cop fsl_dibu_empty.metrics over them. It is legal for a
     given builder to reset these in their start(), finish(), or
     finally() methods, depending on how the builder is used.

     Note that all metrics apply to the RHS version, not the LHS.
  */
  struct {
    /** Number of lines inserted performed so far. */
    uint32_t insertions;
    /** Number of lines deleted so far. */
    uint32_t deletions;
    /** Number of line-level edits performed so far. */
    uint32_t edits;
    /** Number of line replacements performed so far.
        These are different from edits in that the whole line
        differs in the LHS/RHS. */
    uint32_t replacements;
  } metrics;
};

/** Initialized-with-defaults fsl_dibu structure, intended for
    const-copy initialization. */
#define fsl_dibu_empty_m { \
  NULL/*opt*/,NULL/*typeID*/,                                         \
  NULL/*start()*/,NULL/*chunkHeader()*/,NULL/*skip()*/, NULL/*common()*/, \
  NULL/*insertion()*/,NULL/*deletion()*/, NULL/*replacement()*/, \
  NULL/*edit()*/, NULL/*finish()*/, NULL/*finally()*/,NULL/*finalize()*/, \
  false/*twoPass*/,0U/*passNumber*/, \
  NULL/*pimpl*/, 0U/*pimplFlags*/,0U/*implFlags*/,0U/*fileCount*/,         \
  0/*lnLHS*/,0/*lnRHS*/,                                              \
  {/*metrics*/0,0,0,0} \
}

/** Initialized-with-defaults fsl_dibu structure, intended for
    non-const copy initialization. */
extern const fsl_dibu fsl_dibu_empty;

/**
   Type IDs for use with fsl_dibu_factory().
*/
enum fsl_dibu_e {
/**
   Sentinel entry.
*/
FSL_DIBU_INVALID = 0,
/**
   A "dummy" diff builder intended only for testing the
   fsl_dibu interface and related APIs. It does not produce
   output which is generically useful.
*/
FSL_DIBU_DEBUG = 1,
/**
   Generates diffs in a compact low(ist)-level form originally
   designed for use by diff renderers implemented in JavaScript.

   This diff builder outputs a JSON object with the following
   properties:

   - hashLHS, hashRHS: the hashes of the LHS/RHS content.

   - nameLHS, nameRHS: the filenames of the LHS/RHS. By convention, if
     the RHS is NULL but the LHS is not, both sides have the same
     name.

   - diff: raw diff content, an array with the structure described
     below.

   Note that it is legal for the names and hashes to be "falsy" (null,
   not set, or empty strings).

   The JSON array consists of integer opcodes with each opcode
   followed by zero or more arguments:

   ```
   Syntax        Mnemonic    Description

   -----------   --------    --------------------------
   0             END         This is the end of the diff.
   1  INTEGER    SKIP        Skip N lines from both files.
   2  STRING     COMMON      The line STRING is in both files.
   3  STRING     INSERT      The line STRING is in only the right file.
   4  STRING     DELETE      The line STRING is in only the left file.
   5  SUBARRAY   EDIT        One line is different on left and right.
   ```

   The SUBARRAY is an array of 3*N+1 strings with N>=0.  The triples
   represent common-text, left-text, and right-text.  The last string
   in SUBARRAY is the common-suffix.  Any string can be empty if it
   does not apply.
*/
FSL_DIBU_JSON1,

/**
   A diff builder which produces output compatible with the patch(1)
   command. Its output is functionally identical to fossil(1)'s
   default diff output except that by default includes an Index line
   at the top of each file (use the FSL_DIFF2_NOINDEX flag in its
   fsl_dibu_opt::diffFlags to disable that).

   Supported flags:

   - FSL_DIFF2_LINE_NUMBERS (makes it incompatible with patch(1))
   - FSL_DIFF2_NOINDEX
*/
FSL_DIBU_UNIFIED_TEXT,

/**
   A diff builder which outputs a description of the diff in a
   TCL-readable form. It requires external TCL code in order to
   function.
*/
FSL_DIBU_TCL,
/**
   A pain-text side-by-side (a.k.a. split) diff view. This diff always
   behaves as if the FSL_DIFF2_LINE_NUMBERS flag were set because its
   output is fairly useless without line numbers. It optionally
   supports ANSI coloring.
*/
FSL_DIBU_SPLIT_TEXT
};
typedef enum fsl_dibu_e fsl_dibu_e;

/**
   A factory for creating fsl_dibu instances of types which
   are built in to the library. This does not preclude the creation of
   client-side diff builders (e.g. ones which write to ncurses widgets
   or similar special-case output).

   On success, returns 0 and assigns *pOut to a new builder instance
   which must eventually be freed by calling its pOut->finalize()
   method. On error, returns non-0 and *pOut is not modified. Error
   codes include FSL_RC_OOM (alloc failed) and FSL_RC_TYPE (unknown
   type ID), FSL_RC_TYPE (type is not (or not yet) implemented).
*/
FSL_EXPORT int fsl_dibu_factory( fsl_dibu_e type,
                                 fsl_dibu **pOut );

/**
   Base allocator for fsl_dibu instances. If extra is >0 then
   that much extra space is allocated as part of the same memory block
   and the pimpl member of the returned object is pointed to that
   space. Example (OOM handling elided for legibility):

   ```
   struct MyState { int x; int y; };
   typedef struct MyState MyState;
   fsl_dibu * b = fsl_dibu_alloc(sizeof(MyState));
   MyState * my = (MyState*)b->pimpl;
   my->x = 1;
   my->y = 2;
   ... populate b's members ...
   ... use b, then clean it up ...
   b->finalize(b);
   ```

   From within b's methods, the custom state can be accessed via its
   `pimpl` member.

   @see fsl_dibu_finalizer()
*/
FSL_EXPORT fsl_dibu * fsl_dibu_alloc(fsl_size_t extra);

/**
   This is a generic finalizer function for use as a
   fsl_dibu::finalize() method. It simply zeroes out b and
   passes it fsl_free(). This is suitable for builders created using
   fsl_dibu_alloc() _only_ if their custom state manages no
   extra memory. If they manage any custom memory then the require a
   custom, type-specific finalizer method.
*/
FSL_EXPORT void fsl_dibu_finalizer(fsl_dibu *  b);

/**
   This counterpart of fsl_diff_text() defines its output format in
   terms of a fsl_dibu instance which the caller must provide.
   The caller is responsible for pointing pBuilder->opt to a
   configuration object suitable for the desired diff. In particular,
   pBuilder->opt->out and (if necessary) pBuilder->opt->outState must
   be set to non-NULL values.

   This function generates a low-level diff of two versions of content,
   contained in the given buffers, and passes that diff through the
   given diff builder to format it.

   Returns 0 on success. On error, it is not generally knowable whether
   or not any diff output was generated. This function has no error
   object, so it sets no error message: the caller reports the
   failure, naming the inputs.

   The builder may produce any error codes it wishes, in which case
   they are propagated back to the caller. Common error codes include:

   - FSL_RC_OOM if an allocation fails.

   - FSL_RC_RANGE if the diff is "too big" and
   pBuilder->opt->diffFlags contains the FSL_DIFF2_NOTTOOBIG flag.

   - FSL_RC_DIFF_WS_ONLY if pBuilder->opt->diffFlags contains
   FSL_DIFF2_IGNORE_ALLWS and the inputs differ only in whitespace
   or are identical and non-empty. No output is generated in that
   case.

   - FSL_RC_MISUSE if pv1 or pv2 is NULL.

   - FSL_RC_DIFF_BINARY if the to-diff content appears to be binary,
   noting that "appears to be" is heuristric-driven and subject to
   false positives. Specifically, files with extremely long lines will
   be recognized as binary (and are, in any case, generally less than
   useful for most graphical diff purposes).

   @see fsl_dibu_factory()
   @see fsl_diff_text()
   @see fsl_diff_v2_raw()
*/
FSL_EXPORT int fsl_diff_v2(fsl_b const * pv1,
                           fsl_b const * pv2,
                           fsl_dibu *  pBuilder);

/**
   Performs a diff, as for fsl_diff_v2(), but returns the results in
   the form of an array of COPY, DELETE, INSERT triples terminated by
   3 entries with the value 0.

   Each triple in the list specifies how many *lines* of each half of
   the diff (the first 2 arguments to this function) to COPY as-is
   (common code), DELETE (exists in the LHS but not in the RHS), and
   INSERT (exists in the RHS but not in the LHS). By breaking the
   input into lines and following these values, a line-level text-mode
   diff of the two blobs can be generated.

   See fsl_diff_v2() for the details, all of which apply except for
   the output:

   - cfg may be NULL, in which case fsl_dibu_opt_empty is used.

   - cfg->out is ignored.

   - On success, *outRaw is assigned to the output array and ownership
     of it is transfered to the caller, who must eventually pass it to
     fsl_free() to free it.

*/
FSL_EXPORT int fsl_diff_v2_raw(fsl_b const * pv1,
                               fsl_b const * pv2,
                               fsl_dibu_opt const * cfg,
                               int **outRaw );

/**
   If zDate is an ISO8601-format string, optionally with a .NNN
   fractional suffix, then this function returns true and sets
   *pOut (if pOut is not NULL) to the corresponding Julian
   value. If zDate is not an ISO8601-format string then this
   returns false and pOut is not modified. A field out of range
   (month 01-12, day 01-31, hour 00-24, minute and second 00-59) also
   makes it return false. The day is not checked against the month,
   so 2024-02-31 is accepted, as it is by fossil(1).

   This function does NOT confirm that zDate ends with a NUL
   byte. i.e.  if passed a valid date string which has trailing
   bytes after it then those are simply ignored. This is so that it
   can be used to read subsets of larger strings.

   Achtung: this calculation may, due to voodoo-level
   floating-point behaviours, differ by a small fraction of a point
   (at the millisecond level) for a given input compared to other
   implementations (e.g. sqlite's strftime() _might_ differ by a
   millisecond or two or _might_ not). Thus this routine should not
   be used when 100% round-trip fidelity is required, but is close
   enough for routines which do not require 100% millisecond-level
   fidelity in time conversions.

   @see fsl_julian_to_iso8601()
*/
FSL_EXPORT bool fsl_iso8601_to_julian( char const * zDate, double * pOut );

/**
    Converts the Julian Day J to an ISO8601 time string. If addMs is
    true then the string includes the '.NNN' fractional part, else
    it will not. This function writes (on success) either 20 or 24
    bytes (including the terminating NUL byte) to pOut, depending on
    the value of addMs, and it is up to the caller to ensure that
    pOut is at least that long.

    Returns true (non-0) on success and the only error conditions
    [it can catch] are if pOut is NULL, J is less than 0, or
    evaluates to a time value which does not fit in ISO8601
    (e.g. only years 0-9999 are supported).

    @see fsl_iso8601_to_julian()
*/
FSL_EXPORT bool fsl_julian_to_iso8601( double J, char * pOut, bool addMs );

/**
   Returns the Julian Day time J value converted to a Unix Epoch
   timestamp. It assumes 86400 seconds per day and does not account
   for leap seconds, leap years, leap frogs, or any other kind of
   leap, up to and including leaps of faith.
*/
FSL_EXPORT fsl_time_t fsl_julian_to_unix( double J );

/**
   Performs a chdir() to the directory named by zChDir.

   Returns 0 on success. On error it tries to convert the
   underlying errno to one of the FSL_RC_xxx values, falling
   back to FSL_RC_IO if it cannot figure out anything more
   specific.
*/
FSL_EXPORT int fsl_chdir(const char *zChDir);

/**
   Works like fsl_chdir(zTo) but passes (zCurrent,nCurrent,NULL) to
   fsl_getcwd() to save the current dir name. Returns non-0 if either
   fsl_getcwd() or fsl_chdir() fails. To "pop" the dir just
   fsl_chdir() to zCurrent.
*/
FSL_EXPORT int fsl_chdir2(const char *zTo, char * zCurrent, fsl_size_t nCurrent);

/**
   A custom strftime() implementation.

   dest must be valid memory at least destLen bytes long. The result
   will be written there.

   fmt must contain the format string. See the source file strftime.c
   for the complete list of format specifiers and their descriptions.

   timeptr must be the time the caller wants to format.

   Returns 0 if any arguments are NULL.

   On success it returns the number of bytes written to dest, not
   counting the terminating NUL byte (which it also writes). It
   returns 0 on any error, and the client may need to distinguish
   between real errors and (destLen==0 or !*fmt), both of which could
   also look like errors.

   TODOs:

   - Refactor this to take a callback or a fsl_b, so that we can
   format arbitrarily long output.

   - Refactor it to return an integer error code.

   (This implementation is derived from public domain sources
   dating back to the early 1990's.)
*/
FSL_EXPORT fsl_size_t fsl_strftime(char *dest, fsl_size_t destLen,
                                   const char *format,
                                   const struct tm *timeptr);

/**
   A convenience form of fsl_strftime() which takes its timestamp in
   the form of a Unix Epoch time. See fsl_strftime() for the
   semantics of the first 3 arguments and the return value. If
   convertToLocal is true then epochTime gets converted to local
   time (via, oddly enough, localtime(3)), otherwise gmtime(3) is
   used for the conversion.
*/
FSL_EXPORT fsl_size_t fsl_strftime_unix(char * dest, fsl_size_t destLen,
                                        char const * format,
                                        fsl_time_t epochTime,
                                        bool convertToLocal);


/**
   A convenience form of fsl_strftime() which assumes that the
   formatted string is of "some reasonable size" and appends its
   formatted representation to b. Returns 0 on success, non-0 on
   error. If any argument is NULL or !*format then FSL_RC_MISUSE is
   returned. FSL_RC_RANGE is returned if the underlying call to
   fsl_strftime() fails (which it will if the format string
   resolves to something "unususually long"). It returns FSL_RC_OOM
   if appending to b fails due to an allocation error.
*/
FSL_EXPORT int fsl_b_strftime(fsl_b *  b,
                                   char const * format,
                                   const struct tm *timeptr);

/**
   "whence" values for use with fsl_b_seek(). They are analog to
   the "whence" argument of fseek(2) but are not guaranteed to have
   the same values.
*/
enum fsl_b_seek_e {
FSL_B_SEEK_SET = 1,
FSL_B_SEEK_CUR = 2,
FSL_B_SEEK_END = 3
};
typedef enum fsl_b_seek_e fsl_b_seek_e;

/**
   "Seeks" b's internal cursor to a position specified by the given offset
   from either the current cursor position (FSL_B_SEEK_CUR), the start
   of the buffer (FSL_B_SEEK_SET), or the end (FSL_B_SEEK_END).
   If the cursor would be placed out of bounds, it will be placed at the start
   resp. end of the buffer.

   The "end" of a buffer is the value of its fsl_b::used member,
   i.e. its one-after-the-end marker, as opposed to the at-the-end
   marker. That is: a seek to FSL_B_SEEK_END with an offset of -1
   would leave the cursor at the last available byte, not
   one-past-the-end.

   Returns the new position.

   Note that most buffer algorithms, e.g. fsl_b_append(), do not
   modify the cursor. Only certain special-case algorithms use it.

   @see fsl_b_tell()
   @see fsl_b_rewind()
*/
FSL_EXPORT fsl_size_t fsl_b_seek(fsl_b *  b, fsl_int_t offset,
                                      fsl_b_seek_e  whence);

/**
   Returns the buffer's current cursor position.

   @see fsl_b_rewind()
   @see fsl_b_seek()
*/
FSL_EXPORT fsl_size_t fsl_b_tell(fsl_b const * b);

/**
   Resets b's cursor to the beginning of the buffer.

   @see fsl_b_tell()
   @see fsl_b_seek()
*/
FSL_EXPORT void fsl_b_rewind(fsl_b *  b);

/**
   Read from buf until consuming a character matching delim, which must
   be representable as an unsigned char. The consumed bytes, including any
   matching delim character, are stored in *ret, and a terminating NUL
   added when the delimiter or end-of-buffer is encountered.

   If *retsz is non-zero, *ret must either be pre-allocated to at least
   *retsz bytes, or be a NULL pointer. *ret must be passable to fsl_free();
   it is grown as needed as if by fsl_realloc() and *retsz updated with
   its new size. It is the caller's responsiblity to fsl_free() *ret when
   it is no longer needed. Even on failure, *ret may be updated.

   Return the number of bytes read, including any matched delim character.
   If no bytes were read and the stream is at end-of-buffer, return -1.
   If an error occurs, return -1 and set buf->errCode to indicate the error.

   n.b. This routine matches getdelim(3) semantics. Callers must check
   buf->errCode to distinguish between end-of-buffer and error.
   https://pubs.opengroup.org/onlinepubs/9799919799/functions/getdelim.html

   Example:

   ```
   char *line = NULL;
   size_t sz = 0;
   ssize_t len;

   while ((len = fsl_b_getdelim(&line, &sz, '\n', &buf)) != -1)
     fprintf(stdout, "line (%ld bytes): %s\n", len, line);

   fsl_free(line);
   if (fsl_b_err(&buf))
     errx(buf.errCode, "fsl_b_getdelim: %s", fsl_rc_cstr(buf.errCode));
   ```

   @see fsl_b_getline()
*/
FSL_EXPORT fsl_int_t fsl_b_getdelim(char **ret, size_t *retsz,
                                         int delim, fsl_b *buf);

/**
   Equivalent to fsl_b_getdelim() with `delim` equal to '\n'.

   @see fsl_b_getdelim()
*/
FSL_EXPORT fsl_int_t fsl_b_getline(char **ret, size_t *retsz,
                                        fsl_b *buf);

/**
   The "Path Finder" class is a utility class for searching the
   filesystem for files matching a set of common prefixes and/or
   suffixes (i.e. directories and file extensions).

   Example usage:

   ```
   fsl_pathfinder pf = fsl_pathfinder_empty;
   int rc;
   char const * found = NULL;
   rc = fsl_pathfinder_ext_add( &pf, ".doc" );
   if(rc) { ...error... }
   // The following error checks are elided for readability:
   rc = fsl_pathfinder_ext_add( &pf, ".txt" );
   rc = fsl_pathfinder_ext_add( &pf, ".wri" );
   rc = fsl_pathfinder_dir_add( &pf, "." );
   rc = fsl_pathfinder_dir_add( &pf, "/my/doc/dir" );
   rc = fsl_pathfinder_dir_add( &pf, "/other/doc/dir" );

   rc = fsl_pathfinder_search( &pf, "MyDoc", &found, NULL);
   if(0==rc){ assert(NULL!=found); }

   // Eventually clean up:
   fsl_pathfinder_clear(&pf);
   ```

   @see fsl_pathfinder_dir_add()
   @see fsl_pathfinder_ext_add()
   @see fsl_pathfinder_clear()
   @see fsl_pathfinder_search()
*/
struct fsl_pathfinder {
  /**
     Holds the list of search extensions. Each entry
     is a (char *) owned by this object.
  */
  fsl_list ext;
  /**
     Holds the list of search directories. Each entry is a (char *)
     owned by this object.
  */
  fsl_list dirs;
  /**
     Used to build up a path string during fsl_pathfinder_search(),
     and holds the result of a successful search. We use a buffer,
     as opposed to a simple string, because (A) it simplifies the
     search implementation and (B) reduces allocations (it gets
     reused for each search).
  */
  fsl_b buf;
};

typedef struct fsl_pathfinder fsl_pathfinder;
/**
   Initialized-with-defaults fsl_pathfinder instance, intended for
   const copy initialization.
*/
#define fsl_pathfinder_empty_m {\
  .ext = fsl_list_empty_m,      \
  .dirs = fsl_list_empty_m,     \
  .buf = fsl_b_empty_m     \
}

/**
   Initialized-with-defaults fsl_pathfinder instance, intended for
   copy initialization.
*/
FSL_EXPORT const fsl_pathfinder fsl_pathfinder_empty;

/**
   Frees all memory associated with pf, but does not free pf.
   Is a no-op if pf is NULL.
*/
FSL_EXPORT void fsl_pathfinder_clear(fsl_pathfinder *  pf);

/**
   Equivalent to fsl_pathfinder_dir_add2() with -1 as a final
   argument.

   @see fsl_pathfinder_ext_add()
   @see fsl_pathfinder_search()
*/
FSL_EXPORT int fsl_pathfinder_dir_add(fsl_pathfinder *  pf,
                                      char const * dir);

/**
   Adds the given directory to pf's search path. Returns 0 on
   success, FSL_RC_MISUSE if !pf or !dir (dir _may_ be an empty
   string), FSL_RC_OOM if copying the string or adding it to the
   list fails.

   If strLen is negative, fsl_strlen() is used to calculate the length
   of the string.

   @see fsl_pathfinder_ext_add()
   @see fsl_pathfinder_search()
*/
FSL_EXPORT int fsl_pathfinder_dir_add2(fsl_pathfinder *  pf, char const * dir,
                                       fsl_int_t strLen);

/**
   Adds the given directory to pf's search extensions. Returns 0 on
   success, FSL_RC_MISUSE if !pf or !dir (dir _may_ be an empty
   string), FSL_RC_OOM if copying the string or adding it to the
   list fails.

   Note that the client is responsible for adding a "." to the
   extension, if needed, as this API does not apply any special
   meaning to any characters in a search extension. e.g. "-journal"
   and "~" are both perfectly valid extensions for this purpose.

   @see fsl_pathfinder_dir_add()
   @see fsl_pathfinder_search()
*/
FSL_EXPORT int fsl_pathfinder_ext_add2(fsl_pathfinder *  pf, char const * ext,
                                       fsl_int_t strLen);

/**
   Equivalent to fsl_pathfinder_ext_add2() with -1 as a final
   argument.

   @see fsl_pathfinder_dir_add()
   @see fsl_pathfinder_search()
*/
FSL_EXPORT int fsl_pathfinder_ext_add(fsl_pathfinder *  pf,
                                      char const * ext);

/**
   Splits a conventional path-separator-delimited string into tokens
   and adds each as either a directory (if isDirs is true) or an
   extension in the given fsl_pathfinder object. Returns 0 on success,
   FSL_RC_OOM on allocation error. pathLen is the length of the path
   string. If it's negative, fsl_strlen() is used to calculate it.

   See fsl_path_splitter for the semantics of the splitting.
*/
FSL_EXPORT int fsl_pathfinder_split( fsl_pathfinder *  tgt,
                                     bool isDirs,
                                     char const * path,
                                     fsl_int_t pathLen );

/**
   Searches for a file whose name can be constructed by some
   combination of pf's directory/extension lists and the given base
   name.

   It searches for files in the following manner:

   If the 2nd parameter exists as-is in the filesystem, it is
   treated as a match, otherwise... Loop over all directories
   in pf->dirs. Create a path with DIR/base, or just base if
   the dir entry is empty (length of 0). Check for a match.
   If none is found, then... Loop over each extension in
   pf->ext, creating a path named DIR/baseEXT (note that it
   does not add any sort of separator between the base and the
   extensions, so "~" and "-foo" are legal extensions). Check
   for a match.

   On success (a readable filesystem entry is found):

   - It returns 0.

   - If pOut is not NULL then `*pOut` is set to the NUL-terminated
     path it found. The bytes of the returned string are only valid
     until the next search operation on pf, so copy them if you need
     them.  Note that the returned path is _not_ normalized via
     fsl_file_canonical_name() or similar, and it may very well return
     a relative path (if base or one of pf->dirs contains a relative
     path part). As a special case, if `base` is found as-is, without
     a lookup, `*pOut` is set to `base`, so has its lifetime.

   - If outLen is not NULL, *outLen will be set to the length of the
     returned string.

   On error:

   - Returns FSL_RC_MISUSE if !pf, !base, !*base.

   - Returns FSL_RC_OOM on allocation error (it uses a buffer to hold
     its path combinations and return value).

   - Returns FSL_RC_NOT_FOUND if it finds no entry.

   The host platform's customary path separator is used to separate
   directory/file parts ('\\' on Windows and '/' everywhere else).

   Note that it _is_ legal for pOut and outLen to both be NULL, in
   which case a return of 0 signals that an entry was found, but the
   client has no way of knowing what path it might be (unless, of
   course, they rely on internal details of the fsl_pathfinder API,
   which they most certainly should not do).

   Tip: if the client wants to be certain that this function will not
   allocate memory, simply use fsl_b_reserve() on pf->buf to
   reserve the desired amount of space in advance. As long as the
   search paths never surpass that length, this function will not need
   to allocate. (Until/unless the following TODO is implemented...)

   Potential TODO: use fsl_file_canonical_name() so that the search
   dirs themselves do not need to be entered using
   platform-specific separators. The main reason it's not done now
   is that it requires another allocation. The secondary reason is
   because it's sometimes useful to use relative paths in this
   context (based on usage in previous trees from which this code
   derives).

   @see fsl_pathfinder_dir_add()
   @see fsl_pathfinder_ext_add()
   @see fsl_pathfinder_clear()
*/
FSL_EXPORT int fsl_pathfinder_search(fsl_pathfinder *  pf,
                                     char const * base,
                                     char const ** pOut,
                                     fsl_size_t *  outLen );


/**
   A utility class for creating ZIP-format archives. All members
   are internal details and must not be mucked about with by the
   client. See fsl_zip_file_add() for an example of how to use it.

   Note that it creates ZIP content in memory, as opposed to
   streaming it (it is not yet certain if abstractly streaming a
   ZIP is possible), so creating a ZIP file this way is exceedingly
   memory-hungry.

   @see fsl_zip_file_add()
   @see fsl_zip_timestamp_set_julian()
   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_end()
   @see fsl_zip_body()
   @see fsl_zip_finalize()
*/
struct fsl_zip_writer {
  /**
     Number of entries (files + dirs) added to the zip file so far.
  */
  fsl_size_t entryCount;
  /**
     Current DOS-format time of the ZIP.
  */
  int32_t dosTime;
  /**
     Current DOS-format date of the ZIP.
  */
  int32_t dosDate;
  /**
     Current Unix Epoch time of the ZIP.
  */
  fsl_time_t unixTime;
  /**
     An artificial root directory which gets prefixed
     to all inserted filenames.
  */
  char * rootDir;
  /**
     The buffer for the table of contents.
  */
  fsl_b toc;
  /**
     The buffer for the ZIP file body.
  */
  fsl_b body;
  /**
     Internal scratchpad for ops which often allocate
     small buffers.
  */
  fsl_b scratch;
  /**
     The current list of directory entries (as (char *)).
  */
  fsl_list dirs;
};
typedef struct fsl_zip_writer fsl_zip_writer;

/**
   An initialized-with-defaults fsl_zip_writer instance, intended
   for in-struct or const-copy initialization.
*/
#define fsl_zip_writer_empty_m {                \
  0/*entryCount*/,                            \
  0/*dosTime*/,                             \
  0/*dosDate*/,                             \
  0/*unixTime*/,                            \
  NULL/*rootDir*/,                          \
  fsl_b_empty_m/*toc*/,                \
  fsl_b_empty_m/*body*/,               \
  fsl_b_empty_m/*scratch*/,            \
  fsl_list_empty_m/*dirs*/                  \
}

/**
   An initialized-with-defaults fsl_zip_writer instance,
   intended for copy-initialization.
*/
FSL_EXPORT const fsl_zip_writer fsl_zip_writer_empty;

/**
   Sets a virtual root directory in z, such that all files added
   with fsl_zip_file_add() will get this directory prefixed to
   it.

   If zRoot is NULL or empty then this clears the virtual root,
   otherwise is injects any directory levels it needs to into the
   being-generated ZIP. Note that zRoot may contain multiple levels of
   directories, e.g. "foo/bar/baz", but it must be legal for use in a
   ZIP file.

   This routine copies zRoot's bytes, so they may be transient.

   Returns 0 on success, FSL_RC_MISUSE if !z, FSL_RC_OOM on
   allocation error. Returns FSL_RC_RANGE if zRoot is an absolute
   path or if zRoot cannot be normalized to a "simplified name" (as
   per fsl_is_simple_pathname(), with the note that this routine
   will pass a copy of zRoot through fsl_file_simplify_name()
   first).

   @see fsl_zip_finalize()
*/
FSL_EXPORT int fsl_zip_root_set(fsl_zip_writer *  z,
                                char const * zRoot );

/**
   Adds a file or directory to the ZIP writer z. zFilename is the
   virtual name of the file or directory. If pContent is NULL then
   it is assumed that we are creating one or more directories,
   otherwise the ZIP's entry is populated from pContent. The
   permsFlag argument specifies the fossil-specific permission
   flags from the fsl_fileperm_e enum, but currently ignores the
   permsFlag argument for directories. Not that this function
   creates directory entries for any files automatically, so there
   is rarely a need for client code to create them (unless they
   specifically want to ZIP an empty directory entry).

   Notes of potential interest:

   - The ZIP is created in memory, and thus creating ZIPs with this
   API is exceedingly memory-hungry.

   - The timestamp of any given file must be set separately from
   this call using fsl_zip_timestamp_set_unix() or
   fsl_zip_timestamp_set_julian(). That value is then used for
   subsequent file-adds until a new time is set.

   - If a root directory has been set using fsl_zip_root_set() then
   that name, plus '/' (if the root does not end with one) gets
   prepended to all files added via this routine.

   - The ZIP is written without the zip64 extensions, so this
   returns FSL_RC_RANGE for content larger than 4GiB minus one byte,
   a name longer than 65535 bytes, or an archive which has grown
   past 4GiB.

   Returns 0 on success, FSL_RC_OOM on allocation error, or
   FSL_RC_RANGE as described above. z has no error message state,
   so the caller reports the failure.

   An example of the ZIP-generation process:

   ```
   int rc;
   fsl_zip_writer z = fsl_zip_writer_empty;
   fsl_b buf = fsl_b_empty;
   fsl_b const * zipBody;

   // ...fill the buf buffer (not shown here)...

   // Optionally set a virtual root dir for new files:
   rc = fsl_zip_root_set( &z, "myRootDir" ); // trailing slash is optional
   if(rc) { ... error ...; goto end; }

   // We must set a timestamp which will be used until we set another:
   fsl_zip_timestamp_set_unix( &z, time(NULL) );

   // Add a file:
   rc = fsl_zip_file_add( &z, "foo/bar.txt", &buf, FSL_FILE_PERM_REGULAR );
   // Clean up our content:
   fsl_b_reuse(&buf); // only needed if we want to re-use the buffer's memory
   if(rc) goto end;

   // ... add more files the same way (not shown) ...

   // Now "seal" the ZIP file:
   rc = fsl_zip_end( &z );
   if(rc) goto end;

   // Fetch the ZIP content:
   zipBody = fsl_zip_body( &z );
   // zipBody now points to zipBody->used bytes of ZIP file content
   // which can be sent to an arbitrary destination, e.g.:
   rc = fsl_b_to_filename( zipBody, "my.zip" );

   end:
   fsl_b_clear(&buf);
   // VERY important, once we're done with z:
   fsl_zip_finalize( &z );
   if(rc){...we had an error...}
   ```

   @see fsl_zip_timestamp_set_julian()
   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_end()
   @see fsl_zip_body()
   @see fsl_zip_finalize()
*/
FSL_EXPORT int fsl_zip_file_add( fsl_zip_writer *  z,
                                 char const * zFilename,
                                 fsl_b const * pContent,
                                 int permsFlag );

/**
   Ends the ZIP-creation process, padding all buffers, writing all
   final required values, and freeing up most of the memory owned
   by z. After calling this, z->body contains the full generated
   ZIP file.

   Returns 0 on success, FSL_RC_OOM on allocation error, or
   FSL_RC_RANGE if z holds more than 65535 entries or its central
   directory would start beyond 4GiB, limits of the ZIP format
   without the zip64 extensions. On error z's
   contents may still be partially intact (for debugging purposes)
   and z->body will not hold complete/valid ZIP file contents. Results are undefined if
   !z or z has not been properly initialized.

   The caller must eventually pass z to fsl_zip_finalize() to free
   up any remaining resources.

   @see fsl_zip_timestamp_set_julian()
   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_file_add()
   @see fsl_zip_body()
   @see fsl_zip_finalize()
   @see fsl_zip_end_take()
*/
FSL_EXPORT int fsl_zip_end( fsl_zip_writer *  z );

/**
   This variant of fsl_zip_end() transfers the current contents
   of the zip's body to dest, replacing (freeing) any contents it may
   hold when this is called, then passes z to fsl_zip_finalize()
   to free any other resources (which are invalidated by the removal
   of the body).

   Returns 0 on success, FSL_RC_MISUSE if either pointer is NULL,
   some non-0 code if the proxied fsl_zip_end() call fails. On
   error, the transfer of contents to dest does NOT take place, but
   z is finalized (if it is not NULL) regardless of success or
   failure (even if dest is NULL). i.e. on error z is still cleaned
   up.
*/
FSL_EXPORT int fsl_zip_end_take( fsl_zip_writer *  z,
                                 fsl_b *  dest );

/**
   This variant of fsl_zip_end_take() passes z to fsl_zip_end(),
   write's the ZIP body to the given filename, passes
   z to fsl_zip_finalize(), and returns the result of
   either end/save combination. Saving is not attempted
   if ending the ZIP fails.

   On success 0 is returned and the contents of the ZIP are in the
   given file. On error z is STILL cleaned up, and the file might
   have been partially populated (only on I/O error after writing
   started). In either case, z is cleaned up and ready for re-use or
   (in the case of a heap-allocated instance) freed.
*/
FSL_EXPORT int fsl_zip_end_to_filename( fsl_zip_writer *  z,
                                        char const * filename );


/**
   Returns a pointer to z's ZIP content buffer. The contents are ONLY
   valid after fsl_zip_end() returns 0.

   @see fsl_zip_timestamp_set_julian()
   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_file_add()
   @see fsl_zip_end()
   @see fsl_zip_end_take()
   @see fsl_zip_finalize()
*/
FSL_EXPORT fsl_b const * fsl_zip_body( fsl_zip_writer const * z );

/**
   Frees all memory owned by z and resets it to a clean state, but
   does not free z. Any fsl_zip_writer instance which has been
   modified via the fsl_zip_xxx() family of functions MUST
   eventually be passed to this function to clean up any contents
   it might have accumulated during its life. After this returns,
   z is legal for re-use in creating a new ZIP archive.

   @see fsl_zip_timestamp_set_julian()
   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_file_add()
   @see fsl_zip_end()
   @see fsl_zip_body()
*/
FSL_EXPORT void fsl_zip_finalize(fsl_zip_writer *  z);

/**
   Set z's date and time from a Julian Day number. Results are
   undefined if !z. Results will be invalid if rDate is negative. The
   timestamp is applied to all fsl_zip_file_add() operations until it
   is re-set.

   @see fsl_zip_timestamp_set_unix()
   @see fsl_zip_file_add()
   @see fsl_zip_end()
   @see fsl_zip_body()
*/
FSL_EXPORT void fsl_zip_timestamp_set_julian(fsl_zip_writer *  z,
                                             double rDate);

/**
   Set z's date and time from a Unix Epoch time. Results are
   undefined if !z. Results will be invalid if rDate is negative. The
   timestamp is applied to all fsl_zip_file_add() operations until it
   is re-set.
*/
FSL_EXPORT void fsl_zip_timestamp_set_unix(fsl_zip_writer *  z,
                                           fsl_time_t epochTime);

/**
   State for the fsl_timer_xxx() family of functions.

   Achtung: timer support is only enabled if the library is built with
   the proper clock support. Windows builds mostly support it
   automatically (all except wall clock time) and non-Windows builds
   do if the library is built with HAVE_CLOCK_GETTIME (for
   clock_gettime(2)) and HAVE_GETRUSAGE (for getrusage(2)) both set to
   true values. That said: the library currently _assumes_ that
   non-Windows builds have both of those POSIX-2008 functions. On
   Windows, building with HAVE_CLOCK_GETTIME is necessary only for
   fsl_timer::wall.

   Example usage:

   ```
   fsl_timer tTotal = fsl_timer_empty;
   fsl_timer tRun;
   fsl_timer_start(&tRun);
   ... do some work ...
   fsl_timer_add(&tRun, &tTotal);
   ```

   After that, `tTotal` contains the microseconds of time which
   elapsed between the time `tRun` was started and the time
   fsl_timer_add() was called.

   @see fsl_timer_start()
   @see fsl_timer_fetch()
   @see fsl_timer_add()
   @see fsl_timer_stop()
*/
struct fsl_timer {
  /**
     The amount of time (microseconds) spent in "user space".
  */
  uint64_t user;

  /**
     The amount of time (microseconds) spent in "kernel space".
  */
  uint64_t system;

  /**
     The microseconds of "wall clock" time. Only available if built
     with HAVE_CLOCK_GETTIME. (Patches for a Windows alternative would
     be welcomed.)
  */
  uint64_t wall;
};
typedef struct fsl_timer fsl_timer;

/**
   Initialized-with-defaults fsl_timer instance,
   intended for const copy initialization.
*/
#define fsl_timer_empty_m {.user=0,.system=0,.wall=0}

/**
   Initialized-with-defaults fsl_timer instance,
   intended for non-const copy initialization.
*/
FSL_EXPORT const fsl_timer fsl_timer_empty;

/**
   Sets t's counter state to the current CPU timer usage, as
   determined by the OS. It is legal to pass an uninitialized instance
   to this function, as this function will fully populate it.

   @see fsl_timer_fetch()
   @see fsl_timer_add()
*/
FSL_EXPORT void fsl_timer_start(fsl_timer *  t);

/**
   Sets each of pUser, pSys, and pWall to the number of
   microseconds which have elapsed since t was passed
   to fsl_timer_start().
*/
FSL_EXPORT void fsl_timer_fetch(fsl_timer const * t,
                                uint64_t * pUser, uint64_t * pSys,
                                uint64_t * pWall);

/**
   Captures the current time and adds the difference of tStart and
   the current time to tgt's members. Intended for
   keeping track of interruptable running times.

   Example usage:

   ```
   fsl_timer timerTotal = fsl_timer_empty; // copy init is important
   fsl_timer timerWork;                    // here it's not

   fsl_timer_start(&timerWork);
   ... do some timed work...
   fsl_timer_add(&timerWork, &timerTotal);

   ... do some non-timed work ...

   fsl_timer_start(&timerWork);
   ... do some timed work...
   fsl_timer_add(&timerWork, &timerTotal);
   ```

   The end result will be that timerTotal holds the accumulated times
   between each start/add invocation.
*/
FSL_EXPORT void fsl_timer_add(fsl_timer const * tStart,
                                fsl_timer *  tgt);

/**
   Returns the difference in _CPU_ times in microseconds since t was
   last passed to fsl_timer_start() or fsl_timer_reset().  It might
   return 0 due to system-level precision restrictions. Note that this
   is not useful for measuring wall times.
*/
FSL_EXPORT uint64_t fsl_timer_cpu(fsl_timer const * t);

/**
   Resets t's state to contain relative times by subtracting its
   starting time from the current time. Returns the post-adjustment
   (t->system+t->user).

   @see fsl_timer_start()
   @see fsl_timer_reset()
*/
FSL_EXPORT uint64_t fsl_timer_stop(fsl_timer *  t);

/**
   A convenience macro for timing a block of code (BODY) with the
   fsl_timer API. TGT is a (fsl_timer*) object which must initially
   start out zeroed out (e.g. initialied by copying from
   fsl_timer_empty or fsl_timer_empty_m). SUFFIX is a unique-per-scope
   name suffix for a scope-local temporary fsl_timer object, so must
   be suitable as the suffix of a C identifier. The run-time of BODY
   is fsl_timer_add()'d to (fsl_timer*) TGT.

   Example usage:

   ```
   fsl_timer_scope3(__COUNTER__,&myTimer,{
     ... your code to time ...
   });
   ```

   For compilers which do not like `__COUNTER__`, just use any
   identifier suffix which is unique to the call scope, e.g. an
   integer.
*/
#define fsl_timer_scope3(SUFFIX,TGT,BODY)  \
  fsl_timer _tm ## SUFFIX;                 \
  fsl_timer_start(&_tm ## SUFFIX);         \
  BODY;                                    \
  fsl_timer_add(&_tm ## SUFFIX, TGT)

/**
   Convenience form of fsl_timer_scope3() which uses __COUNTER__ as
   its 2nd argument. Note that __COUNTER__ is a C extension but is
   believed to be supported on all modern (as of 2025) C compilers.
*/
#define fsl_timer_scope(TGT,BODY) \
  fsl_timer_scope3(__COUNTER__,TGT,BODY)


/**
   For the given red/green/blue values (all in the range of 0 to
   255, or truncated to be so!) this function returns the RGB
   encoded in the lower 24 bits of a single number. See
   fsl_gradient_color() for an explanation and example.

   For those asking themselves, "why does an SCM API have a function
   for encoding RGB colors?" the answer is: fossil(1) has a long
   history of using HTML color codes to set the color of branches,
   and this is provided in support of such features.

   @see fsl_rgb_decode()
   @see fsl_gradient_color()
*/
FSL_EXPORT unsigned int fsl_rgb_encode( int r, int g, int b );

/**
   Given an RGB-encoded source value, this function decodes
   the lower 24 bits into r, g, and b. Any of r, g, and b may
   be NULL to skip over decoding of that part.

   @see fsl_rgb_encode()
   @see fsl_gradient_color()
*/
FSL_EXPORT void fsl_rgb_decode( unsigned int src, int *r, int *g, int *b );

/**
   For two color values encoded as RRGGBB values (see below for the
   structure), this function computes a gradient somewhere between
   those colors. c1 and c2 are the edges of the gradient.
   numberOfSteps is the number of steps in the gradient. stepNumber
   is a number less than numberOfSteps which specifies the "degree"
   of the gradients. If either numberOfSteps or stepNumber is 0, c1
   is returned. stepNumber of equal to or greater than c2 returns
   c2.

   The return value is an RGB-encoded value in the lower 24 bits,
   ordered in big-endian. In other words, assuming rc is the return
   value:

   - red   = (rc&0xFF0000)>>16
   - green = (rc&0xFF00)>>8
   - blue  = (rc&0xFF)

   Or use fsl_rgb_decode() to break it into its component parts.

   It can be passed directly to a printf-like function, using the
   hex-integer format specifier, e.g.:

   ```
   fsl_b_appendf(&myBuf, "#%06x", rc);
   ```

   Tip: for a given HTML RRGGBB value, its C representation is
   identical: HTML \#F0D0A0 is 0xF0D0A0 in C.

   @see fsl_rgb_encode()
   @see fsl_rgb_decode()
*/
FSL_EXPORT unsigned int fsl_gradient_color(unsigned int c1, unsigned int c2,
                                           unsigned int numberOfSteps,
                                           unsigned int stepNumber);

/**
   "Simplifies" an SQL string by making the following modifications
   inline:

   - Consecutive non-newline spaces outside of an SQL string are
   collapsed into one space.

   - Consecutive newlines outside of an SQL string are collapsed into
   one space.

   Contents of SQL strings are not transformed in any way.

   len must be the length of the sql string. If it is negative,
   fsl_strlen(sql) is used to calculate the length.

   Returns the number of bytes in the modified string (its strlen) and
   NUL-terminates it at the new length. Thus the input string must be
   at least one byte longer than its virtual length (its NUL
   terminator byte suffices, provided it is NUL-terminated, as we can
   safely overwrite that byte).

   If !sql or its length resolves to 0, this function returns 0
   without side effects.
*/
FSL_EXPORT fsl_size_t fsl_simplify_sql( char * sql, fsl_strlen_t len );

/**
   Convenience form of fsl_simplify_sql() which assumes b holds an SQL
   string. It gets processed by fsl_simplify_sql() and its 'used'
   length potentially gets adjusted to match the adjusted SQL string.
*/
FSL_EXPORT fsl_size_t fsl_simplify_sql_buffer( fsl_b *  b );

/**
   Returns the result of calling the platform's equivalent of
   isatty(fd). e.g. on Windows this is _isatty() and on Unix
   isatty(). i.e. it returns true if it thinks that the given file
   descriptor value is attached to an interactive terminal, else it
   returns false.

   The standard file descriptors are: 0=stdin, 1=stdout, and 2=stderr.
*/
FSL_EXPORT bool fsl_isatty(int fd);

/**
   A container type for lists of db record IDs. This is used in
   several places as a cache for record IDs, to keep track of ones
   we know about, ones we know that we don't know about, and to
   avoid duplicate processing in some contexts.

   This container does not support modification during traversal and
   has undefined behavior in such cases.
*/
struct fsl_id_bag {
  /**
     Number of entries of this->list which are in use (have a
     positive value). They need not be contiguous!  Must be <=
     capacity.
  */
  fsl_size_t entryCount;
  /**
     The number of elements allocated for this->list.
  */
  fsl_size_t capacity;
  /**
     The number of elements in this->list which have a zero or
     positive value. Must be <= capacity.
  */
  fsl_size_t used;
  /**
     Array of IDs this->capacity elements long. "Used" elements
     have a positive value. Unused ones are set to 0.
  */
  fsl_id_t * list;
};

/**
   Initialized-with-defaults fsl_id_bag structure,
   intended for copy initialization.
*/
FSL_EXPORT const fsl_id_bag fsl_id_bag_empty;

/**
   Initialized-with-defaults fsl_id_bag structure,
   intended for in-struct initialization.
*/
#define fsl_id_bag_empty_m {      \
  .entryCount = 0, .capacity = 0, \
  .used = 0, .list = NULL         \
}

/**

   Return the number of elements in the bag.
*/
FSL_EXPORT fsl_size_t fsl_id_bag_count(fsl_id_bag const * p);

/**

   Remove element e from the bag if it exists in the bag. If e is not
   in the bag, this is a no-op. Returns true if it removes an element,
   else false.

   e must be positive. Results are undefined if e<=0.
*/
FSL_EXPORT bool fsl_id_bag_remove(fsl_id_bag *  p, fsl_id_t e);

/**
   Returns true if e is in the given bag. Returns false if it is
   not. It is illegal to pass an e value of 0, and that will trigger
   an assertion in debug builds. In non-debug builds, behaviour if
   passed 0 is undefined.
*/
FSL_EXPORT bool fsl_id_bag_contains(fsl_id_bag const * p, fsl_id_t e);

/**
   Insert element e into the bag if it is not there already.  Returns
   0 if it actually inserts something or if it already contains such
   an entry, and some other value on error (namely FSL_RC_OOM on
   allocation error).

   e must be positive or an assertion is triggered in debug builds. In
   non-debug builds, behaviour is undefined if passed 0.
*/
FSL_EXPORT int fsl_id_bag_insert(fsl_id_bag *  p, fsl_id_t e);

/**
   Returns the ID of the first element in the bag.  Returns 0 if the
   bag is empty.

   ```
   fsl_id_t rid = fsl_id_bag_first(debag);
   int rc = 0;
   for( ; !rc && rid>0; rid = fsl_id_bag_next(debag, rid) ){
     rc = ...;
   }
   ```

*/
FSL_EXPORT fsl_id_t fsl_id_bag_first(fsl_id_bag const * p);

/**
   Returns the next element in the bag after e.  Return 0 if e is
   the last element in the bag.  Any insert or removal from the bag
   might reorder the bag. It is illegal to pass this 0 (and will
   trigger an assertion in debug builds). For the first call, pass
   it the non-0 return value from fsl_id_bag_first(). For
   subsequent calls, pass the previous return value from this
   function.

   @see fsl_id_bag_first()
*/
FSL_EXPORT fsl_id_t fsl_id_bag_next(fsl_id_bag const * p, fsl_id_t e);

/**
   Swaps the contents of the given bags.
*/
FSL_EXPORT void fsl_id_bag_swap(fsl_id_bag *  lhs, fsl_id_bag *  rhs);

/**
   Copies all entries from src into dest. Returns 0 on success,
   FSL_RC_OOM on allocation error.

   An alternative approach: if dest is empty then
   fsl_id_bag_swap(src,dest), perhaps followed by
   fsl_id_bag_clear(src) or fsl_id_bag_reuse(src), is more efficient
   (does not allocate).
*/
FSL_EXPORT int fsl_id_bag_copy(fsl_id_bag const * src, fsl_id_bag * dest);

/**
   Frees any memory owned by p, but does not free p.
*/
FSL_EXPORT void fsl_id_bag_clear(fsl_id_bag *  p);

/**
   Resets p's internal list, effectively emptying it for re-use, but
   does not free its memory. Immediately after calling this
   fsl_id_bag_count() will return 0. Returns p.
*/
FSL_EXPORT fsl_id_bag * fsl_id_bag_reuse(fsl_id_bag *  p);

/** @deprecated

   Older (deprecated) name of fsl_id_bag_reuse().
*/
#define fsl_id_bag_reset fsl_id_bag_reuse

/**
   Return true if p contains a merge marker on a line by itself, else
   returns false.

   @see fsl_b_merge3()
*/
FSL_EXPORT bool fsl_b_contains_merge_marker(fsl_b const *p);

/**
   Performs a three-way merge.

   The merge is an edit against pV2. Both pV1 and pV2 have a common
   origin at pPivot. Apply the changes of pPivot ==> pV1 to pV2,
   appending them to pOut. (Pedantic side-note: the input buffers are
   not const because we need to manipulate their cursors, but their
   buffered memory is not modified.)

   If merge conflicts are encountered, it continues as best as it can
   and injects "indiscrete" markers in the output to denote the nature
   of each conflict. If conflictCount is not NULL then on success the
   number of merge conflicts is written to *conflictCount.

   Returns 0 on success, FSL_RC_OOM on OOM, FSL_RC_DIFF_BINARY if any
   input appears to be binary.

   @see fsl_b_contains_merge_marker()
*/
FSL_EXPORT int fsl_b_merge3(fsl_b *  pPivot,
                                 fsl_b *  pV1,
                                 fsl_b *  pV2,
                                 fsl_b *  pOut,
                                 unsigned int *  conflictCount);

/**
   Appends the first n bytes of string z to buffer b in the form of
   TCL-format string literal. If n<0 then fsl_strlen() is used to
   determine the length. Returns 0 on success, FSL_RC_OOM on error.

   If fsl_b_err() is true for the given buffer, that code is
   returned without other side effects.

   If the 2nd argument is true, squiggly braces within the string are
   escaped, else they are not. Whether that's required or not depends
   on how the resulting TCL will be used. If it will be eval'd directly,
   it must be escaped. If it will be read as a file and tokenized, it
   needn't be.
 */
FSL_EXPORT int fsl_b_append_tcl_literal(fsl_b *  b,
                                             bool escapeSquigglies,
                                             char const * z, fsl_int_t n);


/**
   Event IDs for use with fsl_confirm_callback_f implementations.

   The idea here is to send, via callback, events from the library to
   the client when a potentially interactive response is necessary.
   We define a bare minimum of information needed for the client to
   prompt a user for a response. To that end, the interface passes on
   2 pieces of information to the client: the event ID and a filename.
   It is up to the application to translate that ID into a
   user-readable form, get a response (using a well-defined set of
   response IDs), and convey that back to the
   library via the callback's result pointer interface.

   This enum will be extended as the library develops new requirements
   for interactive use.

   @see fsl_confirm_response_e
*/
enum fsl_confirm_event_e {
/**
   Sentinal value.
*/
FSL_CEVENT_INVALID = 0,
/**
   An operation requests permission to overwrite a locally-modified
   file. e.g. when performing a checkout over a locally-edited
   version. Overwrites of files which are known to be in the previous
   (being-overwritten) checkout version are automatically overwritten.
*/
FSL_CEVENT_OVERWRITE_MOD_FILE = 1,
/**
   An operation requests permission to overwrite an SCM-unmanaged file
   with one which is managed by SCM. This can happen, e.g., when
   switching from a version which did not contain file X, but had file
   X on disk, to a version which contains file X.
*/
FSL_CEVENT_OVERWRITE_UNMGD_FILE = 2,
/**
   An operation requests permission to remove a LOCALLY-MODIFIED file
   which has been removed from SCM management. e.g. when performing a
   checkout over a locally-edited version and an edited file was
   removed from the SCM somewhere between those two versions.
   UMODIFIED files which are removed from the SCM between two
   checkouts are automatically removed on the grounds that it poses no
   data loss risk because the other version is "somewhere" in the SCM.
*/
FSL_CEVENT_RM_MOD_UNMGD_FILE = 3,

/**
   Indicates that the library cannot determine which of multiple
   potential versions to choose from and requires the user to
   select one.
*/
FSL_CEVENT_MULTIPLE_VERSIONS = 4

};
typedef enum fsl_confirm_event_e fsl_confirm_event_e;

/**
   Answers to questions posed to clients via the
   fsl_confirm_callback_f() interface.

   This enum will be extended as the library develops new requirements
   for interactive use.

   @see fsl_confirm_event_e
*/
enum fsl_confirm_response_e {
/**
   Sentinel/default value - not a valid answer. Guaranteed to have a
   value of 0. No other entries in this enum are guaranteed to have
   well-known/stable values: always use the enum symbols instead of
   integer values.
*/
FSL_CRESPONSE_INVALID = 0,
/**
   Accept the current event and continue processes.
*/
FSL_CRESPONSE_YES = 1,
/**
   Reject the current event and continue processes.
*/
FSL_CRESPONSE_NO = 2,
/**
   Reject the current event and stop processesing. Cancellation is
   generally considered to be a recoverable error.
*/
FSL_CRESPONSE_CANCEL = 3,
/**
   Accept the current event and all identical event types for the
   current invocation of this particular SCM operation.
*/
FSL_CRESPONSE_ALWAYS = 5,
/**
   Reject the current event and all identical event types for the
   current invocation of this particular SCM operation.
*/
FSL_CRESPONSE_NEVER = 6,
/**
   For events which are documented as being multiple-choice,
   this answer indicates that the client has set the index of
   their choice in the fsl_confirm_response::multipleChoice
   field:

   - FSL_CEVENT_MULTIPLE_VERSIONS
*/
FSL_CRESPONSE_MULTI = 7
};
typedef enum fsl_confirm_response_e fsl_confirm_response_e;

/**
   A response for use with the fsl_confirmer API. It is intended to
   encapsulate, with a great deal of abstraction, answers to typical
   questions which the library may need to interactively query a user
   for. e.g. confirmation about whether to overwrite a file or which
   one of 3 versions to select.

   This type will be extended as the library develops new requirements
   for interactive use.
*/
struct fsl_confirm_response {
  /**
     Client response to the current fsl_confirmer question.
  */
  fsl_confirm_response_e response;
  /**
     If this->response is FSL_CRESPONSE_MULTI then this must be set to
     the index of the client's multiple-choice answer.

     Events which except this in their response:

     - FSL_CEVENT_MULTIPLE_VERSIONS
  */
  uint16_t multipleChoice;
};
/**
   Convenience typedef.
*/
typedef struct fsl_confirm_response fsl_confirm_response;

/**
   Empty-initialized fsl_confirm_detail instance to be used for
   const copy initialization.
*/
#define fsl_confirm_response_empty_m {FSL_CRESPONSE_INVALID, -1}

/**
   Empty-initialized fsl_confirm_detail instance to be used for
   non-const copy initialization.
*/
FSL_EXPORT const fsl_confirm_response fsl_confirm_response_empty;

/**
   A struct for passing on interactive questions to
   fsl_confirmer_callback_f implementations.
*/
struct fsl_confirm_detail {
  /**
     The message ID of this confirmation request. This value
     determines how the rest of this struct's values are to
     be interpreted.
  */
  fsl_confirm_event_e eventId;
  /**
     Depending on the eventId, this might be NULL or might refer to a
     filename. This will be a filename for following confirmations
     events:

     - FSL_CEVENT_OVERWRITE_MOD_FILE
     - FSL_CEVENT_OVERWRITE_UNMGD_FILE
     - FSL_CEVENT_RM_MOD_UNMGD_FILE

     For all others it will be NULL.

     Whether this name refers to an absolute or relative path is
     context-dependent, and not specified by this API. In general,
     relative paths should be used if/when what they are relative to
     (e.g. a checkout root) is/should be clear to the user. The intent
     is that applications can display that name to the user in a UI
     control, so absolute paths "should" "generally" be avoided
     because they can be arbitrarily long.
  */
  const char * filename;
  /**
     Depending on the eventId, this might be NULL or might
     refer to a list of details of a type specified in the
     documentation for that eventId.

     Implementation of such an event is still TODO, but we have at
     least one use case lined up (asking a user which of several
     versions is intended when the checkout-update operation is given
     an ambiguous hash prefix).

     Events for which this list will be populated:

     - FSL_CEVENT_MULTIPLE_VERSIONS: each list entry will be a (char
     const*) with a version number, branch name, or similar, perhaps
     with relevant metadata such as a checkin timestamp. The client is
     expected to pick one answer, set its list index to the
     fsl_confirm_response::multipleChoice member, and to set
     fsl_confirm_response::response to FSL_CRESPONSE_MULTI.

     In all cases, a response of FSL_CRESPONSE_CANCEL will trigger a
     cancellation.

     In all cases, the memory for the items in this list is owned by
     (or temporarily operated on the behalf of) the routine which has
     launched this query. fsl_confirm_callback_f implements must never
     manipulate the list's or its content's state.
  */
  const fsl_list * multi;
};
typedef struct fsl_confirm_detail fsl_confirm_detail;

/**
   Empty-initialized fsl_confirm_detail instance to be used for
   const-copy initialization.
*/
#define fsl_confirm_detail_empty_m \
  {FSL_CEVENT_INVALID, NULL, NULL}

/**
   Empty-initialized fsl_confirm_detail instance to be used for
   non-const-copy initialization.
*/
FSL_EXPORT const fsl_confirm_detail fsl_confirm_detail_empty;

/**
   Should present the user (if appropriate) with an option of how to
   handle the given event write that answer to
   outAnswer->response. Return 0 on success, non-0 on error, in which
   case the current operation will fail with that result code.
   Answering with FSL_CRESPONSE_CANCEL is also considered failure but
   recoverably so, whereas a non-cancel failure is considered
   unrecoverable.
*/
typedef int (*fsl_confirm_callback_f)(fsl_confirm_detail const * detail,
                                      fsl_confirm_response *outAnswer,
                                      void * confirmerState);

/**
   A fsl_confirm_callback_f and its callback state, packaged into a
   neat little struct for easy copy/replace/restore of confirmers.
*/
struct fsl_confirmer {
  /**
     Callback which can be used for basic interactive confirmation
     purposes, within the very libfossil-centric limits of the
     interface.
  */
  fsl_confirm_callback_f callback;
  /**
     Opaque state pointer for this->callback. Its lifetime is not
     managed by this object and it is assumed, if not NULL, to live at
     least as long as this object.
  */
  void * callbackState;
};
typedef struct fsl_confirmer fsl_confirmer;
/** Empty-initialized fsl_confirmer instance for const-copy
    initialization. */
#define fsl_confirmer_empty_m {NULL,NULL}
/** Empty-initialized fsl_confirmer instance for non-const-copy
    initialization. */
FSL_EXPORT const fsl_confirmer fsl_confirmer_empty;

/**
   State for use with fsl_dircrawl_f() callbacks.

   @see fsl_dircrawl()
*/
struct fsl_dircrawl_state {
  /**
     Absolute directory name of the being-visited directory.
  */
  char const *absoluteDir;
  /**
     Name (no path part) of the entry being visited.
  */
  char const *entryName;
  /**
     Filesystem entry type.
  */
  fsl_fstat_type_e entryType;
  /**
     Opaque client-specified pointer which was passed to
     fsl_dircrawl().
  */
  void * callbackState;

  /**
     Directory depth of the crawl process, starting at 1 with
     the directory passed to fsl_dircrawl().
  */
  unsigned int depth;
};
typedef struct fsl_dircrawl_state fsl_dircrawl_state;

/**
   Callback type for use with fsl_dircrawl(). Its argument contains
   all crawling-relevant state for entry being visited.

   Implementations must return 0 on success or another FSL_RC_xxx
   value on error.

   Special return values:

   - FSL_RC_BREAK will cause directory-crawling to stop without an
     error (returning 0).

   - Returning FSL_RC_NOOP will cause recursion into a directory to
     be skipped, but traversal to otherwise continue.

   All pointers in the state argument are owned by fsl_dircrawl() and
   will be invalidated as soon as the callback returns, thus they must
   be copied if they are needed for later.
*/
typedef int (*fsl_dircrawl_f)(fsl_dircrawl_state const *);

/**
   Recurses into a directory and calls a callback for each filesystem
   entry.  It does not change working directories, but callbacks are
   free to do so as long as they restore the working directory before
   returning.

   The first argument is the name of the directory to crawl. In order
   to avoid any dependence on a specific working directory, if it is
   not an absolute path then this function will expand it to an
   absolute path before crawling begins. For each entry under the
   given directory, it calls the given callback, passing it a
   fsl_dircrawl_state object holding various state. All pointers in
   that object, except for the callbackState pointer, are owned by
   this function and may be invalidated as soon as the callback
   returns.

   For each directory entry, it recurses into that directory,
   depth-first _after_ passing it to the callback.

   It DOES NOT resolve/follow symlinks, instead passing them on to the
   callback for processing. Note that passing a symlink to this
   function will not work because this function does not resolve
   symlinks. Thus it provides no way to traverse symlinks, as its
   scope is only features suited for the SCM and symlinks have no
   business being in an SCM. (Fossil supports symlinks, more or less,
   but libfossil does not.)

   It silently skips any files for which stat() fails or is not of a
   "basic" file type (e.g. character devices and such).

   Returns 0 on success, FSL_RC_TYPE if the given name is not a
   directory, and FSL_RC_RANGE if it recurses "too deep," (some
   "reasonable" internally hard-coded limit), in order to help avoid a
   stack overflow.

   If the callback returns non-0, iteration stops and returns that
   result code unless the result is FSL_RC_BREAK or FSL_RC_NOOP, with
   those codes being treated specially, as documented for
   fsl_dircrawl_f() callbacks.
*/
FSL_EXPORT int fsl_dircrawl(char const * dirName, fsl_dircrawl_f callback,
                            void * callbackState);

/**
   Strips any trailing slashes ('/') from the given string by
   assigning those bytes to NUL and returns the number of slashes
   NUL'd out. nameLen must be the length of the string. If nameLen is
   negative, fsl_strlen() is used to calculate its length.
*/
FSL_EXPORT fsl_size_t fsl_strip_trailing_slashes(char * name, fsl_int_t nameLen);

/**
   A convenience from of fsl_strip_trailing_slashes() which strips
   trailing slashes from the given buffer and changes its b->used
   value to account for any stripping. Results are undefined if b is
   not properly initialized.

   If b is an external buffer, this routine materializes it and strips
   it on success. On materialization error b->errCode will be non-0.
*/
FSL_EXPORT void fsl_b_strip_slashes(fsl_b *  b);

/**
   Edits b in-place, stripping out any hash-style single-line comments
   and adjusting b->used.

   If b is an external buffer then this is a no-op but a potential
   TODO is have it materialize the buffer in that case and return an
   int (FSL_RC_OOM on OOM).
*/
FSL_EXPORT void fsl_b_strip_hash_comments(fsl_b * b);

/**
   Appends each ID from the given bag to the given buffer using the given
   separator string. Returns FSL_RC_OOM on allocation error.

   If fsl_b_err() is true for the given buffer, that code is
   returned without other side effects.
*/
FSL_EXPORT int fsl_id_bag_to_buffer(fsl_id_bag const * bag,
                                    fsl_b *  b,
                                    char const * separator);

/**
   Flags for use with the fsl_looks family of functions.
*/
enum fsl_lookslike_e {
/* Nothing special was found. */
FSL_LOOKSLIKE_NONE    = 0x00000000,
/* One or more NUL chars were found. */
FSL_LOOKSLIKE_NUL     = 0x00000001,
/* One or more CR chars were found. */
FSL_LOOKSLIKE_CR      = 0x00000002,
/* An unpaired CR char was found. */
FSL_LOOKSLIKE_LONE_CR = 0x00000004,
/* One or more LF chars were found. */
FSL_LOOKSLIKE_LF      = 0x00000008,
/* An unpaired LF char was found. */
FSL_LOOKSLIKE_LONE_LF = 0x00000010,
/* One or more CR/LF pairs were found. */
FSL_LOOKSLIKE_CRLF    = 0x00000020,
/* An over length line was found. */
FSL_LOOKSLIKE_LONG    = 0x00000040,
/* An odd number of bytes was found. */
FSL_LOOKSLIKE_ODD     = 0x00000080,
/* Unable to perform full check. */
FSL_LOOKSLIKE_SHORT   = 0x00000100,
/* Invalid sequence was found. */
FSL_LOOKSLIKE_INVALID = 0x00000200,
/* Might be binary. */
FSL_LOOKSLIKE_BINARY  = FSL_LOOKSLIKE_NUL | FSL_LOOKSLIKE_LONG | FSL_LOOKSLIKE_SHORT,
 /* Line separators. */
FSL_LOOKSLIKE_EOL     = (FSL_LOOKSLIKE_LONE_CR | FSL_LOOKSLIKE_LONE_LF | FSL_LOOKSLIKE_CRLF)
};

/**
   Returns true if b appears to contain "binary" (non-UTF8/16) content,
   else returns false.
*/
FSL_EXPORT bool fsl_looks_like_binary(fsl_b const * b);

/**
   If b appears to contain any non-UTF8 content, returns a truthy
   value: one or more values from the fsl_lookslike_e enum indicating
   which sort of data was seen which triggered its conclusion:

   - FSL_LOOKSLIKE_BINARY means the content appears to be binary
     because it contains embedded NUL bytes or an "extremely long"
     line. This function may diagnose UTF-16 as binary.

   - !FSL_LOOKSLIKE_BINARY means the content is non-binary but may
     not necessarily be valid UTF-8.

   - 0 means the contents appear to be valid UTF-8.

   It b's content is empty, returns 0.

   The 2nd argument can be a mask of any values from fsl_lookslike_e
   and will cause this routine to stop inspecting the input once it
   encounters any content described by those flags.

   The contents are examined until the end is reached or a condition
   described by the 2nd parameter's flags is encountered.

   WARNINGS:

   - This function does not validate that the blob content is properly
     formed UTF-8.  It assumes that all code points are the same size.
     It does not validate any code points.  It makes no attempt to
     detect if any [invalid] switches between UTF-8 and other
     encodings occur.

   - The only code points that this function cares about are the NUL
     character, carriage-return, and line-feed.
*/
FSL_EXPORT int fsl_looks_like_utf8(fsl_b const * b, int stopFlags);

/**
   Returns true if b's contents appear to contain anything other than valid
   UTF8.

   It uses the approach described at:

   http://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences

   except for the "overlong form" of \\u0000 which is not considered
   invalid here: Some languages, like Java and Tcl, use it. This function
   also considers valid the derivatives CESU-8 & WTF-8.
*/
FSL_EXPORT bool fsl_invalid_utf8(fsl_b const * b);

/**
   Returns a static pointer to bytes of a UTF8 BOM. If the argument is
   not NULL, it is set to the strlen of those bytes (always 3).
*/
FSL_EXPORT unsigned char const *fsl_utf8_bom(unsigned int *pnByte);

/**
   Returns true if b starts with a UTF8 BOM. If the 2nd argument is
   not NULL, *pBomSize is set to the number of bytes in the BOM
   (always 3), regardless of whether or not the function returns true
   or false.
*/
FSL_EXPORT bool fsl_starts_with_bom_utf8(fsl_b const * b, unsigned int *pBomSize);

/**
   Returns true if b starts with a UTF-8 byte-order mark (EF BB BF) or
   a UTF-16 one (FF FE or FE FF).
*/
FSL_EXPORT bool fsl_b_has_bom(fsl_b const * b);

/**
   Converts b in place to UTF-8 with no byte-order mark, as fossil(1)
   does with the inputs to diff and annotate:

   - A UTF-8 byte-order mark is removed.
   - Text that starts with a UTF-16 byte-order mark, in either byte
     order, is converted to UTF-8. Surrogate pairs become characters
     above U+FFFF, and an unpaired surrogate becomes U+FFFD.
   - Anything else is left unchanged.

   Returns 0 on success or FSL_RC_OOM if allocation fails, in which
   case b is unchanged.
*/
FSL_EXPORT int fsl_b_to_utf8_no_bom(fsl_b * b);

/**
   Populates the first n bytes of tgt with random bytes. Note that n
   must be 31 bits or less (2GB). The exact source of randomness is
   not guaranteed by the API, but the implementation currently uses
   sqlite3_randomness().
*/
FSL_EXPORT void fsl_randomness(unsigned int n, void *tgt);


/**
   Given a filename and its length, this function returns a pointer to
   the last instance of a path separator character in that string,
   checking for both `/` and `\\`. If the length is negative,
   fsl_strlen() is used to calculate it. If no separator is found,
   NULL is returned.
*/
FSL_EXPORT char const * fsl_last_path_sep(char const * str, fsl_int_t slen );

/**
   A helper type for tokenizing conventional PATH-style strings.
   Initialize them with fsl_path_splitter_init() and iterate over them
   with fsl_path_splitter_next().
*/
struct fsl_path_splitter {
  /** Begining of the input range. */
  char const * begin;
  /** One-after-the-end of the input range. */
  char const * end;
  /** Position for the next token lookup. */
  char const * pos;
  /** List of token separator characters (ASCII only). */
  char const * separators;
};
typedef struct fsl_path_splitter fsl_path_splitter;
/** @def fsl_path_splitter_empty_m

   Default-initialized fsl_path_splitter instance, intended for const-copy
   initialization. On Windows builds its separators member is set to
   ";" and on other platforms it's set to ":;".
*/
#if FSL_PLATFORM_IS_WINDOWS
#  define fsl_path_splitter_empty_m {NULL,NULL,NULL,";"}
#else
#  define fsl_path_splitter_empty_m {NULL,NULL,NULL,":;"}
#endif

/**
   Default-initialized fsl_path_splitter instance, intended for
   copy initialization.

   @see fsl_path_splitter_empty_m
*/
FSL_EXPORT const fsl_path_splitter fsl_path_splitter_empty;

/**
   Wipes out pt's current state by copying fsl_path_splitter_empty
   over it and initializes pt to use the given path as its input. If
   len is 0 or more then it must be the length of the string, in
   bytes. If len is less than 0, fsl_strlen() is used to determine the
   path's length.  (When dealing with inputs which are not
   NUL-terminated, it's critical that the user pass the correct
   non-negative length.)

   If the client wants to modify pt->separators, it must be done
   *after* calling this.

   Use fsl_path_splitter_next() to iterate over the path entries.
*/
void fsl_path_splitter_init( fsl_path_splitter *  pt, char const * path,
                             fsl_int_t len );

/**
   Given a fsl_path_splitter which was formerly initialized using
   fsl_path_splitter_init(), this iterates over the next-available
   path component in the input, skipping over empty entries (leading,
   consecutive, or trailing separator characters).

   The separator characters are specified by pt->separators, which must
   be a NUL-terminated string of 1 or more characters.

   If a non-empty entry is found then:

   - *token is set to the first byte of the entry.

   - *len is assigned to the byte length of the entry.

   If no entry is found then:

   - *token, and *len are not modified.

   - FSL_RC_NOT_FOUND is returned if the end of the path was found
   while tokenizing.

   - FSL_RC_MISUSE is returned if pt->separators is NULL or empty or
   contains any non-ASCII characters.

   - FSL_RC_RANGE is returned if called after the previous case, or
   if the input object's path has a length of 0.

   In any non-0-return case, it's not a fatal error, it's simply
   information about why tokenization cannot continue, and can
   normally be ignored. After non-0 is returned, the tokenizer must be
   re-initialized if it is to be used again.

   Example:

   @code
   char const * t = 0;
   fsl_size_t tLen = 0;
   fsl_path_splitter pt = fsl_path_splitter_empty;
   fsl_path_splitter_init(&pt, path, pathLen);
   while(0==fsl_path_splitter_next(&pt, &t, &tLen)){
      // The next element is the tLen bytes of memory starting at t:
      printf("Path element: %.*s\n", (int)tLen, t);
   }
   @endcode
*/
int fsl_path_splitter_next( fsl_path_splitter *  pt, char const ** token,
                            fsl_size_t *  len );

/**
   Implements a cross-platform system(3) interface. It passes its
   argument, which must not be NULL or empty, to the equivalent of
   system(3). Returns 0 if that call returns 0, else it will return a
   FSL_RC code approximating the lower-level error code (noting that
   this system's man pages are a bit vague on the exact return
   semantics of system(3)). If it cannot convert an errno value to an
   approximate FSL_RC value, it will return FSL_RC_ERROR.
*/
int fsl_system(const char *zOrigCmd);

typedef struct fsl_url fsl_url;

/**
   A type for parsing URLs. Its memory is managed by fsl_url_parse()
   and fsl_url_cleanup().
*/
struct fsl_url {
  /** The raw, unparsed URL. */
  char const * raw;
  /** The URL's scheme, in lower case. */
  char const * scheme;
  /** The URL's username, with %XX escapes decoded, or NULL. */
  char const * username;
  /** The URL's username's password, with %XX escapes decoded, or
      NULL. */
  char const * password;
  /** The remote host name, with %XX escapes decoded, or an IP literal
      with its brackets, such as "[::1]". Is only NULL for file
      URLs. */
  char const * host;
  /** The :portNumber part or 0. */
  uint16_t port;
  /** The path. For file URLs, this is where the file's name is
      stored, with %XX escapes decoded when the URL has an explicit
      "file:" scheme. */
  char const * path;
  /** The query string, including the '?' prefix. */
  char const * query;
  /** The fragment part, including the '#' prefix. */
  char const * fragment;

  /**
     Private implementation details. fsl_url_parse() allocates this
     buffer a single time and points the other members into the memory
     owned by impl.b. Its approximate allocated size is a handful of
     bytes more than twice the strlen() of this->raw.
  */
  struct { fsl_b b; } impl;
};

/** Initialized-with-defaults fsl_url structure, intended for
    const-copy initialization. */
#define fsl_url_empty_m {                        \
    .raw=0, .scheme=0, .username=0, .password=0, \
    .host=0, .port=0, .path=0, .query=0,         \
    .fragment=0, .impl = {.b=fsl_b_empty_m} \
}

/** Initialized-with-defaults fsl_url structure, intended for
    non-const copy initialization. */
extern const fsl_url fsl_url_empty;

/**
   Attempts to parse zUrl as a URL, filling out u with the
   results.

   It passes u to fsl_url_cleanup2(), with a false 2nd argument,
   before starting.

   Results are undefined if zUrl is NULL.

   On success, returns 0 and populates u. On error, returns
   FSL_RC_OOM, FSL_RC_SYNTAX, or FSL_RC_MISUSE (if zUrl is NULL or
   empty), and it passes u to fsl_url_cleanup() before returning.

   All memory referenced by u's members is invalidated by any of
   the fsl_url APIs. Do not hold copies of pointers to a fsl_url
   member for later use.

   For each missing component of the URL, the corresponding member of
   u will be NULL. A missing port is designated by 0, and a port value
   ouside of the range (1..65535) triggers a syntax error.

   Quirks:

   - It may mis-parse malformed URLs.

   - It does no unescaping of the string. It "could" provide the query
     string in an unescaped form but that would require some
     refactoring.

   - file URLs (in this API) do not support a host name, port, query
     string, or fragment. Everything after the scheme is available via
     u->path.

   - zUrl may be a filesystem path, starting with either '/' or '.',
     in which case it is treated as if it were prefixed with
     "file://".

   - file:/X and file:///X both resolve to /X. file://X, though
     technically illegal[^1] resolves to X.

   - It does not recognize Windows drive letters as such. A URL in the
     form "file:/c:/..." or "file:///c:/..." will be assigned a
     u->path of "/c:/...", and "file:c:/..." will have a u->path of
     "c:/...". In non-file URLs, a drive letter will very probably be
     treated like a hostname with an invalid port (so will fail to
     parse).

   [^1]: https://en.wikipedia.org/wiki/File_URI_scheme
*/
FSL_EXPORT int fsl_url_parse(fsl_url * u, char const * zUrl);

/**
   Flags for use with fsl_url_render().
*/
enum fsl_url_render_e {

  /** Elide the scheme:// prefix. */
  FSL_URL_RENDER_NO_SCHEME = 0x01,

  /** Elide the user name and password. */
  FSL_URL_RENDER_NO_USER = 1<<1,

  /** Elide any password part of the URL. */
  FSL_URL_RENDER_NO_PASSWORD = 1<<2,

  /**
     Render any password part of the URL as some unspecified number of
     "*" characters.
  */
  FSL_URL_RENDER_MASK_PASSWORD = 1<<3,

  /** Elide the query string and fragment. */
  FSL_URL_RENDER_NO_QUERY = 1<<4,

  /** Elide the fragment. */
  FSL_URL_RENDER_NO_FRAGMENT = 1<<5
};

/**
   Appends a rendering of the given parsed url object to the given
   buffer.  The final argument can be used to modify how the rendering
   is done.

   Returns pOut->errCode. If pOut->errCode is non-0 when this is
   called, this call is a no-op.
*/
FSL_EXPORT int fsl_url_render(fsl_url const * u, fsl_b * pOut,
                              fsl_flag32_t flags);

/**
   Equivalent to fsl_url_cleanup2(u, true).
*/
FSL_EXPORT void fsl_url_cleanup(fsl_url * u);

/**
   Frees all memory owned by u, and zeroes it out, but does not free
   u.  If freeBuffer is false then u's internal buffer is also freed
   otherwise it is retained, which will lead to a leak if u is not
   later either passed to fsl_url_cleanup() or to this function with a
   true freeBuffer value.
*/
FSL_EXPORT void fsl_url_cleanup2(fsl_url * u, bool freeBuffer);

/**
   Swaps the contents of the given objects.
*/
FSL_EXPORT void fsl_url_swap(fsl_url * lhs, fsl_url *rhs);

/**
   Parses key-value pairs from u->query. On the initial call, the
   second argument should be a pointer to a call-local NULL value.

   If this returns true:

   - It will have replaced bKey's contents with the
     next query string key, and bVal's contents to its value (if any).

   - It sets `*zCursor` to the next parse position. The intent is that
     the caller pass the same pointer to each call until this function
     returns false.

   It returns false if:

   - No more URL args are found.
   - An allocation error while appending to bKey or bVal.

   Regardless of success or failure, it calls fsl_b_reuse() on
   its output buffers before beginning work.

   The query string is assumed to be URL-encoded and the parsed-out
   keys and values get URL-decoded when adding them to the output
   buffers.

   Example:

   ```
   fsl_b key = fsl_b_empty;
   fsl_b val = fsl_b_empty;
   char const * zTail = 0;
   while( fsl_url_next_query_arg(myUrl, &zTail, &key, &val) ){
     // key holds the key and val might hold a value
     // (else it will be empty)
   }
   fsl_b_clear(&key);
   fsl_b_clear(&val);
   ```

   That example ignores alloc errors which happen during parsing but
   for completeness one should check key.errCode and val.errCode,
   either of which might be FSL_RC_OOM.
*/
FSL_EXPORT bool fsl_url_next_query_arg(fsl_url const * u,
                                       char const **zCursor,
                                       fsl_b * bKey,
                                       fsl_b * bVal);

/**
   Converts the first nBytes bytes from pBytes to hex form, writing
   the result to pOut. pOut must have at least 2*nBytes+1 bytes of
   space, as this function writes 2*nBytes of hex and a NUL
   terminator to it.
*/
FSL_EXPORT void fsl_to_hex(unsigned char const *pBytes,
                           fsl_size_t nBytes, char *pOut);

/**
   Searches for the given word in the given Tcl-style "enum": a list
   of words.

   nWord is the byte length of word, or negative to use fsl_nstrlen().

   nList has two forms: if it's negative then aList MUST be terminated
   with a NULL entry and this function will stop at that entry. If
   nList is positive, aList is assumed to have that many valid,
   non-NULL entries.

   On a match it returns the index of the match.  On no match, returns
   a negative value.

   This is an O(N) scan. It's intended for application-level command
   dispatching, not for use in hot loops. We're assured by those who
   know better that for nList approx. 16-32 this is every bit as
   performant as a binary search would be on all modern systems.
*/
FSL_EXPORT int fsl_enum_search(char const *word, fsl_strlen_t nWord,
                               char const * const *aList, fsl_int_t nList);



#if 0
/**
   The UTF16 counterpart of fsl_looks_like_utf8(), with the addition that the
   2nd argument, if true, specifies that the 2nd argument is true then
   the contents of the buffer are byte-swapped for checking purposes.

   This does not validate that the blob is valid UTF16. It assumes that all
   code points are the same size and does not validate any of them, nor does
   it attempt to detect (invalid) switches between big-endian and little-endian.
 */
FSL_EXPORT int fsl_looks_like_utf16(fsl_b const * pContent,
                                    bool reverse, int stopFlags);

/**
   Returns true if b'c contents begin with a UTF-16 BOM. If pBomSize is not NULL
   then it is set to the byte length of the UTF-16 BOM (2 bytes). If isReversed
   is not NULL, it gets assigned to true if the input appears to be in little-endian
   format and false if it appears to be in big-endian format.
*/
FSL_EXPORT bool fsl_starts_with_bom_utf16(fsl_b const * b, unsigned int *pBomSize,
                                          bool * isReversed);
/**
   Returns true if b's content _might_ be valid UTF-16. If the 2nd argument is not NULL,
   it gets set to true if the input appears to be little-endian and false if it appears
   to be big-endian.
*/
FSL_EXPORT bool fsl_might_be_utf16(fsl_b const * b, bool * isReversed);
#endif
/* ^^^^ UTF-16 interfaces */

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_UTIL_H_INCLUDED */
/* end of file include/fossil-scm/util.h */
/* start of file include/fossil-scm/core.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_CORE_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_CORE_H_INCLUDED
/*
  Copyright 2013-2025 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

#include <stdbool.h>

/** @file core.h

  This file declares the core SCM-related public APIs.
*/

#include <time.h> /* struct tm, time_t */
#if defined(__cplusplus)
/**
  The fsl namespace is reserved for an eventual C++ wrapper for the API.
*/
namespace fsl {}
extern "C" {
#endif

/**
    An internal helper macro to help localize OOM error reports (which
    are most often side effects of other issues, rather than being
    real OOM cases). It's intended to be used like:

    ```
    void * someAllocedMemory = fsl_malloc(...); // any allocating routine
    if(!someAllocedMemory){
      fsl_report_oom;
      rc = FSL_RC_OOM;
      goto end;
    }
    ```

    or:

    ```
    if(FSL_RC_OOM==fs){ fsl_report_oom; }
    ```

    Note that this macro _may_ expand to encompass multiple commands
    so must never be used as the RHS of an `if` without squiggly
    braces surrounding it (as in the above example).

    This macro is _not_ invoked in _every_ possible OOM case, so
    cannot simply be replaced with abort() to kill the app on OOM.
    For that, apply a custom allocator via fsl_lib_configurable.
*/
#if !defined(fsl_report_oom_impl)
#define fsl_report_oom_impl \
  fprintf(stderr,"OOM @ %s:%d\n", __FILE__, __LINE__)
#endif

/* older name fos fsl_report_oom */
#define FSL__WARN_OOM fsl_report_oom_impl
#define fsl_report_oom fsl_report_oom_impl
#if defined(FSL_DEBUG_CHECK_OOM_RC)
#define fsl_check_oom_rc(RC) if(FSL_RC_OOM==(RC)){fsl_report_oom;}(void)0
#else
#define fsl_check_oom_rc(RC) (void)0
#endif

/**
   @struct fsl_cx

   The main Fossil "context" type. This is the first argument to
   many Fossil library API routines, and holds all state related
   to a checkout and/or repository and/or global fossil configuration
   database(s).

   An instance's lifetime looks something like this:

   ```
   int rc;
   fsl_cx * f = NULL; // ALWAYS initialize to NULL or results are undefined
   rc = fsl_cx_init( &f, NULL );
   assert(!rc);
   rc = fsl_repo_open( f, "myrepo.fsl" );
   ...use the context, and clean up when done...
   fsl_cx_finalize(f);
   ```

   The contents of an fsl_cx instance are strictly private, for use
   only by APIs in this library. Any client-side dependencies on
   them will lead to undefined behaviour at some point.
*/
typedef struct fsl_cx_config fsl_cx_config;
typedef struct fsl_db fsl_db;
typedef struct fsl_stmt fsl_stmt;
//typedef struct fsl__cx fsl_cx;
typedef struct fsl_cx fsl_cx;

/**
   This enum defines type ID tags with which the API tags fsl_db
   instances so that the library can figure out which DB is
   which. This is primarily important for certain queries, which
   need to know whether they are accessing the repo or config db,
   for example.

   As of 2021-10, the fossil context db model has long been, and is
   very, very likely to remain:

   - When a context starts up, it creates a temporary db for use
     as its `main` db.

   - When a repo or checkout db are opened, they are `ATTACH`ed to the
     main db with the names `repo` resp. `ckout`. (Note that those
     differ from the names fossil(1) uses: `repository` and
     `localdb`.)

   A large amount of the library code is written _as if_ the library
   (roughly) followed fossil's model of using separate sqlite3
   objects, even though it does not do so. The reason is historical:
   when starting the libfossil port, it was clear that fossil's
   internal connection juggling was going to be painful for the
   library, so the internal API was shaped to permit two separate
   approaches:

   Approach 1: the first db which gets opened (repo, checkout, or
   config) becomes the `main` db and all others get attached using
   their API-standard alias. That is _mostly_ what fossil does, but it
   leads to fossil sometimes having to "swap" connections by closing
   the db and re-opening it so that the db names are in a state which
   fits the current use. That model led to the creation of this
   enum. However, it also leads to unpredictable database names for
   purposes of queries, as we're never sure (at the client level or
   higher library-level APIs) which db is `main` and which has an
   alias.

   Approach 2: open a temp (or in-memory) db and attach all of the
   others to that using well-defined names.

   The latter has proven to work well enough that returning to the
   first approach seems _extremely_ unlikely at this point. Thus some
   newer library-level code behaves as if the latter model is in effect
   (which it is).

   The long and the short of the above diversion is that APIs like
   fsl_cx_db_repo() and fsl_cx_db_ckout() will always return the same
   database handle, but they can tell whether a given role has been
   attached or not and will fail in their documented ways when the
   role's corresponding database has not yet been attached. e.g.
   `fsl_cx_db_repo()` will return `NULL` if a repo database is not
   attached.

   @see fsl_db_role_name()
   @see fsl_cx_db_file_for_role()
*/
enum fsl_dbrole_e {
/**
   Sentinel "no role" value.
*/
FSL_DBROLE_NONE = 0,
/**
   The global (per user) config db. Analog to fossil's "configdb".
*/
FSL_DBROLE_CONFIG = 0x01,
/**
   The repository db. Analog to fossil's "repository".
*/
FSL_DBROLE_REPO = 0x02,
/**
   The checkout db. Analog to fossil's "localdb".
*/
FSL_DBROLE_CKOUT = 0x04,
/**
   Analog to fossil's "main", which is an alias for the first db
   opened. In this API a fsl_cx instance has a temporary/transient
   main db opened even if it does not have a repository, checkout, or
   config db opened.
*/
FSL_DBROLE_MAIN = 0x08,
/**
   Refers to the "temp" database. This is only used by a very few APIs
   and is outright invalid for most.
*/
FSL_DBROLE_TEMP = 0x10
};
typedef enum fsl_dbrole_e fsl_dbrole_e;

/**
   Bitmask values specifying "configuration sets".  The values in
   this enum come directly from fossil(1), but they are not part of
   the db structure, so may be changed over time.

   It seems very unlikely that these will ever be used at the level of
   this library. They are a "porting artifact" and retained for the
   time being, but will very likely be removed.
*/
enum fsl_configset_e {
/** Sentinel value. */
FSL_CONFSET_NONE = 0x000000,
/** Style sheet only */
FSL_CONFIGSET_CSS = 0x000001,
/** WWW interface appearance */
FSL_CONFIGSET_SKIN = 0x000002,
/** Ticket configuration */
FSL_CONFIGSET_TKT = 0x000004,
/** Project name */
FSL_CONFIGSET_PROJ = 0x000008,
/** Shun settings */
FSL_CONFIGSET_SHUN = 0x000010,
/** The USER table */
FSL_CONFIGSET_USER = 0x000020,
/** The CONCEALED table */
FSL_CONFIGSET_ADDR = 0x000040,
/** Transfer configuration */
FSL_CONFIGSET_XFER = 0x000080,
/** Everything */
FSL_CONFIGSET_ALL = 0x0000ff,
/** Causes overwrite instead of merge */
FSL_CONFIGSET_OVERWRITE = 0x100000,
/** Use the legacy format */
FSL_CONFIGSET_OLDFORMAT = 0x200000
};
typedef enum fsl_configset_e fsl_configset_e;

/**
   Runtime-configurable flags for a fsl_cx instance.

   @see fsl_cx_flag_set()
   @see fsl_cx_flags_get()
*/
enum fsl_cx_flags_e {
/**
   The "no flags" value. Guaranteed to be 0 and this is the only entry
   in this enum which is guaranteed to have a stable value.
*/
FSL_CX_F_NONE = 0,
/**
   Tells us whether or not we want to calculate R-cards by default.
   Historically they were initially required but eventually made
   optional due largely to their memory costs.
*/
FSL_CX_F_CALC_R_CARD = 0x01,

/**
   When encounting artifact types in the crosslinking phase which
   the library does not currently support crosslinking for, skip over
   them instead of generating an error. For day-to-day use this is,
   perhaps counter-intuitively, generally desirable.

   As of 2021-12-04, crosslinking of all core fossil artifact types is
   supported, so this flag is effectively a no-op until/unless a new
   artifact type is added to fossil.
*/
FSL_CX_F_SKIP_UNKNOWN_CROSSLINKS = 0x02,

/**
   By default, fsl_reserved_fn_check() will fail if the given filename
   is reserved on Windows platforms because such filenames cannot be
   checked out on Windows.  This flag removes that limitation. It
   should only be used, if at all, for repositories which will _never_
   be used on Windows.
*/
FSL_CX_F_ALLOW_WINDOWS_RESERVED_NAMES = 0x04,

/**
   If on (the default) then an internal cache will be used for
   artifact loading to speed up operations which do lots of that.
   Disabling this will save memory but may hurt performance for
   certain operations.
*/
FSL_CX_F_MANIFEST_CACHE = 0x08,

/**
   If on (the default) then fsl_content_get() will use an internal
   cache to speed up loading of repeatedly-fetched artifacts.
   Disabling this can be costly.
*/
FSL_CX_F_BLOB_CACHE = 0x10,

/**
   Internal use only to prevent duplicate initialization of some
   bits.
*/
FSL_CX_F_IS_OPENING_CKOUT = 0x100,

/**
   Default flags for all fsl_cx instances.
*/
FSL_CX_F_DEFAULTS = FSL_CX_F_MANIFEST_CACHE | FSL_CX_F_BLOB_CACHE

};
typedef enum fsl_cx_flags_e fsl_cx_flags_e;

/**
    List of hash policy values. New repositories should generally use
    only SHA3 hashes, but older repos may contain SHA1 hashes (perhaps
    only SHA1), so we have to support those. Repositories may contain
    a mix of hash types.

    Maintenance ACHTUNG: this enum's values must align with those from
    fossil(1) because their integer values are used in the
    `repo.config` table.
*/
enum fsl_hashpolicy_e {
/** Use only SHA1 hashes. */
FSL_HPOLICY_SHA1 = 0,
/** Accept SHA1 hashes but auto-promote to SHA3. */
FSL_HPOLICY_AUTO = 1,
/** Use SHA3 hashes. */
FSL_HPOLICY_SHA3 = 2,
/** Use SHA3 hashes exclusively. */
FSL_HPOLICY_SHA3_ONLY = 3,
/** With this policy, fsl_uuid_is_shunned() will always return true
    for SHA1 hashes, making it "impossible" to get SHA1-hashed content
    into the repository (for a given value of "impossible"). */
FSL_HPOLICY_SHUN_SHA1 = 4
};
typedef enum fsl_hashpolicy_e fsl_hashpolicy_e;


/**
   A macro which invokes its argument (a macro name) to expand to all
   possible values of fsl_rc_e entries. The macro name passed to it is
   invoked once for each entry and passed 3 arguments: the enum
   entry's full name (FSL_RC_...), its integer value, and a help-text
   string.
*/
#define fsl_rc_e_map(E) \
  E(FSL_RC_OK, 0, \
    "The quintessential not-an-error value.")    \
  E(FSL_RC_ERROR, 100, \
    "Generic/unknown error.")                                           \
  E(FSL_RC_NYI, 101, \
    "A placeholder return value for not yet implemented functions.")    \
  E(FSL_RC_OOM, 102, \
    "Out of memory. Indicates that a resource allocation request failed.") \
  E(FSL_RC_MISUSE, 103, \
    "API misuse (invalid args).")                                       \
  E(FSL_RC_RANGE, 104, \
    "Some range was violated (function argument, UTF character, etc.).") \
  E(FSL_RC_ACCESS, 105, \
    "Indicates that access to or locking of a resource was denied "     \
    "by some security mechanism or other.")                             \
  E(FSL_RC_IO, 106, \
    "Indicates an I/O error. Whether it was reading or "                \
    "writing is context-dependent.")                                    \
  E(FSL_RC_NOT_FOUND, 107, \
    "Requested resource not found")                                     \
  E(FSL_RC_ALREADY_EXISTS, 108,                                         \
    "Indicates that a to-be-created resource already exists.")          \
  E(FSL_RC_CONSISTENCY, 109, \
    "Data consistency problem")                                         \
  E(FSL_RC_REPO_NEEDS_REBUILD, 110,                                     \
    "Indicates that the requested repo needs to be rebuilt.")           \
  E(FSL_RC_NOT_A_REPO, 111,                                             \
    "Indicates that the requested repo is not, in fact, a repo. "       \
    "Also used by some APIs to indicate that they require a "           \
    "repository db but none has been opened.")                          \
  E(FSL_RC_REPO_VERSION, 112,                                           \
    "Indicates an attempt to open a too-old or too-new repository db.") \
  E(FSL_RC_DB, 113, \
    "Indicates db-level error (e.g. statement prep failed). In such "   \
    "cases, the error state of the related db handle (fsl_db) or "      \
    "Fossil context (fsl_cx) will be updated to contain more "          \
    "information directly from the db driver.")                         \
  E(FSL_RC_BREAK, 114, \
    "Used by some iteration routines to indicate that "                 \
    "iteration should stop prematurely without an error.")              \
  E(FSL_RC_STEP_ROW, 115, \
    "Indicates that fsl_stmt_step() has fetched a row and "             \
    "the cursor may be used to access the current row state (e.g. using " \
    "fsl_stmt_get_int32() and friends). It is strictly illegal to use " \
    "the fsl_stmt_get_xxx() APIs unless fsl_stmt_step() has returned "  \
    "this code.")                                                       \
  E(FSL_RC_STEP_DONE, 116, \
    "Indicates that fsl_stmt_step() has reached the end of "            \
    "the result set and that there is no row data to process. This is also the " \
    "result for non-fetching queries (INSERT and friends). It is strictly " \
    "illegal to use the fsl_stmt_get_xxx() APIs after fsl_stmt_step() has " \
    "returned this code.")                                              \
  E(FSL_RC_STEP_ERROR, 117, \
    "Indicates that a db-level error occurred "                         \
    "during a fsl_stmt_step() iteration.")                              \
  E(FSL_RC_TYPE, 118,                                                   \
    "Indicates that some data type or logical type is incorrect "       \
    "(e.g. an invalid card type in conjunction with a given fsl_deck).") \
  E(FSL_RC_NOT_A_CKOUT, 119,                                            \
    "Indicates that an operation which requires a checkout does not "   \
    "have a checkout to work on.")                                      \
  E(FSL_RC_REPO_MISMATCH, 120, \
    "Indicates that a repo and checkout do not belong together.")       \
  E(FSL_RC_CHECKSUM_MISMATCH, 121,                                      \
    "Indicates that a checksum comparison failed, possibly indicating " \
    "that corrupted or unexpected data was just read.")                 \
  E(FSL_RC_LOCKED, 122, \
    "Indicates a resource-locking error of some sort, normally a db lock.") \
  E(FSL_RC_CONFLICT, 123,                                               \
    "Indicates that a merge conflict, or some other context-dependent " \
    "type of conflict, was detected.")                                  \
  E(FSL_RC_UNKNOWN_RESOURCE, 124, \
    "This is a special case of FSL_RC_NOT_FOUND, intended specifically " \
    "to differentiate from \"file not found in filesystem\" " \
    "(FSL_RC_NOT_FOUND) and \"fossil does not know about this file\" in " \
    "routines for which both might be an error case. An example is a " \
    "an operation which wants to update a repo file with contents " \
    "from the filesystem - the file might not exist or it might not be " \
    "in the current repo db. " \
    "That said, this can also be used for APIs which search for other " \
    "resources (UUIDs, tickets, etc.), but FSL_RC_NOT_FOUND is already " \
    "fairly well entrenched in those cases and is unambiguous, so this " \
    "code is only needed by APIs for which both cases described above " \
     "might happen." ) \
  E(FSL_RC_SIZE_MISMATCH, 125, \
    "Indicates that a size comparison check failed. " \
    "TODO: remove this if it is not used." )          \
  E(FSL_RC_DELTA_INVALID_SEPARATOR, 126, \
    "Indicates that an invalid separator was encountered while " \
    "parsing a delta." )                                         \
  E(FSL_RC_DELTA_INVALID_SIZE, 127, \
    "Indicates that an invalid size value was encountered while " \
    "parsing a delta." )                                          \
  E(FSL_RC_DELTA_INVALID_OPERATOR, 128, \
    "Indicates that an invalid operator was encountered while parsing " \
    "a delta.")                                             \
  E(FSL_RC_DELTA_INVALID_TERMINATOR, 129, \
    "Indicates that an invalid terminator was encountered while " \
    "parsing a delta.")                                        \
  E(FSL_RC_SYNTAX, 130, \
    "Indicates a generic syntax error in a structural artifact. Some " \
     "types of manifest-releated errors are reported with more specific " \
    "error codes, e.g. FSL_RC_RANGE if a given card type appears too " \
    "often.")                                                          \
  E(FSL_RC_AMBIGUOUS, 131, \
    "Indicates that some value or expression is ambiguous. Typically " \
    "caused by trying to resolve ambiguous symbolic names or hash " \
    "prefixes to their full hashes.")                               \
  E(FSL_RC_NOOP, 132, \
    "Used by fsl_checkin_commit(), and similar operations, to indicate " \
    "that they're failing because they would be no-ops. That would " \
    "normally indicate a \"non-error\", but a condition the caller " \
    "certainly needs to know about.")                                \
  E(FSL_RC_PHANTOM, 133, \
    "A special case of FSL_RC_NOT_FOUND which indicates that the " \
    "requested repository blob could not be loaded because it is a " \
    "phantom. That is, the record is found but its contents are not " \
    "available. Phantoms are blobs which fossil knows should exist, " \
    "because it's seen references to their hashes, but for which it does " \
    "not yet have any content.")                                        \
  E(FSL_RC_UNSUPPORTED, 134, \
    "Indicates that the requested operation is unsupported.")   \
  E(FSL_RC_MISSING_INFO, 135, \
    "Indicates that the requested operation is missing certain required " \
    "information.")                                         \
  E(FSL_RC_DIFF_BINARY, 136, \
    "Special case of FSL_RC_TYPE triggered in some diff APIs, indicating " \
    "that the API cannot diff what appears to be binary data.") \
  E(FSL_RC_DIFF_WS_ONLY, 137, \
    "Triggered by some diff APIs to indicate that only whitespace " \
    "changes we found and the diff was requested to ignore whitespace.") \
  E(FSL_RC_INTERRUPTED, 138, \
    "Intended to be used with fsl_cx_interrupt() by signal handlers " \
    "and UI threads.")                                                \
  E(FSL_RC_WOULD_FORK, 139, \
    "Intended to be used by operations which would cause what is " \
    "presumably an unintended fork. Fossil does not have any issues with " \
    "forking, but practice suggests that most forks (that is, checking " \
    "in to a non-leaf version) are unintentional.")                     \
  E(FSL_RC_CANNOT_HAPPEN, 140, \
    "This is intended only for internal use with fsl__fatal(), to " \
    "report conditions which \"cannot possibly happen\".") \
  E(FSL_RC_TIMEOUT, 141, \
    "Indicates that a context-specific timeout was triggered.") \
  E(FSL_RC_REMOTE, 142, \
    "Indicates that an error was received from a remote during " \
    "syncing.")                                                  \
  E(FSL_RC_SHUNNED, 143, \
    "Indicates that a given blob is in the SHUNNED list.")  \
  E(FSL_RC_end,999, \
    "Must be the final entry in the enum. Used for creating client-side " \
    "result codes which are guaranteed to live outside of this one's " \
    "range.")

/**
   Most functions in this library which return an int return result
   codes from the fsl_rc_e enum.  None of these entries are guaranteed
   to have a specific value across library versions except for
   FSL_RC_OK, which is guaranteed to always be 0 (and the API
   guarantees that no other code shall have a value of zero).

   The only reasons numbers are hard-coded to the values is to
   simplify debugging during development. Clients may use
   fsl_rc_cstr() to get some human-readable (or programmer-readable)
   form for any given value in this enum.
*/
enum fsl_rc_e {

#define E(N,V,H) N = V,
  fsl_rc_e_map(E)
#undef E

};
typedef enum fsl_rc_e fsl_rc_e;

/**
   File permissions flags supported by fossil manifests. Their numeric
   values are a hard-coded part of the Fossil architecture and must
   not be changed. These refer to manifest-level permissions, not
   filesystem-level permissions (though they translate to/from
   filesystem-level meanings at some point).
*/
enum fsl_fileperm_e {
/**
   Indicates a regular, writable file. Fossil has no concept of
   SCM-managed read-only files, nor has a need for such an oddity ever
   come up.
*/
FSL_FILE_PERM_REGULAR = 0,
/** Indicates a regular file with the executable bit set. */
FSL_FILE_PERM_EXE = 0x1,
/**
   Indicates a symlink. Symlinks do not have the executable bit set
   separately on Unix systems.
*/
FSL_FILE_PERM_LINK = 0x2
};
typedef enum fsl_fileperm_e fsl_fileperm_e;

/**
   Returns a "standard" string form for a fsl_rc_e code.  The string
   is primarily intended for debugging purposes.  The returned bytes
   are guaranteed to be static and NUL-terminated. They are not
   guaranteed to contain anything useful for any purposes other than
   debugging and tracking down problems. If passed a code which is
   not in the fsl_rc_e enum, it returns NULL.
*/
FSL_EXPORT char const * fsl_rc_cstr(int rc);

/**
   Returns the value of FSL_LIBRARY_VERSION used to compile the
   library. If this value differs from the value the caller was
   compiled with, Chaos might ensue.

   The API does not yet have any mechanism for determining
   compatibility between library versions and it also currently does
   no explicit checking to disallow incompatible versions.
*/
FSL_EXPORT char const * fsl_library_version(void);

/**
   Returns the SCM-specific version info for libfossil (the hash and
   timestamp of its own source's version).
*/
FSL_EXPORT char const * fsl_library_version_scm(void);

/**
   Returns true if yourLibVersion compares lexically equal to
   FSL_LIBRARY_VERSION, else it returns false. It is intended to be
   passed the FSL_LIBRARY_VERSION string the client code was built
   with.
*/
FSL_EXPORT bool fsl_library_version_matches(char const * yourLibVersion);

/**
   This type, accessible to clients via the ::fsl_lib_configurable
   global, contains configuration-related data for the library which
   can be swapped out by clients. All modifications must be made
   before using any of the library's APIs.
*/
struct fsl_lib_configurable_t {
  /**
     Library-wide allocator. It may be replaced by the client IFF it
     is replaced before the library allocates any memory. The default
     implementation uses the C-standard de/re/allocators.  Modifying
     this member while any memory allocated through it is still "live"
     leads to undefined results. There is an exception: a "read-only"
     middleman proxy which does not change how the memory is allocated
     or intepreted can safely be swapped in or out at any time
     provided the underlying allocator stays the same and the client
     can ensure that there are no thread-related race
     conditions. e.g. it is legal to swap this out with a proxy which
     logs allocation requests and then forwards the call on to the
     original implementation, and it is legal to do so at essentially
     any time. The important thing this that all of the
     library-allocated memory goes through a single underlying
     (de)allocator for the lifetime of the application.
  */
  fsl_allocator allocator;
};
typedef struct fsl_lib_configurable_t fsl_lib_configurable_t;
FSL_EXPORT fsl_lib_configurable_t fsl_lib_configurable;

/**
   SQLite Encryption Extension (SEE) key types for use with
   fsl_see_key_f(). Each of these options corresponds to one
   of the key-entry modes supported by SEE via pragmas,
   e.g. PRAGMA key, PRAGMA textkey, and PRAGMA hexkey.

   See (as it were): https://sqlite.org/see

   As of 2026-10-28, this is deprecated, in that it's not a necessary
   part of the API.
*/
enum fsl_see_keytype_e {
  /** Sentinel value indicating "not an SEE key". */
  FSL_SEE_KEYTYPE_NONE = 0,
  /** Corresponses to (PRAGMA key). */
  FSL_SEE_KEYTYPE_PLAIN = 1,
  /** Corresponses to (PRAGMA hexkey). Binary data to be hex-encoded
      by the library. */
  FSL_SEE_KEYTYPE_BINARY = 2,
  /** Corresponses to (PRAGMA hexkey). Encoded by the client as a
      series of hex digits. */
  FSL_SEE_KEYTYPE_HEXKEY = 3,
  /** Corresponses to (PRAGMA textkey). */
  FSL_SEE_KEYTYPE_TEXTKEY = 4
};
typedef enum fsl_see_keytype_e fsl_see_keytype_e;

/**
   EXPERIMENTAL and subject to change. But it seems to do its job
   reasonably well.

   A callback type for fetching an encryption key for use with the
   SQLite Encryption Extension API. This is only for use in
   SEE-capable builds.

   `pState` is the pointer provided by the client for use here
   (typically via fsl_cx_config::see::pState). It is opaque to the
   library, intended solely for the SEE client's use.

   `zDbFile` is the NUL-terminated name of the db for which the key is
   being requested.

   If a key is available, it must be appended to pOut using
   fsl_b_append() (or equivalent).

   On success, it must return 0. Any non-0 result value is treated by
   the library as failure to open the db, with one exception:
   FSL_RC_UNSUPPORTED indicates that decryption is not supported but
   opening of a database will not fail fatally for this result.
   Instead, if the db really is encrypted, it will fail later when the
   db is first used.

   If it populates pOut then it must set `*keyType` to one of the
   entries from the fsl_see_keytype_e enum, indicating the type of the
   key.

   If the implementation has no key to provide for the db, but does
   not know that to be an error, it should simply return 0 and not add
   any bytes to pOut. It need not set `*keyType` in this case, as the
   library guarantees that it will initially have the value
   FSL_SEE_KEYTYPE_NONE.

   The library guarantees that the pOut->mem memory holding the
   collected key (A) is not copied beyond that necessary for passing
   it to SQLite and (B) is zeroed out immediately after its use (by
   the routine which invokes this callback). It cannot, however, make
   the same guaranty about the SQLite-side memory which holds that
   key.

   The library does not cache the results of these calls and may need
   to call this multiple times for the same database during the life
   of a single fsl_cx. (Ordinarily, though, the SCM databases are
   opened a single time and left that way.)

   A recommended convention, derived from fossil(1), is to name
   encrypted repositories with a suffix of ".efossil". Implementations
   of this callback could use such a convention to determine whether
   or not a key is necessary for the db (something this library cannot
   do on its own[^1]).

   [^1]: 2026-10-28: if we read the first bytes of the db, bypassing
   sqlite, we could assume that files without the standard db header
   are encrypted, but using POSIX APIs to open/close files which
   SQLite uses can mess up their locks.
*/
typedef int (*fsl_see_key_f)(void * pState, const char *zDbFile,
                             fsl_b * pOut, int *keyType);

/**
   Expands to a mapping of all fsl_msg types by invoking
   E(NAME,VALUE,PayloadDescription) for each one. NAME is the suffix
   part of the name, e.g. mask_type instead of
   FSL_MSG_mask_type. VALUE is its integer value. PayloadDescription
   is a human-legible string typically noting the data type of the
   payload.

   Each entry encodes the data type corresponding to the associated
   fsl_msg object's payload member: mask the message type value
   against FSL_MSG_mask_type to get the payload's type.

   The top 8 bits are a single-digit value, not a bitmask.

   This mechanism was added for the sync subsystem and the goal is now
   to replace some of the library's disparate callbacks with this
   mechanism.
*/
#define fsl_msg_map(E)                                     \
  E(INVALID,           0, "Sentinel value")                \
  E(mask_type,         0x7F000000, "Data type mask")       \
  E(mask_reserved,     0x00FFFF00, "Reserved")             \
  E(mask_purpose,      0x000000FF, "Message purpose ID")   \
  E(type_null,         0x01000000, "NULL")                 \
  E(type_string,       0x02000000, "(char const *)")       \
  E(type_buffer,       0x03000000, "(fsl_b const *)") \
  E(type_size,         0x04000000, "(fsl_size_t const *)") \
  E(type_blob,         0x06000000, "(fsl_msg_blob const *)" ) \
  E(type_rebuild,      0x07000000, "(fsl_msg_rebuild const *)" )  \
  E(type_xfer,         0x08000000, "(fsl_msg_xfer const *)" )  \
  E(ERROR,         0x01 | FSL_MSG_type_string, "Error string") \
  E(INFO,          0x02 | FSL_MSG_type_string, "Info string")  \
  E(DEBUG,         0x03 | FSL_MSG_type_string, "Debugging string") \
  E(TMPFILE,       0x04 | FSL_MSG_type_string, "value=name of temp file left over") \
  E(CONNECT,       0x05 | FSL_MSG_type_size, "value=trip number") \
  E(RCV_BLOB,      0x06 | FSL_MSG_type_blob, "Blob received")     \
  E(RCV_MESSAGE,   0x07 | FSL_MSG_type_string, "\"message\" card from remote") \
  E(RCV_CONFIG,    0x08 | FSL_MSG_type_string, "Config group name") \
  E(REBUILD,       0x09 | FSL_MSG_type_rebuild, "(fsl_msg_rebuild const *)") \
  E(XFER,          0x0A | FSL_MSG_type_xfer, "(fsl_msg_xfer const *)") \
  /* TODO: consolidate TXN_X into TXN and pass an info object. */ \
  E(TXN_BEGIN,     0x0B | FSL_MSG_type_size, "value=transaction level") \
  E(TXN_COMMIT,    0x0C | FSL_MSG_type_size, "value=transaction level") \
  E(TXN_ROLLBACK,  0x0D | FSL_MSG_type_size, "value=transaction level") \
  E(VERBOSE,       0x0E | FSL_MSG_type_string, "Info string") \
  E(VERIFY,        0x0F | FSL_MSG_type_size, "value=artifacts left to verify")

/**
   Message type flags Indicators for use with fsl_sc::status,
   fsl_cx_emit(), and friends.
*/
enum fsl_msg_e {
#define E(NAME,VAL,IGNORED) FSL_MSG_ ## NAME = VAL,
  fsl_msg_map(E)
#undef E
};

typedef enum fsl_msg_e fsl_msg_e;

/**
   Message payload type for FSL_MSG_type_blob.
*/
struct fsl_msg_blob {
  char const * hash;
  fsl_int_t size /* negative for phantom blobs */;
};
typedef struct fsl_msg_blob fsl_msg_blob;

/**
   Returns the C-string form of the given sync message type, or NULL
   if e is invalid.
*/
char const * fsl_msg_type_cstr(fsl_msg_e e);

/**
   A "transfer context" type used by many of the sync transfer
   APIs. This type is opaque to client code.
*/
typedef struct fsl_xfer fsl_xfer;

/**
   A message object type for sending synchronous messages to callbacks
   during certain processing steps in the library, the intent
   primarily being for UIs to be able to provide feedback during
   long-running or multi-step operations.
*/
struct fsl_msg {
  /** The type of status message. */
  fsl_msg_e type;

  /**
     An optional bit of informative text. If set, the bytes are owned
     by the library and may be (and likely are) invalidated as soon as
     the message callback returns. The data type depends on this->type
     and it can be interpreted by deciphering fsl_msg_e.
  */
  void const * payload;

  /**
     This message's fsl_cx context, providing the callback with access
     to the associated SCM state.
  */
  fsl_cx * f;
};

typedef struct fsl_msg fsl_msg;

/** fsl_msg instance intended for const-copy initialization. */
#define fsl_msg_empty_m { \
    .type = FSL_MSG_INVALID, .payload = NULL, \
    .f = NULL \
  }

/** fsl_msg instance intended for non-const copy initialization. */
extern const fsl_msg fsl_msg_empty;

/**
   A callback for use with the library's message-passing subsystem, to
   provide feedback during potentially long-running work, in
   particular synchronization with a remote.

   Implementations are passed the a message object and any state
   associated with the callback.

   If the function returns non-0, the operation is aborted and that
   result is propagated back up through the API.  On error, this
   callback is expected to call either of fsl_cx_err_set() or the
   fsl_xfer_error() family of functions and return that code.

   Messages are synchronous - the library must wait on a response from
   this function before continuing. Ergo, clients should not perform
   long work in the status callback (or should do so in a separate
   thread which _does_not_ use msg->f (which is not
   thread-safe)).

   This method is intended primarily for logging or non-interactive
   feedback, with the exception of the ability to return non-0 to
   interrupt the sync. e.g. an implementation could return
   FSL_RC_BREAK in response to an application-side cancel/interrupt
   button being triggered.

   When triggered via a sync operation, the library guarantees that a
   db transaction will be in place when it calls this, a further
   incentive to keep implementations short and fast because the db is
   necessarily locked during that time. The exception is
   FSL_MSG_TMPFILE, which the popen-based channels emit during the
   exchange of a request. Sync commits its transaction before each
   exchange and begins the next one after it, except during a clone
   or inside a transaction the caller opened.
*/
typedef int (*fsl_msg_f)(fsl_msg const * msg, void *state);

/**
   Client callback info for receiving various events during
   fossil sync processing.
*/
struct fsl_msg_listener {
  /** Callback function. */
  fsl_msg_f callback;
  /** State for the final argument to this->callback(). */
  void * state;
};
typedef struct fsl_msg_listener fsl_msg_listener;
#define fsl_msg_listener_empty_m { .callback=0, .state=0 }
extern const fsl_msg_listener fsl_msg_listener_empty;


/**
   An alternative approach to fsl_see_key_f() which is both more
   generic and keeps the library from ever having to lay eyes on the
   encryption key.

   The fsl_cx class uses this as follows:

   Immediately after a db is sqlite3_open()'d, before the library
   connects the db to a fsl_cx instance, the callback of this type set
   in fsl_cx_config::dbOnOpen is called and passed the db handle and
   the fsl_cx_config::dbOnOpen::state. If that callback returns 0 then
   the context continues as normal, otherwise the open is considered
   to have failed. Errors "should" be reported via the db->error
   object. If this function returns non-0 but does not update
   db->error then the library attempts to extract an error message
   from the db handle. Failing that, it will propagate the unadorned
   result code.

   This callback is _really_ only intended for use in setting an
   encryption key on an encrypted database. Implementations are
   strongly encourages to avoid any temptation to perform other
   db-side work here, e.g.  schema validation or manipulation.

   The following operations are very expressly forbidden to
   implementations:

   - Any which require libfossil-level functionality. At the point
     this is called, the pending fsl_cx owner has not yet been
     connected with the database.

   - Using sqlite3_db_config() with the SQLITE_DBCONFIG_MAINDBNAME
     option.  The library aliases "main" to either "repo" or "ckout",
     depending on which db is opened.

   - Closing the db.
*/
typedef int (*fsl_db_on_open_f)(fsl_db *db, void *pState);


/**
   A part of the configuration used by fsl_cx_init() and friends.
*/
struct fsl_cx_config {
  /**
     If true, all SQL which goes through the fossil engine will be
     traced to stdout. This is, of course, only intended for use in
     debugging.

     TODO: replace this with a fsl_outputer.
  */
  bool traceSql;
  /**
     If true, the fsl_print() SQL function will output its output to the
     fsl_output()-configured channel, else it is a no-op.
  */
  bool sqlPrint;

  /**
     Specifies the default hash policy.
  */
  fsl_hashpolicy_e hashPolicy;

  /**
     Listener for fsl_msg-type events. This is how the library
     provides status updates for potentially long-running operations
     like synchronization.

     Potential TODO is support multiple listeners.
  */
  fsl_msg_listener listener;

  /**
     The output channel for the Fossil instance.

     Reminder to self: if this is not used at the library level then
     consider removing it. This addition may have been a piece of
     unnecessary overengineering. To the best of my recollection, the
     library internals do not use this, but the fcli API does. If that
     is indeed the case, we can move it into that API.
  */
  fsl_outputer output;

  /**
     A hook called when a db is opened, intended primarily for
     supplying a SEE decryption key to it.
  */
  struct {
    /**
       See fsl_db_on_open_f() for the semantics.
    */
    fsl_db_on_open_f callback;
    /**
       Client-defined state for this->callback()'s second argument.
    */
    void * state;
  } dbOnOpen;
};

/**
   fsl_cx_config instance initialized with defaults, intended for
   const-copy initialization.
*/
#define fsl_cx_config_empty_m {     \
    .traceSql = 0,                  \
    .sqlPrint = 0,                  \
    .hashPolicy = FSL_HPOLICY_SHA3, \
    .listener = fsl_msg_listener_empty_m,      \
    .output = {.out=NULL, .state=NULL},        \
    .dbOnOpen = {.callback=NULL, .state=NULL}  \
}

/**
   fsl_cx_config instance initialized with defaults, intended for
   non-const copy initialization.
*/
FSL_EXPORT const fsl_cx_config fsl_cx_config_empty;

/**
   Allocates a new fsl_cx instance, which must eventually
   be passed to fsl_cx_finalize() to clean it up.
   Normally clients do not need this - they can simply pass
   a pointer to NULL as the first argument to fsl_cx_init()
   to let it allocate an instance for them.
*/
FSL_EXPORT fsl_cx * fsl_cx_malloc(void);

/**
   Initializes a fsl_cx instance. tgt must be a pointer to NULL,
   e.g.:

   ```
   fsl_cxt * f = NULL; // NULL is important - see below
   int rc = fsl_cx_init( &f, NULL );
   ```

   It is very important that f be initialized to NULL _or_ to an
   instance which has been properly allocated and empty-initialized
   (e.g. via fsl_cx_malloc()). If *tgt is NULL, this routine
   allocates the context, else it assumes the caller did. If f
   points to unitialized memory then results are undefined.

   If the second parameter is NULL then default implementations are
   used for the context's output routine and other options. If it
   is not NULL then param->allocator and param->output must be
   initialized properly before calling this function. The contents
   of param are bitwise copied by this function and ownership of
   the returned value is transfered to *tgt in all cases except
   one:

   If passed a pointer to a NULL context and this function cannot
   allocate it, it returns FSL_RC_OOM and does not modify *tgt. In
   this one case, ownership of the context is not changed (as there's
   nothing to change!). On any other result (including errors),
   ownership of param's contents are transfered to *tgt and the client
   is responsible for passing *tgt ot fsl_cxt_finalize() when he is
   done with it. Note that (like in sqlite3), *tgt may be valid memory
   even if this function fails, and the caller must pass it to
   fsl_cx_finalize() whether or not this function succeeds unless it
   fails at the initial OOM (which the client can check by seeing if
   (*tgt) is NULL, but only if he set it to NULL before calling this).

   Returns 0 on success, FSL_RC_OOM on an allocation error,
   FSL_RC_MISUSE if (!tgt). If this function fails, it is illegal to
   use the context object except to pass it to fsl_cx_finalize(), as
   explained above.

   @see fsl_cx_finalize()
*/
FSL_EXPORT int fsl_cx_init( fsl_cx ** tgt, fsl_cx_config const * param );

/**
   Frees all memory associated with f, which must have been
   allocated/initialized using fsl_cx_malloc(), fsl_cx_init(), or
   equivalent, or created on the stack and properly initialized (via
   fsl_cx_init() or copy-constructed from fsl_cx_empty).  If it was
   allocated using fsl_cx_malloc(), this function frees f, else the
   memory is owned by someone else and it is not freed.

   This function triggers any finializers set for f's client state
   or output channel.

   This is a no-op if !f and is effectively a no-op if f has no
   state to destruct.
*/
FSL_EXPORT void fsl_cx_finalize( fsl_cx * f );


/**
   Sets or unsets one or more option flags on the given fossil
   context.  flags is the flag or a bitmask of flags to set (from the
   fsl_cx_flags_e enum).  If enable is true the flag(s) is (are) set,
   else it (they) is (are) unset. Returns the _previous_ set of flags
   (that is, the state they were in before this call was made).

   @see fsl_cx_flags_get()
*/
FSL_EXPORT fsl_flag32_t fsl_cx_flag_set( fsl_cx * f, fsl_flag32_t flags,
                                         bool enable );

/**
   Returns f's flags.

   @see fsl_cx_flag_set()
*/
FSL_EXPORT fsl_flag32_t fsl_cx_flags_get( fsl_cx const * f );

/**
   Sets the Fossil error state to the given error code and
   fsl_appendf()-style format string/arguments. On success it
   returns the code parameter. It does not return 0 unless code is
   0, and if it returns a value other than code then something went
   seriously wrong (e.g. allocation error: FSL_RC_OOM) or the
   arguments were invalid: !f results in FSL_RC_MISUSE.

   If !fmt then fsl_rc_cstr(code) is used to create the
   error string.

   As a special case, if code is FSL_RC_OOM, no error string is
   allocated (because it would likely fail, assuming the OOM
   is real).

   As a special case, if code is 0 (the non-error value) then fmt is
   ignored and any error state is cleared.
*/
FSL_EXPORT int fsl_cx_err_set( fsl_cx * f, int code, char const * fmt, ... );

/**
   va_list counterpart to fsl_cx_err_set().
*/
FSL_EXPORT int fsl_cx_err_setv( fsl_cx * f, int code, char const * fmt,
                                va_list args );

/**
   Fetches the error state from f. See fsl_error_get() for the semantics
   of the parameters and return value.
*/
FSL_EXPORT int fsl_cx_err_get( fsl_cx * f, char const ** str, fsl_size_t * len );

/**
   Returns f's persistent error code, or 0 if it has no error state.
*/
FSL_EXPORT int fsl_cx_err_code( fsl_cx const * f );


/**
   Returns f's error object. It is owned by f, and its address is
   stable as long as f is valid. It's provided as a semi-formal way
   for not-quite-core code to get access to f->error without having to
   reach into f directly.  It should only be preferred over
   fsl_cx_err_set()/get() when an arbitrary fsl_error object is needed
   for an API (like fsl_b_escape_arg()) and we know we'd like to
   unconditionally propagate that error via f's error state. In such
   cases, using this object can avoid a second allocation to copy the
   error message.
*/
FSL_EXPORT fsl_error const * fsl_cx_err_ec(fsl_cx const * f);

/** Non-const counterpart of fsl_cx_err_ec(). */
FSL_EXPORT fsl_error * fsl_cx_err_e(fsl_cx * f);

/**
   Resets's f's error state, basically equivalent to
   fsl_cx_err_set(f,0,NULL). This may be necessary for apps if they
   rely on looking at fsl_cx_err_get() at the end of their
   app/routine, because error state survives until it is cleared, even
   if the error held there was caught and recovered. This function
   might keep error string memory around for re-use later on.

   This does NOT reset the fsl_cx_interrupted() flag!
*/
FSL_EXPORT void fsl_cx_err_reset(fsl_cx * f);

/**
   Replaces f's error state with the contents of err, taking over
   any memory owned by err (but not err itself). Returns the new
   error state code (the value of err->code before this call) on
   success. The only error case is if !f (FSL_RC_MISUSE). If err is
   NULL then f's error state is cleared and 0 is returned. err's
   error state is cleared by this call.
*/
FSL_EXPORT int fsl_cx_err_set_e( fsl_cx * f, fsl_error * err );

/**
   If f has error state then it outputs its error state to its output
   channel and returns the result of fsl_output(). Returns 0 if f has
   no error state our output of the state succeeds. If addNewline is
   true then it adds a trailing newline to the output, else it does
   not.

   This is intended for testing and debugging only, and not as an
   error reporting mechanism for a full-fledged application.
*/
FSL_EXPORT int fsl_cx_err_report( fsl_cx * f, bool addNewline );

/**
   If db has error state, moves that state into f (without requiring
   any allocation), replacing f's error state. If db has no error
   state, f's error state is left as it is. If db is NULL then f's
   primary db connection is used. Returns FSL_RC_MISUSE if (!db &&
   f-is-not-opened), with the caveat f _always_ has a db connection
   under the current connection architecture. On success it returns
   f's resulting error code (which may be 0).

   The main purpose of this function is to propagate db-level errors
   up to higher-level code which deals directly with the f object but
   not the underlying db(s).

   @see fsl_cx_uplift_db_error2()
*/
FSL_EXPORT int fsl_cx_uplift_db_error( fsl_cx * f, fsl_db * db );

/**
   If rc is not 0, f has no error state, and db's error code is rc,
   this calls fsl_cx_uplift_db_error() and returns its result, else
   returns rc. If db is NULL, f's main db connection is used. It is
   intended to be called immediately after calling a db operation
   which might have failed, and passed that operation's result. A db
   error code which differs from rc is assumed to be left over from
   an earlier operation, and is not uplifted, so that it cannot
   replace rc or describe a different failure.

   As a special case, if rc is FSL_RC_OOM, this function has no side
   effects and returns rc. The intention of that is to keep a
   propagated db-level error (which may perhaps be stale by the time
   this is called) from hiding an OOM error.

   Results are undefined if db is NULL and f has no main db
   connection.
*/
FSL_EXPORT int fsl_cx_uplift_db_error2(fsl_cx * f, fsl_db * db, int rc);

/**
   Outputs the first n bytes of src to f's configured output
   channel. Returns 0 on success, 0 (without side effects) if !n, else
   it returns the result of the underlying output call. This is a
   harmless no-op if f is configured with no output channel.

   Results are undefined if f or src are NULL.

   @see fsl_outputf()
   @see fsl_flush()
*/
FSL_EXPORT int fsl_output( fsl_cx * f, void const * src,
                           fsl_size_t n );

/**
   Flushes f's output channel. Returns 0 on success. If the flush
   routine is NULL then this is a harmless no-op. Results are undefined
   if f is NULL.

   @see fsl_outputf()
   @see fsl_output()
*/
FSL_EXPORT int fsl_flush( fsl_cx * f );

/**
   Uses fsl_appendf() to append formatted output to the channel
   configured for use with fsl_output(). Returns 0 on success, and
   will otherwise return the result of the underlying fsl_cx_format()
   call. (Prior to 2025-08-11, it used fsl_appendf() instead.)

   Results are undefined if f or fmt are NULL or otherwise malformed.

   @see fsl_output()
   @see fsl_flush()
*/
FSL_EXPORT int fsl_outputf( fsl_cx * f, char const * fmt, ... );

/**
   va_list counterpart to fsl_outputf().
*/
FSL_EXPORT int fsl_outputfv( fsl_cx * f, char const * fmt, va_list args );


/**
   A proxy for fsl_appendfv() which pre-processes the format-specifier
   string (zFmt) to replace certain placeholders with information
   about the fsl_cx object. After doing so, it passes on the adjusted
   zFmt to fsl_appendfv().

   Placeholders are in the form {{X}}, where X is one of the words
   listed below. Any unknown X will cause the whole {{X}} to be
   emitted as-is.

   Known X values (with quotes for clarity, but the quotes are not
   part of X):

   - "chkout.dir": gets replaced with the path to the current checkout
     directory, without a trailing slash.

   - "chkout.dir/": as for ckout-dir but with a trailing slash.

   - "repo.db": gets replaced with the path to the current repository
     database.

   - "user.name": gets replaced with fsl_cx_user_guess().

   - "dbname.repo", "dbname.ckout", "bare.repo.NAME",
     "bare.ckout.NAME", "temp.NAME" and "bare.temp.NAME": get replaced
     with the names of the repository's and checkout's schemas, of the
     repository resp. checkout table NAME and of f's own TEMP table
     NAME on f's db connection, as the fsl_db SQL functions do (see
     fsl_db_prepare()). Unlike those, this function never expands
     "{{dbname.ckout}}.NAME" or "{{dbname.repo}}.NAME" as a unit, so
     while f's checkout resp. repository tables are prefixed tables of
     a host's main db (fsl_repo_open_ckout_opt::hostTablePrefix,
     fsl_repo_open_host()), a {{dbname.ckout}} resp. {{dbname.repo}}
     fails with FSL_RC_MISUSE, with f's error state set.

   File and directory names which are empty are emitted as such.

   The parser is not robust enough to attempt to recover from failures
   related to the "{{" and "}}" parts, and malformed tags may cause it
   to skip expansion on the remaining parts of the input (it will be
   passed on as-is, warts and all).

   Returns 0 on success. Returns FSL_RC_OOM if allocation of the
   formatting buffer fails. Else returns the value of the
   fsl_appendfv() call.
*/
FSL_EXPORT int fsl_cx_formatv(fsl_cx * f, fsl_output_f out,
                              void * outState, char const *zFmt,
                              va_list args );

/**
   The elipsis counterpart of fsl_cx_formatv().
*/
FSL_EXPORT int fsl_cx_format(fsl_cx * f, fsl_output_f out,
                             void * outState, char const *zFmt, ... );

/**
   Convenience formof fsl_cx_format() which appends the formatted
   output to tgt.
*/
FSL_EXPORT int fsl_cx_format_buffer(fsl_cx * f, fsl_b * tgt,
                                    char const *zFmt, ... );

/**
   Convenience formof fsl_cx_format() which appends the formatted
   output to tgt.
*/
FSL_EXPORT int fsl_cx_format_FILE(fsl_cx * f, FILE * tgt,
                                  char const *zFmt, ... );


/**
   Sets or clears (if userName is NULL or empty) the default
   repository user name for operations which require one.

   Returns 0 on success, FSL_RC_MISUSE if f is NULL,
   FSL_RC_OOM if copying of the userName fails.

   Example usage:
   ```
   char * u = fsl_user_name_guess();
   int rc = fsl_cx_user_set(f, u);
   fsl_free(u);
   ```

   (Sorry about the extra string copy there, but adding a function
   which passes ownership of the name string seems like overkill.)

   @see fsl_cx_user_guess()
*/
FSL_EXPORT int fsl_cx_user_set( fsl_cx * f, char const * userName );

/**
   If f has a user name set (via fsl_cx_user_set()) then this function
   returns that value. If none has been set, this tries to guess one,
   using the first of:

   - The "default-user" value from the checkout db's vvar table.
   - The user entry from the repo db's user table with id 1.
   - fsl_user_name_guess()

   and then assigns it as f's current user name. Returns NULL only on
   allocation error or if an environment setup error prevents
   detection of the user name. Not having a user name is not normally
   a problem, but trying to create new artifacts will fail if they
   have no user name to apply to their U-cards.

   The returned bytes are owned by f and will be invalidated by
   any future calls to fsl_cx_user_set().

   The user name is, by default, determined automatically when a repo
   or a checkout/repo combination is opened, so client code does not
   normally need to call this.
*/
FSL_EXPORT char const * fsl_cx_user_guess(fsl_cx * f);

/**
   Returns the name set by fsl_cx_user_set(), or NULL if f has no
   default user name set. The returned bytes are owned by f and will
   be invalidated by any future calls to fsl_cx_user_set().

   @see fsl_cx_user_guess()
*/
FSL_EXPORT char const * fsl_cx_user_get( fsl_cx const * f );

/**
   If f is not NULL and has a checkout db opened then this function
   returns its name. The bytes are valid until that checkout db
   connection is closed. If len is not NULL then *len is (on
   success) assigned to the length of the returned string, in
   bytes. The string is NUL-terminated, so fetching the length (by
   passing a non-NULL 2nd parameter) is optional.

   Returns NULL if !f or f has no checkout opened.

   @see fsl_ckout_open_dir()
   @see fsl_cx_ckout_dir_name()
   @see fsl_cx_db_file_config()
   @see fsl_cx_db_file_repo()
*/
FSL_EXPORT char const * fsl_cx_db_file_ckout(fsl_cx const * f,
                                             fsl_size_t * len);

/**
   Equivalent to fsl_ckout_db_file() except that
   it applies to the name of the opened repository db,
   if any. For a repository which is tables of a host's main db
   (fsl_repo_open_host()), that is the host main db's file name.

   @see fsl_cx_db_file_ckout()
   @see fsl_cx_db_file_config()
*/
FSL_EXPORT char const * fsl_cx_db_file_repo(fsl_cx const * f,
                                            fsl_size_t * len);

/**
   Equivalent to fsl_ckout_db_file() except that
   it applies to the name of the opened config db,
   if any.

   @see fsl_cx_db_file_ckout()
   @see fsl_cx_db_file_repo()
*/
FSL_EXPORT char const * fsl_cx_db_file_config(fsl_cx const * f,
                                              fsl_size_t * len);

/**
   Similar to fsl_cx_db_file_ckout() and friends except that it
   applies to db file implied by the specified role (2nd
   parameter). If no such role is opened, or the role is invalid,
   NULL is returned.

   Note that the role of FSL_DBROLE_TEMP is invalid here.
*/
FSL_EXPORT char const * fsl_cx_db_file_for_role(fsl_cx const * f,
                                                fsl_dbrole_e r,
                                                fsl_size_t * len);

/**
   If f has an opened checkout db (from fsl_ckout_open_dir()) then
   this function returns the directory part of the path for the
   checkout, including (for historical and internal convenience
   reasons) a trailing slash. The returned bytes are valid until that
   db connection is closed. If len is not NULL then *len is (on
   success) assigned to the length of the returned string, in bytes.
   The string is NUL-terminated, so fetching the length by passing a
   non-NULL 2nd parameter is optional.

   Returns NULL if !f or f has no checkout opened.

   @see fsl_ckout_open_dir()
   @see fsl_ckout_db_file()
*/
FSL_EXPORT char const * fsl_cx_ckout_dir_name(fsl_cx const * f,
                                              fsl_size_t * len);

/**
   Returns a handle to f's main db (which may or may not have any
   relationship to the repo/checkout/config databases - that's
   unspecified!), or NULL if f has no opened repo or checkout db.  The
   returned object is owned by f and the client MUST NOT do any of the
   following:

   - Close the db handle.

   - Use transactions without using fsl_db_txn_begin()
   and friends.

   - Fiddle with the handle's internals. Doing so might confuse its
   owning context.

   Clients MAY add new user-defined functions, use the handle with
   fsl_db_prepare(), and other "mundane" db-related tasks.

   The global config db uses a separate db handle accessible via
   fsl_cx_db_config().

   @see fsl_cx_db_repo()
   @see fsl_cx_db_ckout()
   @see fsl_cx_db_config()
*/
FSL_EXPORT fsl_db * fsl_cx_db( fsl_cx * f );

/**
   If f is not NULL and has had its repo opened via
   fsl_repo_open(), fsl_ckout_open_dir(), or similar, this
   returns a pointer to that database, else it returns NULL.

   @see fsl_cx_db()
*/
FSL_EXPORT fsl_db * fsl_cx_db_repo( fsl_cx * f );

/**
   If f is not NULL and has had a checkout opened via
   fsl_ckout_open_dir() or similar, this returns a pointer to that
   database, else it returns NULL.

   @see fsl_cx_db()
*/
FSL_EXPORT fsl_db * fsl_cx_db_ckout( fsl_cx * f );

/**
   A helper which fetches f's repository db. If f has no repo db
   then it sets f's error state to FSL_RC_NOT_A_REPO with a message
   describing the requirement, then returns NULL.  Returns NULL if
   !f.

   @see fsl_cx_db()
   @see fsl_cx_db_repo()
   @see fsl_needs_ckout()
   @see fsl_cx_has_ckout()
*/
FSL_EXPORT fsl_db * fsl_needs_repo(fsl_cx * f);

/**
   The checkout-db counterpart of fsl_needs_repo(). If no checkout is
   opened, f's error state is updated with a FSL_RC_NOT_A_CKOUT code
   and description of the problem.

   @see fsl_cx_db()
   @see fsl_needs_repo()
   @see fsl_cx_db_ckout()
   @see fsl_cx_has_ckout()
*/
FSL_EXPORT fsl_db * fsl_needs_ckout(fsl_cx * f);

/**
   Returns true if the given context has a checkout opened, else
   false.

   There is no counterpart fsl_cx_has_repo() for the simple reason
   that we've never needed one. Having a checkout implies having a
   repo, as a checkout is always opened with its repo db counterpart.

   @see fsl_needs_ckout()
*/
FSL_EXPORT bool fsl_cx_has_ckout(fsl_cx const * f );

/**
   Opens the given database file as f's configuration database.

   If f already has a config database opened then:

   1) If passed a NULL dbName or dbName is an empty string then this
   function returns 0 without side-effects.

   2) If passed a non-NULL/non-empty dbName, any existing config db is
   closed before opening the named one. The database is created and
   populated with an initial schema if needed.

   If no config db is opened and dbName is NULL or empty then it uses
   a default db name, "probably" under the user's home directory (see
   fsl_config_global_preferred_name()). To get the name of the
   database after it has been opened/attached, use
   fsl_cx_db_file_config().

   Returns 0 on success. On error, f's error state describes the
   failure and the result is non-0, including:

   - FSL_RC_NOT_FOUND or FSL_RC_TYPE if dbName is NULL or empty and
     no home directory can be determined (see
     fsl_config_global_preferred_name()).

   - The result of fsl_config_close() if a config db is opened and
     cannot be closed.

   - A db-related code if the database cannot be created or opened.
     A database file which exists but is read-only is opened, and
     attempts to change settings in it then fail.

   Results are undefined if f is NULL or not properly initialized.

   @see fsl_cx_db_config()
   @see fsl_config_close()
   @see fsl_config_global_preferred_name()
*/
FSL_EXPORT int fsl_config_open( fsl_cx * f, char const * dbName );

/**
   Closes/detaches the database connection opened by
   fsl_config_open(). If the config db is not opened, this
   is a harmless no-op. Note that it does not propagate db-closing
   errors because there is no sensible recovery strategy from
   such cases.

   This operation only fails if the config db is opened and has
   an active transaction, in which case f's error state is updated
   to reflect that cause of the error.

   ACHTUNG: it is imperative that any prepared statements compiled
   against the config db be finalized before closing the db. Any
   statements prepared using fsl_db_prepare_cached() against the
   config db will be automatically finalized by the closing process.

   Potential TODO: if a transaction is pending, force a rollback and
   close the db anyway. If we do that, this function will change to
   return void.

   @see fsl_cx_db_config()
   @see fsl_config_open()
*/
FSL_EXPORT int fsl_config_close( fsl_cx * f );

/**
   If f has an opened configuration db then its handle is returned,
   else 0 is returned.

   For API consistency's sake, the db handle's "MAIN" name is aliased
   to fsl_db_role_name(FSL_DBROLE_CONFIG).

   @see fsl_config_open()
   @see fsl_config_close()
*/
FSL_EXPORT fsl_db * fsl_cx_db_config( fsl_cx * f );

/**
   Convenience form of fsl_db_prepare() which uses f's main db.
   Returns 0 on success. On preparation error, any db error state is
   uplifted from the db object to the fsl_cx object.  Returns
   FSL_RC_RANGE if !*sql.

   Results are undefined if f or sql are NULL or otherwise
   invalid.
*/
FSL_EXPORT int fsl_cx_prepare( fsl_cx * f, fsl_stmt * tgt,
                               char const * sql, ... );

/**
   va_list counterpart of fsl_cx_prepare().
*/
FSL_EXPORT int fsl_cx_preparev( fsl_cx * f, fsl_stmt * tgt,
                                char const * sql, va_list args );

/**
   Convenience form of fsl_db_prepare_cached() which uses f's main db.
   Returns 0 on success. On preparation error, any db error state is
   uplifted from the db object to the fsl_cx object.  Returns
   FSL_RC_RANGE if !*sql.

   Results are undefined if f or sql are NULL or otherwise
   invalid.
*/
FSL_EXPORT int fsl_cx_prepare_cached( fsl_cx * f, fsl_stmt ** tgt,
                                      char const * sql, ... );

/**
   va_list counterpart of fsl_cx_prepare_cached().
*/
FSL_EXPORT int fsl_cx_preparev_cached( fsl_cx * f, fsl_stmt ** tgt,
                                       char const * sql, va_list args );

/**
   Convenience form of fsl_db_exec() which uses f's main db handle.
   Returns 0 on success. On statement preparation or execution error,
   the db's error state is uplifted into f and that result is
   returned. Results are undefined if f or sql are NULL or otherwise
   invalid.
*/
FSL_EXPORT int fsl_cx_exec( fsl_cx * f, char const * sql, ... );

/**
   va_list counterpart of fsl_cx_exec().
*/
FSL_EXPORT int fsl_cx_execv( fsl_cx * f, char const * sql, va_list args );

/**
   The fsl_db_exec_multi() counterpart of fsl_cx_exec(). Results are
   undefined if f or sql are NULL or otherwise invalid.
*/
FSL_EXPORT int fsl_cx_exec_multi( fsl_cx * f, char const * sql, ... );

/**
   va_list counterpart of fsl_cx_exec_multi().
*/
FSL_EXPORT int fsl_cx_exec_multiv( fsl_cx * f, char const * sql,
                                   va_list args );

/**
   Wrapper around fsl_db_last_insert_id() which uses f's main
   database. Returns -1 if !f or f has no opened db.

   @see fsl_cx_db()
*/
FSL_EXPORT fsl_id_t fsl_cx_last_insert_id(fsl_cx * f);


/**
   Works similarly to fsl_stat(), except that zName must refer to a
   path under f's current checkout directory. Note that this stats
   local files, not repository-level content.

   If relativeToCwd is true then the filename is
   resolved/canonicalized based on the current working directory (see
   fsl_getcwd()), otherwise f's current checkout directory is used as
   the virtual root. This makes a subtle yet important difference in
   how the name is resolved. Applications taking input from users
   (e.g. CLI apps) will normally want to resolve from the current
   working dir (assuming the filenames were passed in from the
   CLI). In a GUI environment, where the current directory is likely
   not the checkout root, resolving based on the checkout root
   (i.e. relativeToCwd=false) is probably saner.

   Returns 0 on success. Errors include, but are not limited to:

   - FSL_RC_MISUSE if !zName.

   - FSL_RC_NOT_A_CKOUT if f has no opened checkout.

   - If fsl_is_simple_pathname(zName) returns false then
   fsl_ckout_filename_check() is used to normalize the name. If
   that fails, its failure code is returned.

   - As for fsl_stat().

   See fsl_stat() for more details regarding the tgt parameter.

   Symlinks are handled as fossil(1) handles checkout files: if
   fsl_cx_allows_symlinks() is true, a symlink is stat()ed itself
   and reported as FSL_FSTAT_TYPE_LINK. If it is false, the link is
   followed, so the result describes whatever it points to, and a
   dangling link fails with FSL_RC_NOT_FOUND. Either way, a symlink
   in the name's directory part is followed. fsl_stat() takes an
   explicit flag for callers which need one behaviour regardless of
   that setting.

   @see fsl_cx_stat2()
*/
FSL_EXPORT int fsl_cx_stat( fsl_cx * f, bool relativeToCwd,
                            char const * zName, fsl_fstat * tgt );

/**
   This works identically to fsl_cx_stat(), but provides more
   information about the file being stat'd.

   If nameOut is not NULL then the resolved/normalized path to to
   that file is appended to nameOut. If fullPath is true then an
   absolute path is written to nameOut, otherwise a
   checkout-relative path is written.

   Returns 0 on success. On stat() error, nameOut is not updated,
   but after stat()'ing, allocation of memory for nameOut's buffer
   may fail.

   If zName ends with a trailing slash, that slash is retained in
   nameOut.

   Symlinks are resolved, or not, as described for fsl_cx_stat().

   @see fsl_cx_stat()
*/
FSL_EXPORT int fsl_cx_stat2( fsl_cx * f, bool relativeToCwd,
                             char const * zName,
                             fsl_fstat * tgt,
                             fsl_b * nameOut,
                             bool fullPath);

/**
   Sets the case-sensitivity flag for f to the given value. This flag
   alters how some filename-search/comparison operations operate. This
   option is only intended to have an effect on plaforms with
   case-insensitive filesystems.

   Note that this does not save the option in the config database
   (repo-level "case-sensitive" boolean config option). It arguably
   should, and this behavior may change in the future.

   @see fsl_cx_is_case_sensitive()
*/
FSL_EXPORT void fsl_cx_case_sensitive_set(fsl_cx * f, bool caseSensitive);

/**
   Returns true if f is set for case-sensitive filename
   handling, else false. This setting is cached when a repository
   is opened, but passing true for the second argument forces the
   config option to be re-loaded from the repository db.
   Results are undefined if !f.

   When the repository does not set "case-sensitive", the default is
   false on Windows, Cygwin and macOS and true elsewhere, as in
   fossil(1). Case-insensitive comparison folds only the ASCII letters
   A to Z, as fossil(1)'s does.

   @see fsl_cx_case_sensitive_set()
*/
FSL_EXPORT bool fsl_cx_is_case_sensitive(fsl_cx *  const f, bool forceRecheck);

/**
   Compares two strings, represumably filenames, using either
   fsl_strcmp() or fsl_stricmp(), depending on f's filename
   case-sensitivity setting.
*/
FSL_EXPORT int fsl_cx_filename_cmp(fsl_cx * f, char const * z1, char const *z2);

/**
   If f is set to use case-sensitive filename handling,
   returns a pointer to an empty string, otherwise a pointer
   to the string "COLLATE nocase" is returned.
   Results are undefined if f is NULL. The returned bytes
   are static.

   @see fsl_cx_case_sensitive_set()
   @see fsl_cx_is_case_sensitive()
*/
FSL_EXPORT char const * fsl_cx_filename_collation(fsl_cx const * f);

/**
   Invokes macro E with 2 arguments one time for each of the core
   fsl_satype_e entries. Argument 1 is the entry's name (identifier)
   and argument 2 is its value (integer).
*/
#define fsl_satype_e_map(E) \
  E(FSL_SATYPE_INVALID, -1/** Sentinel value used for some error
                              reporting.*/)                    \
  E(FSL_SATYPE_ANY, 0/** Sentinel value used to mark a deck as being
                         "any" type. This is a placeholder on a deck's
                         way to completion. */) \
  E(FSL_SATYPE_CHECKIN, 1/** Indicates a "manifest" artifact (a checkin
                             record). */)                               \
  E(FSL_SATYPE_CLUSTER, 2/** Indicates a "cluster" artifact. These
                             are used during synchronization. */)   \
  E(FSL_SATYPE_CONTROL, 3/** Indicates a "control" artifact (a tag
                             change).*/) \
  E(FSL_SATYPE_WIKI, 4/** Indicates a "wiki" artifact. */) \
  E(FSL_SATYPE_TICKET, 5/** Indicates a "ticket" artifact. */) \
  E(FSL_SATYPE_ATTACHMENT, 6/** Indicates an "attachment" artifact
                                (used in the ticketing subsystem). */)  \
  E(FSL_SATYPE_TECHNOTE, 7/** Indicates a technote (formerly
                                "event") artifact (kind of like a blog
                                entry). */) \
  E(FSL_SATYPE_FORUMPOST, 8/** Indicates a forum post artifact (a
                               close relative of wiki pages).*/)

/**
   An enumeration of the types of structural artifacts used by
   Fossil. The numeric values of all entries before FSL_SATYPE_count,
   with the exception of FSL_SATYPE_INVALID, are a hard-coded part of
   the Fossil db architecture and must never be changed. Any after
   FSL_SATYPE_count are libfossil extensions.
*/
enum fsl_satype_e {
#define E(N,V) N = V,
  fsl_satype_e_map(E)
#undef E
  /**
     The number of non-pseudo artifact types in this enum.  It is used
     to size arrays and must have a value of the last entry in
     fsl_satype_e_map() plus 1.
  */
  FSL_SATYPE_count,

  /**  @deprecated
       Historical (deprecated) name for FSL_SATYPE_TECHNOTE.
  */
  FSL_SATYPE_EVENT = FSL_SATYPE_TECHNOTE,

  /**
     A pseudo-type for use with fsl_sym_to_rid() which changes the
     behavior of checkin lookups to return the RID of the start of the
     branch rather than the tip, with the caveat that the results are
     unspecified if the given symbolic name refers to multiple
     branches.

     fsl_satype_event_cstr() returns the same as FSL_SATYPE_CHECKIN for
     this entry.

     This entry IS NOT VALID for most APIs which require a fsl_satype_e
     value.
  */
  FSL_SATYPE_BRANCH_START = 100
};
typedef enum fsl_satype_e fsl_satype_e;

/**
   Returns some arbitrary but distinct string for the given
   fsl_satype_e. The returned bytes are static and
   NUL-terminated. Intended primarily for debugging and informative
   purposes, not actual user output.
*/
FSL_EXPORT char const * fsl_satype_cstr(fsl_satype_e t);

/**
   For a given artifact type, it returns the key string used in the
   event.type db table. Returns NULL if passed an unknown value or
   a type which is not used in the event table, otherwise the
   returned bytes are static and NUL-terminated.

   The returned strings for a given type are as follows:

   - FSL_SATYPE_ANY returns "*"
   - FSL_SATYPE_CHECKIN and FSL_SATYPE_BRANCH_START return "ci"
   - FSL_SATYPE_WIKI returns "w"
   - FSL_SATYPE_TAG returns "g"
   - FSL_SATYPE_TICKET returns "t"
   - FSL_SATYPE_EVENT returns "e"

   The other control artifact types do not have representations
   in the event table, and NULL is returned for them.

   All of the returned values can be used in comparison clauses in
   queries on the event table's 'type' field (but use GLOB instead
   of '=' so that the "*" returned by FSL_ATYPE_ANY can match).
   For example, to get the comments from the most recent 5 commits:

   ```
   SELECT
   datetime(mtime),
   coalesce(ecomment,comment),
   user
   FROM event WHERE type='ci'
   ORDER BY mtime DESC LIMIT 5;
   ```

   Where 'ci' in the SQL is the non-NULL return value from this
   function. When escaping this value via fsl_b_appendf() (or
   anything functionally similar), use the %%q/%%Q format
   specifiers to escape it.
*/
FSL_EXPORT char const * fsl_satype_event_cstr(fsl_satype_e t);

/**
   A collection of bitmaskable values indicating categories
   of fossil-standard glob sets. These correspond to the following
   configurable settings:

   ignore-glob, crnl-glob, binary-glob
*/
enum fsl_glob_category_e{
/** Sentinel entry. */
FSL_GLOBS_INVALID = 0,
/** Corresponds to the ignore-glob config setting. */
FSL_GLOBS_IGNORE = 0x01,
/** Corresponds to the crnl-glob config setting. */
FSL_GLOBS_CRNL = 0x02,
/** Corresponds to the binary-glob config setting. */
FSL_GLOBS_BINARY = 0x04,
/** A superset of all config-level glob categories. */
FSL_GLOBS_ANY = 0xFF
/*
  Potential TODO: add FSL_GLOBS_CURRENT_OP for use with SQL UDFs. The
  idea would be that SCM operations which could make use of
  op-specific glob lists, e.g., checkin/add/merge, could set a custom
  glob set as the current one and then access it via their SQL using
  `fsl_glob('_', ...)` or some such.
*/
};
typedef enum fsl_glob_category_e fsl_glob_category_e;

/**
   Checks one or more of f's configurable glob lists to see if str
   matches one of them. If it finds a match, it returns a pointer to
   the matching glob (as per fsl_glob_list_matches()), the bytes
   of which are owned by f and may be invalidated via modification
   or reloading of the underlying glob list. In generally the return
   value can be used as a boolean - clients generally do not need
   to know exactly which glob matched.

   gtype specifies the glob list(s) to check in the form of a
   bitmask of fsl_glob_category_e values. Note that the order of the
   lists is unspecified, so if that is important for you then be
   sure that gtype only specifies one glob list
   (e.g. FSL_GLOBS_IGNORE) and call it again (e.g. passing
   FSL_GLOBS_BINARY) if you need to distinguish between those two
   cases.

   str must be a non-NULL, non-empty empty string.

   Returns NULL !str, !*str, gtype does not specify any known
   glob list(s), or no glob match is found.

   Performance is, abstractly speaking, horrible, because we're
   comparing arbitrarily long lists of glob patterns against an
   arbitrary string. That said, it's fast enough for our purposes.
*/
FSL_EXPORT char const * fsl_cx_glob_matches( fsl_cx * f, int gtype,
                                             char const * str );

/**
   Converts a well-known fossil glob list configuration key to
   a fsl_glob_category_e value:

   - "ignore-glob" = FSL_GLOBS_IGNORE
   - "binary-glob" = FSL_GLOBS_BINARY
   - "crnl-glob" = FSL_GLOBS_CRNL
   - Anything else = FSL_GLOBS_INVALID

   To simplify this function's use via an SQL-accessible UDF, the
   `*-glob` names may be passed in without their `-glob` suffix,
   e.g. `"ignore"` instead of `"ignore-glob"`.
*/
FSL_EXPORT fsl_glob_category_e fsl_glob_name_to_category(char const * str);

/**
   Fetches f's glob list of the given category. If forceReload is true
   then the context will check whether the list has had any content
   added to its source since it was initially loaded.

   On success, returns 0 and assigns `*tgt` to the list (noting that
   it may be empty). On error `*tgt` is not modified.

   Returns FSL_RC_RANGE if gtype is not one of FSL_GLOBS_IGNORE,
   FSL_GLOBS_CRNL, or FSL_GLOBS_BINARY. Returns FSL_RC_OOM if there is
   an allocation error during list reloading. May return lower-level
   result codes from the filesystem or db layer if loading a given
   list fails.
*/
FSL_EXPORT int fsl_cx_glob_list( fsl_cx * f,
                                 fsl_glob_category_e gtype,
                                 fsl_list ** tgt,
                                 bool forceReload );

/**
   Sets f's hash policy and returns the previous value. If f has a
   repository db open then the setting is stored there and any error
   in setting it is placed into f's error state but otherwise ignored
   for purposes of this call.

   If p is FSL_HPOLICY_AUTO *and* the current repository contains any
   SHA3-format hashes, the policy is interpreted as FSL_HPOLICY_SHA3.

   This value is a *suggestion*, and may be trumped by various
   conditions, in particular in repositories containing older (SHA1)
   hashes.
*/
FSL_EXPORT fsl_hashpolicy_e fsl_cx_hash_policy_set(fsl_cx *f, fsl_hashpolicy_e p);

/**
   Returns f's current hash policy.
*/
FSL_EXPORT fsl_hashpolicy_e fsl_cx_hash_policy_get(fsl_cx const*f);

/**
   Returns a human-friendly name for the given policy, or NULL for an
   invalid policy value. The returned strings are the same ones used
   by fossil's hash-policy command.
*/
FSL_EXPORT char const * fsl_hash_policy_name(fsl_hashpolicy_e p);

/**
   Hashes all of pIn, appending the hash to pOut. Returns 0 on succes,
   FSL_RC_OOM if allocation of space in pOut fails. The hash algorithm
   used depends on the given fossil context's current hash policy and
   the value of the 2nd argument.

   If the 2nd argument is false, the hash is performed per the first
   argument's current hash policy. If the 2nd argument is true, the
   hash policy is effectively inverted. e.g. if the context prefers
   SHA3 hashes, the alternate form will use SHA1.

   Returns FSL_RC_UNSUPPORTED, without updating f's error state, if
   the hash is not possible due to conflicting values for the policy
   and its alternate. e.g. a context with policy FSL_HPOLICY_SHA3_ONLY
   will refuse to apply an SHA1 hash. Whether or not this result can
   be ignored is context-dependent, but it normally can be. This
   result is only possible when the 2nd argument is true.

   Returns 0 on success.
*/
FSL_EXPORT int fsl_cx_hash_buffer( const fsl_cx * f, bool useAlternate,
                                   fsl_b const * pIn,
                                   fsl_b * pOut);
/**
   The file counterpart of fsl_cx_hash_buffer(), behaving exactly the
   same except that its data source is a file and it may return
   various error codes from fsl_b_fill_from_filename(), in which
   case it updates f's error state with the file's name. Note that
   the contents of the file, not its name, are hashed.
*/
FSL_EXPORT int fsl_cx_hash_filename( fsl_cx * f, bool useAlternate,
                                     const char * zFilename, fsl_b * pOut);

/**
   Works like fsl_getcwd() but updates f's error state on error and
   appends the current directory's name to the given buffer. Returns 0
   on success.
*/
FSL_EXPORT int fsl_cx_getcwd(fsl_cx * f, fsl_b * pOut);

/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_txn_level(), or 0 if f has no db opened.

   @see fsl_cx_db()
*/
FSL_EXPORT int fsl_cx_txn_level(fsl_cx * f);
/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_txn_begin().
*/
FSL_EXPORT int fsl_cx_txn_begin(fsl_cx * f);
/**
   Like fsl_cx_txn_begin(), but also takes the write lock on each db
   in roles, a mask of FSL_DBROLE_REPO and FSL_DBROLE_CKOUT, which is
   attached and which the transaction has not write-locked already, as
   fossil(1)'s BEGIN IMMEDIATE does. Start every transaction which will
   write the repository or checkout db with this.

   fsl_cx_txn_begin() starts a deferred transaction. When a deferred
   transaction which has read a db then writes it while another
   connection holds that db's write lock, SQLite returns SQLITE_BUSY at
   once, without calling the busy handler, since waiting could
   deadlock, and the write fails with FSL_RC_LOCKED. A transaction
   which takes the lock before it reads waits in the busy handler for
   the other writer instead. Inside a transaction which has already
   read a db without write-locking it, taking that db's lock can still
   fail at once.

   On error, this ends the transaction level it began and updates f's
   error state.
*/
FSL_EXPORT int fsl_cx_txn_begin_write(fsl_cx * f, int roles);
/**
   Returns the same as passing fsl_cx_db() and the 2nd/3rd arguments
   to fsl_db_txn_end_v2() and propagates any db errors from that
   operation into f.
*/
FSL_EXPORT int fsl_cx_txn_end_v2(fsl_cx * f, bool keepSavepoint,
                                 bool bubbleRollback);

#if 0
/* Legacy behavior. */
#define fsl_cx_txn_end(F, RollbackMode) \
  fsl_cx_txn_end_v2((F), !(RollbackMode), !!(RollbackMode))
#else
/* What we probably should have been doing instead but
   now breaks stuff. */
#define fsl_cx_txn_end(F, RollbackMode) \
  fsl_cx_txn_end_v2((F), !(RollbackMode), false)
#endif
/**
   Installs or (if f is NULL) uninstalls a confirmation callback for
   use by operations on f which require user confirmation. The exact
   implications of *not* installing a confirmer depend on the
   operation in question: see fsl_cx_confirm().

   The 2nd argument bitwise copied into f's internal confirmer
   object. If the 2nd argument is NULL, f's confirmer is cleared,
   which will cause fsl_cx_confirm() to use certain default responses
   (see that function for details).

   If the final argument is not NULL then the previous confirmer is
   bitwise copied to it.

   @see fsl_confirm_callback_f
   @see fsl_cx_confirm()
   @see fsl_cx_confirmer_get()
*/
FSL_EXPORT void fsl_cx_confirmer(fsl_cx * f,
                                 fsl_confirmer const * newConfirmer,
                                 fsl_confirmer * prevConfirmer);
/**
   Stores a bitwise copy of f's current confirmer object into *dest. Can
   be used to save the confirmer before temporarily swapping it out.

   @see fsl_cx_confirmer()
*/
FSL_EXPORT void fsl_cx_confirmer_get(fsl_cx const * f, fsl_confirmer * dest);

/**
   If fsl_cx_confirmer() was used to install a confirmer callback in f
   then this routine calls that confirmer and returns its result code
   and its answer via *outAnswer. If no confirmer is currently
   installed, it responds with default answers, depending on the
   eventId:

   - FSL_CEVENT_OVERWRITE_MOD_FILE: FSL_CRESPONSE_NEVER

   - FSL_CEVENT_OVERWRITE_UNMGD_FILE: FSL_CRESPONSE_NEVER

   - FSL_CEVENT_RM_MOD_UNMGD_FILE: FSL_CRESPONSE_NEVER

   - FSL_CEVENT_MULTIPLE_VERSIONS: FSL_CRESPONSE_CANCEL

   Those are not 100% set in stone and are up for reconsideration.

   If a confirmer has been installed, this function does not modify
   outAnswer->response if the installed confirmer does not. Thus
   routines should set it to some acceptable default/sentinel value
   before calling this, to account for callbacks which ignore the
   given detail->eventId.

   If a confirmer callback responds with FSL_CRESPONSE_ALWAYS or
   FSL_CRESPONSE_NEVER, the code which is requesting confirmation must
   honor that by *NOT* calling the callback again for the current
   processing step of that eventId. e.g. if a loop asks for
   confirmation of FSL_CEVENT_RM_MOD_FILE and any response is one of
   the above, that one loop must not ask for confirmation again, and
   must instead accept that response for future queries within the
   same logical library operation (e.g. one checkout-update
   cycle). This is particularly important for applications which
   interactively present the question to the user for confirmation so
   that users have a way to *not* get spammed with a confirmation
   message showing up for each and every one of an arbitrary number of
   confirmations.

   @see fsl_confirm_callback_f
   @see fsl_cx_confirmer()
*/
FSL_EXPORT int fsl_cx_confirm(fsl_cx * f, fsl_confirm_detail const * detail,
                              fsl_confirm_response *outAnswer);

/**
   Sets f's is-interrupted flag and, if the 3rd argument is not NULL,
   its error state. The is-interrupted flag is separate from f's
   normal error state and is _not_ cleared by fsl_cx_err_reset(). To
   clear the interrupted flag, call this function with values of 0 and
   NULL for the 2nd and 3rd arguments, respectively. This flag is
   _not_ fetched by fsl_cx_err_get() but:

   1) If this function is passed a non-NULL 3rd argument, then the
   normal error state, as well as the is-interrupted flag, is updated
   and can be fetched normally via fsl_cx_err_get(). However...

   2) It is possible for any error message provided via this routine
   to be overwritten or reset by another routine before the
   interrupted flag can be acted upon, whereas the interrupted flag
   itself can only be modified by this routine.

   Returns its 2nd argument on success or FSL_RC_OOM if given a
   formatted string and allocation of it fails. In either case, the
   interrupted flag, as returned by fsl_cx_interrupted(), is _always_
   assigned to the passed-in code.

   If passed a code of 0, the is-interrupted flag is reset but the
   general error state is not modified.

   Results are undefined if this function is called twice concurrently
   with the same fsl_cx object. i.e. all calls for a given fsl_cx must
   come from a single thread. Results are also undefined if it is
   called while f is in its finalization phase (typically during
   application shutdown).

   ACHTUNG: this is new as of 2021-11-18 and is not yet widely honored
   within the API.

   Library maintenance notes:

   - Long-running actions which honor this flag should, if it is set,
   clear it before returning its error code. Also, they should prefer
   to pass on non-interruption errors if one has been set set, in
   addition to clearing the interruption flag. Only routines which
   honor this flag, or top-most routines in the application, should
   ever clear this flag.

   @see fsl_cx_interrupted()
   @see fsl_cx_interruptv()
*/
FSL_EXPORT int fsl_cx_interrupt(fsl_cx * f, int code,
                                const char * fmt, ...);

/**
   The va_list counterpart of fsl_cx_interrupt().
*/
FSL_EXPORT int fsl_cx_interruptv(fsl_cx * f, int code, char const * fmt, va_list args);

/**
   If f's is-interrupted flag is set, this function returns its
   value. Note that there is inherently a race condition when calling
   fsl_cx_interrupt() (to set the flag) from another thread (e.g. a
   UI thread while showing a progress indicator).
*/
FSL_EXPORT int fsl_cx_interrupted(fsl_cx const * f);

/**
   Returns true if f has the "allow-symlinks" repo-level configuration
   option set to a truthy value, else returns false. That setting is
   cached to avoid performing a db lookup on each call, but passing
   true for the second argument causes the repository to be
   re-checked.
*/
FSL_EXPORT bool fsl_cx_allows_symlinks(fsl_cx * f, bool forceRecheck);

/**
   Closes any opened repository and/or checkout database(s) opened by
   f, freeing any associated resources and clearing out f's current
   user name. Returns 0 on success or if no dbs are opened (noting
   that this does NOT close the separate global configuration db: see
   fsl_config_close()). Returns FSL_RC_MISUSE if the opened SCM db(s)
   have an opened transaction, but that behaviour may change in the
   future to force a rollback and close the database(s).
*/
FSL_EXPORT int fsl_close_scm_dbs(fsl_cx * f);

/**
   Shorthand for calling both fsl_close_scm_dbs() and, if it succeeds,
   fsl_config_close(). Returns the result of the former if it fails,
   else returns the result of the latter.
*/
FSL_EXPORT int fsl_close_dbs(fsl_cx * f);

/**
   Extracts the "last-sync-url" entry from f's repository
   configuration and appends it to tgt. On success, returns 0. Returns
   FSL_RC_NOT_A_REPO if f has no opened repository, FSL_RC_NOT_FOUND
   if the repository has no such entry, else the result of
   fsl_config_get_buffer(). On error, f's error state describes the
   problem.
*/
FSL_EXPORT int fsl_cx_last_sync_url(fsl_cx * f, fsl_b *tgt);

/**
   Flags for use with fsl_buildinfo().
*/
enum fsl_buildinfo_e {
  FSL_BUILDINFO_VERSION,
  FSL_BUILDINFO_VERSION_HASH,
  FSL_BUILDINFO_VERSION_TIMESTAMP,
  FSL_BUILDINFO_CONFIG_TIMESTAMP
};

/**
   Fetches the piece of library-level build information specified by
   its argument. If no such info is available, NULL is returned.
*/
FSL_EXPORT char const * fsl_buildinfo(enum fsl_buildinfo_e what);

/**
   If both where and where->callback are not NULL, msg is passed to
   where->callback and its result is returned, else this is a no-op
   and 0 is returned.

   Results are undefined if msg is NULL or either argument is
   improperly populated.
*/
FSL_EXPORT int fsl_msg_emit(fsl_msg const * msg,
                            fsl_msg_listener const * where);

/**
   If f has a fsl_msg listener, a fsl_msg composed from the given type
   and payload is passed to the the listener and its result is
   returned, else this is a no-op and 0 is returned. Results are
   undefined if the data type of p does not match that described for
   the given type.
*/
FSL_EXPORT int fsl_cx_emit(fsl_cx * const f, fsl_msg_e type, void const * p);

/**
   va_list counterpart of fsl_cx_emit() which emits a
   fsl_appendf()-formatted message as a string or a buffer, depending
   on the message type.

   It may (and does) fatally fail if passed a message type for which
   (type & FSL_MSG_mask_type) is not one of FSL_MSG_type_string or
   FSL_MSG_type_buffer.
*/
FSL_EXPORT int fsl_cx_emitfv(fsl_cx * f, fsl_msg_e type, char const * zFmt,
                             va_list args);

/** Elipsis counterpart of fsl_cx_emitfv(). */
FSL_EXPORT int fsl_cx_emitf(fsl_cx *f, fsl_msg_e type, char const * zFmt, ...);

/**
   Replace's f's current fsl_msg listener with a bitwise copy of
   pNew. If pOld is not NULL then a bitwise copy of the previous
   listener is written there.
*/
FSL_EXPORT void fsl_cx_listener_replace(fsl_cx * f, fsl_msg_listener const *pNew,
                                        fsl_msg_listener * pOld);

/**
   Borrows a buffer from f's buffer recycling pool, allocating one if
   needed. It returns NULL only on allocation error. If f is currently
   flagged with a FSL_RC_OOM error state when this is called, it
   becomes a no-op and NULL is returned. Similarly, if allocation
   fails, f's error state is set.

   This transfers ownership of the buffer to the caller, who is
   obligated to eventually do ONE of the following:

   - Pass it to fsl_cx_b_return() with the same f argument.

   - Pass it to fsl_b_clear() then fsl_free().

   The purpose of this function is a memory reuse optimization.  Much,
   perhaps even most, libfossil-using code uses transient buffers
   something or other and this gives them a way to reuse buffers.

   It is not recommended to use this for buffers which invariably take
   over ownership of the underlying memory, e.g. by returning it as a
   (char*) to a caller, because that defeats the purpose of this
   cache: re-using the buffer memory (as distinct from the fsl_b
   instances themselves). Such (mis)uses might end up stealing 2mb of
   otherwise reusable memory to return a short string like a user name
   or some such.

   Potential TODO: How this pool optimizes (or not) buffer allotment
   is an internal detail. Maybe add an argument which provides a hint
   about the buffer usage.

   Example usage:

   @code
   fsl_b * const b = fsl_cx_b_borrow(f, false);
   if( !b ) return FSL_RC_OOM;
   ... use b...
   fsl_cx_b_return(f, b);
   @endcode
*/
FSL_EXPORT fsl_b * fsl_cx_b_borrow(fsl_cx *f);

/**
   Returns a buffer borrowed from fsl_cx_b_borrow(), transferring
   ownership back to f. Passing a non-NULL b which was not returned
   by fsl_cx_b_borrow() invokes undefined behavior (possibly delayed
   until the list is cleaned up). To simplify usage, b may be NULL.

   After calling this, b must be considered "freed" - it must not be
   used again. This function is free (as it were) to immediately free
   the object's memory instead of recycling it.
*/
FSL_EXPORT void fsl_cx_b_return(fsl_cx *f, fsl_b *b);

/**
   Works exactly like fsl_cx_b_return() except that if b is not NULL
   and b->capacity>0 then the first b->capacity bytes of b->mem are
   zeroed out before the buffer is returned to the pool.
*/
FSL_EXPORT void fsl_cx_b_return_wipe(fsl_cx *f, fsl_b *b);


#if 0
/**
   DO NOT USE - not yet tested and ready.

   Returns the result of either localtime(clock) or gmtime(clock),
   depending on f:

   - If f is NULL, returns localtime(clock).

   - If f has had its FSL_CX_F_LOCALTIME_GMT flag set (see
   fsl_cx_flag_set()) then returns gmtime(clock), else
   localtime(clock).

   If clock is NULL, NULL is returned.

   fsl_cx instances default to using UTC for everything, which is the
   opposite of fossil(1).
*/
FSL_EXPORT struct tm * fsl_cx_localtime( fsl_cx const * f, const time_t * clock );

/**
   Equivalent to fsl_cx_localtime(NULL, clock).
*/
FSL_EXPORT struct tm * fsl_localtime( const time_t * clock );

/**
   DO NOT USE - not yet tested and ready.

   This function passes (f, clock) to fsl_cx_localtime(),
   then returns the result of mktime(3) on it. So...
   it adjusts a UTC Unix timestamp to either the same UTC
   local timestamp or to the local time.
*/
FSL_EXPORT time_t fsl_cx_time_adj(fsl_cx const * f, time_t clock);
#endif

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif /* ORG_FOSSIL_SCM_FSL_CORE_H_INCLUDED */
/* end of file include/fossil-scm/core.h */
/* start of file include/fossil-scm/db.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_DB_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_DB_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).


  ******************************************************************************
  This file declares public APIs for working with fossil's database
  abstraction layer.
*/

/*
  We don't _really_ want to include sqlite3.h at this point, but if we
  do not then we have to typedef the sqlite3 struct here and that
  breaks when client code includes both this file and sqlite3.h.
*/

#if defined(__cplusplus)
extern "C" {
#endif

#if 0
/* We can't do this because it breaks when clients include both
   this header and sqlite3.h. Is there a solution which lets us
   _not_ include sqlite3.h from this file and also compiles when
   clients include both?
*/
#if !defined(SQLITE_OK)
typedef struct sqlite3 sqlite3;
#endif
#endif

/**
   Flags for use with fsl_db_open() and friends.
*/
enum fsl_db_open_flags_e {
/**
   The "no flags" value.
*/
FSL_DB_OPEN_NONE = 0,

/**
   Flag for fsl_db_open() specifying that the db should be opened
   in read-only mode.
*/
FSL_DB_OPEN_RO = 0x01,

/**
   Flag for fsl_db_open() specifying that the db should be opened
   in read-write mode, but should not create the db if it does
   not already exist.
*/
FSL_DB_OPEN_RW = 0x02,

/**
   Flag for fsl_db_open() specifying that the db should be opened in
   read-write mode, creating the db if it does not already exist.

   ACHTUNG: this flag propagates from an OPEN'd db handle to the
   ATTACH SQL command run via that handle, such that ATTACHing a
   non-existing db file will fail if the FSL_DB_OPEN_CREATE flag is
   _not_ used. Historically (prior to 2022-01-01), fsl_db_open() would
   automatically apply this flag to DBs named ":memory:" or ""
   (unnamed temp dbs), but that ended up causing a full day of
   confusion, hair-pulling, and bug-hunting when lib-level code was
   migrated from an anonymous temp db to a "real" db and ATTACH
   suddenly failed. As of 2022-01-01, fsl_db_open() always takes the
   open-mode flags as provided by the client, regardless of the DB
   name, and never automatically rewrites them to include
   FSL_DB_OPEN_CREATE.
*/
FSL_DB_OPEN_CREATE = 0x04,

/**
   Shorthand for RW+CREATE flags.
*/
FSL_DB_OPEN_RWC = FSL_DB_OPEN_RW | FSL_DB_OPEN_CREATE,

/**
   Currently unused. It "should" be used to tell fsl_repo_open_xxx()
   to confirm that the db is a repository, but how to propagate
   that through the corresponding APIs is not currently clear.
*/
FSL_DB_OPEN_SCHEMA_VALIDATE = 0x20,

/**
   Used by fsl_db_open() to to tell the underlying db connection to
   trace all SQL to stdout. This is often useful for testing,
   debugging, and learning about what's going on behind the scenes.
*/
FSL_DB_OPEN_TRACE_SQL = 0x40
};

/**
   A level of indirection to "hide" the actual db driver
   implementation from the public API. It uses SQLite3 but this gives
   us a comforting level of abstraction.

   Sidebar: at the time this code was originally written, sqlite4 was
   in an experimental stage to explore a new storage engine which, it
   was hoped, would speed up sqlite considerably. It ended up never
   leaving that stage because the performance gains of the storage
   engine did not justify such a significant upheaval. Even so,
   sqlite4 "might" come around sometime within the lifetime of this
   project, so it behooves us to abstract away this type from the
   public API.
*/
typedef sqlite3 fsl_db_t;

/**
   Bitmasks for use with fsl_db_event_e.
*/
enum fsl_db_event_mask_e {
  FSL_DB_EVENT_mask_reserved     = 0x7ffff000,

  /**
     Describes a data type for fsl_db_event::payload.
  */
  FSL_DB_EVENT_mask_payload      = 0x00000f00,

  /** (fsl_b const *) payload. */
  FSL_DB_EVENT_payload_buffer    = 0x00000100,

  /**
     All concrete message IDs are masked with this.
  */
  FSL_DB_EVENT_mask_id           = 0x000000ff,

  /**
     Convenience entry for use with fsl_db_event_listener().
  */
  FSL_DB_EVENT_listen_all        = FSL_DB_EVENT_mask_id
};

/**
   A map of fsl_db_event types.
*/
#define fsl_db_event_map(E)          \
  E(FSL_DB_EVENT_BEGIN,        0x01) \
  E(FSL_DB_EVENT_COMMIT,       0x02) \
  E(FSL_DB_EVENT_ROLLING_BACK, 0x04) \
  E(FSL_DB_EVENT_ROLLED_BACK,  0x08) \
  E(FSL_DB_EVENT_CLOSING,      0x10) \
  E(FSL_DB_EVENT_TRACE_SQL,    0x20  \
    | FSL_DB_EVENT_payload_buffer    \
    /*unexpanded SQL*/)              \
  E(FSL_DB_EVENT_TRACE_SQLX,   0x40  \
    | FSL_DB_EVENT_payload_buffer    \
    /*expanded SQL*/)

/**
   A flag type for use with fsl_db_event_f() implementations.
*/
enum fsl_db_event_e {
#define E(X,V) X = V,
  fsl_db_event_map(E)
#undef E
};
typedef enum fsl_db_event_e fsl_db_event_e;

/**
   Convenience FSL_DB_EVENT_... entries which cannot be defined until
   after fsl_db_event_e is.
*/
enum fsl_db_event_mask2_e {
  /** Mask of the IDs of transaction-specific events. */
  FSL_DB_EVENT_group_txn = FSL_DB_EVENT_mask_id
  & (FSL_DB_EVENT_BEGIN | FSL_DB_EVENT_COMMIT
     | FSL_DB_EVENT_ROLLING_BACK | FSL_DB_EVENT_ROLLED_BACK),
  /** Mask of the IDs of SQL tracing events. */
  FSL_DB_EVENT_group_sql_trace = FSL_DB_EVENT_mask_id
  & (FSL_DB_EVENT_TRACE_SQL
     | FSL_DB_EVENT_TRACE_SQLX)
};

/**
   An "event" message type for use with fsl_db.
*/
struct fsl_db_event {
  /**
     The event-firing db.
  */
  fsl_db * db;
  /**
     The event listener state.
  */
  void * state;
  /**
     A message-type-specific payload. Its native type is encoded in
     this->type.
  */
  void const * payload;
  /**
     Event type.
  */
  fsl_db_event_e type;
  /**
     The db's current savepoint level (because most events deal with
     transactions and this info has proven useful in downstream code).
     This will usually have a value of 1 or higher, the exception
     being FSL_DB_EVENT_CLOSING, where a that level is 0.
  */
  int savepointLevel;
};
typedef struct fsl_db_event fsl_db_event;

/**
   An event callback for fsl_db objects, primarily for communicating
   on-transaction-start/end. Each fsl_db instance may have a single
   one of these installed and it gets called via at various points to
   fire well-defined events.

   When the docs below refer to BEGIN and COMMIT, they're actually
   referring to their SAVEPOINT counterparts. That's partly
   historical, from a time when this API uses BEGIN/COMMIT, but it's
   also thought to be clearer terminology here.

   Doc references below to fsl_db_txn_begin() and fsl_db_txn_end()
   also imply their v2 variants.

   ev->state holds the state registered with the callback in
   fsl_db_event_listener().

   ev->type explains the nature of the event:

   - FSL_DB_EVENT_CLOSING is fired early on in fsl_db_close(). If
   closing is forced to roll back savepoints, those events are fired
   first and their result codes are ignored. The result of this event
   is likewise also ignored. Though the callback may (technically
   speaking) still perform db operations, it must never start a new
   transaction (unless it also closes it before returning) nor may it
   close the db object. If either of those conditions is violated,
   results are undefined. This event is _not_ fired when a DETACH'ing
   database, as this API does not have any insight into when ATTACH
   and DETACH are used.

   - FSL_DB_TXN_BEGIN is passed immediately after fsl_db_txn_begin()
   starts the transaction. If this function returns non-0, the
   transaction is _immediately_ rolled back but the rollback event is
   not triggered for this particular failure. Unless the starting of a
   new transaction level actually fails, the callback's return value
   because the result of fsl_db_txn_begin().

   - FSL_DB_TXN_COMMIT is called immediately before fsl_db_txn_end()
   runs COMMIT on the db. If it returns non-0, the pending COMMIT is
   replaced with a ROLLBACK and that result code becomes the result of
   fsl_db_txn_end().  The rollback events are _not_ triggered in this
   case.

   - FSL_DB_TXN_ROLLING_BACK is called immediately before
   fsl_db_txn_end() runs ROLLBACK on the db. If it returns non-0 but
   the SQL-level succeeds, its result becomes the result of
   fsl_db_txn_end(), but it does not cancel the pending db-side
   ROLLBACK.  Only one of FSL_DB_TXN_COMMIT or FSL_DB_TXN_ROLLING_BACK
   is invoked for a given call to fsl_db_txn_end(). If
   FSL_DB_TXN_COMMIT returns non-zero, no FSL_DB_TXN_ROLLING_BACK
   invocation is made.

   - FSL_DB_TXN_ROLLED_BACK is called immediately after
   fsl_db_txn_end() has run a ROLLBACK. If this function returns non-0
   but both the the SQL-level rollback and the FSL_DB_TXN_ROLLING_BACK
   event succeededsucceeded, this event's result becames the result
   value of fsl_db_txn_end().

   To summarize, priority of determining which error code to return
   from fsl_db_txn_end(), in combination with the potential for errors
   when submitting the resulting SQL to commit/roll back, are:

   - Commit: COMMIT event (this callback) -> SQLite step()

   - Rollback: ROLLING_BACK event -> SQLite step() -> ROLLBACK event

   This hook is NOT called for IMPLICIT transactions. It is only
   called for explicit calls to fsl_db_txn_begin(), fsl_db_txn_end(),
   and fsl_db_rollback_force(). Clients must never execute SQL-level
   (BEGIN, COMMIT, ROLLBACK, SAVEPOINT) calls on fsl_db instances or
   they risk getting it out of sync. There are exceptions where
   they're safe but, generically speaking, they're not.

   @see fsl_db_event_listener()
*/
typedef int (*fsl_db_event_f)(fsl_db_event const * e);

/**
   Db handle wrapper class. Each instance wraps a single sqlite
   database handle. Though this type's interface is not opaque, it is
   never legal for clients to directly manipulate the members.

   Fossil is built upon sqlite3, but this abstraction is intended to
   hide that, insofar as possible, from clients so as to simplify an
   eventual port from v3 to v4. Clients should avoid relying on the
   underlying db being sqlite (or at least not rely on a specific
   version), but may want to register custom functions with the driver
   (or perform similar low-level operations) and the option is left
   open for them to access that handle via the fsl_db::dbh member. In
   practice, library clients do not ever need to use the underlying
   sqlite API.

   When sqlite is compiled into libfossil (configure
   --with-sqlite=tree, which is the default), the
   shared library does not export sqlite's API. A client which calls
   sqlite3_*() on fsl_db::dbh must then link against the static
   library, or use a libfossil built against the same shared sqlite
   library as the client, so that one sqlite implementation owns each
   handle.

   @see fsl_db_open();
   @see fsl_db_close();
   @see fsl_stmt
*/
struct fsl_db {

  /**
     Underlying db driver handle.
  */
  fsl_db_t * dbh;

  /**
     Holds error state from the underlying driver.  fsl_db and
     fsl_stmt operations which fail at the driver level "should"
     update this state to include error info from the driver.
     fsl_cx APIs which fail at the DB level uplift this (using
     fsl_error_swap()) so that they can pass it on up the call chain.
  */
  fsl_error error;

  /**
     Holds the file name used when opening this db. Might not refer to
     a real file (e.g. might be ":memory:" or "" (similar to
     ":memory:" but may swap to temp storage).

     Design note: we currently hold the name as it is passed to the
     db-open routine, without canonicalizing it. That is very possibly
     a mistake, as it makes it impossible to properly compare the name
     to another arbitrary checkout-relative name for purposes of
     fsl_reserved_fn_check(). For purposes of fsl_cx we currently
     (2021-03-12) canonicalize db's which we fsl_db_open(), but not
     those which we ATTACH (which includes the repo and checkout
     dbs). We cannot reasonably canonicalize the repo db filename
     because it gets written into the checkout db so that the checkout
     knows where to find the repository. History has shown that that
     path needs to be stored exactly as a user entered it, which is
     often relative.

     Memory is owned by this object.
  */
  char * filename;

  /**
     Holds the database name for use in creating queries.
     Might or might not be set/needed, depending on
     the context.

     Memory is owned by this object.
  */
  char * name;
  /**
     Describes what role(s) this db connection plays in fossil (if
     any). This is a bitmask of fsl_dbrole_e values, and a db
     connection may have multiple roles. This is only used by the
     fsl_cx-internal API.
  */
  fsl_flag16_t role;

  /**
     Private implementation details.
  */
  struct {
    /**
       Debugging/test counter. Closing a db with opened statements
       might assert() or trigger debug output when the db is closed.
    */
    int openStatementCount;

    /**
       Internal flags.
    */
    fsl_flag32_t flags;

    struct {
      /** Event listener callback. */
      fsl_db_event_f f;
      /** Impl-specific state for f. */
      void * state;
      /**
         The FSL_DB_EVENT_mask_id-masked part of event IDs to
         fire the callback for.
      */
      fsl_flag32_t maskIds;
      /** Older-style (pre-fsl_db_event) trace output channel. */
      FILE * fpTrace;
    } event;

    /** Transaction-related state. */
    struct {
      /** Counter for fsl_db_txn_begin/end(). */
      int level;
      /** Prepared statements for SAVEPOINT management. */
      sqlite3_stmt * sSavepoint;
      /** Prepared statements for SAVEPOINT RELEASE. */
      sqlite3_stmt * sRelease;
      /** Prepared statements for ROLLBACK TO SAVEPOINT. */
      sqlite3_stmt * sRollback;
    } txn;

    /** State for use with fsl_db_prepare_cached(). */
    struct {

      /**
         An internal cache of "static" queries - those which do not rely
         on call-time state unless that state can be bind()ed. Holds a
         linked list of (fsl_stmt*) instances, managed by the
         fsl_db_prepare_cached() and fsl_stmt_cached_yield() APIs.

         @see fsl_db_prepare_cached()
      */
      fsl_stmt * head;
    } stCache;
    /**
       Internal buffer to reduce reallocations caused via
       fsl_db_prepare_cached(), fsl_db_see_check(),
       and perhaps other internals.
    */
    fsl_b buffer;

    /**
       A marker which tells fsl_db_close() whether or not
       fsl_db_malloc() allocated this instance (in which case
       fsl_db_close() will fsl_free() it) or not (in which case it
       does not fsl_free() it).
    */
    void const * allocStamp;

    /**
       For a fsl_cx's main db: the connection's registry of the
       contexts using it, the context owning this db, its id there,
       and, where they differ from fsl_db_role_name()'s, the names of
       its repository and checkout schemas. Library-internal.

       zCkoutPrefix is set while the checkout's tables are tables of
       the host's main db named with that prefix
       (fsl_repo_open_ckout_opt::hostTablePrefix), in which case
       zCkout is "main". Likewise zRepoPrefix and zRepo for the
       repository's tables (fsl_repo_open_host()).
    */
    struct {
      void * reg;
      void * cx;
      unsigned id;
      char * zRepo;
      char * zCkout;
      char * zCkoutPrefix;
      char * zRepoPrefix;
    } share;
  } impl;
};
/**
   Empty-initialized fsl_db structure, intended for const-copy
   initialization.
*/
#define fsl_db_empty_m {       \
  .dbh = NULL,                 \
  .error = fsl_error_empty_m,  \
  .filename = NULL,            \
  .name = NULL,                \
  .role = 0,                   \
  .impl = {                    \
    .openStatementCount = 0,   \
    .flags = 0,                \
    .event = {                 \
      .f=NULL,                 \
      .state=NULL,             \
      .maskIds=0,              \
      .fpTrace=NULL            \
    },                         \
    .txn = {                   \
      .level = 0,              \
      .sSavepoint=NULL,        \
      .sRelease=NULL,          \
      .sRollback=NULL          \
    },                         \
    .stCache = {               \
      .head = NULL             \
    },                         \
    .buffer = fsl_b_empty_m, \
    .allocStamp = NULL,        \
    .share = {                 \
      .reg = NULL, .cx = NULL, .id = 0, \
      .zRepo = NULL, .zCkout = NULL,    \
      .zCkoutPrefix = NULL,             \
      .zRepoPrefix = NULL               \
    }                          \
  }                            \
}

/**
   Empty-initialized fsl_db structure, intended for copy
   initialization.
*/
FSL_EXPORT const fsl_db fsl_db_empty;

/**
   If db is not NULL then this function returns its name (the one used
   to fsl_db_open() it). The bytes are valid until the db connection
   is closed or until someone mucks with db->filename. If len is not
   NULL then *len is (on success) assigned to the length of the
   returned string, in bytes. The string is NUL-terminated, so
   fetching the length (by passing a non-NULL 2nd parameter) is
   optional but sometimes useful to eliminate a downstream call to
   fsl_strlen().

   Results are undefined if db is NULL or was improperly initialized.
   Will return NULL if db was properly initialized (via copying
   fsl_db_empty) but has not yet been opened.
*/
FSL_EXPORT char const * fsl_db_filename(fsl_db const * db, fsl_size_t * len);

typedef sqlite3_stmt fsl_stmt_t;
/**
   Represents a prepared statement handle.
   Intended usage:

   ```
   fsl_stmt st = fsl_stmt_empty;
   int rc = fsl_db_prepare( db, &st, "..." );
   if(rc){ // Error!
   assert(!st.stmt);
   // db->error might hold driver-level error details.
   }else{
   // use st and eventually finalize it:
   fsl_stmt_finalize( &st );
   }
   ```


   Script binding implementations can largely avoid exposing the
   statement handle (and its related cleanup ordering requirements)
   to script code. They need to have some mechanism for binding
   values to SQL (or implement all the escaping themselves), but
   that can be done without exposing all of the statement class if
   desired. For example, here's some hypothetical script code:

   ```
   var st = db.prepare(".... where i=:i and x=:x");
   // st is-a Statement, but we need not add script bindings for
   // the whole Statement.bind() API. We can instead simplify that
   // to something like:
   try {
   st.exec( {i: 42, x: 3} )
   // or, for a SELECT query:
   st.each({
   bind{i:42, x:3},
   rowType: 'array', // or 'object'
   callback: function(row,state,colNames){ print(row.join('\t')); },
   state: {...callback function state...}
   });
   } finally {
   st.finalize();
   // It is critical that st gets finalized before its DB, and
   // that'shard to guaranty if we leave st to the garbage collector!
   }
   // see below for another (less messy) alternative
   ```

   Ideally, script code should not have direct access to the
   Statement because managing lifetimes can be difficult in the
   face of flow-control changes caused by exceptions (as the above
   example demonstrates). Statements can be completely hidden from
   clients if the DB wrapper is written to support it. For example,
   in pseudo-JavaScript that might look like:

   ```
   db.exec("...where i=? AND x=?", 42, 3);
   db.each({sql:"select ... where id<?", bind:[10],
   rowType: 'array', // or 'object'
   callback: function(row,state,colNames){ print(row.join('\t')); },
   state: {...arbitrary state for the callback...}
   });
   ```
*/
struct fsl_stmt {
  /**
     The db which prepared this statement.
  */
  fsl_db * db;

  /**
     Underlying db driver-level statement handle. Clients should
     not rely on the specify concrete type if they can avoid it, to
     simplify an eventual port from sqlite3 to sqlite4.
  */
  fsl_stmt_t * stmt;

  /**
     Describes the database(s) used by this statement handle, in the
     form of a bitmask of fsl_dbrole_e values. This is a bit of a
     kludge used to allow the internals to flush cached statements
     from the fossil global config db when detaching that database.
     Code which requires this to be set must set it itself and must
     set it correctly. Hypothetically, no client-level code requires
     it but _some_ libfossil-internal code does.
  */
  fsl_flag16_t role;

  /**
     The SQL used to prepare this statement. We keep this, rather than
     simply fetching the SQL on demand, only for facilitate
     fsl_db_prepare_cached(). But since we have it, and it might be
     interesting, in client code, it's a public part of the interface.
  */
  fsl_b sql;

  /**
     The number of times this statement has fetched a row via
     fsl_stmt_step(). This is primarily intended for use by
     fsl_stmt_each_f() implementations so that they can keep track of
     when to emit a header (or similar pre-first-row setup).
  */
  fsl_size_t rowCount;

  /**
     Private implementation details.
  */
  struct {

    /**
       Internal state flags.
    */
    fsl_flag16_t flags;

    /**
       Internal use only: counts the number of times this query has
       been resolved as cached via fsl_db_prepare_cached().
    */
    uint32_t cachedHits;

    /**
       For _internal_ use in creating linked lists. Clients _must_not_
       modify this field.
    */
    fsl_stmt * next;

    /**
       A marker which tells fsl_stmt_finalize() whether or not
       fsl_stmt_malloc() allocated this instance (in which case
       fsl_stmt_finalize() will fsl_free() it) or not (in which case
       it does not free() it).
    */
    void const * allocStamp;
  } impl;
};

/**
   Empty-initialized fsl_stmt instance, intended for use as an
   in-struct initializer.
*/
#define fsl_stmt_empty_m {    \
  .db = NULL,                 \
  .stmt = NULL,               \
  .role = 0,                  \
  .sql = fsl_b_empty_m,  \
  .rowCount = 0,              \
  .impl = {                   \
    .flags = 0,               \
    .cachedHits = 0,          \
    .next = NULL,             \
    .allocStamp = NULL        \
  }                           \
}

/**
   Empty-initialized fsl_stmt instance, intended for
   copy-constructing.
*/
FSL_EXPORT const fsl_stmt fsl_stmt_empty;

/**
   Allocates a new, cleanly-initialized fsl_stmt instance using
   fsl_malloc(). The returned pointer must eventually be passed to
   fsl_stmt_finalize() to free it (whether or not it is ever passed
   to fsl_db_prepare()).

   Returns NULL on allocation error.
*/
FSL_EXPORT fsl_stmt * fsl_stmt_malloc(void);


/**
   Behaves like fsl_error_get(), using the db's underlying error
   state. Results are undefined if !db.
*/
FSL_EXPORT int fsl_db_err_get( fsl_db const * db,
                               char const ** msg, fsl_size_t * len );

/**
   Resets any error state in db, but might keep the string
   memory allocated for later use.
*/
FSL_EXPORT void fsl_db_err_reset( fsl_db * db );

/**
   Prepares an SQL statement for execution. On success it returns
   0, populates tgt with the statement's state, and the caller is
   obligated to eventually pass tgt to fsl_stmt_finalize(). tgt
   must have been cleanly initialized, either via allocation via
   fsl_stmt_malloc() or by copy-constructing fsl_stmt_empty
   resp. fsl_stmt_empty_m (depending on the context).

   On error non-0 is returned and tgt is not modified. If
   preparation of the statement fails at the db level then
   FSL_RC_DB is returned f's error state (fsl_cx_err_get())
   "should" contain more details about the problem. Returns
   FSL_RC_MISUSE if !db, !callback, or !sql. Returns
   FSL_RC_NOT_FOUND if db is not opened. Returns FSL_RC_RANGE if
   !*sql.

   The sql string and the following arguments get routed through
   fsl_appendf(), so any formatting options supported by that
   routine may be used here. In particular, the %%q and %%Q
   formatting options are intended for use in escaping SQL for
   routines such as this one.

   Before that, the placeholders {{dbname.repo}} and {{dbname.ckout}}
   in the sql string (not in the values formatted into it) are
   replaced with the names of the repository's and checkout's
   schemas, as in "SELECT uuid FROM {{dbname.repo}}.blob";
   {{temp.NAME}} with the TEMP table NAME of db's context ("temp.NAME"
   for the first context on db's connection, "temp.fslN_NAME" for the
   Nth); and
   {{bare.temp.NAME}} with that table's bare name, without the "temp."
   schema, for where SQLite wants one, as in
   "CREATE INDEX {{temp.x_idx}} ON {{bare.temp.x}}(a)"; and
   {{bare.ckout.NAME}} and {{bare.repo.NAME}} with the checkout resp.
   repository table NAME without its schema, for the same uses, e.g.
   "ON {{bare.ckout.vmerge}}".

   A context's checkout tables may instead be tables of a host's main
   db whose names have a prefix P
   (fsl_repo_open_ckout_opt::hostTablePrefix). Then
   "{{dbname.ckout}}.NAME" as a whole becomes main."PNAME",
   {{bare.ckout.NAME}} becomes "PNAME", and a {{dbname.ckout}} which
   is not followed by ".NAME" (NAME being of [A-Za-z0-9_] characters)
   is an error (FSL_RC_MISUSE), since it cannot name a prefixed
   table. The same goes for the repository's tables, with
   {{dbname.repo}} and {{bare.repo.NAME}}, while they are prefixed
   tables of a host's main db (fsl_repo_open_host()). Without a
   prefix, the expansions are as described above, e.g. "ckout.NAME"
   and "NAME". Other text in double braces is left as is. The same applies to every fsl_db
   function which takes SQL in this form, e.g. fsl_db_prepare_cached(),
   fsl_db_exec() and fsl_db_exec_multi().

   Compatibility note: in sqlite, empty SQL code evaluates
   successfully but with a NULL statement. This API disallows empty
   SQL because it uses NULL as a "no statement" marker and because
   empty SQL is arguably not a query at all.

   Tips:

   - fsl_stmt_col_count() can be used to determine whether a
   statement is a fetching query (fsl_stmt_col_count()>0) or not
   (fsl_stmt_col_count()==0) without having to know the contents
   of the query.

   - fsl_db_prepare_cached() can be used to cache often-used or
   expensive-to-prepare queries within the context of their parent
   db handle.
*/
FSL_EXPORT int fsl_db_prepare( fsl_db * db, fsl_stmt * tgt,
                               char const * sql, ... );

/**
   va_list counterpart of fsl_db_prepare().
*/
FSL_EXPORT int fsl_db_preparev( fsl_db * db, fsl_stmt * tgt,
                                char const * sql, va_list args );

/**
   A special-purpose variant of fsl_db_prepare() which caches
   statements based on their SQL code. This works very much like
   fsl_db_prepare() and friends except that it can return the same
   statement (via *st) multiple times (statements with identical
   SQL are considered equivalent for caching purposes). Clients
   need not explicitly pass the returned statement to
   fsl_stmt_finalize() - the db holds these statements and will
   finalize them when it is closed. It is legal to pass them to
   finalize, in which case they will be cleaned up immediately but
   that also invalidates _all_ pointers to the shared instances.

   If client code does not call fsl_stmt_finalize(), it MUST pass
   the statement pointer to fsl_stmt_cached_yield(st) after is done
   with it. That makes the query available for use again with this
   routine. If a cached query is not yielded via
   fsl_stmt_cached_yield() then this routine will return
   FSL_RC_ACCESS on subsequent requests for that SQL to prevent
   that recursive (mis)use of the statement causes problems.

   This routine is intended to be used in oft-called routines
   where the cost of re-creating statements on each execution could
   be prohibitive (or at least a bummer).

   Returns 0 on success, FSL_RC_MISUSE if any arguments are
   invalid. On error, *st is not written to.  On other errors
   db->error might be updated with more useful information.  See the
   Caveats section below for more details.

   Its intended usage looks like:

   ```
   fsl_stmt * st = NULL;
   int rc = fsl_db_prepare_cached(myDb, &st, "SELECT ...");
   if(rc) { assert(!st); ...error... }
   else {
   ...use it, and _be sure_ to yield it when done:...
   fsl_stmt_cached_yield(st);
   }
   ```

   Though this function allows a formatted SQL string, caching is
   generally only useful with statements which have "static" SQL,
   i.e. no call-dependent values embedded within the SQL. It _can_,
   however, contain bind() placeholders which get reset for each
   use. Note that fsl_stmt_cached_yield() resets the statement, so
   most uses of cached statements do not require that the client
   explicitly reset cached statements (doing so is harmless,
   however).

   Caveats:

   Cached queries must not be used in contexts where recursion might
   cause the same query to be returned from this function while it is
   being processed at another level in the execution stack. Results
   would be undefined. Caching is primarily intended for often-used
   routines which bind and fetch simple values, and not for queries
   which bind large inlined values or might invoke recursion. Because
   of the potential for recursive breakage, this function flags
   queries it doles out and requires that clients call
   fsl_stmt_cached_yield() to un-flag them for re-use. It will return
   FSL_RC_ACCESS if an attempt is made to (re)prepare a statement for
   which a fsl_stmt_cached_yield() is pending, and db->error will be
   populated with a (long) error string describing the problem and
   listing the SQL which caused the collision/misuse. Such SQL can
   often be disambiguated by adding a \%s, wrapped in a C-style
   comment, to the end and passing `__func__` as its value (which is
   also useful for debugging in conjunction with SQL tracing).

   Design note: for the recursion/parallel use case we "could"
   reimplement this to dole out a new statement (e.g. by appending
   " -- a_number" to the SQL to bypass the collision) and free it in
   fsl_stmt_cached_yield(), but that (A) gets uglier than it needs
   to be and (B) is not needed unless/until we really need cached
   queries in spots which would normally break them. The whole
   recursion problem is still theoretical at this point but could
   easily affect small, often-used queries without recursion.

   @see fsl_db_stmt_cache_clear()
   @see fsl_stmt_cached_yield()
*/
FSL_EXPORT int fsl_db_prepare_cached( fsl_db * db, fsl_stmt ** st,
                                      char const * sql, ... );

/**
   The va_list counterpart of fsl_db_prepare_cached().
*/
FSL_EXPORT int fsl_db_preparev_cached( fsl_db * db, fsl_stmt ** st,
                                       char const * sql, va_list args );

/**
   "Yields" a statement which was prepared with
   fsl_db_prepare_cached(), such that that routine can once again
   use/re-issue that statement. Statements prepared this way must be
   yielded in order to prevent that recursion causes
   difficult-to-track errors when a given cached statement is used
   concurrently in different code contexts.

   If st is not NULL then this also calls fsl_stmt_reset() and
   fsl_stmt_clear_bindings() on the statement.

   Returns 0 on success, FSL_RC_MISUSE if !st or if st does not
   appear to have been doled out from fsl_db_prepare_cached().

   @see fsl_db_prepare_cached()
   @see fsl_db_stmt_cache_clear()
*/
FSL_EXPORT int fsl_stmt_cached_yield( fsl_stmt * st );

/**
   If stmt is NULL, returns 0 without side-effects, otherwise this
   frees all memory associated with stmt but does not free stmt unless
   it was allocated by fsl_stmt_malloc() (these objects are normally
   stack-allocated). Returns a FSL_RC_... form of whatever
   sqlite3_finalize() returns.

   If finalization fails (returns non-0) then the error state of
   stmt->db is updated unless it already has error state, in which
   case that is retained. This function's result code is that of the
   finalization, not such a pending/propagating error. That is: it is
   possible for this to succeed but stmt->db to still have pending
   error state.

   It is legal and harmless to pass a given object to this function
   multiple times.

   Prior to 2026-10-28: (A) this function returned FSL_RC_MISUSE if
   stmt==0. (B) it returned 0 regardless of the sqlite3_finalize()
   result due to the programmer's ignorance regarding the subtleties
   of statement finalization result codes.
*/
FSL_EXPORT int fsl_stmt_finalize( fsl_stmt * stmt );

/**
   "Steps" the given SQL cursor one time. The return values
   FSL_RC_STEP_ROW and FSL_RC_STEP_DONE are both success cases, the
   former indicating that one row has been fetched and the latter
   indicating that either no rows are left to fetch or the statement
   is a non-fetching query. On error some other non-zero code will be
   returned.  On a db error this will update the underlying db's error
   state.  This function increments stmt->rowCount by 1 if it returns
   FSL_RC_STEP_ROW.

   Returns FSL_RC_MISUSE if !stmt or stmt has not been prepared.

   It is only legal to call the fsl_stmt_g_xxx() and
   fsl_stmt_get_xxx() functions if this functon returns
   FSL_RC_STEP_ROW. FSL_RC_STEP_DONE is returned upon successfully
   ending iteration or if there is no iteration to perform
   (e.g. typically an UPDATE or INSERT, but see the next paragraph).

   Though the historical definition of non-fetching query was pretty
   clear, the addition of the RETURNING keyword to sqlite3's dialect
   means that even an INSERT or DELETE can return data.

   @see fsl_stmt_reset()
   @see fsl_stmt_reset2()
   @see fsl_stmt_each()
*/
FSL_EXPORT int fsl_stmt_step( fsl_stmt * stmt );

/**
   A callback interface for use with fsl_stmt_each() and
   fsl_db_each(). It will be called one time for each row fetched,
   passed the statement object and the state parameter passed to
   fsl_stmt_each() resp. fsl_db_each().  If it returns non-0 then
   iteration stops and that code is returned UNLESS it returns
   FSL_RC_BREAK, in which case fsl_stmt_each() stops iteration and
   returns 0. i.e. implementations may return FSL_RC_BREAK to
   prematurly end iteration without causing an error.

   This callback is not called for non-fetching queries or queries
   which return no results, though it might (or might not) be
   interesting for it to do so, passing a NULL stmt for that case.

   stmt->rowCount can be used to determine how many times the
   statement has called this function. Its counting starts at 1.

   It is strictly illegal for a callback to pass stmt to
   fsl_stmt_step(), fsl_stmt_reset(), fsl_stmt_finalize(), or any
   similar routine which modifies its state. It must only read the
   current column data (or similar metatdata, e.g. column names)
   from the statement, e.g. using fsl_stmt_g_int32(),
   fsl_stmt_get_text(), or similar.
*/
typedef int (*fsl_stmt_each_f)( fsl_stmt * stmt, void * state );

/**
   Calls the given callback one time for each result row in the
   given statement, iterating over stmt using fsl_stmt_step(). It
   applies no meaning to the callbackState parameter, which gets
   passed as-is to the callback. See fsl_stmt_each_f() for the
   semantics of the callback.

   Returns 0 on success. Returns FSL_RC_MISUSE if !stmt or
   !callback. If the callback returns non-0 (other than
   FSL_RC_BREAK), that code is returned. If stepping the statement
   fails, the code from fsl_stmt_step() is returned and stmt's db
   holds the error details.
*/
FSL_EXPORT int fsl_stmt_each( fsl_stmt * stmt, fsl_stmt_each_f callback,
                              void * callbackState );

/**
   Resets the given statement, analog to sqlite3_reset(). Should be
   called one time between fsl_stmt_step() iterations when running
   multiple INSERTS, UPDATES, etc. via the same statement. If
   resetRowCounter is true then the statement's row counter
   (st->rowCount) is also reset to 0, else it is left
   unmodified. (Most use cases don't use the row counter.)

   Returns 0 on success, FSL_RC_MISUSE if stmt has not been prepared
   or has not been cleanly initialized via copying from fsl_stmt_empty
   or fsl_stmt_empty_m, FSL_RC_DB if the underlying reset fails (in
   which case the error state of the stmt->db handle is updated to
   contain the error information).

   @see fsl_stmt_db()
   @see fsl_stmt_reset()
*/
FSL_EXPORT int fsl_stmt_reset2( fsl_stmt * stmt, bool resetRowCounter );

/**
   Equivalent to fsl_stmt_reset2(stmt, false).
*/
FSL_EXPORT int fsl_stmt_reset( fsl_stmt * stmt );

/**
   Clears memory associtated with any bindings on this statement.
   This is a no-op if stmt is not prepared.
*/
FSL_EXPORT void fsl_stmt_clear_bindings(fsl_stmt * stmt);

/**
   Returns the db handle which prepared the given statement, or
   NULL if stmt has not been prepared.
*/
FSL_EXPORT fsl_db * fsl_stmt_db( fsl_stmt * stmt );

/**
   Returns the SQL string used to prepare the given statement, or NULL
   if stmt has not been prepared. If len is not NULL then *len is set
   to the length of the returned string (which is NUL-terminated). The
   returned bytes are owned by stmt and are invalidated when it is
   finalized.
*/
FSL_EXPORT char const * fsl_stmt_sql( fsl_stmt * stmt,
                                      fsl_size_t * len );

/**
   Returns the name of the given 0-based result column index, or
   NULL if !stmt, stmt is not prepared, or index is out out of
   range. The returned bytes are owned by the statement object and
   may be invalidated shortly after this is called, so the caller
   must copy the returned value if it needs to have any useful
   lifetime guarantees. It's a bit more complicated than this, but
   assume that any API calls involving the statement handle might
   invalidate the column name bytes.

   The API guarantees that the returned value is either NULL or
   NUL-terminated.

   @see fsl_stmt_param_count()
   @see fsl_stmt_col_count()
*/
FSL_EXPORT char const * fsl_stmt_col_name(fsl_stmt * stmt, int index);

/**
   Returns the result column count for the given statement, or -1 if
   !stmt or it has not been prepared. Note that this value is cached
   when the statement is created. Note that non-fetching queries
   (e.g. INSERT and UPDATE) have a column count of 0 unless they have
   a RETURNING clause. Some non-SELECT constructs, e.g. PRAGMA
   table_info(tname) and INSERT/UPDATE/DELETE with a RETURNING clause,
   behave like a SELECT and have a positive column count.

   @see fsl_stmt_param_count()
   @see fsl_stmt_col_name()
*/
FSL_EXPORT int fsl_stmt_col_count( fsl_stmt const * stmt );

/**
   Returns the bound parameter count for the given statement, or -1
   if !stmt or it has not been prepared. Note that this value is
   cached when the statement is created.

   @see fsl_stmt_col_count()
   @see fsl_stmt_col_name()
*/
FSL_EXPORT int fsl_stmt_param_count( fsl_stmt const * stmt );

/**
   Returns the index of the given named parameter for the given
   statement, or -1 if !stmt or stmt is not prepared.
*/
FSL_EXPORT int fsl_stmt_param_index( fsl_stmt * stmt, char const * param);

/**
   Binds NULL to the given 1-based parameter index.  Returns 0 on
   succcess. Sets the DB's error state on error.
*/
FSL_EXPORT int fsl_stmt_bind_null( fsl_stmt * stmt, int index );

/**
   Equivalent to fsl_stmt_bind_null_name() but binds to
   a named parameter.
*/
FSL_EXPORT int fsl_stmt_bind_null_name( fsl_stmt * stmt, char const * param );

/**
   Binds v to the given 1-based parameter index.  Returns 0 on
   succcess. Sets the DB's error state on error.
*/
FSL_EXPORT int fsl_stmt_bind_int32( fsl_stmt * stmt, int index, int32_t v );

/**
   Equivalent to fsl_stmt_bind_int32() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_int32_name( fsl_stmt * stmt, char const * param, int32_t v );

/**
   Binds v to the given 1-based parameter index.  Returns 0 on
   succcess. Sets the DB's error state on error.
*/
FSL_EXPORT int fsl_stmt_bind_int64( fsl_stmt * stmt, int index, int64_t v );

/**
   Equivalent to fsl_stmt_bind_int64() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_int64_name( fsl_stmt * stmt, char const * param, int64_t v );

/**
   Binds v to the given 1-based parameter index.  Returns 0 on
   succcess. Sets the Fossil context's error state on error.
*/
FSL_EXPORT int fsl_stmt_bind_double( fsl_stmt * stmt, int index, double v );

/**
   Equivalent to fsl_stmt_bind_double() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_double_name( fsl_stmt * stmt, char const * param, double v );

/**
   Binds v to the given 1-based parameter index.  Returns 0 on
   succcess. Sets the DB's error state on error.
*/
FSL_EXPORT int fsl_stmt_bind_id( fsl_stmt * stmt, int index, fsl_id_t v );

/**
   Equivalent to fsl_stmt_bind_id() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_id_name( fsl_stmt * stmt, char const * param, fsl_id_t v );

/**
   Binds the first n bytes of v as text to the given 1-based bound
   parameter column in the given statement. If makeCopy is true then
   the binding makes an copy of the data. Set makeCopy to false ONLY
   if you KNOW that the bytes will outlive the binding.

   Returns 0 on success. On error stmt's underlying db's error state
   is updated, hopefully with a useful error message.
*/
FSL_EXPORT int fsl_stmt_bind_text( fsl_stmt * stmt, int index,
                                   char const * v, fsl_int_t n,
                                   bool makeCopy );

/**
   Equivalent to fsl_stmt_bind_text() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_text_name( fsl_stmt * stmt, char const * param,
                                        char const * v, fsl_int_t n,
                                        bool makeCopy );
/**
   Binds the first n bytes of v as a blob to the given 1-based bound
   parameter column in the given statement. See fsl_stmt_bind_text()
   for the semantics of the makeCopy parameter and return value.
*/
FSL_EXPORT int fsl_stmt_bind_blob( fsl_stmt * stmt, int index,
                                   void const * v, fsl_size_t len,
                                   bool makeCopy );

/**
   Equivalent to fsl_stmt_bind_blob() but binds to a named
   parameter.
*/
FSL_EXPORT int fsl_stmt_bind_blob_name( fsl_stmt * stmt, char const * param,
                                        void const * v, fsl_int_t len,
                                        bool makeCopy );

/**
   Gets an integer value from the given 0-based result set column,
   assigns *v to that value, and returns 0 on success.

   Returns FSL_RC_RANGE if index is out of range for stmt, FSL_RC_MISUSE
   if stmt has no result columns.
*/
FSL_EXPORT int fsl_stmt_get_int32( fsl_stmt * stmt, int index, int32_t * v );

/**
   Gets an integer value from the given 0-based result set column,
   assigns *v to that value, and returns 0 on success.

   Returns FSL_RC_RANGE if index is out of range for stmt, FSL_RC_MISUSE
   if stmt has no result columns.
*/
FSL_EXPORT int fsl_stmt_get_int64( fsl_stmt * stmt, int index, int64_t * v );

/**
   The fsl_id_t counterpart of fsl_stmt_get_int32(). Depending on
   the sizeof(fsl_id_t), it behaves as one of fsl_stmt_get_int32()
   or fsl_stmt_get_int64().
*/
FSL_EXPORT int fsl_stmt_get_id( fsl_stmt * stmt, int index, fsl_id_t * v );

/**
   Convenience form of fsl_stmt_get_id() which returns the value
   directly but cannot report errors. It returns -1 on error, but
   that is not unambiguously an error value.
*/
FSL_EXPORT fsl_id_t fsl_stmt_g_id( fsl_stmt * stmt, int index );

/**
   Convenience form of fsl_stmt_get_int32() which returns the value
   directly but cannot report errors. It returns 0 on error, but
   that is not unambiguously an error.
*/
FSL_EXPORT int32_t fsl_stmt_g_int32( fsl_stmt * stmt, int index );

/**
   Convenience form of fsl_stmt_get_int64() which returns the value
   directly but cannot report errors. It returns 0 on error, but
   that is not unambiguously an error.
*/
FSL_EXPORT int64_t fsl_stmt_g_int64( fsl_stmt * stmt, int index );

/**
   Convenience form of fsl_stmt_get_double() which returns the value
   directly but cannot report errors. It returns 0 on error, but
   that is not unambiguously an error.
*/
FSL_EXPORT double fsl_stmt_g_double( fsl_stmt * stmt, int index );

/**
   Convenience form of fsl_stmt_get_text() which returns the value
   directly but cannot report errors. It returns NULL on error, but
   that is not unambiguously an error because it also returns NULL
   if the column contains an SQL NULL value. If outLen is not NULL
   then it is set to the byte length of the returned string.
*/
FSL_EXPORT char const * fsl_stmt_g_text( fsl_stmt * stmt, int index, fsl_size_t * outLen );

/**
   Gets double value from the given 0-based result set column,
   assigns *v to that value, and returns 0 on success.

   Returns FSL_RC_RANGE if index is out of range for stmt, FSL_RC_MISUSE
   if stmt has no result columns.
*/
FSL_EXPORT int fsl_stmt_get_double( fsl_stmt * stmt, int index, double * v );

/**
   Gets a string value from the given 0-based result set column,
   assigns *out (if out is not NULL) to that value, assigns *outLen
   (if outLen is not NULL) to *out's length in bytes, and returns 0
   on success. Ownership of the string memory is unchanged - it is owned
   by the statement and the caller should immediately copy it if
   it will be needed for much longer.

   Returns FSL_RC_RANGE if index is out of range for stmt,
   FSL_RC_MISUSE if stmt has no result columns. Returns FSL_RC_OOM if
   fetching the text from the underlying statement handle fails due to
   an allocation error.
*/
FSL_EXPORT int fsl_stmt_get_text( fsl_stmt * stmt, int index, char const **out,
                                  fsl_size_t * outLen );

/**
   The Blob counterpart of fsl_stmt_get_text(). Identical to that
   function except that its output result (3rd paramter) type
   differs, and it fetches the data as a raw blob, without any sort
   of string interpretation.

   Returns FSL_RC_RANGE if index is out of range for stmt,
   FSL_RC_MISUSE if stmt has no result columns. Returns FSL_RC_OOM if
   fetching the text from the underlying statement handle fails due to
   an allocation error.
*/
FSL_EXPORT int fsl_stmt_get_blob( fsl_stmt * stmt, int index, void const **out, fsl_size_t * outLen );

/**
   Executes multiple SQL statements, ignoring any results they might
   collect. Returns 0 on success, non-0 on error.  On error
   db->error might be updated to report the problem.
*/
FSL_EXPORT int fsl_db_exec_multi( fsl_db * db, const char * sql, ...);

/**
   va_list counterpart of db_exec_multi().
*/
FSL_EXPORT int fsl_db_exec_multiv( fsl_db * db, const char * sql, va_list args);

/**
   Executes a single SQL statement, skipping over any results it may
   have. Returns 0 on success. On error db's error state may be
   updated. Note that this function translates FSL_RC_STEP_DONE and
   FSL_RC_STEP_ROW to 0. For cases where those particular result codes
   are significant, use fsl_db_prepare() and fsl_stmt_step() (for
   which this function is just a proxy).
*/
FSL_EXPORT int fsl_db_exec( fsl_db * db, char const * sql, ... );

/**
   va_list counterpart of fs_db_exec().
*/
FSL_EXPORT int fsl_db_execv( fsl_db * db, char const * sql, va_list args );

/**
   Begins a transaction on the given db.

   This API historically used pseudo-nested transactions based off of
   BEGIN/COMMIT.  As of 2025-08-09 it uses SAVEPOINTs instead. The
   difference is subtle but was a necessary change for the libfossil
   SCM pieces to be able to behave sensibly in some cases. These docs
   use the term "transaction" to mean "savepoint".

   Returns FSL_RC_MISUSE if !db or the db is not connected, else the
   result of the underlying db call(s).

   Transactions are an easy way to implement "dry-run" mode for
   some types of applications. For example:

   ```
   bool dryRunMode = ...;
   fsl_db_txn_begin(db);
   ...do your stuff...
   fsl_db_txn_end_v2(db, !dryRunMode, false);
   ```

   Here's a tip for propagating error codes when using
   transactions:

   ```
   ...
   if(rc) fsl_db_txn_end_v2(db, false, possiblyTrue);
   else rc = fsl_db_txn_end_v2(db, true, false);
   ```

   That ensures that we propagate rc in the face of a rollback but we
   also capture the rc for a commit (which might yet fail).

   Sidebar: this API, prior to 2025-08, used pseudo-nested
   transactions directly ported from fossil(1) (essentially a
   reference-counted BEGIN/END block, with each level representing one
   reference count point). As of 2025-08 it exclusively uses sqlite3's
   SAVEPOINT[^1] feature, which is essentially nested transactions.
   This change enables better support for dry-run modes and more
   flexible non-fatal-to-the-transaction error handling. e.g. we can
   fail certain opertations, e.g. lookup of a resources, without
   inherently invalidating the whole transaction stack.

   [^1]: https://sqlite.org/lang_savepoint.html
*/
FSL_EXPORT int fsl_db_txn_begin(fsl_db * db);

/**
   Equivalent to fsl_db_txn_end_v2(db, true, false).
*/
FSL_EXPORT int fsl_db_txn_commit(fsl_db * db);

/**
   Equivalent to fsl_db_txn_end_v2(db, false, true), noting that the
   final value of true there is for historical API compatibility and
   will be changed to false if we can get away with it elsewhere.
*/
FSL_EXPORT int fsl_db_txn_rollback(fsl_db * db);

#if 0
/**
   Forces a rollback of any pending transaction in db, regardless of
   the internal transaction begin/end counter. Returns FSL_RC_MISUSE
   if db is not opened, else returns the value of the underlying
   ROLLBACK call. This also re-sets/frees any transaction-related
   state held by db (e.g. db->beforeCommit).  Use with care, as this
   mucks about with db state in a way which is not all that pretty and
   it may confuse downstream code.

   Returns 0 on success.

   Never, ever use this. In 12+ years it has never proven necessary to
   use this function, and doing so can easily lead to a mismatch in
   transaction-using code and the transaction stack level.
*/
FSL_EXPORT int fsl_db_rollback_force(fsl_db * db);
#endif

/**
   Decrements the transaction counter incremented by
   fsl_db_txn_begin() and commits or rolls back the
   savepoint if the counter goes to 0.

   The behavior of keepSavepoint depends on the transaction depth:

   - If this is not the top-most savepoint, it is "released" (applied)
     if keepSavepoint is true or rolled back if keepSavepoint false,
     and that resulting db result code is returned. A value of true
     releases this savepoint regardless of the bubbleRollback flag
     (see below).

   - If this is the top-most savepoint then keepSavepoint will be
     considered to be false if bubbleRollback is true or if any call
     to this function in the same top-level transaction stack flag has
     passed true for that argument.

   If bubbleRollback is true, or any call to this function within the
   same top-level savepoint passed true as the bubbleRollback
   argument, the transaction is put into a persistent will-rollback
   mode.  In this mode, individual savepoints can still be applied by
   passing true as the second argument, but when the final one is
   popped, the whole thing will be rolled back instead of applied.

   To reiterate: if db fsl_db_txn_begin() is used in a nested manner
   and bubbleRollback is true for any one of the nested calls, then
   that value will be remembered, such that the downstream calls to
   this function within the same transaction will behave as if
   bubbleRollback were true even if they pass false for the third
   argument.

   Achtung: the bubbleRollback==true behavior is, as of 2025-08,
   considered "legacy" and should no longer be used, but much code
   still currently expects that behavior.

   The distinction been whether retaining a savepoint should put the
   transaction into a persistent rollback state is primarily of
   interest to operations which implement "dry-run" mode.  For
   dry-run, keepSavepoint should always ben false, while
   bubbleRollback should be true if the operation failed in a way
   which could impact further operations in the same transaction.

   Returns FSL_RC_MISUSE if db is not opened, 0 if the transaction
   counter is above 0, else the result of the (potentially many)
   underlying database operations.
*/
FSL_EXPORT int fsl_db_txn_end_v2(fsl_db * db, bool keepSavepoint,
                                 bool bubbleRollback);

/**
   Equivalent to fsl_db_txn_end_v2(DB, !DOROLLBACK, !!DOROLLBACK),
   which mimics the historical behavior of this API.
*/
#define fsl_db_txn_end(DB,DOROLLBACK) \
  fsl_db_txn_end_v2((DB), !(DOROLLBACK), !!(DOROLLBACK))

/**
   Returns the given db's current transaction depth. If the value is
   negative, its absolute value represents the depth but indicates
   that a rollback is pending. If it is positive, the transaction is
   still in a "good" state. If it is 0, no transaction is active.
*/
FSL_EXPORT int fsl_db_txn_level(fsl_db * db);

/**
   Runs the given SQL query on the given db and returns true if the
   query returns any rows, else false. Returns 0 for any error as
   well.
*/
FSL_EXPORT bool fsl_db_exists(fsl_db * db, char const * sql, ... );

/**
   va_list counterpart of fsl_db_exists().
*/
FSL_EXPORT bool fsl_db_existsv(fsl_db * db, char const * sql, va_list args );

/**
   Runs the given SQL query on the given db and sets *rv to true if
   the query returns any rows, else false.

   Returns 0 on success. On error db's error state is updated and *rv
   is not modified.

   Returns FSL_RC_MISUSE without side effects if !db, !rv, !sql,
   or !*sql.
*/
FSL_EXPORT int fsl_db_exists2(fsl_db * db, bool * rv,
                              char const * sql, ... );

/**
   va_list counterpart of fsl_db_exists2().
*/
FSL_EXPORT int fsl_db_exists2v(fsl_db * db, bool * rv,
                               char const * sql, va_list args );

/**
   Runs a fetch-style SQL query against DB and returns the first
   column of the first result row via *rv. If the query returns no
   rows, *rv is not modified. The intention is that the caller sets
   *rv to his preferred default (or sentinel) value before calling
   this.

   The format string (the sql parameter) accepts all formatting
   options supported by fsl_appendf().

   Returns 0 on success. On error db's error state is updated and
   *rv is not modified.

   Returns FSL_RC_MISUSE without side effects if !db, !rv, !sql,
   or !*sql.
*/
FSL_EXPORT int fsl_db_get_int32( fsl_db * db, int32_t * rv,
                                 char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_int32().
*/
FSL_EXPORT int fsl_db_get_int32v( fsl_db * db, int32_t * rv,
                                  char const * sql, va_list args);

/**
   Convenience form of fsl_db_get_int32() which returns the value
   directly but provides no way of checking for errors. On error,
   or if no result is found, defaultValue is returned.
*/
FSL_EXPORT int32_t fsl_db_g_int32( fsl_db * db,
                                   int32_t defaultValue,
                                   char const * sql, ... );

/**
   The int64 counterpart of fsl_db_get_int32(). See that function
   for the semantics.
*/
FSL_EXPORT int fsl_db_get_int64( fsl_db * db, int64_t * rv,
                      char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_int64().
*/
FSL_EXPORT int fsl_db_get_int64v( fsl_db * db, int64_t * rv,
                       char const * sql, va_list args);

/**
   Convenience form of fsl_db_get_int64() which returns the value
   directly but provides no way of checking for errors. On error,
   or if no result is found, defaultValue is returned.
*/
FSL_EXPORT int64_t fsl_db_g_int64( fsl_db * db, int64_t defaultValue,
                            char const * sql, ... );


/**
   The fsl_id_t counterpart of fsl_db_get_int32(). See that function
   for the semantics.
*/
FSL_EXPORT int fsl_db_get_id( fsl_db * db, fsl_id_t * rv,
                   char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_id().
*/
FSL_EXPORT int fsl_db_get_idv( fsl_db * db, fsl_id_t * rv,
                    char const * sql, va_list args);

/**
   Convenience form of fsl_db_get_id() which returns the value
   directly but provides no way of checking for errors. On error,
   or if no result is found, defaultValue is returned.
*/
FSL_EXPORT fsl_id_t fsl_db_g_id( fsl_db * db, fsl_id_t defaultValue,
                      char const * sql, ... );


/**
   The fsl_size_t counterpart of fsl_db_get_int32(). See that
   function for the semantics. If this function would fetch a
   negative value, it returns FSL_RC_RANGE and *rv is not modified.
*/
FSL_EXPORT int fsl_db_get_size( fsl_db * db, fsl_size_t * rv,
                     char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_size().
*/
FSL_EXPORT int fsl_db_get_sizev( fsl_db * db, fsl_size_t * rv,
                      char const * sql, va_list args);

/**
   Convenience form of fsl_db_get_size() which returns the value
   directly but provides no way of checking for errors. On error,
   or if no result is found, defaultValue is returned.
*/
FSL_EXPORT fsl_size_t fsl_db_g_size( fsl_db * db,
                                     fsl_size_t defaultValue,
                                     char const * sql, ... );


/**
   The double counterpart of fsl_db_get_int32(). See that function
   for the semantics.
*/
FSL_EXPORT int fsl_db_get_double( fsl_db * db, double * rv,
                                  char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_double().
*/
FSL_EXPORT int fsl_db_get_doublev( fsl_db * db, double * rv,
                                   char const * sql, va_list args);

/**
   Convenience form of fsl_db_get_double() which returns the value
   directly but provides no way of checking for errors. On error,
   or if no result is found, defaultValue is returned.
*/
FSL_EXPORT double fsl_db_g_double( fsl_db * db, double defaultValue,
                                   char const * sql, ... );

/**
   The C-string counterpart of fsl_db_get_int32(). On success *rv
   will be set to a dynamically allocated string copied from the
   first column of the first result row. If rvLen is not NULL then
   *rvLen will be assigned the byte-length of that string. If no
   row is found, *rv is set to NULL and *rvLen (if not NULL) is set
   to 0, and 0 is returned. Note that NULL is also a legal result
   (an SQL NULL translates as a NULL string), The caller must
   eventually free the returned string value using fsl_free().
*/
FSL_EXPORT int fsl_db_get_text( fsl_db * db, char ** rv, fsl_size_t * rvLen,
                                char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_text().
*/
FSL_EXPORT int fsl_db_get_textv( fsl_db * db, char ** rv, fsl_size_t * rvLen,
                      char const * sql, va_list args );

/**
   Convenience form of fsl_db_get_text() which returns the value
   directly but provides no way of checking for errors. On error,
   or if no result is found, NULL is returned. The returned string
   must eventually be passed to fsl_free() to free it.  If len is
   not NULL then if non-NULL is returned, *len will be assigned the
   byte-length of the returned string.
*/
FSL_EXPORT char * fsl_db_g_text( fsl_db * db, fsl_size_t * len,
                      char const * sql,
                      ... );

/**
   The Blob counterpart of fsl_db_get_text(). Identical to that
   function except that its output result (2nd paramter) type
   differs, and it fetches the data as a raw blob, without any sort
   of string interpretation. The returned *rv memory must
   eventually be passed to fsl_free() to free it. If len is not
   NULL then on success *len will be set to the byte length of the
   returned blob. If no row is found, *rv is set to NULL and *rvLen
   (if not NULL) is set to 0, and 0 is returned. Note that NULL is
   also a legal result (an SQL NULL translates as a NULL string),
*/
FSL_EXPORT int fsl_db_get_blob( fsl_db * db, void ** rv, fsl_size_t * len,
                     char const * sql, ... );


/**
   va_list counterpart of fsl_db_get_blob().
*/
FSL_EXPORT int fsl_db_get_blobv( fsl_db * db, void ** rv, fsl_size_t * stmtLen,
                      char const * sql, va_list args );

/**
   Convenience form of fsl_db_get_blob() which returns the value
   directly but provides no way of checking for errors. On error,
   or if no result is found, NULL is returned.
*/
FSL_EXPORT void * fsl_db_g_blob( fsl_db * db, fsl_size_t * len,
                      char const * sql,
                      ... );
/**
   Similar to fsl_db_get_text() and fsl_db_get_blob(), but writes
   its result to tgt, appending its results to the given buffer.

   If asBlob is true then the underlying BLOB API is used to
   populate the buffer, else the underlying STRING/TEXT API is
   used.  For many purposes there will be no difference, but if you
   know you might have binary data, be sure to pass a true value
   for asBlob to avoid any potential encoding-related problems.

   Results are undefined if any pointer argument is NULL. Returns
   FSL_RC_MISUSE if the SQL is an empty string.
*/
FSL_EXPORT int fsl_db_get_buffer( fsl_db * db, fsl_b * tgt,
                                  bool asBlob, char const * sql,
                                  ... );

/**
   va_list counterpart of fsl_db_get_buffer().
*/
FSL_EXPORT int fsl_db_get_bufferv( fsl_db * db, fsl_b * tgt,
                                   bool asBlob, char const * sql,
                                   va_list args );


/**
   Expects sql to be a SELECT-style query which (potentially)
   returns a result set. For each row in the set callback() is
   called, as described for fsl_stmt_each(). Returns 0 on success.
   The callback is _not_ called for queries which return no
   rows. If clients need to know if rows were returned, they can
   add a counter to their callbackState and increment it from the
   callback.

   Returns FSL_RC_MISUSE if db is not opened, !callback,
   !sql. Returns FSL_RC_RANGE if !*sql.
*/
FSL_EXPORT int fsl_db_each( fsl_db * db, fsl_stmt_each_f callback,
                            void * callbackState, char const * sql, ... );

/**
   va_list counterpart to fsl_db_each().
*/
FSL_EXPORT int fsl_db_eachv( fsl_db * db, fsl_stmt_each_f callback,
                             void * callbackState, char const * sql, va_list args );


/**
   Returns the given Julian date value formatted as an ISO8601
   string (with a fractional seconds part if msPrecision is true,
   else without it).  Returns NULL if !db, db is not connected, j
   is less than 0, or on allocation error. The returned memory must
   eventually be freed using fsl_free().

   If localTime is true then the value is converted to the local time,
   otherwise it is not.

   @see fsl_db_unix_to_iso8601()
   @see fsl_julian_to_iso8601()
   @see fsl_iso8601_to_julian()
*/
FSL_EXPORT char * fsl_db_julian_to_iso8601( fsl_db * db, double j,
                                            bool msPrecision, bool localTime );

/**
   Returns the given Julian date value formatted as an ISO8601
   string (with a fractional seconds part if msPrecision is true,
   else without it).  Returns NULL if !db, db is not connected, j
   is less than 0, or on allocation error. The returned memory must
   eventually be freed using fsl_free().

   If localTime is true then the value is converted to the local time,
   otherwise it is not.

   @see fsl_db_julian_to_iso8601()
   @see fsl_julian_to_iso8601()
   @see fsl_iso8601_to_julian()
*/
FSL_EXPORT char * fsl_db_unix_to_iso8601( fsl_db * db, fsl_time_t j,
                                          bool localTime );


/**
   Returns the current time in Julian Date format. Returns a negative
   value if !db or db is not opened.
*/
FSL_EXPORT double fsl_db_julian_now(fsl_db * db);

/**
   Uses the given db to convert the given time string to Julian Day
   format. If it cannot be converted, a negative value is returned.
   The str parameter can be anything suitable for passing to sqlite's:

   SELECT julianday(str)

   Note that this routine will escape str for use with SQL - the
   caller must not do so.

   @see fsl_julian_to_iso8601()
   @see fsl_iso8601_to_julian()
*/
FSL_EXPORT double fsl_db_string_to_julian(fsl_db * db, char const * str);

/**
   Opens the given db file and populates db with its handle.  db
   must have been cleanly initialized by copy-initializing it from
   fsl_db_empty (or fsl_db_empty_m) or by allocating it using
   fsl_db_malloc(). Failure to do so will lead to undefined
   behaviour.

   openFlags may be a mask of FSL_DB_OPEN_xxx values, but not all are
   used/supported here. If FSL_DB_OPEN_CREATE is _not_ set in
   openFlags and dbFile does not exist, it will return
   FSL_RC_NOT_FOUND. The existence of FSL_DB_OPEN_CREATE in the flags
   will cause this routine to try to create the file if needed. If
   conflicting flags are specified (e.g. FSL_DB_OPEN_RO and
   FSL_DB_OPEN_RWC) then which one takes precedence is unspecified and
   possibly unpredictable. If openFlags is 0 then FSL_DB_OPEN_RO is
   assumed.

   This routine normally looks for the given file before attempting to
   open it and will update db's error state if the file cannot be
   found. Those checks are skipped if (1) openFlags has the
   FSL_DB_OPEN_CREATE bit set, (2) dbName is empty (indicating a
   nameless temporary database), (3) the string contains a ":" in any
   byte position, in which case it is assumed to be a URL-style name
   or ":memory:". The exception to (3) is on Windows platforms, where
   it recognize drive letter prefixes in the form "X:".

   See this page for the differences between ":memory:" and "":

   https://www.sqlite.org/inmemorydb.html

   This routine does not handle URL-style file names.

   Returns FSL_RC_MISUSE if !db, !dbFile, or if db->dbh is not NULL
   (i.e. if it is already opened or its memory was default-initialized
   (use fsl_db_empty to cleanly copy-initialize new stack-allocated
   instances).

   On error db->dbh will be NULL, but db->error might contain error
   details.

   Regardless of success or failure, db should be passed to
   fsl_db_close() to free up all memory associated with it. It is
   not closed automatically by this function because doing so cleans
   up the error state, which the caller will presumably want to
   have.

   @see fsl_db_close()
   @see fsl_db_prepare()
   @see fsl_db_malloc()
*/
FSL_EXPORT int fsl_db_open( fsl_db * db, char const * dbFile,
                            fsl_flag32_t openFlags );

/**
   Closes the given db handle and frees any resources owned by
   db. This function is a no-op if db is NULL.

   If db was allocated using fsl_db_malloc() (as determined by
   examining db->allocStamp) then this routine also fsl_free()s it,
   otherwise it is assumed to either be on the stack or part of a
   larger struct and is not freed, but any resources it allocated are
   freed.

   If db has any pending transactions, they are rolled back by this
   function before a FSL_DB_EVENT_CLOSING event is fired.
*/
FSL_EXPORT void fsl_db_close( fsl_db * db );

/**
   If db is an opened db handle, this registers a debugging
   function with the db which traces all SQL to the given FILE
   handle. If outStream is NULL then tracing events will be
   emitted via FSL_DB_EVENT_TRACE_SQLX instead.

   If expandedSql is true then it uses sqlite3_expanded_sql() to
   expand each traced statement, else it uses unexpanded SQL (which is
   much faster).

   If outStream is not NULL then tracing will go there, otherwise it
   will go out via a FSL_DB_EVENT_TRACE_SQL or FSL_DB_EVENT_TRACE_SQLX
   event (depending on the value of expandedSql). Ownership of
   outStream is not modified by this call and outStream must outlive
   its association with db.

   This is a no-op if db is closed.

   This mechanism is only intended for debugging and exploration of
   how Fossil works. Tracing is often as easy way to ensure that a
   given code block is getting run.

   TODOs:

   - Expand this API to take a client-side callback and state
   object, rather than a FILE pointer.

   - Provide a toggle for the tracing level: with and without
   "expanded" SQL. Expanding the SQL to include its bound values is
   far more expensive (but also far more informative).
*/
FSL_EXPORT void fsl_db_sqltrace_enable( fsl_db * db, FILE * outStream,
                                        bool expandSql);

/**
   Returns the row ID of the most recent insertion,
   or -1 if !db, db is not connected, or 0 if no inserts
   have been performed.
*/
FSL_EXPORT fsl_id_t fsl_db_last_insert_id(fsl_db * db);

/**
   Returns non-0 (true) if the database (which must be open) table
   identified by zTableName has a column named zColName
   (case-sensitive), else returns 0.
*/
FSL_EXPORT bool fsl_db_table_has_column( fsl_db * db,
                                         char const *zTableName,
                                         char const *zColName );

/**
   If a db name has been associated with db then it is returned,
   otherwise NULL is returned. A db has no name by default, but
   fsl_cx-used ones get their database name assigned to them
   (e.g. "main" for the main db).
*/
FSL_EXPORT char const * fsl_db_name(fsl_db const * db);

/**
   Returns a db name string for the given fsl_db_role value. The
   string is static, guaranteed to live as long as the app.  It
   returns NULL if passed FSL_DBROLE_NONE or some value out of range
   for the enum.
*/
FSL_EXPORT const char * fsl_db_role_name(enum fsl_dbrole_e r);

/**
   Allocates a new fsl_db instance(). Returns NULL on allocation
   error. Note that fsl_db instances can often be used from the
   stack - allocating them dynamically is an uncommon case necessary
   for script bindings.

   Achtung: the returned value's allocStamp member is used for
   determining if fsl_db_close() should free the value or not.  Thus
   if clients copy over this value without adjusting allocStamp back
   to its original value, the library will likely leak the instance.
   Been there, done that.
*/
FSL_EXPORT fsl_db * fsl_db_malloc(void);

/**
   The fsl_stmt counterpart of fsl_db_malloc(). See that function
   for when you might want to use this and a caveat involving the
   allocStamp member of the returned value. fsl_stmt_finalize() will
   free statements created with this function.
*/
FSL_EXPORT fsl_stmt * fsl_stmt_malloc(void);

/**
   ATTACHes the file zDbName to db using the database name zLabel
   (which gets quoted as an SQL identifier). Returns 0 on
   success. Returns FSL_RC_MISUSE if any argument is NULL or any
   string argument starts with a NUL byte, else it returns the result
   of fsl_db_exec() which attaches the db. On db-level errors db's
   error state will be updated.
*/
FSL_EXPORT int fsl_db_attach(fsl_db * db, const char *zDbName,
                             const char *zLabel);

/**
   The converse of fsl_db_detach(). Must be passed the same arguments
   which were passed as the 1st and 3rd arguments to fsl_db_attach().
   Returns 0 on success, FSL_RC_MISUSE if !db, !zLabel, or !*zLabel,
   else it returns the result of the underlying fsl_db_exec()
   call.
*/
FSL_EXPORT int fsl_db_detach(fsl_db * db, const char *zLabel);

/**
   Binds f to a db handle owned by a host application, such as a
   program which loads libfossil as a SQLite extension. It must be
   called before a repository or checkout is opened, and returns
   FSL_RC_MISUSE otherwise.

   While bound, opening a repository or checkout ATTACHes it to dbh
   under the usual schema names ("repo" and "ckout") instead of
   opening a connection of its own. All of libfossil's work then runs
   in dbh's transaction, as SAVEPOINTs nested in any transaction the
   host has open. Closing it DETACHes it, and never closes dbh. The
   host must keep dbh open until then.

   Several contexts may be bound to one dbh. A context gets the usual
   schema names unless dbh already has schemas of those names (e.g.
   another context's), in which case it gets "repo_2", "ckout_2", and
   so on. Each context after the first
   to join the connection also gets TEMP table and savepoint names of
   its own, which carry its place in that order. Their transactions
   nest in dbh's: a context must end each of its transaction levels
   before any other context's which began outside it, and is refused
   (FSL_RC_MISUSE) otherwise. A context closed while another's
   transaction is inside its own (closing belongs outside of any
   transaction) leaves its savepoints open in dbh's transaction, and,
   as SQLite cannot DETACH there, its schemas attached, for the host
   to end and DETACH. The SQL functions libfossil adds act for
   the context whose statement calls them, and for the host's own SQL,
   for the first of the contexts still bound; closing the last one
   removes them. The host's SQL which names no schema reaches the
   repository attached first.

   Opening fails if:

   - dbh is a connection libfossil opened for a context of its own,
   - dbh has PRAGMA foreign_keys=ON,
   - a table in a schema SQLite searches first (temp, main, or one
     attached earlier, other than another context's) has the name of
     one of the opened db's tables, so that the host's SQL which names
     no schema would use that table in place of fossil's, or
   - a repository and a checkout would both be opened and dbh's main
     db is not a file, e.g. ":memory:". A check-in writes both in one
     transaction, which SQLite can only commit atomically if it is in a
     super-journal. Super-journals can only contain DELETE mode dbs.

   Unlike on a connection libfossil opens itself, libfossil does not
   change dbh's busy timeout, WAL checkpoint, or foreign_keys settings,
   install a commit hook, or define now() or regexp() on it.

   Opening and closing must happen outside of any transaction, as
   SQLite requires for ATTACH and DETACH.

   Pass NULL to unbind (only while nothing is opened).

   @see fsl_cx_host_db_closing()
*/
FSL_EXPORT int fsl_cx_host_db( fsl_cx * f, fsl_db_t * dbh );

/**
   Tells f that its host db handle is being closed and can no longer
   run SQL, e.g. from a virtual table's xDisconnect method during
   sqlite3_close(). A following fsl_cx_finalize() or fsl_close_dbs()
   then finalizes libfossil's statements without running DETACH, which
   lets the host's close succeed.
*/
FSL_EXPORT void fsl_cx_host_db_closing( fsl_cx * f );

/**
   Registers libfossil's SQLite extension on db: the SQL functions
   fsl_open(), fsl_close(), fsl_commit(), fsl_tag(), fsl_sync(),
   fsl_clone(), fsl_checkout(), fsl_update(), fsl_merge(),
   fsl_status(), fsl_add(), fsl_rm(), fsl_mv() and fsl_revert(), which
   run libfossil on db itself through fsl_cx_host_db(). Its signature
   matches what sqlite3_auto_extension() expects, so a program which
   links libfossil can register it for every new connection with:

   ```
   sqlite3_auto_extension((void(*)(void))fsl_sqlext_init);
   ```

   pApi is unused. It returns a SQLite result code. On error, if
   pzErrMsg is not NULL, *pzErrMsg is set to a message which the
   caller must free with sqlite3_free(). src/sqlext.c documents the SQL
   functions.
*/
FSL_EXPORT int fsl_sqlext_init(fsl_db_t * db, char ** pzErrMsg,
                               sqlite3_api_routines const * pApi);

/**
   Expects fmt to be a SELECT-style query. For each row in the
   query, the first column is fetched as a string and appended to
   the tgt list.

   Returns 0 on success, FSL_RC_MISUSE if !fmt or fmt is empty, or any
   number of potential FSL_RC_OOM or db-related errors.

   Results rows with a NULL value (resulting from an SQL NULL) are
   added to the list as NULL entries.

   Each entry appended to the list is a (char *) which must
   be freed using fsl_free(). To easiest way to clean up
   the list and its contents is:

   ```
   fsl_list_visit_free(tgt,...);
   ```

   On error the list may be partially populated.

   Complete example:

   ```
   fsl_list li = fsl_list_empty;
   int rc = fsl_db_select_slist(db, &li,
            "SELECT uuid FROM blob WHERE rid<20");
   if(!rc){
     fsl_size_t i;
     for(i = 0;i < li.used; ++i){
       char const * uuid = (char const *)li.list[i];
       fsl_fprintf(stdout, "UUID: %s\n", uuid);
     }
   }
   fsl_list_visit_free(&li, 1);
   ```

   Of course fsl_list_visit() may be used to traverse the list as
   well, as long as the visitor expects (char [const]*) list
   elements.
*/
FSL_EXPORT int fsl_db_select_slist( fsl_db * db, fsl_list * tgt,
                                    char const * fmt, ... );

/**
   The va_list counterpart of fsl_db_select_slist().
*/
FSL_EXPORT int fsl_db_select_slistv( fsl_db * db, fsl_list * tgt,
                                     char const * fmt, va_list args );

/**
   Returns n bytes of random lower-case hexidecimal characters
   using the given db as its data source, plus a terminating NUL
   byte. The returned memory must eventually be freed using
   fsl_free(). Returns NULL if !n, db is not opened, or on a db-level error.
*/
FSL_EXPORT char * fsl_db_random_hex(fsl_db * db, fsl_size_t n);

/**
   Returns the "number of database rows that were changed or inserted
   or deleted by the most recently completed SQL statement" (to quote
   the underlying APIs). Returns 0 if db is not opened.

   See: https://sqlite.org/c3ref/changes.html
*/
FSL_EXPORT int fsl_db_changes_recent(fsl_db * db);

/**
   Returns "the number of row changes caused by INSERT, UPDATE or
   DELETE statements since the database connection was opened" (to
   quote the underlying APIs). Returns 0 if db is not opened.

   See; https://sqlite.org/c3ref/total_changes.html
*/
FSL_EXPORT int fsl_db_changes_total(fsl_db * db);

/**
   Initializes the given database file. zFilename is the name of
   the db file. It is created if needed, but any directory
   components are not created. zSchema is the base schema to
   install.  The following arguments may be (char const *) SQL
   code, each of which gets run against the db after the main
   schema is called.  The variadic argument list MUST end with NULL
   (0), even if there are no non-NULL entries.

   Returns 0 on success.

   On error, if err is not NULL then it is populated with any error
   state from the underlying (temporary) db handle.
*/
FSL_EXPORT int fsl_db_init( fsl_error * err, char const * zFilename,
                 char const * zSchema, ... );

/**
   A fsl_stmt_each_f() impl, intended primarily for debugging, which
   simply outputs row data in tabular form via fsl_output(). The
   state argument must be a valid fsl_cx pointer. On
   the first row, the column names are output.

   Achtung: this function's expectations were changed on 2024-09-16:
   prior to this, stmt's db handle had access to a fsl_cx instance,
   but that was factored out. It now requires the state argument to be
   a fsl_cx.
*/
FSL_EXPORT int fsl_stmt_each_f_dump( fsl_stmt * stmt, void * state );

/**
   Returns true if the table name specified by the final argument
   exists in the fossil database specified by the 2nd argument on the
   db connection specified by the first argument, else returns false.
   For FSL_DBROLE_CKOUT and FSL_DBROLE_REPO, zTable is the name of a
   checkout resp. repository table, which is looked up with its prefix
   if those tables are prefixed tables of a host's main db
   (fsl_repo_open_ckout_opt::hostTablePrefix, fsl_repo_open_host()).

   Trivia: this is one of the few libfossil APIs which makes use of
   FSL_DBROLE_TEMP.

   Potential TODO: this is a bit of a wonky interface. Consider
   changing it to eliminate the role argument, which is only really
   needed if we have duplicate table names across attached dbs or if
   we internally mess up and write a table to the wrong db.
*/
FSL_EXPORT bool fsl_db_table_exists(fsl_db * db, fsl_dbrole_e whichDb,
                                    const char *zTable);

/**
   The elipsis counterpart of fsl_stmt_bind_fmtv().
*/
FSL_EXPORT int fsl_stmt_bind_fmt( fsl_stmt * st, char const * fmt, ... );

/**
    Binds a series of values using a formatting string.

    The string may contain the following characters, each of which
    refers to the next argument in the args list:

    '-': binds a NULL and expects a NULL placeholder
         in the argument list (for consistency's sake).

    'i': binds an int32

    'I': binds an int64

    'R': binds a fsl_id_t ('R' as in 'RID' or 'ROWID')

    'f': binds a double

    's': binds a (char const *) as text or NULL. See below.

    'S': binds a (char const *) as a blob or NULL. See below.

    'b': binds a (fsl_b const *) as text or NULL. See below.

    'B': binds a (fsl_b const *) as a blob or NULL. See below.

    ' ': spaces are allowed for readability and are ignored.

    '^': An optional modifier for "sSbB". See below.

    Returns 0 on success, any number of other FSL_RC_xxx codes on
    error.

    About the sSbB bindings:

    - If their argument is NULL they bind as SQL NULL.

    - ACHTUNG: the "sSbB" bindings assume, because of how this API is
      normally used, that the memory pointed to by the given argument
      will outlive the pending step of the given statement, so that
      memory is NOT copied by this call. Thus results are undefined if
      such an argument's memory is invalidated before the statement is
      done with it. The default behavior can be overridden by adding
      the character '^' immediately after the "sSbB" entry (with no
      intervening spaces), which will tell it to make a copy of the
      content. e.g. "ss^i" would bind one string without making a
      copy, then one string with a copy, then an int32.

    Example:

    ```
    int rc = fsl_stmt_bind_fmt(&stmt, "ss^i", "hello", "world", (int32_t)12);
    ```

    Note the cast on the final argument to ensure that it's of the
    proper size for the 'i' type.
*/
FSL_EXPORT int fsl_stmt_bind_fmtv( fsl_stmt * st, char const * fmt,
                                   va_list args );

/**
   Works like fsl_stmt_bind_fmt() but:

   1) It calls fsl_stmt_reset() before binding the arguments.

   2) If binding succeeds then it steps the given statement a single
      time.

   3) If the result is _NOT_ FSL_RC_STEP_ROW then it also resets the
      statement before returning. It does not do so for
      FSL_RC_STEP_ROW because doing so would make it impossible to
      fetch the current row's data.

   Returns the result of the underlying step() call. It never returns
   0.

   Design note: the return value for FSL_RC_STEP_ROW, as opposed to
   returning 0, is necessary for proper statement use if the client
   wants to fetch any result data from the statement afterwards (which
   is only legal if FSL_RC_STEP_ROW was the result). This is also why
   it cannot reset the statement if that result is returned.
*/
FSL_EXPORT int fsl_stmt_bind_stepv_v2( fsl_stmt * st, char const * fmt,
                                       va_list args );

/**
   The elipsis counterpart of fsl_stmt_bind_step_v2().
*/
FSL_EXPORT int fsl_stmt_bind_step_v2( fsl_stmt * st, char const * fmt, ... );

/**
   Works exactly like fsl_stmt_bind_stepv_v2() except that it returns
   0 if stepping results in FSL_RC_STEP_DONE. That behavior is legacy
   and now consider to have been a poor design decision, but those
   semantics are currently heavily relied on throughout the library.

   To re-iterate: this routine NEVER returns FSL_RC_STEP_DONE. We say
   that because some folks (🙋‍♂️) keep breaking things by checking for
   that code instead of 0. That's why fsl_stmt_bind_step_v2() was
   introduced.
*/
FSL_EXPORT int fsl_stmt_bind_stepv( fsl_stmt * st, char const * fmt,
                                      va_list args );

/**
   The elipsis counterpart of fsl_stmt_bind_step().
*/
FSL_EXPORT int fsl_stmt_bind_step( fsl_stmt * st, char const * fmt, ... );

/**
   Sets the on-transaction hook for the given db, overwriting any
   prior one.  To clear the hook, pass NULL for the 2nd and 3rd
   arguments.

   The final argument specifies what events type to look for.  It may
   be an OR of any FSL_DB_EVENT_... events. Use
   FSL_DB_EVENT_listen_all to listen to all events. The stored mask is
   bitwise ANDed against FSL_DB_EVENT_mask_id, so only the concrete
   message IDs are recorded here.

   Achtung: fsl_cx instances install this hook on database handles
   they manage, so never call this on such a handle.
*/
FSL_EXPORT void fsl_db_event_listener( fsl_db * db, fsl_db_event_f f,
                                       void * pState, fsl_flag32_t mask);

/**
   Returns true if db is opened and sqlite3_db_readonly() returns 0
   for it, else returns false. If zSchema is NULL then "main" is
   assumed.
*/
FSL_EXPORT bool fsl_db_is_writeable( fsl_db * db, char const *zSchema );

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif /* ORG_FOSSIL_SCM_FSL_DB_H_INCLUDED */
/* end of file include/fossil-scm/db.h */
/* start of file include/fossil-scm/hash.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_HASH_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_HASH_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).

  *****************************************************************************
  This file declares public APIs relating to hashing.
*/

#if defined(__cplusplus)
extern "C" {
#endif

/**
   Various set-in-stone constants used by the API.
*/
enum fsl_hash_constants {
/**
   The length, in bytes, of a hex-format SHA1 hash string.
*/
FSL_STRLEN_SHA1 = 40,
/**
   The length, in bytes, of a hex-format SHA3-256 hash string.
*/
FSL_STRLEN_K256 = 64,
/**
   The length, in bytes, of a hex-format MD5 hash string.
*/
FSL_STRLEN_MD5 = 32,

/** Minimum length of a full fossil UUID. */
FSL_UUID_STRLEN_MIN = FSL_STRLEN_SHA1,
/** Maximum length of a full fossil UUID. */
FSL_UUID_STRLEN_MAX = FSL_STRLEN_K256
};

/**
   Unique IDs for hash types supported by fossil.
*/
enum fsl_hash_types_e {
/** Invalid hash type. */
FSL_HTYPE_ERROR = 0,
/** SHA1. */
FSL_HTYPE_SHA1 = 1,
/** SHA3-256. */
FSL_HTYPE_K256 = 2
};
typedef enum fsl_hash_types_e fsl_hash_types_e;

typedef struct fsl_md5_cx fsl_md5_cx;
typedef struct fsl_sha1_cx fsl_sha1_cx;
typedef struct fsl_sha3_cx fsl_sha3_cx;

/**
   The hash string of the initial MD5 state. Used as an
   optimization for some places where we need an MD5 but know it
   will not hash any data.

   Equivalent to what the md5sum command outputs for empty input:

   ```
   # md5sum < /dev/null
   d41d8cd98f00b204e9800998ecf8427e  -
   ```
*/
#define FSL_MD5_INITIAL_HASH "d41d8cd98f00b204e9800998ecf8427e"

/**
   Holds state for MD5 calculations. It is intended to be used like
   this:

   ```
   unsigned char digest[FSL_STRLEN_MD5/2];
   char hex[FSL_STRLEN_MD5+1];
   fsl_md5_cx cx = fsl_md5_cx_empty;
   // alternately: fsl_md5_init(&cx);
   ...call fsl_md5_update(&cx,...) any number of times to
   ...incrementally calculate the hash.
   fsl_md5_final(&cx, digest); // ends the calculation
   fsl_md5_digest_to_base16(digest, hex);
   // digest now contains the raw 16-byte MD5 digest.
   // hex now contains the 32-byte MD5 + a trailing NUL
   ```
*/
struct fsl_md5_cx {
  int isInit;
  uint32_t buf[4];
  uint32_t bits[2];
  unsigned char in[64];
};

/**
   A filled-with-defaults fsl_md5_cx instance appropriate for
   const-copy initialization. Instances must either be
   copy-initialized from this instance or they must be
   passed to fsl_md5_init() before they are used.
*/
#define fsl_md5_cx_empty_m {                                  \
    1/*isInit*/,                                              \
    {/*buf*/0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 }, \
    {/*bits*/0,0},                                            \
    {0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,                \
     0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,                \
     0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,                \
     0,0,0,0}}

/**
   Equivalent to fsl_md5_cx_empty_m but suitable for non-const
   copy initialization.
*/
FSL_EXPORT const fsl_md5_cx fsl_md5_cx_empty;

/**
   Initializes the given context pointer. It must not be NULL.  This
   must be the first routine called on any fsl_md5_cx instances.
   Alternately, copy-constructing from fsl_md5_cx_empty has the same
   effect.

   @see fsl_md5_update()
   @see fsl_md5_final()
*/
FSL_EXPORT void fsl_md5_init(fsl_md5_cx *cx);

/**
   Updates cx's state to reflect the addition of the data specified by
   the range (buf, buf+len]. Neither cx nor buf may be NULL. This may
   be called an arbitrary number of times between fsl_md5_init() and
   fsl_md5_final().

   @see fsl_md5_init()
   @see fsl_md5_final()
*/
FSL_EXPORT void fsl_md5_update(fsl_md5_cx *cx, void const * buf, fsl_size_t len);

/**
   Finishes up the calculation of the md5 for the given context and
   writes a 16-byte digest value to the 2nd parameter.  Use
   fsl_md5_digest_to_base16() to convert the digest output value to
   hexadecimal form.

   @see fsl_md5_init()
   @see fsl_md5_update()
   @see fsl_md5_digest_to_base16()
*/
FSL_EXPORT void fsl_md5_final(fsl_md5_cx * cx, unsigned char * digest);

/**
   Converts an md5 digest value (from fsl_md5_final()'s 2nd
   parameter) to a 32-byte (FSL_STRLEN_MD5) CRC string plus a
   terminating NUL byte. i.e.  zBuf must be at least
   (FSL_STRLEN_MD5+1) bytes long.

   @see fsl_md5_final()
*/
FSL_EXPORT void fsl_md5_digest_to_base16(unsigned char const *digest,
                                         char *zBuf);

/**
   The md5 counterpart of fsl_sha1sum_buffer(), identical in
   semantics except that its result is an MD5 hash instead of an
   SHA1 hash and the resulting hex string is FSL_STRLEN_MD5 bytes
   long plus a terminating NUL.
*/
FSL_EXPORT int fsl_md5sum_buffer(fsl_b const *pIn, fsl_b *pCksum);

/**
   The md5 counterpart of fsl_sha1sum_cstr(), identical in
   semantics except that its result is an MD5 hash instead of an
   SHA1 hash and the resulting string is FSL_STRLEN_MD5 bytes long
   plus a terminating NUL.
*/
FSL_EXPORT char *fsl_md5sum_cstr(const char *zIn, fsl_int_t len);

/**
   The MD5 counter part to fsl_sha1sum_stream(), with identical
   semantics except that the generated hash is an MD5 string
   instead of SHA1.
*/
FSL_EXPORT int fsl_md5sum_stream(fsl_input_f src, void * srcState, fsl_b *pCksum);

/**
   Reads all input from src() and passes it through fsl_md5_update(cx,...).
   Returns 0 on success, FSL_RC_MISUSE if !cx or !src. If src returns
   a non-0 code, that code is returned from here.
*/
FSL_EXPORT int fsl_md5_update_stream(fsl_md5_cx *cx, fsl_input_f src, void * srcState);

/**
   Equivalent to fsl_md5_update(cx, b->mem, b->used). Results are undefined
   if either pointer is invalid or NULL.
*/
FSL_EXPORT void fsl_md5_update_buffer(fsl_md5_cx *cx, fsl_b const * b);

/**
   Passes the first len bytes of str to fsl_md5_update(cx). If len
   is less than 0 then fsl_strlen() is used to calculate the
   length.  Results are undefined if either pointer is invalid or
   NULL. This is a no-op if !len or (len<0 && !*str).
*/
FSL_EXPORT void fsl_md5_update_cstr(fsl_md5_cx *cx, char const * str, fsl_int_t len);

/**
   A fsl_md5_update_stream() proxy which updates cx to include the
   contents of the given file.

   Returns 0 on success and FSL_RC_MISUSE if !cx or !fname. If the
   file cannot be opened it returns fsl_errno_to_rc() of the
   resulting errno, with FSL_RC_IO as the default. A read error gives
   FSL_RC_IO.
*/
FSL_EXPORT int fsl_md5_update_filename(fsl_md5_cx *cx, char const * fname);

/**
   The MD5 counter part to fsl_sha1sum_filename(), with identical
   semantics except that the generated hash is an MD5 string
   instead of SHA1.
*/
FSL_EXPORT int fsl_md5sum_filename(const char *zFilename, fsl_b *pCksum);


typedef void(*fsl_sha1h_collision_callback)(uint64_t, const uint32_t*, const uint32_t*, const uint32_t*, const uint32_t*);
/**
   Holds state for SHA1 calculations. It is intended to be used
   like this:

   ```
   unsigned char digest[FSL_STRLEN_SHA1/2]
   char hex[FSL_STRLEN_SHA1+1];
   fsl_sha1_cx cx;
   fsl_sha1_init(&cx); // REQUIRED, unlike its md5 counterpart

   ...call fsl_sha1_update(&cx,...) any number of times to
   ...incrementally calculate the hash.

   fsl_sha1_final(&cx, digest); // ends the calculation
   fsl_sha1_digest_to_base16(digest, hex);

   // digest now contains the raw 20-byte SHA1 digest.
   // hex now contains the 40-byte SHA1 + a trailing NUL
   ```
*/
struct fsl_sha1_cx {
  uint64_t total;
  uint32_t ihv[5];
  unsigned char buffer[64];
  int found_collision;
  int safe_hash;
  int detect_coll;
  int ubc_check;
  int reduced_round_coll;
  fsl_sha1h_collision_callback callback;
  uint32_t ihv1[5];
  uint32_t ihv2[5];
  uint32_t m1[80];
  uint32_t m2[80];
  uint32_t states[80][5];
};
/**
   fsl_sha1_cx instance intended for in-struct copy initialization.
*/
#define fsl_sha1_cx_empty_m {0}

/**
   fsl_sha1_cx instance intended for copy initialization. For build
   config portability, the copied-to object must still be passed to
   fsl_sha1_init() to initialize it.
*/
FSL_EXPORT const fsl_sha1_cx fsl_sha1_cx_empty;

/**
   Initializes the given context with the initial SHA1 state.  This
   must be the first routine called on an SHA1 context, and passing
   this context to other SHA1 routines without first having passed
   it to this will lead to undefined results.

   @see fsl_sha1_update()
   @see fsl_sha1_final()
*/
FSL_EXPORT void fsl_sha1_init(fsl_sha1_cx *context);

/**
   Updates the given context to include the hash of the first len
   bytes of the given data.

   @see fsl_sha1_init()
   @see fsl_sha1_final()
*/
FSL_EXPORT void fsl_sha1_update( fsl_sha1_cx *context, void const *data, fsl_size_t len);

/**
   Add padding and finalizes the message digest. If digest is not NULL
   then it writes 20 bytes of digest to the 2nd parameter. This
   function returns non-0 if a collision is detected while hashing. If
   no collision is detected, it returns 0.

   @see fsl_sha1_update()
   @see fsl_sha1_digest_to_base16()
*/
FSL_EXPORT int fsl_sha1_final(fsl_sha1_cx *context, unsigned char * digest);

/**
   A convenience form of fsl_sha1_final() which writes
   FSL_STRLEN_SHA1+1 bytes (hash plus terminating NUL byte) to the
   2nd argument and returns a (const char *)-type cast of the 2nd
   argument.
*/
FSL_EXPORT const char * fsl_sha1_final_hex(fsl_sha1_cx *context, char * zHex);

/**
   Convert a digest into base-16.  digest must be at least 20 bytes
   long and hold an SHA1 digest. zBuf must be at least (FSL_STRLEN_SHA1
   + 1) bytes long, to which FSL_STRLEN_SHA1 characters of
   hexidecimal-form SHA1 hash and 1 NUL byte will be written.

   @see fsl_sha1_final()
*/
FSL_EXPORT void fsl_sha1_digest_to_base16(unsigned char const *digest,
                                          char *zBuf);

/**
   Computes the SHA1 checksum of pIn and stores the resulting
   checksum in the buffer pCksum.  pCksum's memory is re-used if is
   has any allocated to it. pCksum may == pIn, in which case this
   is a destructive operation (replacing the hashed data with its
   hash code).

   Return 0 on success, FSL_RC_OOM if (re)allocating pCksum fails.
*/
FSL_EXPORT int fsl_sha1sum_buffer(fsl_b const *pIn, fsl_b *pCksum);

/**
   Works like fsl_sha1sum_buffer() except that it appends the hash to
   the target buffer, rather than re-using the whole target. It is
   legal for both arguments to refer to the same object.
*/
FSL_EXPORT int fsl_sha1sum_buffer2(fsl_b const *pIn, fsl_b *pCksum);

/**
   Computes the SHA1 checksum of the first len bytes of the given
   string.  If len is negative then zIn must be NUL-terminated and
   fsl_strlen() is used to find its length. The result is a
   FSL_UUID_STRLEN-byte string (+NUL byte) returned in memory
   obtained from fsl_malloc(), so it must be passed to fsl_free()
   to free it. If NULL==zIn or !len then NULL is returned.
*/
FSL_EXPORT char *fsl_sha1sum_cstr(const char *zIn, fsl_int_t len);

/**
   Consumes all input from src and calculates its SHA1 hash. The
   result is set in pCksum (its contents, if any, are overwritten,
   not appended to). Returns 0 on success. Returns FSL_RC_MISUSE if
   !src or !pCksum. It keeps consuming input from src() until that
   function reads fewer bytes than requested, at which point EOF is
   assumed. If src() returns non-0, that code is returned from this
   function.
*/
FSL_EXPORT int fsl_sha1sum_stream(fsl_input_f src, void * srcState, fsl_b *pCksum);


/**
   A fsl_sha1sum_stream() wrapper which calculates the SHA1 of
   given file.

   Returns FSL_RC_MISUSE if !zFilename or !pCksum. If the file cannot
   be opened it returns fsl_errno_to_rc() of the resulting errno,
   with FSL_RC_IO as the default, so a missing file gives
   FSL_RC_NOT_FOUND and a permissions failure FSL_RC_ACCESS. Else it
   returns as per fsl_sha1sum_stream(), which gives FSL_RC_IO for a
   read error. This function has no error object, so callers which
   report the failure must name the file themselves.

   TODO: the v1 impl has special behaviour for symlinks which this
   function lacks. For that support we need a variant of this
   function which takes a fsl_cx parameter (for the allow-symlinks
   setting).
*/
FSL_EXPORT int fsl_sha1sum_filename(const char *zFilename, fsl_b *pCksum);

/**
   Reads all input from src() and passes it through fsl_sha1_update(cx,...).
   Returns 0 on success, FSL_RC_MISUSE if !cx or !src. If src returns
   a non-0 code, that code is returned from here.
*/
FSL_EXPORT int fsl_sha1sum_update_stream(fsl_sha1_cx *ctx, fsl_input_f src,
                                         void * srcState);

/**
   Legal values for SHA3 hash sizes, in bits: an increment of 32 bits
   in the inclusive range (128..512).

   The hexidecimal-code size, in bytes, of any given bit size in this
   enum is the bit size/4.
*/
enum fsl_sha3_hash_size {
/** Sentinel value. Must be 0. */
FSL_SHA3_INVALID = 0,
FSL_SHA3_128 = 128, FSL_SHA3_160 = 160, FSL_SHA3_192 = 192,
FSL_SHA3_224 = 224, FSL_SHA3_256 = 256, FSL_SHA3_288 = 288,
FSL_SHA3_320 = 320, FSL_SHA3_352 = 352, FSL_SHA3_384 = 384,
FSL_SHA3_416 = 416, FSL_SHA3_448 = 448, FSL_SHA3_480 = 480,
FSL_SHA3_512 = 512,
/* Default SHA3 flavor */
FSL_SHA3_DEFAULT = 256
};

/**
   Type for holding SHA3 processing state. Each instance must be
   initialized with fsl_sha3_init(), populated with fsl_sha3_update(),
   and "sealed" with fsl_sha3_end().

   Sample usage:

   ```
   fsl_sha3_cx cx;
   fsl_sha3_init(&cx, FSL_SHA3_DEFAULT);
   fsl_sha3_update(&cx, memory, lengthOfMemory);
   fsl_sha3_end(&cx);
   printf("Hash = %s\n", (char const *)cx.hex);
   ```

   After fsl_sha3_end() is called cx.hex contains the hex-string forms
   of the digest. fsl_sha3_update() may be called an arbitrary number
   of times to feed in chunks of memory (e.g. to stream in arbitrarily
   large data).
*/
struct fsl_sha3_cx {
    union {
        uint64_t s[25];         /* Keccak state. 5x5 lines of 64 bits each */
        unsigned char x[1600];  /* ... or 1600 bytes */
    } u;
    unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
    unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
    unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
    enum fsl_sha3_hash_size size; /* Size of the hash, in bits. */
    unsigned char hex[132]; /* Hex form of final digest: 56-128 bytes
                               plus terminating NUL. */
};

/**
   If the given number is a valid fsl_sha3_hash_size value, its enum
   entry is returned, else FSL_SHA3_INVALID is returned.

   @see fsl_sha3_init()
*/
FSL_EXPORT enum fsl_sha3_hash_size fsl_sha3_hash_size_for_int(int);

/**
   Initialize a new hash. The second argument specifies the size of
   the hash in bits. Results are undefined if cx is NULL or sz is not
   a valid positive value.

   After calling this, use fsl_sha3_update() to hash data and
   fsl_sha3_end() to finalize the hashing process and generate a digest.
*/
FSL_EXPORT void fsl_sha3_init2(fsl_sha3_cx *cx, enum fsl_sha3_hash_size sz);

/**
   Equivalent to fsl_sha3_init2(cx, FSL_SHA3_DEFAULT).
*/
FSL_EXPORT void fsl_sha3_init(fsl_sha3_cx *cx);

/**
   Updates cx's state to include the first len bytes of data.

   If cx is NULL results are undefined (segfault!). If mem is not
   NULL then it must be at least n bytes long. If n is 0 then this
   function has no side-effects.

   @see fsl_sha3_init()
   @see fsl_sha3_end()
*/
FSL_EXPORT void fsl_sha3_update( fsl_sha3_cx *cx, void const *data, unsigned int len);

/**
   To be called when SHA3 hashing is complete: finishes the hash
   calculation and populates cx->hex with the final hash code in
   hexidecimal-string form. Returns the binary-form digest value,
   which refers to cx->size/8 bytes of memory which lives in the cx
   object. After this call cx->hex will be populated with cx->size/4
   bytes of lower-case ASCII hex codes plus a terminating NUL byte.

   Potential TODO: change fsl_sha1_final() and fsl_md5_final() to use
   these same return semantics.

   @see fsl_sha3_init()
   @see fsl_sha3_update()
*/
FSL_EXPORT unsigned char const * fsl_sha3_end(fsl_sha3_cx *cx);

/**
   SHA3-256 counterpart of fsl_sha1_digest_to_base16(). digest must be at least
   32 bytes long and hold an SHA3 digest. zBuf must be at least (FSL_STRLEN_K256+1)
   bytes long, to which FSL_STRLEN_K256 characters of
   hexidecimal-form SHA3 hash and 1 NUL byte will be written

   @see fsl_sha3_end().
*/
FSL_EXPORT void fsl_sha3_digest_to_base16(unsigned char const *digest,
                                          char *zBuf);
/**
   SHA3 counter part of fsl_sha1sum_buffer().
*/
FSL_EXPORT int fsl_sha3sum_buffer(fsl_b const *pIn, fsl_b *pCksum);
/**
   SHA3 counter part of fsl_sha1sum_cstr().
*/
FSL_EXPORT char *fsl_sha3sum_cstr(const char *zIn, fsl_int_t len);
/**
   SHA3 counterpart of fsl_sha1sum_stream().
*/
FSL_EXPORT int fsl_sha3sum_stream(fsl_input_f src, void * srcState,
                                  fsl_b *pCksum);
/**
   SHA3 counterpart of fsl_sha1sum_filename().
*/
FSL_EXPORT int fsl_sha3sum_filename(const char *zFilename, fsl_b *pCksum);

/**
   Expects zHash to be a full-length hash value of one of the
   fsl_hash_types_t-specified types, and nHash to be the length, in
   bytes, of zHash's contents (which must be the full hash length, not
   a prefix). If zHash can be validated as a hash, its corresponding
   hash type is returned, else FSL_HTYPE_ERROR is returned.
*/
FSL_EXPORT fsl_hash_types_e fsl_validate_hash(const char *zHash,
                                              fsl_size_t nHash);

/**
   Expects (zHash, nHash) to refer to a full hash (of a supported
   content hash type) of pIn's contents. This routine hashes pIn's
   contents and, if it compares equivalent to zHash then the ID of the
   hash type is returned.  On a mismatch, FSL_HTYPE_ERROR is returned.
*/
FSL_EXPORT fsl_hash_types_e fsl_verify_blob_hash(fsl_b const * pIn,
                                                 const char *zHash, int nHash);

/**
   Returns a human-readable name for the given hash type, or its
   second argument h is not a supported hash type.
 */
FSL_EXPORT const char * fsl_hash_type_name(fsl_hash_types_e h,
                                           const char *zUnknown);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_HASH_H_INCLUDED */
/* end of file include/fossil-scm/hash.h */
/* start of file include/fossil-scm/repo.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_REPO_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_REPO_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/** @file repo.h

    repo.h declares APIs specifically dealing with repository-db-side
    state, as opposed to specifically checkout-side state or
    non-content-related APIs.
*/


#if defined(__cplusplus)
extern "C" {
#endif

typedef struct fsl_card_F fsl_card_F;
typedef struct fsl_card_J fsl_card_J;
typedef struct fsl_card_Q fsl_card_Q;
typedef struct fsl_card_T fsl_card_T;
typedef struct fsl_checkin_opt fsl_checkin_opt;
typedef struct fsl_deck fsl_deck;
typedef struct fsl_uperm fsl_uperm;

/**
   Opens the given db file name as f's repository. Returns 0 on
   success. On error it sets f's error state and returns that code
   unless the error was FSL_RC_MISUSE (which indicates invalid
   arguments and it does not set the error state).

   Returns FSL_RC_ACCESS if f already has an opened repo db (use
   fsl_repo_close() or fsl_ckout_close() to close it).

   Returns FSL_RC_NOT_FOUND if repoDbFile is not found, as this
   routine cannot create a new repository db.

   Returns FSL_RC_NOT_A_REPO if repoDbFile is not an SQLite database
   or lacks the tables of a repository schema (the same check
   fossil(1) applies), in which case it is not left opened.

   Results are undefined if any argument is NULL.

   When a repository is opened, the fossil-level user name
   associated with f (if any) is overwritten with the default user
   from the repo's login table (the one with uid=1). Thus
   fsl_cx_user_get() may return a value even if the client has not
   called fsl_cx_user_set().

   It would be nice to have a parameter specifying that the repo
   should be opened read-only. That's not as straightforward as it
   sounds because of how the various dbs are internally managed
   (via one db handle). Until then, the permissions of the
   underlying repo file will determine how it is opened. i.e. a
   read-only repo will be opened read-only.


   Potentially interesting side-effects:

   - On success this re-sets several bits of f's configuration to
   match the repository-side settings.

   @see fsl_repo_create()
   @see fsl_repo_close()
   @see fsl_close_scm_dbs()
*/
FSL_EXPORT int fsl_repo_open( fsl_cx * f, char const * repoDbFile/*, char readOnlyCurrentlyIgnored*/ );

/**
   Opens as f's repository the repository whose tables are tables of
   the main db of f's host db handle (fsl_cx_host_db()) with names
   starting with zPrefix, e.g. "fslrepo_lib_" for main.fslrepo_lib_blob
   and so on, as made by fsl_repo_create() with
   fsl_repo_create_opt::hostTablePrefix or by fsl_repo_import().
   Nothing is ATTACHed, and the host's own tables, including any named
   like repository tables without the prefix, are not touched. One
   host db can so hold several repositories, each with a prefix of its
   own, beside working copies (fsl_repo_open_ckout_opt::hostTablePrefix)
   and the host's own tables, and a host transaction can span all of
   them.

   The prefix must match [A-Za-z_][A-Za-z0-9_]*, so that the prefixed
   names are identifiers without quoting, and must not start with
   "sqlite_" (in any case), else FSL_RC_RANGE. Since some repository
   tables are only created when first used (e.g. the forum's), the
   prefix is the repository's namespace: it may neither be the start
   of another repository's or working copy's prefix nor start with
   one, ignoring case, else FSL_RC_ALREADY_EXISTS. That holds for the
   prefixes of the other contexts on that handle, for those of the
   repositories and working copies recorded in the main db (see
   fsl_repo_open_ckout_opt::hostTablePrefix; a repository is a P with
   tables Pblob and Pconfig, the latter with a 'content-schema' row),
   and for the names of the SQLite extension's working copies, which
   start with "fslfiles_", "fslclock_" and "fslwc_". The prefix must
   be spelled as the tables are, including case, else FSL_RC_MISUSE
   with the stored spelling in the error message, since SQLite's GLOB,
   which picks the repository's tables (e.g. for fsl_repo_export()),
   does not ignore case.

   Returns FSL_RC_ACCESS if f already has an opened repository,
   FSL_RC_MISUSE if f is not bound to a host db handle,
   FSL_RC_UNSUPPORTED if the host's main db is not a file, and
   FSL_RC_NOT_A_REPO if the main db lacks the prefixed tables of a
   repository (the same check as fsl_repo_open()'s). Otherwise it
   behaves like fsl_repo_open().

   The host db's settings are left as they are: its application_id is
   not set, its journal mode and synchronous setting are not changed
   (fsl_repo_journal_mode_set() fails), and a check-in to a checkout
   whose tables are in the same db needs no particular journal mode.
   Closing the repository drops none of its tables. A rebuild
   (fsl_repo_rebuild()) drops and recreates only the tables which
   libfossil's transient schemas define (see fsl_schema_repo2()), with
   the prefix, never others with it, which may be the host's. The
   repository's ticket schema (its "ticket-table" setting) gets the
   prefix for every object it makes and every table it names; one
   which names a table it does not make itself (e.g. in a trigger),
   which would be the host's, or makes anything but tables, indexes,
   views and triggers, is refused with FSL_RC_CONSISTENCY when the
   ticket tables are made (e.g. by a rebuild). fsl_cx_db_file_repo() returns the host main db's file name,
   which fsl_reserved_fn_check() then treats as the repository db.

   A repository so opened has no file name of its own: its identity is
   the host db and the prefix, and a checkout of it records it, in its
   vvar "repository" entry, as "fsl-host-prefix:" followed by the
   prefix (which is never the canonical file name which libfossil and
   fossil(1) record for a repository db), along with its
   "project-code". Such a checkout, in the host db or on disk, reopens
   with its repository only on a context bound to a host db handle
   whose main db has those tables, and only if they have that
   project-code (else FSL_RC_REPO_MISMATCH). The global config db's
   list of repositories ("repo:" entries) does not list them.

   The schema's REFERENCES clauses name the prefixed tables, but
   foreign keys are not enforced: libfossil requires PRAGMA
   foreign_keys=OFF on a host's handle.

   @see fsl_repo_export()
   @see fsl_repo_import()
*/
FSL_EXPORT int fsl_repo_open_host( fsl_cx * f, char const * zPrefix );

/**
   Writes f's opened repository, whether a db file of its own or tables
   of a host's main db (fsl_repo_open_host()), to the new file zFile
   as a standalone repository db, with the normal unprefixed table
   names and its PRAGMA application_id, which fossil(1) can open. If
   zFile exists, this fails with FSL_RC_ALREADY_EXISTS unless overwrite
   is true, in which case zFile and its -journal, -wal and -shm files
   are removed first, but never a db file of f's db connection (e.g.
   the repository's own or the host's), for which it fails with
   FSL_RC_MISUSE.

   Every table is copied as stored, including those which only
   fossil(1) creates (e.g. accesslog, unversioned, chat, alias,
   subscriber, pending_alert, admin_log, modreq, purgeevent, purgeitem,
   fx_*), with its rows, artifacts as they are stored (compressed and
   deltified, so that nothing is re-encoded and no rebuild is needed),
   its indexes and AUTOINCREMENT counters, along with the views and
   triggers. Left out are the virtual tables, i.e. the full-text
   search indexes (fossil(1)'s ftsidx and chatfts1), with their shadow
   tables and the documents of the search index (ftsdocs, its indexes
   and the view ftscontent), whose module arguments name tables which
   renaming cannot follow: the export has no search index, which
   "fossil fts-config index on" makes anew, and fossil(1) makes its chat
   index again the next time it uses chat (its chat_create_tables()).

   It reads the repository in one transaction, so the export is a
   consistent snapshot. It must be called outside a transaction,
   including one on a host db handle (else FSL_RC_MISUSE), since it
   ATTACHes zFile and an in-memory scratch db, which it DETACHes
   afterwards. On error, the new file is removed. Returns 0 on
   success, else an error code, with f's error state set.

   @see fsl_repo_import()
*/
FSL_EXPORT int fsl_repo_export( fsl_cx * f, char const * zFile,
                                bool overwrite );

/**
   Copies repository db file zFile into the main db of f's host db
   handle (fsl_cx_host_db()) as tables whose names start with zPrefix,
   in one transaction, and opens them as f's repository, as
   fsl_repo_open_host() does. Once it has checked the prefix and that
   zFile is a repository, it closes any repository and checkout f has
   opened, which fails inside a transaction.

   The copy is the reverse of fsl_repo_export()'s, with the same
   tables, rows and artifacts as stored, and the same exception for
   the search indexes. The rules for zPrefix are fsl_repo_open_host()'s,
   and the main db may have no table, index, trigger or view whose
   name starts with it (ignoring case), else FSL_RC_ALREADY_EXISTS:
   the copy never adopts or drops a table of the host's or of another
   repository or working copy. To import again, drop the tables
   first. The transaction holds the main db's write lock from before
   its checks. If zFile is not a repository (FSL_RC_NOT_A_REPO), or
   anything fails, nothing is left in the main db.

   Returns FSL_RC_NOT_FOUND if zFile does not exist, FSL_RC_MISUSE if f
   is not bound to a host db handle or the handle is in a transaction
   (SQLite cannot ATTACH zFile there), and otherwise 0 or an error
   code, with f's error state set.
*/
FSL_EXPORT int fsl_repo_import( fsl_cx * f, char const * zFile,
                                char const * zPrefix );

/**
   This function is a programmatic interpretation of
   this table:

   https://fossil-scm.org/index.html/doc/trunk/www/fileformat.wiki#summary

   For a given control artifact type and a card name in the form of
   the card name's letter (e.g. 'A', 'W', ...), this function
   returns 0 (false) if that card type is not permitted in this
   control artifact type, a negative value if the card is optional
   for this artifact type, and a positive value if the card type is
   required for this artifact type.

   As a special case, if t==FSL_SATYPE_ANY then this function
   always returns a negative value as long as card is a valid card
   letter.

   Another special case: when t==FSL_SATYPE_CHECKIN and card=='F',
   this returns a negative value because the table linked to above
   says F-cards are optional. In practice we have yet to find a use
   for checkins with no F-cards, so this library currently requires
   F-cards at checkin-time even though this function reports that
   they are optional.
*/
FSL_EXPORT int fsl_card_is_legal( fsl_satype_e t, char card );

/**
   Artifact tag types used by the Fossil framework. Their values
   are a hard-coded part of the Fossil format, and not subject to
   change (only extension, possibly).
*/
enum fsl_tagtype_e {
/**
   Sentinel value for use with constructors/initializers.
*/
FSL_TAGTYPE_INVALID = -1,
/**
   The "cancel tag" indicator, a.k.a. an anti-tag.
*/
FSL_TAGTYPE_CANCEL = 0,
/**
   The "add tag" indicator, a.k.a. a singleton tag.
*/
FSL_TAGTYPE_ADD = 1,
/**
   The "propagating tag" indicator.
*/
FSL_TAGTYPE_PROPAGATING = 2
};
typedef enum fsl_tagtype_e fsl_tagtype_e;

/**
   Hard-coded IDs used by the 'tag' table of repository DBs. These
   values get installed as part of the base Fossil db schema in new
   repos, and they must never change.
*/
enum fsl_tagid_e {
/**
   DB string tagname='bgcolor'.
*/
FSL_TAGID_BGCOLOR = 1,
/**
   DB: tag.tagname='comment'.
*/
FSL_TAGID_COMMENT = 2,
/**
   DB: tag.tagname='user'.
*/
FSL_TAGID_USER = 3,
/**
   DB: tag.tagname='date'.
*/
FSL_TAGID_DATE = 4,
/**
   DB: tag.tagname='hidden'.
*/
FSL_TAGID_HIDDEN = 5,
/**
   DB: tag.tagname='private'.
*/
FSL_TAGID_PRIVATE = 6,
/**
   DB: tag.tagname='cluster'.
*/
FSL_TAGID_CLUSTER = 7,
/**
   DB: tag.tagname='branch'.
*/
FSL_TAGID_BRANCH = 8,
/**
   DB: tag.tagname='closed'.
*/
FSL_TAGID_CLOSED = 9,
/**
   DB: tag.tagname='parent'.
*/
FSL_TAGID_PARENT = 10,
/**
   DB: tag.tagname='note'

   Extra text appended to a check-in comment.

   2026-09: neither fossil(1) nor libfossil have ever implemented this
   capability.
*/
FSL_TAGID_NOTE = 11,

/**
   Largest tag ID reserved for internal use.
*/
FSL_TAGID_MAX_INTERNAL = 99
};


/**
   Returns one of '-', '+', or '*' for a valid input parameter, 0
   for any other value.
*/
FSL_EXPORT char fsl_tag_prefix_char( fsl_tagtype_e t );


/**
   A list of fsl_card_F objects. F-cards used a custom list type,
   instead of the framework's generic fsl_list, because experience has
   shown that the number of (de)allocations we need for F-card lists
   has a large negative impact when parsing and creating artifacts en
   masse. This list type, unlike fsl_list, uses a conventional object
   array approach to storage, as opposed to an array of pointers (each
   entry of which has to be separately allocated).

   These lists, and F-cards in generally, are typically maintained
   internally in the library. There's probably "no good reason" for
   clients to manipulate them.
*/
struct fsl_card_F_list {
  /**
     The list of F-cards. The first this->used elements are in-use.
     This pointer may change any time the list is reallocated.
  */
  fsl_card_F * list;
  /**
     The number of entries in this->list which are in use.
  */
  uint32_t used;
  /**
     The number of entries currently allocated in this->list.
  */
  uint32_t capacity;
  /**
     An internal cursor into this->list, used primarily for
     properly traversing the file list in delta manifests.

     Maintenance notes: internal updates to this member are the only
     reason some of the deck APIs require a non-const deck. This type
     needs to be signed for compatibility with some of the older
     algos, e.g. fsl__deck_F_seek_base().
  */
  int32_t cursor;
  /**
     Internal flags. Never, ever modify these from client code.
  */
  uint32_t flags;
};
typedef struct fsl_card_F_list fsl_card_F_list;
/** Empty-initialized fsl_card_F instance for const copy
    initialization */
#define fsl_card_F_list_empty_m {NULL, 0, 0, 0, 0}
/** Empty-initialized fsl_card_F instance for non-const copy
    initialization */
FSL_EXPORT const fsl_card_F_list fsl_card_F_list_empty;

/**
   A "deck" stores (predictably enough) a collection of "cards."
   Cards are constructs embedded within Fossil's Structural Artifacts
   to denote various sorts of changes in a Fossil repository, and a
   Deck encapsulates the cards for a single Structural Artifact of an
   arbitrary type, e.g. Manifest (a.k.a. "checkin") or Cluster. A card
   is basically a command with a single-letter name and a well-defined
   signature for its arguments. Each card is represented by a member
   of this struct whose name is the same as the card type
   (e.g. fsl_card::C holds a C-card and fsl_card::F holds a list of
   F-card). Each type of artifact only allows certain types of
   card. The complete list of valid card/construct combinations can be
   found here:

   https://fossil-scm.org/home/doc/trunk/www/fileformat.wiki#summary

   fsl_card_is_legal() can be used determine if a given card type
   is legal (per the above chart) with a given Control Artifiact
   type (as stored in the fsl_deck::type member).

   The type member is used by some algorithms to determine which
   operations are legal on a given artifact type, so that they can
   fail long before the user gets a chance to add a malformed artifact
   to the database. Clients who bypass the fsl_deck APIs and
   manipulate the deck's members "by hand" (so to say) effectively
   invoke undefined behaviour.

   The various routines to add/set cards in the deck are named
   fsl_deck_CARDNAME_add() resp. fsl_deck_CARDNAME_set(). The "add"
   functions represent cards which may appear multiple times
   (e.g. the 'F' card) or have multiple values (the 'P' card), and
   those named "set" represent unique or optional cards. The R-card
   is the outlier, with fsl_deck_R_calc(). NEVER EVER EVER directly
   modify a member of this struct - always use the APIs. The
   library performs some optimizations which can lead to corrupt
   memory and invalid free()s if certain members' values are
   directly replaced by the client (as opposed to via the APIs).

   Note that the 'Z' card is not in this structure because it is a
   hash of the other inputs and is calculated incrementally and
   appended automatically by fsl_deck_output().

   All non-const pointer members of this structure are owned by the
   structure instance unless noted otherwise (the fsl_deck::f member
   being the notable exception).

   Maintenance reminder: please keep the card members alpha sorted to
   simplify eyeball-searching through their docs.

   @see fsl_deck_malloc()
   @see fsl_deck_init()
   @see fsl_deck_parse()
   @see fsl_deck_load_rid()
   @see fsl_deck_finalize()
   @see fsl_deck_clean()
   @see fsl_deck_save()
   @see fsl_deck_A_set()
   @see fsl_deck_B_set()
   @see fsl_deck_C_set()
   @see fsl_deck_D_set()
   @see fsl_deck_E_set()
   @see fsl_deck_F_add()
   @see fsl_deck_J_add()
   @see fsl_deck_K_set()
   @see fsl_deck_L_set()
   @see fsl_deck_M_add()
   @see fsl_deck_N_set()
   @see fsl_deck_P_add()
   @see fsl_deck_Q_add()
   @see fsl_deck_T_add()
   @see fsl_deck_branch_set()
   @see fsl_deck_U_set()
   @see fsl_deck_W_set()
*/
struct fsl_deck {
  /**
     Specifies the the type (or eventual type) of this
     artifact. The function fsl_card_is_legal() can be used to
     determined if a given card type is legal for a given value of
     this member. APIs which add/set cards use that to determine if
     the operation requested by the client is semantically legal.
  */
  fsl_satype_e type;

  /**
     DB repo.blob.rid value. Normally set by fsl_deck_load_rid().
  */
  fsl_id_t rid;

  /**
     The Fossil context responsible for this deck. Though this data
     type is normally, at least conceptually, free of any given fossil
     context, many related algorithms need a context in order to
     perform db- or caching-related work, as well as to simplify error
     message propagation. We store this as a struct member to keep all
     such algorithms from redundantly requiring both pieces of
     information as arguments.

     This object does not own the context and the context object must
     outlive this deck instance.
  */
  fsl_cx * f;

  /**
     The 'A' (attachment) card. Only used by FSL_SATYPE_ATTACHMENT
     decks. The spec currently specifies only 1 A-card per
     manifest, but conceptually this could/should be a list.
  */
  struct {
    /**
       Filename of the A-card.
    */
    char * name;

    /**
       Name of wiki page, or UUID of ticket or event (technote), to
       which the attachment applies.
    */
    char * tgt;

    /**
       UUID of the file being attached via the A-card.
    */
    fsl_uuid_str src;
  } A;

  struct {
    /**
       The 'B' (baseline) card holds the UUID of baseline manifest.
       This is empty for baseline manifests and holds the UUID of
       the parent for delta manifests.
    */
    fsl_uuid_str uuid;

    /**
       Baseline manifest corresponding to this->B. It is loaded on
       demand by routines which need it, typically by calling
       fsl_deck_F_rewind() (unintuitively enough!). The parent/child
       relationship in Fossil is the reverse of conventional -
       children own their parents, not the other way
       around. i.e. this->baseline will get cleaned up when the child
       part of that relationship is cleaned up.

       The baseline "should" be a baseline manifest but may itself be
       a delta manifest. In that case only its own F-cards are used,
       never those it inherits, and its own baseline is not loaded.
       fossil(1) behaves the same way.
    */
    fsl_deck * baseline;
  } B;
  /**
     The 'C' (comment) card.
  */
  char * C;

  /**
     The 'D' (date) card, in Julian format.
  */
  double D;

  /**
     The 'E' (event) card.
  */
  struct {
    /**
       The 'E' card's date in Julian Day format.
    */
    double julian;

    /**
       The 'E' card's UUID.
    */
    fsl_uuid_str uuid;
  } E;

  /**
     The 'F' (file) card container.
  */
  fsl_card_F_list F;

  /**
     UUID for the 'G' (forum thread-root) card.
  */
  fsl_uuid_str G;

  /**
     The H (forum title) card.
  */
  char * H;

  /**
     UUID for the 'I' (forum in-response-to) card.
  */
  fsl_uuid_str I;

  /**
     The 'J' card specifies changes to "value" of "fields" in
     tickets (FSL_SATYPE_TICKET).

     Holds (fsl_card_J*) entries.
  */
  fsl_list J;

  /**
     UUID for the 'K' (ticket) card.
  */
  fsl_uuid_str K;

  /**
     The 'L' (wiki name/title) card.
  */
  char * L;

  /**
     List of UUIDs (fsl_uuid_str) in a cluster ('M' cards).
  */
  fsl_list M;

  /**
     The 'N' (comment mime type) card. Note that this is only
     ostensibly supported by fossil, but fossil does not (as of
     2021-04-13) honor this value and always assumes that its value is
     "text/x-fossil-wiki".
  */
  char * N;

  /**
     List of UUIDs of parents ('P' cards). Entries are of type
     (fsl_uuid_str).
  */
  fsl_list P;

  /**
     'Q' (cherry pick) cards. Holds (fsl_card_Q*) entries.
  */
  fsl_list Q;

  /**
     The R-card holds an MD5 hash which is calculated based on the
     names, sizes, and contents of the files included in a
     manifest. See the class-level docs for a link to a page which
     describes how this is calculated.
  */
  char * R;

  /**
     List of 'T' (tag) cards. Holds (fsl_card_T*) instances.
  */
  fsl_list T;

  /**
     The U (user) card.
  */
  char * U;

  /**
     The W (wiki content) card.
  */
  fsl_b W;

  /**
     This is part of an optimization used when parsing fsl_deck
     instances from source text. For most types of card we re-use
     string values in the raw source text rather than duplicate them,
     and that requires storing the original text (as passed to
     fsl_deck_parse()). This requires that clients never tinker
     directly with values in a fsl_deck, in particular never assign
     over them or assume they know who allocated the memory for that
     bit.
  */
  fsl_b content;

  /**
     To potentially be used for a manifest cache.
  */
  fsl_deck * next;

  /**
     A marker which tells fsl_deck_finalize() whether or not
     fsl_deck_malloc() allocated this instance (in which case
     fsl_deck_finalize() will fsl_free() it) or not (in which case
     it does not fsl_free() it).
  */
  void const * allocStamp;
};

/**
   Initialized-with-defaults fsl_deck structure, intended for copy
   initialization.
*/
FSL_EXPORT const fsl_deck fsl_deck_empty;

/**
   Initialized-with-defaults fsl_deck structure, intended for
   in-struct and const copy initialization.
*/
#define fsl_deck_empty_m {                                  \
    FSL_SATYPE_ANY /*type*/,                                \
    0/*rid*/,                                            \
    NULL/*f*/,                                            \
    {/*A*/ NULL /* name */,                               \
           NULL /* tgt */,                                   \
           NULL /* src */},                                  \
    {/*B*/ NULL /*uuid*/,                                 \
           NULL /*baseline*/},                               \
    NULL /* C */,                                       \
    0.0 /*D*/,                                        \
    {/*E*/ 0.0 /* julian */,                          \
           NULL /* uuid */},                             \
    /*F*/ fsl_card_F_list_empty_m,  \
    0/*G*/,0/*H*/,0/*I*/,                           \
    fsl_list_empty_m /* J */,                       \
    NULL /* K */,                                 \
    NULL /* L */,                                 \
    fsl_list_empty_m /* M */,                     \
    NULL /* N */,                                 \
    fsl_list_empty_m /* P */,                     \
    fsl_list_empty_m /* Q */,                     \
    NULL /* R */,                                 \
    fsl_list_empty_m /* T */,                     \
    NULL /* U */,                                 \
    fsl_b_empty_m /* W */,                   \
    fsl_b_empty_m/*content*/,                \
    NULL/*next*/,                                 \
    NULL/*allocStamp*/                            \
  }


/**
   Allocates a new fsl_deck instance. Returns NULL on allocation
   error. The returned value must eventually be passed to
   fsl_deck_finalize() to free its resources.

   @see fsl_deck_finalize()
   @see fsl_deck_clean()
*/
FSL_EXPORT fsl_deck * fsl_deck_malloc(void);

/**
   Frees all resources belonging to the given deck's members
   (including its parents, recursively), and wipes deck clean of most
   state, but does not free() deck. Is a no-op if deck is NULL. As a
   special case, the (allocStamp, f) members of deck are kept intact.

   @see fsl_deck_finalize()
   @see fsl_deck_malloc()
   @see fsl_deck_clean2()
*/
FSL_EXPORT void fsl_deck_clean(fsl_deck * deck);

/**
   A variant of fsl_deck_clean() which "returns" its content buffer
   for re-use by transferring, after ensuring proper cleanup of its
   internals, its own content buffer's bytes into the given target
   buffer. Decks created "manually" do not have any content
   buffer contents, but those loaded via fsl_deck_load_rid() do. This
   function will fsl_b_swap() the contents of the given buffer
   (if any) with its own buffer, clean up its newly-acquired memory
   (tgt's previous contents, if any), and fsl_b_reuse() the
   output buffer.

   If tgt is NULL, this behaves exactly like fsl_deck_clean().
*/
FSL_EXPORT void fsl_deck_clean2(fsl_deck * deck, fsl_b * tgt);

/**
   Frees all memory owned by deck (see fsl_deck_clean()).  If deck
   was allocated using fsl_deck_malloc() then this function
   fsl_free()'s it, otherwise it does not free it.

   @see fsl_deck_malloc()
   @see fsl_deck_clean()
*/
FSL_EXPORT void fsl_deck_finalize(fsl_deck *deck);

/**
   Sets the A-card for an Attachment (FSL_SATYPE_ATTACHMENT)
   deck. Returns 0 on success.

   Returns FSL_RC_MISUSE if any of (mf, filename, target) are NULL,
   FSL_RC_SYNTAX if !*filename, if !*target, or if uuidSrc is not
   empty and fsl_is_uuid(uuidSrc) returns false.

   Returns FSL_RC_TYPE if mf is not (as determined by its mf->type
   member) of a deck type capable of holding 'A' cards. (Only decks
   of type FSL_SATYPE_ATTACHMENT may hold an 'A' card.) If uuidSrc
   is NULL or starts with a NUL byte then it is ignored, otherwise
   the same restrictions apply to it as to target.

   The target parameter represents the "name" of the
   wiki/ticket/event record to which the attachment applies. For
   wiki pages this is their normal name (e.g. "MyWikiPage"). For
   events and tickets it is their full 40-byte UUID.

   uuidSrc is the UUID of the attachment blob itself. If it is NULL
   or empty then this card indicates that the attachment will be
   "deleted" (insofar as anything is ever deleted in Fossil).
*/
FSL_EXPORT int fsl_deck_A_set( fsl_deck * mf, char const * filename,
                               char const * target,
                               fsl_uuid_cstr uuidSrc);

/**
   Sets or unsets (if uuidBaseline is NULL or empty) the B-card for
   the given manifest to a copy of the given UUID. Returns 0 on
   success, FSL_RC_MISUSE if !mf, FSL_RC_OOM on allocation
   error. Setting this will free any prior values in mf->B, including
   a previously loaded mf->B.baseline.

   If uuidBaseline is not NULL and fsl_is_uuid() returns false,
   FSL_RC_SYNTAX is returned. If it is NULL the current value is
   freed (semantically, though the deck may still own the memory), the
   B card is effectively removed, and 0 is returned.

   Returns FSL_RC_TYPE if mf is not syntactically allowed to have
   this card card (as determined by
   fsl_card_is_legal(mf->type,...)).

   Sidebar: the ability to unset this card is unusual within this API,
   and is a requirement the library-internal delta manifest creation
   process. Most of the card-setting APIs, even when they are
   described as working like this one, do not accept NULL hash values.
*/
FSL_EXPORT int fsl_deck_B_set( fsl_deck * mf, fsl_uuid_cstr uuidBaseline);

/**
   Semantically identical to fsl_deck_B_set() but sets the C-card and
   does not place a practical limit on the comment's length.  comment
   must be the comment text for the change being applied.  If the
   given length is negative, fsl_strlen() is used to determine its
   length.
*/
FSL_EXPORT int fsl_deck_C_set( fsl_deck * mf, char const * comment,
                               fsl_strlen_t cardLen);

/**
   Sets mf's D-card as a Julian Date value. Returns FSL_RC_MISUSE if
   !mf, FSL_RC_RANGE if date is negative, FSL_RC_TYPE if a D-card is
   not valid for the given deck, else 0. Passing a value of 0
   effectively unsets the card.
*/
FSL_EXPORT int fsl_deck_D_set( fsl_deck * mf, double date);

/**
   Sets the E-card in the given deck. date may not be negative -
   use fsl_db_julian_now() or fsl_julian_now() to get a default
   time if needed.  Retursn FSL_RC_MISUSE if !mf or !uuid,
   FSL_RC_RANGE if date is not positive, FSL_RC_RANGE if uuid is
   not a valid UUID string.

   Note that the UUID for an event, unlike most other UUIDs, need
   not be calculated - it may be a random hex string, but it must
   pass the fsl_is_uuid() test. Use fsl_db_random_hex() to generate
   random UUIDs. When editing events, e.g. using the HTML UI, only
   the most recent event with the same UUID is shown. So when
   updating events, be sure to apply the same UUID to the edited
   copies before saving them.
*/
FSL_EXPORT int fsl_deck_E_set( fsl_deck * mf, double date, fsl_uuid_cstr uuid);

/**
   Adds a new F-card to the given deck. The uuid argument is required
   to be NULL or pass the fsl_is_uuid() test. The name must be a
   "simplified path name" (as determined by fsl_is_simple_pathname()),
   or FSL_RC_RANGE is returned. Note that a NULL uuid is only valid
   when constructing a delta manifest, and this routine will return
   FSL_RC_MISUSE and update d->f's error state if uuid is NULL and
   d->B.uuid is also NULL. Returns FSL_RC_RANGE if uuid is not NULL
   and does not pass fsl_is_uuid().

   perms should be one of the fsl_fileperm_e values (0 is the usual
   case).

   priorName must only be non-NULL when renaming a file, and it must
   follow the same naming rules as the name parameter.

   Returns 0 on success.

   @see fsl_deck_F_set()
*/
FSL_EXPORT int fsl_deck_F_add( fsl_deck * d, char const * name,
                               fsl_uuid_cstr uuid,
                               fsl_fileperm_e perm,
                               char const * priorName);

/**
   Works mostly like fsl_deck_F_add() except that:

   1) It enables replacing an existing F-card with a new one matching
   the same name.

   2) It enables removing an F-card by passing a NULL uuid.

   3) It refuses to work on a deck for which d->uuid is not NULL or
   d->rid!=0, returning FSL_RC_MISUSE if either of those apply.

   If d contains no F-card matching the given name (case-sensitivity
   depends on d->f's fsl_cx_is_case_sensitive() value) then:

   - If the 3rd argument is NULL, it returns FSL_RC_NOT_FOUND with
     (effectively) no side effects (aside, perhaps, from sorting d->F
     if needed to perform the search).

   - If the 3rd argument is not NULL then it behaves identically to
     fsl_deck_F_add().

   If a match is found, then:

   - If the 3rd argument is NULL, it removes that entry from the
     F-card list and returns 0.

   - If the 3rd argument is not NULL, the fields of the resulting
     F-card are modified to match the arguments passed to this
     function, copying the values of all C-string arguments. (Sidebar:
     we may need to copy the name, despite already knowing it, because
     of how fsl_deck instances manage F-card memory.)

   In all cases, if the 3rd argument is NULL then the 4th and 5th
   arguments are ignored.

   Returns 0 on success, FSL_RC_OOM if an allocation fails.  See
   fsl_deck_F_add() for other failure modes. On error, d's F-card list
   may be left in an inconsistent state and it must not be used
   further.

   @see fsl_deck_F_add()
   @see fsl_deck_F_set_content()
*/
FSL_EXPORT int fsl_deck_F_set( fsl_deck * d, char const * name,
                               fsl_uuid_cstr uuid,
                               fsl_fileperm_e perm,
                               char const * priorName);
/**
   This variant of fsl_deck_F_set() accepts a buffer of content to
   store as the file's contents. Its hash is derived from that
   content, using fsl_repo_blob_lookup() to hash the given content.
   Thus this routine can replace existing F-cards and save their
   content at the same time. When doing so, it will try to make the
   parent version (if this is a replacement F-card) a delta of the new
   content version (it may refuse to do so for various resources, but
   any heuristics which forbid that will not trigger an error).

   The intended use of this routine is for adding or replacing content
   in a deck which has been prepared using fsl_deck_derive().

   Returns 0 on success, else an error code propagated by
   fsl_deck_F_set(), fsl_repo_blob_lookup(), or some other lower-level
   routine. This routine requires that a transaction is active and
   returns FSL_RC_MISUSE if none is active. For any non-trivial
   error's, d->f's error state will be updated with a description of
   the problem.

   Returns FSL_RC_MISUSE if `d->rid>0` (which indicates that the deck
   has already been saved in the repository). fsl_deck_derive() can be
   used to "extend" a saved deck into a new version before using this API.

   Returns FSL_RC_RANGE if zName is not a valid filename for use as a
   repository entry, as per fsl_is_simple_pathname().

   On error, d->f's error state will be updated with a description of
   the problem.

   TODO: add a fsl_cx-level or fsl_deck-level API for marking content
   saved this way as private. This type of content is intended for use
   cases which do not have a checkout, and thus cannot be processed
   with fsl_checkin_commit() (which includes a flag to mark its
   content as private).

   @see fsl_deck_F_set()
   @see fsl_deck_F_add()
   @see fsl_deck_derive()
*/
FSL_EXPORT int fsl_deck_F_set_content( fsl_deck * d, char const * name,
                                       fsl_b const * src,
                                       fsl_fileperm_e perm,
                                       char const * priorName);

/**
   This routine rewires d such that it becomes the basis for a derived
   version of itself. Requires that d be a loaded from a repository,
   complete with an RID, else FSL_RC_MISUSE is returned.

   In short, this function performs the following:

   - Clears d->P
   - Assigns d->P[0] to the UUID of d->rid
   - Clears d->rid
   - Clears any other members which need to be (re)set by the new
     child/derived version. That includes the following card
     letters: `ACDEGHIJKLMNQRTUW`.
   - If d is a delta manifest it restructures it as a new baseline
     (see below).
   - It specifically keeps d->F intact OR creates a new one (see below).

   Returns 0 on success, FSL_RC_OOM on an allocation error,
   FSL_RC_MISUSE if d->rid<=0 (i.e. the deck has never been saved or
   was not loaded from the db). If d->type is not FSL_SATYPE_CHECKIN,
   FSL_RC_TYPE is returned (supporting other derivable types is
   TODO). On error, d may be left in an inconsistent state and must
   not be used further except to pass it to fsl_deck_finalize().

   The intention of this function is to simplify creation of decks
   which are to be used for creating checkins without requiring a
   checkout.

   To avoid certain corner cases, this function does not allow
   creation of delta manifests. If d has a B-card then it is a delta.
   This function clears its B-card and recreates the F-card list using
   the B-card's F-card list and any F-cards from the current delta. In
   other words, it creates a new baseline manifest.

   The expected workflow for this API is something like:

   - Use fsl_deck_load_rid() to load a deck.
   - Pass that deck to fsl_deck_derive().
   - Update the deck's cards to suit.
   - fsl_deck_save() the deck.

   @todo Extend this to support other inheritable deck types, e.g.
   wiki, forum posts, and technotes.

   @see fsl_deck_F_set_content()
*/
FSL_EXPORT int fsl_deck_derive(fsl_deck * d);

/**
   Callback type for use with fsl_deck_F_foreach() and
   friends. Implementations must return 0 on success, FSL_RC_BREAK
   to abort looping without an error, and any other value on error.
*/
typedef int (*fsl_card_F_visitor_f)(fsl_card_F const * fc,
                                     void * state);

/**
   For each F-card in d, cb(card,visitorState) is called. Returns
   the result of that loop. If cb returns FSL_RC_BREAK, the
   visitation loop stops immediately and this function returns
   0. If cb returns any other non-0 code, looping stops and that
   code is returned immediately.

   This routine calls fsl_deck_F_rewind() to reset the F-card cursor
   and/or load d's baseline manifest (if any). If loading the baseline
   fails, an error code from fsl_deck_baseline_fetch() is returned.

   The F-cards will be visited in the order they are declared in
   d. For loaded-from-a-repo manifests this is always lexical order
   (for delta manifests, consistent across the delta and
   baseline). For hand-created decks which have not yet been
   fsl_deck_unshuffle()'d, the order is unspecified.
*/
FSL_EXPORT int fsl_deck_F_foreach( fsl_deck * d,
                                   fsl_card_F_visitor_f cb,
                                   void * visitorState );

/**
   Fetches the next F-card entry from d. fsl_deck_F_rewind() must
   have be successfully executed one time before calling this, as
   that routine ensures that the baseline is loaded (if needed),
   which is needed for proper iteration over delta manifests.

   This routine always assigns *f to NULL before starting its work, so
   the client can be assured that it will never contain the same value
   as before calling this (unless that value was NULL).

   On success 0 is returned and *f is assigned to the next F-card.
   If *f is NULL when returning 0 then the end of the list has been
   reached (fsl_deck_F_rewind() can be used to re-set it).

   Example usage:

   ```
   int rc;
   fsl_card_F const * fc = NULL;
   rc = fsl_deck_F_rewind(d);
   if(!rc) while( !(rc=fsl_deck_F_next(d, &fc)) && fc ) {...}
   // Or, more simply:
   fsl_deck_F_each(d, fc, rc) {...}
   ```

   The special case of deleted files: files which were deleted in a
   given version are not recorded in baseline manifests but are in
   delta manifests. To avoid inconsistencies, this routine does NOT
   include deleted files in its results, regardless of whether d is a
   baseline or delta. (It used to, but that turned out to be a design
   flaw in that it burdened all callers except for the very few (one?)
   which were (was?) interested in deletions.)

   If d's baseline is itself a delta manifest, only that baseline's
   own F-cards are merged with d's, never those it inherits from its
   own baseline. This is how fossil(1) resolves such a manifest.

   Implementation notes: for baseline manifests this is a very
   fast and simple operation. For delta manifests it gets
   rather complicated.
*/
FSL_EXPORT int fsl_deck_F_next( fsl_deck * d, fsl_card_F const **f );

/**
   A helper macro for looping over fsl_deck_F_next(). Its arguments
   are:

   - DECK: a valid (fsl_deck*)

   - FCARD: a (fsl_card_F const *) to point to the next F-card.

   - RCVAR: the name of a local int-type var to record the result of
     fsl_deck_F_next() and give the client a way to break out early
     without invoking break.

   It loops for so long as 0==RCVAR and fsl_deck_F_next() delivers
   a new card.

   Example:

   ```
    fsl_deck * d = a_fsl_deck_instance;
    fsl_card_F const * fc; // need not be initialized
    int rc = fsl_deck_F_rewind(d);
    fsl_deck_F_each(d, fc, rc){
      rc = doSomething(fc);
    }
    ```
*/
#define fsl_deck_F_each(DECK,FCARD,RCVAR) \
  while( 0==RCVAR && 0==(RCVAR=fsl_deck_F_next(DECK,&(FCARD))) && FCARD )

/**
   Rewinds d's F-card traversal iterator and loads d's baseline
   manifest, if it has one (i.e. if d->B.uuid is not NULL) and it is
   not loaded already (i.e. if d->B.baseline is NULL). Returns 0 on
   success. The only error condition is if loading of the a baseline
   manifest fails, noting that only delta manifests have baselines.

   Results are undefined if d->f is NULL, and that may trigger an
   assert() in debug builds.
*/
FSL_EXPORT int fsl_deck_F_rewind( fsl_deck * d );

/**
   Looks for a file in a manifest or (for a delta manifest) its
   baseline. No normalization of the given filename is performed -
   it is assumed to be relative to the root of the checkout.

   It requires that d->type be FSL_SATYPE_CHECKIN and that d be
   loaded from a stored manifest or have been fsl_deck_unshuffle()'d
   (if called on an under-construction deck). Specifically, this
   routine requires that d->F be sorted properly or results are
   undefined.

   d->f is assumed to be the fsl_cx instance which deck was loaded
   from, which impacts the search process as follows:

   - The search take's d->f's underlying case-insensitive option into
   account. i.e. if case-insensitivy is on then files in any case
   will match.

   - If no match is found in d and is a delta manifest (d->B.uuid
   is set) then d's baseline is lazily loaded (if needed) and
   the search continues there. (Delta manifests are only one level
   deep, so this is not recursive. If the baseline is itself a delta
   manifest, only its own F-cards are searched and a deletion marker
   there counts as no match.)

   Returns NULL if !d, !d->f, or d->type!=FSL_SATYPE_CHECKIN, if no
   entry is found, or if delayed loading of the parent manifest (if
   needed) of a delta manifest fails (in which case d->f's error
   state should hold more information about the problem). A caller
   which must tell "not found" from "could not search" should use
   fsl_deck_F_search2().

   In debug builds this function asserts that d is not NULL.

   Design note: d "should" be const, but search optimizations for
   the typical use case require potentially lazy-loading
   d->B.baseline and updating d->F.
*/
FSL_EXPORT fsl_card_F const * fsl_deck_F_search(fsl_deck *d, const char *zName);

/**
   Works like fsl_deck_F_search() but tells a missing file from a
   search which could not be done: sets *rv to the entry for zName, or
   to NULL if there is none, and returns 0, or returns an error code,
   with d->f's error state set, if the search cannot be done (a delta
   manifest's baseline cannot be loaded). *rv is NULL whenever the
   result is not 0.
*/
FSL_EXPORT int fsl_deck_F_search2(fsl_deck *d, const char *zName,
                                  fsl_card_F const ** rv);

/**
   Given two F-card instances, this function compares their names
   (case-sensitively). Returns a negative value if lhs is
   lexically less than rhs, a positive value if lhs is lexically
   greater than rhs, and 0 if they are lexically equivalent (or are
   the same pointer).


   Though fossil repositories may be case-insensitive, the F-cards use
   a stable casing unless a file is removed and re-added with a
   different case, so this comparison is case-sensitive..

   Results are undefined if either argument is NULL.
*/
FSL_EXPORT int fsl_card_F_compare_name( fsl_card_F const * lhs,
                                        fsl_card_F const * rhs);

/**
   If fc->uuid refers to a blob in f's repository database then that
   content is placed into dest (as per fsl_content_get()) and 0 is
   returned. Returns FSL_RC_NOT_FOUND if fc->uuid is not
   found. Returns FSL_RC_MISUSE if any argument is NULL.  If
   fc->uuid is NULL (indicating that it refers to a file deleted in
   a delta manifest) then FSL_RC_RANGE is returned. Returns
   FSL_RC_NOT_A_REPO if f has no repository opened.

   On any error but FSL_RC_MISUSE (basic argument validation) f's
   error state is updated to describe the error.

   @see fsl_content_get()
*/
FSL_EXPORT int fsl_card_F_content( fsl_cx * f, fsl_card_F const * fc,
                                   fsl_b * dest );

/**
   Sets the 'G' card on a forum-post deck to a copy of the given
   UUID. Returns 0 on success, FSL_RC_SYNTAX if uuid does not pass
   fsl_is_uuid(), FSL_RC_TYPE if mf's type may not have a G-card, or
   FSL_RC_OOM on allocation error.
*/
FSL_EXPORT int fsl_deck_G_set( fsl_deck * mf, fsl_uuid_cstr uuid);
/**
   Sets the 'H' card on a forum-post deck to a copy of the given
   comment. If cardLen is negative then fsl_strlen() is used to
   calculate its length. Returns 0 on success, FSL_RC_SYNTAX if
   comment is not NULL and mf already has an I-card, FSL_RC_TYPE if
   mf's type may not have an H-card, or FSL_RC_OOM on allocation
   error.
 */
FSL_EXPORT int fsl_deck_H_set( fsl_deck * mf, char const * comment, fsl_int_t cardLen);
/**
   Sets the 'I' card on a forum-post deck to a copy of the given
   UUID. Returns 0 on success, FSL_RC_SYNTAX if uuid is not NULL and
   either mf already has an H-card or uuid does not pass
   fsl_is_uuid(), FSL_RC_TYPE if mf's type may not have an I-card,
   or FSL_RC_OOM on allocation error.
*/
FSL_EXPORT int fsl_deck_I_set( fsl_deck * mf, fsl_uuid_cstr uuid);

/**
   Adds a J-card to the given deck, setting/updating the given ticket
   property key to the given value. The key is required but the value
   is optional (may be NULL). If isAppend then the value is appended
   to any existing value, otherwise it replaces any existing value.

   It is currently unclear whether it is legal to include multiple
   J cards for the same key in the same control artifact, in
   particular if their isAppend values differ.

   Returns 0 on success, FSL_RC_MISUSE if !mf or !key, FSL_RC_SYNTAX
   if !*key, FSL_RC_TYPE if mf is of a type for which J cards are
   not legal (see fsl_card_is_legal()), FSL_RC_OOM on allocation
   error.
*/
FSL_EXPORT int fsl_deck_J_add( fsl_deck * mf, bool isAppend,
                               char const * key, char const * value );

/**
   Sets the K-card (ticket ID) on the given deck. If passed NULL, it
   creates a new ticket ID (a 40-digit string of random hex bytes) and
   returns FSL_RC_OOM if allocation of those bytes fails. If uuid is
   not NULL then it must be a 40-byte lower-case hex string, the K-card
   value of the ticket this change is being applied to. Returns
   FSL_RC_SYNTAX if uuid is not NULL and does not pass fsl_is_uuid(),
   and FSL_RC_TYPE if mf's type may not have a K-card.
*/
FSL_EXPORT int fsl_deck_K_set( fsl_deck * mf, fsl_uuid_cstr uuid);

/**
   Semantically identical fsl_deck_B_set() but sets the L-card.
   title must be the wiki page title text of the wiki page this
   change is being applied to. Returns FSL_RC_RANGE if title does not
   pass fsl_wiki_name_is_wellformed(), because fossil(1) rejects an
   artifact with such an L-card.
*/
FSL_EXPORT int fsl_deck_L_set( fsl_deck * mf, char const *title, fsl_int_t len);

/**
   Returns true if the first n bytes of z (all of z, up to its NUL
   terminator, if n is negative) are a well-formed wiki page name, as
   fossil(1) defines it: 1 to 100 bytes long, the first byte greater
   than 0x20, no byte below 0x20, no two spaces in a row, and no
   trailing space.

   The limit is in bytes, not characters. A character outside ASCII
   takes two to four bytes in UTF-8, so a name written in Chinese, for
   example, can have at most 33 characters. fossil(1) rejects an
   artifact whose L-card, or whose A-card wiki target, fails this test.
*/
FSL_EXPORT bool fsl_wiki_name_is_wellformed(char const *z, fsl_int_t n);

/**
   Adds the given UUID as an M-card entry. Returns 0 on success, or:

   FSL_RC_MISUSE if !mf or !uuid

   FSL_RC_TYPE if fsl_deck_check_type(mf,'M') returns false.

   FSL_RC_SYNTAX if !fsl_is_uuid(uuid).

   FSL_RC_OOM if memory allocation fails while adding the entry.
*/
FSL_EXPORT int fsl_deck_M_add( fsl_deck * mf, fsl_uuid_cstr uuid );

/**
   Semantically identical to fsl_deck_B_set() but sets the N card.
   mimeType must be the content mime type for comment text of the
   change being applied.
*/
FSL_EXPORT int fsl_deck_N_set( fsl_deck * mf, char const *mimeType, fsl_int_t len);

/**
   Adds the given UUID as a parent of the given change record. If len
   is less than 0 then fsl_strlen(parentUuid) is used to determine its
   length. Returns FSL_RC_SYNTAX if parentUuid does not pass
   fsl_is_uuid(), which includes an empty string, and FSL_RC_TYPE if
   mf's type may not have a P-card.

   Results are undefined if parentUuid is NULL.

   The first P-card added to a deck MUST be the UUID of its primary
   parent (one which was not involved in a merge operation). All
   others (from merges) are considered "non-primary."

*/
FSL_EXPORT int fsl_deck_P_add( fsl_deck * mf, fsl_uuid_cstr parentUuid);
/**
   A convenience wrapper around fsl_deck_P_add() which resolves the given
   RID to its UUID and passes it on to fsl_deck_P_add(). Returns non-0
   on error.
*/
FSL_EXPORT int fsl_deck_P_add_rid( fsl_deck * mf, fsl_id_t parentRid );

/**
   If d contains a P card with the given index, this returns the RID
   corresponding to the UUID at that index. Returns a negative value
   on error, 0 if there is no entry for that index (the index is out
   of bounds).
*/
FSL_EXPORT fsl_id_t fsl_deck_P_get_id(fsl_deck * d, int index);

/**
   Adds a Q-card record to the given deck. The type argument must
   be negative for a backed-out change, positive for a cherrypicked
   change.  target must be a valid UUID string. If baseline is not
   NULL then it also must be a valid UUID.

   Returns 0 on success, non-0 on error. FSL_RC_MISUSE if !mf or
   !target, FSL_RC_SYNTAX if type is 0 or target/baseline are not
   valid UUID strings (baseline may be NULL).
*/
FSL_EXPORT int fsl_deck_Q_add( fsl_deck * mf, int type,
                               fsl_uuid_cstr target,
                               fsl_uuid_cstr baseline );

/**
   Adds a new T-card (tag) entry to the given deck.

   If uuid is not NULL and fsl_is_uuid(uuid) returns false then
   this function returns FSL_RC_SYNTAX. If uuid is NULL then it is
   assumed to be the UUID of the currently-being-constructed
   artifact in which the tag is contained (which appears as the '*'
   character in generated artifacts).

   Returns 0 on success. Returns FSL_RC_MISUSE if !d or
   !name. Returns FSL_RC_TYPE (and update's d's error state with a
   message) if the T card is not legal for d (see
   fsl_card_is_legal()).  Returns FSL_RC_SYNTAX if !*name, tagType
   is invalid, or if uuid is not NULL and fsl_is_uuid(uuid)
   return false, and for the other tag rules which
   fsl_deck_T_add2() enforces. Returns FSL_RC_OOM if an allocation
   fails.
*/
FSL_EXPORT int fsl_deck_T_add( fsl_deck * d, fsl_tagtype_e tagType,
                               fsl_uuid_cstr uuid, char const * name,
                               char const * value);

/**
   Adds the given tag instance to the given manifest.
   Returns 0 on success, FSL_RC_MISUSE if either argument
   is NULL, FSL_RC_OOM if appending the tag to the list
   fails, FSL_RC_TYPE if mf's type may not have T-cards, and
   FSL_RC_SYNTAX if t's name is empty or entirely hexadecimal, if
   t->uuid is not NULL and does not pass fsl_is_uuid(), if mf is a
   CONTROL artifact and t has no uuid, or if mf is a TECHNOTE and t
   has a uuid or is not an ADD-type tag. On error, mf->f's error
   state describes the problem.

   On success ownership of t is passed to mf. On error ownership is
   not modified.
*/
FSL_EXPORT int fsl_deck_T_add2( fsl_deck * mf, fsl_card_T * t);

/**
   A convenience form of fsl_deck_T_add() which adds two propagating
   tags to the given deck: "branch" with a value of branchName and
   "sym-branchName" with no value.

   Returns 0 on success. Returns FSL_RC_OOM on allocation error and
   FSL_RC_RANGE if branchName is empty or contains any characters with
   ASCII values <=32d. It naively assumes that any characters >=128
   are part of multibyte UTF8 characters.

   ACHTUNG: this does not arrange for canceling the previous branch
   because it doesn't know that branch at this point. To cancel the
   previous branch a cancellation T-card needs to be added to the deck
   named "sym-BRANCHNAME". Historically such tags have had the value
   "Cancelled by branch", but that's not a requirement.
*/
FSL_EXPORT int fsl_deck_branch_set( fsl_deck * d, char const * branchName );

/**
   Calculates the value of d's R-card based on its F-cards and updates
   d->R. It may also, as a side-effect, sort d->F.list lexically (a
   requirement of a R-card calculation).

   Returns 0 on success. Requires that d->f have an opened
   repository db, else FSL_RC_NOT_A_REPO is returned. If d's type is
   not legal for an R-card then FSL_RC_TYPE is returned and d->f's
   error state is updated with a description of the error. If d is of
   type FSL_SATYPE_CHECKIN and has no F-cards then the R-card's value
   is that of the initial MD5 hash state. Various other codes can be
   returned if fetching file content from the db fails.

   Note that this calculation is exceedingly memory-hungry. While
   Fossil originally required R-cards, the cost of calculation
   eventually caused the R-card to be made optional. This API
   allows the client to decide on whether to use them (for more
   (admittedly redundant!) integrity checking) or not (much faster
   but "not strictly historically correct"), but defaults to having
   them enabled for symmetry with fossil(1).

   @see fsl_deck_R_calc2()
*/
FSL_EXPORT int fsl_deck_R_calc(fsl_deck * d);

/**
   A variant of fsl_deck_R_calc() which calculates the given deck's
   R-card but does not assign it to the deck, instead returning it
   via the 2nd argument:

   If *tgt is not NULL when this function is called, it is required to
   point to at least FSL_STRLEN_MD5+1 bytes of memory to which the
   NUL-terminated R-card hash will be written. If *tgt is NULL then
   this function assigns (on success) *tgt to a dynamically-allocated
   R-card hash and transfers ownership of it to the caller (who must
   eventually fsl_free() it). On error, *tgt is not modified.

   Results are undefined if either argument is NULL.

   Returns 0 on success. See fsl_deck_R_calc() for information about
   possible errors, with the addition that FSL_RC_OOM is returned
   if *tgt is NULL and allocating a new *tgt value fails.

   Calculating the R-card necessarily requires that d's F-card list be
   sorted, which this routine does if it seems necessary. The
   calculation also necessarily mutates the deck's F-card-traversal
   cursor, which requires loading the deck's B-card, if it has
   one. Aside from the F-card sorting, and potentially B-card, and the
   cursor resets, this routine does not modify the deck. On success,
   the deck's F-card iteration cursor (and that of d->B, if it's
   loaded) is rewound.
*/
FSL_EXPORT int fsl_deck_R_calc2(fsl_deck *d, char ** tgt);

/**
   Semantically identical fsl_deck_B_set() but sets the U-card.
   userName must be the user who's name should be recorded for
   this change.
*/
FSL_EXPORT int fsl_deck_U_set( fsl_deck * mf, char const *userName);

/**
   Semantically identical fsl_deck_B_set() but sets the W-card.
   content must be the page content of the Wiki page or Event this
   change is being applied to.
*/
FSL_EXPORT int fsl_deck_W_set( fsl_deck * mf, char const *content, fsl_int_t len);

/**
   Must be called to initialize a newly-created/allocated deck
   instance. This function clears out all contents of the d
   parameter except for its (f, type, allocStamp) members, sets its
   (f, type) members, and leaves d->allocStamp intact.

   Note that, prior to calling this, the deck _must_ have been cleanly
   initialized via copying from fsl_deck_empty or (depending on the
   context) fsl_deck_empty_m or results are undefined.
*/
FSL_EXPORT void fsl_deck_init( fsl_cx * cx, fsl_deck * d,
                               fsl_satype_e type );

/**
   Returns true if d contains data for all _required_ cards, as
   determined by the value of d->type, else returns false. It returns
   false if d->type==FSL_SATYPE_ANY, as that is a placeholder value
   intended to be re-set by the deck's user.

   If it returns false, d->f's error state will help a description of
   the problem.

   The library calls this as needed, but clients may, if they want
   to. Note, however, that for FSL_SATYPE_CHECKIN decks it may fail
   if the deck has not been fsl_deck_unshuffle()d yet because the
   R-card gets calculated there (if needed).

   As a special case, d->f is configured to calculate R-cards,
   d->type==FSL_SATYPE_CHECKIN, AND d->R is not set, this will fail
   (with a descriptive error message).

   Another special case: for FSL_SATYPE_CHECKIN decks, if no
   F-cards are in th deck then an R-card is required to avoid a
   potental (admittedly harmless) syntactic ambiguity with
   FSL_SATYPE_CONTROL artifacts. The only legal R-card for a
   checkin with no F-cards has the initial MD5 hash state value
   (defined in the constant FSL_MD5_INITIAL_HASH), and that
   precondition is checked in this routine. fsl_deck_unshuffle()
   recognizes this case and adds the initial-state R-card, so
   clients normally need not concern themselves with this. If d has
   F-cards, whether or not an R-card is required depends on
   whether d->f is configured to require them or not.

   Enough about the R-card. In all other cases not described above,
   R-cards are not required (and they are only ever required on
   FSL_SATYPE_CHECKIN manifests).

   Though fossil(1) does not technically require F-cards in
   FSL_SATYPE_CHECKIN decks, so far none of the Fossil developers
   have found a use for a checkin without F-cards except the
   initial empty checkin. Additionally, a checkin without F-cards
   is potentially syntactically ambiguous (it could be an EVENT or
   ATTACHMENT artifact if it has no F- or R-card). So... this
   library _normally_ requires that CHECKIN decks have at least one
   F-card. This function, however, does not consider F-cards to be
   strictly required.
*/
FSL_EXPORT bool fsl_deck_has_required_cards( fsl_deck const * d );

/**
   Prepares the given deck for output by ensuring that cards
   which need to be sorted are sorted, and it may run some
   last-minute validation checks.

   The cards which get sorted are: F, J, M, Q, T. The P-card list is
   _not_ sorted - the client is responsible for ensuring that the
   primary parent is added to that list first, and after that the
   ordering is largely irrelevant. It is not possible for the library
   to determine a proper order for P-cards, nor to validate that order
   at input-time.

   If calculateRCard is true and fsl_card_is_legal(d,'R') then this
   function calculates the R-card for the deck. The R-card
   calculation is _extremely_ memory-hungry but adds another level
   of integrity checking to Fossil. If d->type is not
   FSL_SATYPE_MANIFEST then calculateRCard is ignored.

   If calculateRCard is true but no F-cards are present AND d->type is
   FSL_SATYPE_CHECKIN then the R-card is set to the initial MD5 hash
   state (the only legal R-card value for an empty F-card list). (This
   is necessary in order to prevent a deck-type ambiguity in one
   corner case.)

   The R-card, if used, must be calculated before
   fsl_deck_output()ing a deck containing F-cards. Clients may
   alternately call fsl_deck_R_calc() to calculate the R card
   separately, but there is little reason to do so. There are rare
   cases where the client can call fsl_deck_R_set()
   legally. Historically speaking the R-card was required when
   F-cards were used, but it was eventually made optional because
   (A) the memory cost and (B) it's part of a 3rd or 4th level of
   integrity-related checks, and is somewhat superfluous.

   @see fsl_deck_output()
   @see fsl_deck_save()
*/
FSL_EXPORT int fsl_deck_unshuffle( fsl_deck * d, bool calculateRCard );

/**
   Renders the given artifact's contents to the given output function
   and calculates any cards which cannot be calculated until the
   contents are complete (namely the R-card and Z-card).

   If both (output, outputState) are NULL then d->f's outputer is
   used.

   The given deck is "logically const" but traversal over F-cards and
   baselines requires non-const operations. To keep this routine from
   requiring an undue amount of pre-call effort on the client's part,
   it also takes care of calling fsl_deck_unshuffle() to ensure that
   all of the deck's cards are in order. (If the deck has no R card,
   but has F-cards, and d->f is configured to generate R-cards, then
   unshuffling will also calculate the R-card.)

   Returns 0 on success, FSL_RC_MISUSE if !d or !d->f or !out. If
   out() returns non-0, output stops and that code is
   returned. outputState is passed as the first argument to out() and
   out() may be called an arbitrary number of times by this routine.

   Returns FSL_RC_SYNTAX if fsl_deck_has_required_cards()
   returns false.

   On errors more serious than argument validation, the deck's
   context's (d->f) error state is updated.

   The exact structure of the ouput depends on the value of
   d->type, and FSL_RC_TYPE is returned if this function cannot
   figure out what to do with the given deck's type.

   @see fsl_deck_unshuffle()
   @see fsl_deck_save()
*/
FSL_EXPORT int fsl_deck_output(fsl_deck * d, fsl_output_f out,
                               void * outputState);

/**
   Emits a JSON representation of the given deck to the given output
   routine. Returns 0 on success, non-0 on error. Any error codes,
   aside from FSL_RC_OOM, will have come from the given callback.

   The output is intended to be compatible with fossil(1)'
   artifact_to_json() (any deviation is a bug). The output is compact,
   not nicely-formatted. It can be sent to sqlite's json_pretty() to
   format it.

   If d->rid<=0, e.g. because it was just processed by
   fsl_deck_parse(), the resulting JSON object will have a "uuid" of
   null. If that property is important, it is up to the caller to set
   it before calling this.
*/
FSL_EXPORT int fsl_deck_to_json(fsl_deck const * d, fsl_output_f fn, void * fState);

/**
   Saves the given deck into f's repository database as new control
   artifact content. If isPrivate is true then the content is
   marked as private, otherwise it is not. Note that isPrivate is a
   suggestion and might be trumped by existing state within f or
   its repository, and such a trumping is not treated as an
   error. e.g. tags are automatically private when they tag private
   content. The deck is saved as private if its first P-card refers
   to private content, and otherwise later P-cards which refer to
   private content are removed from d, as fossil(1) and fsl_checkin_commit()
   do for a checkin's parents: a public child would
   sync and leave other repositories with a phantom for the parent.

   Before saving, the deck is passed through fsl_deck_unshuffle()
   and fsl_deck_output(), which will fail for a variety of
   easy-to-make errors such as the deck missing required cards.
   For unshuffle purposes, the R-card gets calculated if the deck
   has any F-cards AND if the caller has not already set/calculated
   it AND if f's FSL_CX_F_CALC_R_CARD flag is set (it is on by
   default for historical reasons, but this may change at some
   point). If that flag is set and the caller has set the R-card of a
   checkin deck, this calculates the R-card and fails with
   FSL_RC_CONSISTENCY if it differs from the one set.

   Before storing it, this parses the output with fsl_deck_parse(),
   as fossil(1) parses an artifact before crosslinking it, and fails
   with the parser's result code and message if it does not parse.
   It fails with FSL_RC_SYNTAX if the text parses as a different
   artifact type than d->type, and with FSL_RC_RANGE if an F-card has
   a reserved name (see fsl_is_reserved_fn()), which the parser
   drops.

   Returns 0 on success, the usual non-0 suspects on error.

   - If d->rid is positive, it is assumed to refer to a valid
   `blob.rid` and this function returns 0 without side-effects. It
   does _not_ attempt to re-save such a record, as that could very
   possible result in a new hash (and would definitely do so if the
   deck's state had been modified in the slightest bit (literally
   "bit")). It should arguably return FSL_RC_ALREADY_EXISTS for this
   case, but does not do so for historical reasons.

   - PREVIOUSLY (prior to 2021-10-20), we assumed such a deck referred
   to a phantom which we would then save, but that behaviour seems to
   be misguided, as we only ever want to save newly-created decks, not
   decks created from existing content.

   On success, d->rid be set to the new record's RID. It will only be
   set on success because it would otherwise refer to a db record
   which get destroyed when the transaction rolls back.

   After saving, the deck will be cross-linked to update any
   relationships described by the deck.

   The save operation happens within a transaction, of course, and
   on any sort of error, db-side changes are rolled back. Note that
   it _is_ legal to start the transaction before calling this,
   which effectively makes this operation part of that transaction.

   This function will fail with FSL_RC_ACCESS if d is a delta manifest
   (has a B-card) and d->f's forbid-delta-manifests configuration
   option is set to a truthy value. See
   fsl_repo_forbids_delta_manifests().

   Maintenance reminder: this function also does a very small bit of
   artifact-type-specific processing.

   @see fsl_deck_output()
*/
FSL_EXPORT int fsl_deck_save( fsl_deck * d, bool isPrivate );

/**
   Parses src as Control Artifact content and populates d with it.

   d will be cleaned up before parsing if it has any contents,
   retaining its d->f member (which must be set to non-NULL by the
   caller for error-reporting purposes).

   This function _might_ take over the contents of the source
   buffer. If it does, after returning src->mem will be NULL, and all
   other members will be reset to their default state. This function
   only takes over the contents if it decides to implement certain
   memory optimizations. It may fsl_b_reuse() the source buffer
   regardless of how it returns.

   Ownership of src itself is never changed by this function, only the
   ownership of its contents. On success, this function always either
   fsl_b_reuse()s the buffer or takes over ownership of that
   memory and clears src. (Prior to 2026-07-28 it guaranteed to free
   the buffer's memory if it did not take it over. That was a design
   flaw, the correction of which is currently known to only have
   broken a single test app but which _might_ affect other clients.

   In any case, the content of the source buffer is (normally)
   modified by this function because (A) that simplifies tokenization
   greatly, (B) saves us having to make another copy to work on, (C)
   the original implementation did it that way, (D) because in
   historical use the source is normally thrown away after parsing,
   anyway, and (E) in combination with taking ownership of src's
   contents it allows us to optimize away some memory allocations by
   re-using the internal memory of the buffer. This function never
   changes src's size, but it mutilates its contents (injecting NUL
   bytes as token delimiters).

   If d->type is _not_ FSL_SATYPE_ANY when this is called, then
   this function requires that the input to be of that type. We can
   fail relatively quickly in that case, and this can be used to
   save some downstream code some work. Note that the initial type
   for decks created using fsl_deck_malloc() or copy-initialized
   from ::fsl_deck_empty is FSL_SATYPE_ANY, so normally clients do
   not need to set this (unless they want to, as a small
   optimization).

   On success it returns 0 and d will be updated with the state from
   the input artifact and the contents of the source buffer will
   either be cleared or taken over by d. (Ideally, outputing d via
   fsl_deck_output() will produce a lossless copy of the original, but
   timestamp granularity might prevent that.)

   On error, if there is error information to propagate beyond the
   result code then it is stored in d->f. Whether or not such error
   info is propagated depends on the type of error, but anything more
   trivial than invalid arguments will be noted there. On error, the
   source buffer's contents _might_, depending on which phase the
   error happened, be left in place but may have been modified by the
   parsing process.  If the error happens after _certain_ parsing
   steps then the deck will be required to take over the buffer's
   memory in order to keep memory management sane. On error, clients
   should always eventually pass the source buffer to
   fsl_b_clear(). On success its contents are guaranteed to have
   been cleared or or transfered to the destination deck when this
   function returns.

   d might be partially populated on error, so regardless of success
   or failure, the client must eventually pass d to
   fsl_deck_finalize() to free its memory.

   Error result codes include:

   - FSL_RC_SYNTAX on syntax errors, including an empty source
     buffer. Fossil's tried-and-true approach
     to determine "is this an artifact?" is "can it pass through
     fsl_deck_parse()?" This result code simply means that the input
     is, strictly speaking, not a fossil artifact. In some contexts
     this condition must be caught and treated as not-an-error (but
     also not an artifact). The error message names the offending
     card and its line number, in the form "line N: ...", prefixed
     with "artifact [HASH]" if fsl_deck_parse2() was given the
     artifact's rid.

   - FSL_RC_MISUSE if any pointer argument is NULL or d->f is NULL.

   - FSL_RC_CONSISTENCY if validation of a Z-card fails. This is a
     more specialized form of FSL_RC_SYNTAX but indicates that the
     artifact is (or may be) well-formed but has an incorrect hash.
     This check happens relatively early in the parsing process, but
     after this function has uses fsl_might_be_artifact() to do a
     basic sniff-test. In practice, this error "cannot happen" unless
     the source buffer has been manually manipulated. Whether or not
     client-side code wants to treat this as FSL_RC_SYNTAX (i.e. "not
     an artifact but not an error") is up to the client

   - Any number of errors coming from the allocator, database, or
     fsl_deck APIs used here.

   ACHTUNG API CHANGE: prior to 2021-10-20, this routine set d->rid
   (and the now-removed d->uuid) based on the hash of the input buffer
   if a matching record could be found in the db. That proved to be
   a huge performance hit and was removed.

   Maintenance reminder: in keeping with fossil's "if it quacks like
   an artifact, it is an artifact, else it's not" approach to
   determining whether opaque blobs are artifacts, this function
   _must_ continue to return FSL_RC_SYNTAX to indicate that "it
   doesn't quack like an artifact but there's otherwise nothing
   wrong," which downstream code must be able to rely upon as the
   input being a non-artifact. More serious errors, e.g. FSL_RC_OOM,
   are (of course) to be propagated back.

   @see fsl_deck_parse2()
*/
FSL_EXPORT int fsl_deck_parse(fsl_deck * d, fsl_b * src);

/**
    This variant of fsl_deck_parse() works identically to that
    function except for the 3rd argument.

    If you happen to know the _correct_ RID for the deck being parsed,
    pass it as the rid argument, else pass 0. A negative value will
    result in a FSL_RC_RANGE error. This value is (or may be) only
    used as an optimization in this function and/or downstream
    functions. Passing a positive value will cause d->f to do a cache
    lookup which may avoid it having to parse the deck at all.
*/
FSL_EXPORT int fsl_deck_parse2(fsl_deck * d, fsl_b * src, fsl_id_t rid);

/**
   If *pz points to *pn bytes beginning with a PGP or SSH clearsign
   envelope, as fossil(1) writes when its clearsign setting is on,
   this advances *pz past the envelope's header and blank line, sets
   *pn to the length of the enveloped text up to and including the
   newline before the signature block, and returns true. The result
   is the artifact text as it was before signing. If *pz does not
   begin with such an envelope, neither pointer is changed and false
   is returned. Neither pointer may be NULL.

   The artifact parsers call this before parsing, so a signed artifact
   parses like an unsigned one and its hash is that of the signed
   text. This is public so that clients which verify signatures can
   separate the envelope from the text.

   @see fsl_cx_signer()
*/
FSL_EXPORT bool fsl_signature_strip(char const **pz, fsl_size_t *pn);

/**
   Callback type for signing artifacts. fsl_deck_save() calls it with
   the complete artifact text, Z-card included, after that text is
   generated and before it is hashed and stored, as fossil(1)'s
   clearsign() is called. d is the deck being saved and state is the
   fsl_signer::state it was installed with.

   The callback may leave manifest as it is, to decline (e.g. for
   artifact types it does not sign), or replace its contents with the
   same text inside a PGP or SSH clearsign envelope, one which
   fsl_signature_strip() turns back into the text it was given.
   fsl_deck_save() checks that and fails with FSL_RC_CONSISTENCY if
   the result does not strip back to the original text. The artifact's
   hash is then that of the signed text, as in fossil(1).

   It must return 0 on success, including when it declines, or a
   non-0 fsl_rc_e code to fail the save.

   It is never called for private artifacts, which fossil(1) does not
   sign either.
*/
typedef int (*fsl_deck_sign_f)(fsl_deck const * d, fsl_b * manifest,
                               void * state);

/**
   Holds a signing callback and its state. See fsl_cx_signer().
*/
struct fsl_signer {
  /** The callback, or NULL for no signing. */
  fsl_deck_sign_f callback;
  /** Opaque state passed to the callback. */
  void * state;
};
typedef struct fsl_signer fsl_signer;
/** Initialized-with-defaults fsl_signer instance, intended for
    const-copy initialization. */
#define fsl_signer_empty_m {NULL, NULL}
/** Initialized-with-defaults fsl_signer instance, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_signer fsl_signer_empty;

/**
   Installs a bitwise copy of *newSigner as f's artifact signer, which
   fsl_deck_save() calls as described for fsl_deck_sign_f. If
   newSigner is NULL, f's signer is cleared and artifacts are saved
   unsigned. If prevSigner is not NULL, the previous signer is copied
   to it first, so that a caller can restore it later.

   libfossil never signs on its own: the library has no opinion on
   gpg, ssh-keygen or keys, so an application which wants fossil(1)'s
   clearsign behavior installs a callback which runs its pgp-command
   equivalent.

   @see fsl_cx_signer_get()
   @see fsl_signature_strip()
*/
FSL_EXPORT void fsl_cx_signer(fsl_cx * const f, fsl_signer const * newSigner,
                              fsl_signer * prevSigner);

/**
   Stores a bitwise copy of f's current signer into *dest.

   @see fsl_cx_signer()
*/
FSL_EXPORT void fsl_cx_signer_get(fsl_cx const * const f, fsl_signer * dest);

/**
   Quickly determines whether the content held by the given buffer
   "might" be a structural artifact. It performs a fast sanity check
   for prominent features which can be checked either in O(1) or very
   short O(N) time (with a fixed N). If it returns false then the
   given buffer's contents are, with 100% certainty, _not_ a
   structural artifact. If it returns true then they _might_ be, but
   being 100% certain requires passing the contents to
   fsl_deck_parse() to fully parse them.
*/
FSL_EXPORT bool fsl_might_be_artifact(fsl_b const * src);

/**
   Loads the content from given rid and tries to parse it as a
   Fossil artifact. If rid==0 the current checkout (if opened) is
   used. (Trivia: there can never be a checkout with rid==0 but
   rid==0 is sometimes valid for an new/empty repo devoid of
   commits.) If type==FSL_SATYPE_ANY then it will allow any type of
   control artifact, else it returns FSL_RC_TYPE if the loaded
   artifact is of the wrong type.

   Returns 0 on success. Results are undefined if f or d are NULL. The
   potential error result codes include, but are not limited to:

   - FSL_RC_OOM

   - FSL_RC_RANGE if rid is negative or is 0 and no checkout is
     opened.

   - FSL_RC_TYPE if `type` is not `FSL_SATYPE_ANY` and the loaded
     result is of any artifact type other than `type`.

   - Any code from fsl_deck_parse(), whose error message is then
     prefixed with "artifact [HASH]".

   d must be properly initialized, either copy-initialized from
   fsl_deck_empty or populated by the library's API. This function
   will (re)initialize it and may leave it partially populated on
   error. The caller must eventually pass it to fsl_deck_finalize()
   resp. fsl_deck_clean() regardless of success or error. This
   function "could" clean it up on error, but leaving it partially
   populated makes debugging easier.

   f's error state may be updated on error (for anything more
   serious than basic argument validation errors).

   On success this function sets d->rid to rid.

   @see fsl_deck_load_sym()
*/
FSL_EXPORT int fsl_deck_load_rid( fsl_cx * f, fsl_deck * d,
                                  fsl_id_t rid, fsl_satype_e type );

/**
   A convenience form of fsl_deck_load_rid() which uses
   fsl_sym_to_rid() to convert symbolicName into an artifact RID.  See
   fsl_deck_load_rid() for the symantics of the first, second, and
   fourth arguments, as well as the return value. See fsl_sym_to_rid()
   for the allowable values of symbolicName.

   @see fsl_deck_load_rid()
*/
FSL_EXPORT int fsl_deck_load_sym( fsl_cx * f, fsl_deck * d,
                                  char const * symbolicName,
                                  fsl_satype_e type );

/**
   Loads the baseline manifest specified in d->B.uuid, if any and if
   necessary. Returns 0 on success. If d->B.baseline is already loaded
   or d->B.uuid is NULL (in which case there is no baseline), it
   returns 0 and has no side effects.

   Neither argument may be NULL and d must be a fully-populated
   object, complete with a proper d->rid, before calling this.

   On success 0 is returned. If d->B.baseline is NULL then
   it means that d has no baseline manifest (and d->B.uuid will be NULL
   in that case). If d->B.baseline is not NULL then it is owned by
   d and will be cleaned up when d is cleaned/finalized.

   Error codes include, but are not limited to:

   - FSL_RC_MISUSE if !d->f.

   - FSL_RC_NOT_A_REPO if d->f has no opened repo db.

   - FSL_RC_PHANTOM if the baseline is not yet in the repository
   (it is recorded as a phantom, and d is recorded as its orphan if
   d->rid>0).

   - FSL_RC_SHUNNED if the baseline is shunned.

   On non-trivial errors d->f's error state will be updated to hold
   a description of the problem.

   Some misuses trigger assertions in debug builds.
*/
FSL_EXPORT int fsl_deck_baseline_fetch( fsl_deck * d );

/**
   A callback interface for manifest crosslinking, so that we can farm
   out the updating of the event table (and similar bookkeeping) as
   manifests are crosslinked. Each callback registered via
   fsl_xlink_listener() will be called at the end of the so-called
   crosslinking process, which is run every time an artifact is
   processed for d->f's repository database, passed the deck being
   crosslinked and the client-provided state which was registered with
   fsl_xlink_listener(). Note that the deck object itself holds other
   state useful for crosslinking, like the blob.rid value of the deck
   and its fsl_cx instance.

   If an implementation is only interested in a specific type of
   artifact, it must check d->type and return 0 if it's an
   "uninteresting" type.

   Implementations must return 0 on success or some other fsl_rc_e
   value on error. Returning non-0 causes the database transaction
   for the crosslinking operation to roll back, effectively
   cancelling whatever pending operation triggered the
   crosslink. If any callback fails, processing stops immediately -
   no other callbacks are executed.

   Implementations which want to report more info than an integer
   should call fsl_cx_err_set() to set d->f's error state, as that
   will be propagated up to the code which initiated the failed
   crosslink.

   ACHTUNG and WARNING: the fsl_deck parameter "really should" be
   const, but certain operations on a deck are necessarily non-const
   operations. That includes, but may not be limited to:

   - Iterating over F-cards, which requires calling
     fsl_deck_F_rewind() before doing so. Traversal of F-cards
     internally uses a necessarily-mutable cursor.

   - Loading a checkin's baseline (required for F-card iteration and
     performed automatically by fsl_deck_F_rewind()).

   Aside from such iteration-related mutable state, it is STRICTLY
   ILLEGAL to modify a deck's artifact-related state while it is
   undergoing crosslinking. Violating that will lead to undefined
   results.

   Potential TODO: add some client-opaque state to decks so that they
   can be flagged as "being crosslinked" and fail mutation operations
   such as card adders/setters.

   @see fsl_xlink_listener()
*/
typedef int (*fsl_deck_xlink_f)(fsl_deck * d, void * state);

/**
    A type for holding state for artifact crosslinking callbacks.
*/
struct fsl_xlinker {
  /** Human-readable name of the crosslinker, noting that each
      registered crosslinker must have a unique name. Registering a
      crosslinker with the same name as an existing one replaces that
      one.
  */
  char const * name;
  /** Callback function. */
  fsl_deck_xlink_f f;
  /** State for this->f's last argument. */
  void * state;
};
typedef struct fsl_xlinker fsl_xlinker;

/** Empty-initialized fsl_xlinker struct, intended for const-copy
    intialization. */
#define fsl_xlinker_empty_m {NULL,NULL,NULL}

/** Empty-initialized fsl_xlinker struct, intended for copy intialization. */
extern const fsl_xlinker fsl_xlinker_empty;

/**
    A list of fsl_xlinker instances.
*/
struct fsl_xlinker_list {
  /** Number of used items in this->list. */
  fsl_size_t used;
  /** Number of slots allocated in this->list. */
  fsl_size_t capacity;
  /** Array of this->used elements. */
  fsl_xlinker * list;
};
typedef struct fsl_xlinker_list fsl_xlinker_list;

/** Empty-initializes fsl_xlinker_list struct, intended for
    const-copy intialization. */
#define fsl_xlinker_list_empty_m {0,0,NULL}

/** Empty-initializes fsl_xlinker_list struct, intended for copy intialization. */
extern const fsl_xlinker_list fsl_xlinker_list_empty;

/**
    Searches f's crosslink callbacks for an entry with the given
    name and returns that entry, or NULL if no match is found.  The
    returned object is owned by f.
*/
fsl_xlinker * fsl_xlinker_by_name( fsl_cx * f, char const * name );

/**
   Adds the given function as a "crosslink callback" for the given
   Fossil context. The callback is called at the end of a successful
   "artifact crosslink" operation and provides a way for the client to
   perform their own work based on the app having crosslinked an
   artifact. Crosslinking happens when artifacts are saved or upon a
   rebuild operation.

   This function returns 0 on success, non-0 on error. Behaviour is
   undefined if any of the first 3 arguments are NULL.

   Crosslink callbacks are called at the end of the core crosslink
   steps, in the order they are registered, with the caveat that if a
   listener is overwritten by another with the same name, the new
   entry retains the older one's position in the list. The library may
   register its own before the client gets a chance to.

   If _any_ crosslinking callback fails (returns non-0) then the
   _whole_ crosslinking fails and is rolled back (which may very
   well include pending tags/commits/whatever getting rolled back).

   The state parameter has no meaning for this function, but is
   passed on as the final argument to cb(). If not NULL, cbState
   "may" be required to outlive f, depending on cbState's exact
   client-side internal semantics/use, as there is currently no API
   to remove registered crosslink listeners.

   The name must be non-NULL/empty. If a listener is registered with a
   duplicate name then the first one is replaced. This function does
   not copy the name bytes - they are assumed to be static or
   otherwise to live at least as long as f. The name may be
   arbitrarily long, but must have a terminating NUL byte. It is
   recommended that clients choose a namespace/prefix to apply to the
   names they register. The library reserves the prefix "fsl/" for
   its own use, and will happily overwrite client-registered entries
   with the same names. The name string need not be stable across
   application sessions and maybe be a randomly-generated string.

   Caveat: some obscure artifact crosslinking steps do not happen
   unless crosslinking takes place in the context of a
   fsl__crosslink_begin() and fsl__crosslink_end()
   session. Thus, at the time client-side crosslinker callbacks are
   called, certain crosslinking state in the database may still be
   pending. It is as yet unclear how best to resolve that minor
   discrepancy, or whether it even needs resolving.

   As a rule, it is important that crosslink handler checks the
   deck->type field of the deck they are passed, and return 0, without
   side effects, if the type is not specifically handled by that
   handler. Every crosslink handler is passed every crosslinked
   artifact, but it's rare for crosslink handlers to handle more than
   one type of artifact, except perhaps for purposes of notifying a
   user that some progress is being made.

   Default (overrideable) crosslink handlers:

   The library internally splits crosslinking of artifacts into two
   parts: the main one (which clients cannot modify) handles the
   database-level linking of relational state implied by a given
   artifact. The secondary one adds an entry to the "event" table,
   which is where Fossil's timeline lives. The crosslinkers for the
   timeline updates may be overridden by clients by registering
   a crosslink listener with the following names:

   - Attachment artifacts: "fsl/attachment/timeline"

   - Checkin artifacts: "fsl/checkin/timeline"

   - Control artifacts: "fsl/control/timeline"

   - Forum post artifacts: "fsl/forumpost/timeline"

   - Technote artifacts: "fsl/technote/timeline"

   - Wiki artifacts: "fsl/wiki/timeline"

   A context registers listeners under those names when it
   initializes, and clients may override them at any point after that.

   Sidebar: due to how tickets are crosslinked (_after_ the general
   crosslinking phase is actually finished and requiring state which
   other crosslinkers do not), it is not currently possible to
   override the ticket crosslink handler. Thus the core ticket
   crosslinker will always run, and update the [event] table, but a
   custom crosslinker may overwrite the resulting [event] table
   entries (in particular, the comment). Determining whether/how
   ticket crosslinking can be restructured to be consistent with the
   other types is on the TODO list.

   Caveat: updating the timeline requires a bit of knowledge about the
   Fossil DB schema and/or conventions. Updates for certain types,
   e.g. attachment/control/forum post, is somewhat more involved and
   updating the timeline for wiki comments requires observing a "quirk
   of conventions" for labeling such comments, such that they will
   appear properly when the main fossil app renders them. That said,
   the only tricky parts of those updates involve generating the
   "correct" comment text. So long as the non-comment parts are
   updated properly (that part is easy to do), fossil can function
   with it.  The timeline comment text/links are soley for human
   consumption. Fossil makes much use of the "event" table internally,
   however, so the rest of that table must be properly populated.

   Because of that caveat, clients may, rather than overriding the
   defaults, install their own crosslink listners which ammend the
   state applied by the default ones. e.g. add a listener which
   watches for checkin updates and replace the default-installed
   comment with one suitable for your application, leaving the rest of
   the db state in place. At its simplest, that looks more or less
   like the following code (inside a fsl_deck_xlink_f() callback):

   ```
   int rc = fsl_db_exec(fsl_cx_db_repo(deck->f),
                        "UPDATE event SET comment=%Q "
                        "WHERE objid=%"FSL_ID_T_PFMT,
                        "the new comment.", deck->rid);
   ```
*/
FSL_EXPORT int fsl_xlink_listener( fsl_cx * f, char const * name,
                                   fsl_deck_xlink_f cb, void * cbState );


/**
   For the given blob.rid value, returns the blob.size value of
   that record via *rv. Returns 0 or higher on success, -1 if a
   phantom record is found, -2 if no entry is found, or a smaller
   negative value on error (dig around the sources to decode them -
   this is not expected to fail unless the system is undergoing a
   catastrophe).

   @see fsl_content_raw()
   @see fsl_content_get()
   @see fsl_content_size_v2()
*/
FSL_EXPORT fsl_int_t fsl_content_size( fsl_cx * f, fsl_id_t blobRid );

/**
   Given a blob RID, this function extracts its size from the
   `blob.rid` db field. On success, returns 0 and sets *pOut to
   the new size. Negative sizes mean the blob is a "phantom."

   On error it returns non-0 and updates f's error state.

   @see fsl_content_size()
*/
FSL_EXPORT int fsl_content_size_v2(fsl_cx * f, fsl_id_t rid,
                                   fsl_int_t *pOut);

/**
   For the given blob.rid value, fetches the content field of that
   record and overwrites tgt's contents with it (reusing tgt's
   memory if it has any and if it can). The blob's contents are
   uncompressed if they were stored in compressed form. This
   extracts a raw blob and does not apply any deltas - use
   fsl_content_get() to fully expand a delta-stored blob.

   By and large, client-side code will want fsl_content_get() over
   this functino.

   Returns 0 on success. On error tgt might be partially updated,
   e.g. it might be populated with compressed data instead of
   uncompressed. On error tgt's contents should be recycled
   (e.g. fsl_b_reuse()) or discarded (e.g. fsl_b_clear()) by
   the client. Returns FSL_RC_RANGE if blobRid<=0, FSL_RC_NOT_A_REPO
   if f has no repo opened, FSL_RC_OOM on allocation error, or
   potentially any number of other codes via the db layer.

   Results are undefined if any pointer argument is NULL.

   @see fsl_content_get()
   @see fsl_content_size()
*/
FSL_EXPORT int fsl_content_raw( fsl_cx * f, fsl_id_t blobRid,
                                 fsl_b * tgt );

/** @deprecated

    Older (deprecated) name of fsl_content_raw().
*/
#define fsl_content_blob fsl_content_raw

/**
   Functionally similar to fsl_content_raw() but does a lot of
   work to ensure that the returned blob is expanded from its
   deltas, if any. The tgt buffer's memory, if any, will be
   replaced/reused if it has any.

   Returns 0 on success. There are no less than 50 potental
   different errors, so we won't bother to list them all. On error
   tgt might be partially populated. The basic error cases are:

   - FSL_RC_MISUSE if !tgt or !f.

   - FSL_RC_RANGE if rid<=0 or if an infinite loop is discovered in
   the repo delta table links (that is a consistency check to avoid
   an infinite loop - that condition "cannot happen" because the
   verify-before-commit logic catches that error case).

   - FSL_RC_NOT_A_REPO if f has no repo db opened.

   - FSL_RC_NOT_FOUND if the given rid is not in the repo db.

   - FSL_RC_OOM if an allocation fails.


   @see fsl_content_raw()
   @see fsl_content_size()
*/
FSL_EXPORT int fsl_content_get( fsl_cx * f, fsl_id_t blobRid,
                                fsl_b * tgt );

/**
   Uses fsl_sym_to_rid() to convert sym to a record ID, then
   passes that to fsl_content_get(). Returns 0 on success.
*/
FSL_EXPORT int fsl_content_get_sym( fsl_cx * f, char const * sym,
                                    fsl_b * tgt );

/**
   Returns true if the given rid is marked as PRIVATE in f's current
   repository. Returns false (0) on error or if the content is not
   marked as private.
*/
FSL_EXPORT bool fsl_content_is_private(fsl_cx * f, fsl_id_t rid);

/**
   Marks the given rid public, if it was previously marked as
   private, and adds it to the unsent and unclustered tables so that
   the next sync offers it to peers. It is a no-op if rid is not
   private. Returns 0 on success, non-0 on error.

   This affects only the given rid. Unlike fossil(1)'s publish
   command, it does not also publish the files and tags of a
   check-in.

   Note that it is not possible to make public content private.
*/
FSL_EXPORT int fsl_content_make_public(fsl_cx * f, fsl_id_t rid);

/**
   Generic callback interface for visiting decks. The interface
   does not generically require that d survive after this call
   returns.

   Implementations must return 0 on success, non-0 on error. Some
   APIs using this interface may specify that FSL_RC_BREAK can be
   used to stop iteration over a loop without signaling an error.
   In such cases the APIs will translate FSL_RC_BREAK to 0 for
   result purposes, but will stop looping over whatever it is they
   are looping over.

   Note that the passed-in deck "should" be const but is not because
   iterating over a deck's F-cards requires non-const state.
*/
typedef int (*fsl_deck_visitor_f)( fsl_cx * f, fsl_deck * d,
                                   void * state );

/**
   For each unique wiki page name in f's repostory, this calls
   cb(), passing it the manifest of the most recent version of that
   page. The callback should return 0 on success, FSL_RC_BREAK to
   stop looping without an error, or any other non-0 code
   (preferably a value from fsl_rc_e) on error.

   The 3rd parameter has no meaning for this function but it is
   passed on as-is to the callback.

   ACHTUNG: the deck passed to the callback is transient and will
   be cleaned up after the callback has returned, so the callback
   must not hold a pointer to it or its contents.

   @see fsl_wiki_load_latest()
   @see fsl_wiki_latest_rid()
   @see fsl_wiki_names_get()
   @see fsl_wiki_page_exists()
*/
FSL_EXPORT int fsl_wiki_foreach_page( fsl_cx * f, fsl_deck_visitor_f cb, void * state );

/**
   Fetches the most recent RID for the given wiki page name and
   assigns *newId (if it is not NULL) to that value. Returns 0 on
   success, FSL_RC_MISUSE if !f or !pageName, FSL_RC_RANGE if
   !*pageName, and a host of other potential db-side errors
   indicating more serious problems. If no such page is found,
   newRid is not modified and this function returns 0 (as opposed
   to FSL_RC_NOT_FOUND) because that simplifies usage (so far).

   On error *newRid is not modified.

   @see fsl_wiki_load_latest()
   @see fsl_wiki_foreach_page()
   @see fsl_wiki_names_get()
   @see fsl_wiki_page_exists()
*/
FSL_EXPORT int fsl_wiki_latest_rid( fsl_cx * f, char const * pageName, fsl_id_t * newRid );

/**
   Loads the artifact for the most recent version of the given wiki page,
   populating d with its contents.

   Returns 0 on success. On error d might be partially populated,
   so it needs to be passed to fsl_deck_finalize() regardless of
   whether this function succeeds or fails.

   Returns FSL_RC_NOT_FOUND if no page with that name is found, and
   f's error message then contains the page name. Returns
   FSL_RC_MISUSE if any argument is NULL and FSL_RC_RANGE if
   !*pageName.

   @see fsl_wiki_latest_rid()
   @see fsl_wiki_names_get()
   @see fsl_wiki_page_exists()
*/
FSL_EXPORT int fsl_wiki_load_latest( fsl_cx * f, char const * pageName, fsl_deck * d );

/**
   Returns true (non-0) if f's repo database contains a page with the
   given name, else false.

   @see fsl_wiki_load_latest()
   @see fsl_wiki_latest_rid()
   @see fsl_wiki_names_get()
   @see fsl_wiki_names_get()
*/
FSL_EXPORT bool fsl_wiki_page_exists(fsl_cx * f, char const * pageName);

/**
   A helper type for use with fsl_wiki_save(), intended primarily
   to help client-side code readability somewhat.
*/
enum fsl_wiki_save_mode_t {
/**
   Indicates that fsl_wiki_save() must only allow the creation of
   a new page, and must fail if such an entry already exists.
*/
FSL_WIKI_SAVE_MODE_CREATE = -1,
/**
   Indicates that fsl_wiki_save() must only allow the update of an
   existing page, and will not create a brand new page.
*/
FSL_WIKI_SAVE_MODE_UPDATE = 0,
/**
   Indicates that fsl_wiki_save() must allow both the update and
   creation of pages. Trivia: "upsert" is a common SQL slang
   abbreviation for "update or insert."
*/
FSL_WIKI_SAVE_MODE_UPSERT = 1
};

typedef enum fsl_wiki_save_mode_t fsl_wiki_save_mode_t;

/**
   Saves wiki content to f's repository db.

   pageName is the name of the page to update or create.

   b contains the content for the page.

   userName specifies the user name to apply to the change. If NULL
   or empty then fsl_cx_user_get() or fsl_user_name_guess() are
   used (in that order) to determine the name.

   mimeType specifies the mime type for the content (may be NULL).
   Mime type names supported directly by fossil(1) include (as of
   this writing): text/x-fossil-wiki, text/x-markdown,
   text/plain

   Whether or not this function is allowed to create a new page is
   determined by creationPolicy. If it is
   FSL_WIKI_SAVE_MODE_UPDATE, this function will fail with
   FSL_RC_NOT_FOUND if no page with the given name already exists.
   If it is FSL_WIKI_SAVE_MODE_CREATE and a previous version _does_
   exist, it fails with FSL_RC_ALREADY_EXISTS. If it is
   FSL_WIKI_SAVE_MODE_UPSERT then both the save-exiting and
   create-new cases are allowed. In summary:

   - use FSL_WIKI_SAVE_MODE_UPDATE to allow updates to existing pages
   but disallow creation of new pages,

   - use FSL_WIKI_SAVE_MODE_CREATE to allow creating of new pages
   but not of updating an existing page.

   - FSL_WIKI_SAVE_MODE_UPSERT allows both updating and creating
   a new page on demand.

   Returns 0 on success, or any number fsl_rc_e codes on error. On
   error no content changes are saved, and any transaction is
   rolled back or a rollback is scheduled if this function is
   called while a transaction is active.


   Potential TODO: add an optional (fsl_id_t*) output parameter
   which gets set to the new record's RID.

   @see fsl_wiki_page_exists()
   @see fsl_wiki_names_get()
*/
FSL_EXPORT int fsl_wiki_save(fsl_cx * f, char const * pageName,
                  fsl_b const * b, char const * userName,
                  char const * mimeType, fsl_wiki_save_mode_t creationPolicy );

/**
   Fetches the list of all wiki page names in f's current repo db
   and appends them as new (char *) strings to tgt. On error tgt
   might be partially populated (but this will only happen on an
   OOM or serious system-level error).

   It is up to the caller free the entries added to the list. Some
   of the possibilities include:

   ```
   fsl_list_visit( list, 0, fsl_list_v_fsl_free, NULL );
   fsl_list_reserve(list,0);
   // Or:
   fsl_list_clear(list, fsl_list_v_fsl_free, NULL);
   // Or simply:
   fsl_list_visit_free( list, 1 );
   ```

*/
FSL_EXPORT int fsl_wiki_names_get( fsl_cx * f, fsl_list * tgt );

/**
   F-cards each represent one file entry in a Manifest Artifact (i.e.,
   a checkin version).

   All of the non-const pointers in this class are owned by the
   respective instance of the class OR by the fsl_deck which created
   it, and must neither be modified nor freed except via the
   appropriate APIs.
*/
struct fsl_card_F {
  /**
     UUID of the underlying blob record for the file. NULL for
     removed entries.
  */
  fsl_uuid_str uuid;
  /**
     Name of the file.
  */
  char * name;
  /**
     Previous name if the file was renamed, else NULL.
  */
  char * priorName;
  /**
     File permissions. Fossil only supports one "permission" per
     file, and it does not necessarily map to a real
     filesystem-level permission.

     @see fsl_fileperm_e
  */
  fsl_fileperm_e perm;

  /**
     An internal optimization. Do not mess with this.  When this is
     true, the various string members of this struct are not owned
     by this struct, but by the deck which created this struct. This
     is used when loading decks from storage - the strings are
     pointed to the original content data, rather than strdup()'d
     copies of it. fsl_card_F_clean() will DTRT and delete the
     strings (or not).
  */
  bool deckOwnsStrings;
};
/**
   Empty-initialized fsl_card_F structure, intended for use in
   initialization when embedding fsl_card_F in another struct or
   copy-initializing a const struct.
*/
#define fsl_card_F_empty_m {   \
  NULL/*uuid*/,                \
  NULL/*name*/,                \
  NULL/*priorName*/,           \
  0/*perm*/,                   \
  false/*deckOwnsStrings*/     \
}
FSL_EXPORT const fsl_card_F fsl_card_F_empty;

/**
   Represents a J card in a Ticket Control Artifact.
*/
struct fsl_card_J {
  /**
     If true, the new value should be appended to any existing one
     with the same key, else it will replace any old one.
  */
  bool append;
  /**
     For internal use only.
  */
  unsigned char flags;
  /**
     The ticket field to update. The bytes are owned by this object.
  */
  char * field;
  /**
     The value for the field. The bytes are owned by this object.
  */
  char * value;
};
/** Empty-initialized fsl_card_J struct. */
#define fsl_card_J_empty_m {false,0,NULL, NULL}
/** Empty-initialized fsl_card_J struct. */
FSL_EXPORT const fsl_card_J fsl_card_J_empty;

/**
   Represents a tag in a Manifest or Control Artifact.
*/
struct fsl_card_T {
  /**
     The type of tag.
  */
  fsl_tagtype_e type;
  /**
     UUID of the artifact this tag is tagging. When applying a tag to
     a new checkin, this value is left empty (=NULL) and gets replaced
     by a '*' in the resulting control artifact.
  */
  fsl_uuid_str uuid;
  /**
     The tag's name. The bytes are owned by this object.
  */
  char * name;
  /**
     The tag's value. May be NULL/empty. The bytes are owned by
     this object.
  */
  char * value;
};
/** Defaults-initialized fsl_card_T instance. */
#define fsl_card_T_empty_m {FSL_TAGTYPE_INVALID, NULL, NULL,NULL}
/** Defaults-initialized fsl_card_T instance. */
FSL_EXPORT const fsl_card_T fsl_card_T_empty;

/**
   Types of cherrypick merges.
*/
enum fsl_cherrypick_type_e {
/** Sentinel value. */
FSL_CHERRYPICK_INVALID = 0,
/** Indicates a cherrypick merge. */
FSL_CHERRYPICK_ADD = 1,
/** Indicates a cherrypick backout. */
FSL_CHERRYPICK_BACKOUT = -1
};
typedef enum fsl_cherrypick_type_e fsl_cherrypick_type_e;

/**
   Represents a Q card in a Manifest or Control Artifact.
*/
struct fsl_card_Q {
  /** 0==invalid, negative==backed out, positive=cherrypicked. */
  fsl_cherrypick_type_e type;
  /**
     UUID of the target of the cherrypick. The bytes are owned by
     this object.
  */
  fsl_uuid_str target;
  /**
     UUID of the baseline for the cherrypick. The bytes are owned by
     this object.
  */
  fsl_uuid_str baseline;
};
/** Empty-initialized fsl_card_Q struct. */
#define fsl_card_Q_empty_m {FSL_CHERRYPICK_INVALID, NULL, NULL}
/** Empty-initialized fsl_card_Q struct. */
FSL_EXPORT const fsl_card_Q fsl_card_Q_empty;

/**
   Allocates a new J-card record instance

   On success it returns a new record which must eventually be
   passed to fsl_card_J_free() to free its resources. On
   error (invalid arguments or allocation error) it returns NULL.
   field may not be NULL or empty but value may be either.

   These records are immutable - the API provides no way to change
   them once they are instantiated.
*/
FSL_EXPORT fsl_card_J * fsl_card_J_malloc(bool isAppend,
                                          char const * field,
                                          char const * value);
/**
   Frees a J-card record created by fsl_card_J_malloc().
   Is a no-op if cp is NULL.
*/
FSL_EXPORT void fsl_card_J_free( fsl_card_J * cp );

/**
   Allocates a new fsl_card_T instance. If any of the pointer
   parameters are non-NULL, their values are assumed to be
   NUL-terminated strings, which this function copies.  Returns NULL
   on allocation error.  The returned value must eventually be passed
   to fsl_card_T_clean() or fsl_card_T_free() to free its resources.

   If uuid is not NULL and fsl_is_uuid(uuid) returns false then
   this function returns NULL. If it is NULL and gets assigned
   later, it must conform to fsl_is_uuid()'s rules or downstream
   results are undefined.

   @see fsl_card_T_free()
   @see fsl_card_T_clean()
   @see fsl_deck_T_add()
*/
FSL_EXPORT fsl_card_T * fsl_card_T_malloc(fsl_tagtype_e tagType,
                                          fsl_uuid_cstr uuid,
                                          char const * name,
                                          char const * value);
/**
   If t is not NULL, calls fsl_card_T_clean(t) and then passes t to
   fsl_free().

   @see fsl_card_T_clean()
*/
FSL_EXPORT void fsl_card_T_free(fsl_card_T *t);

/**
   Frees up any memory owned by t and clears out t's state,
   but does not free t.

   @see fsl_card_T_free()
*/
FSL_EXPORT void fsl_card_T_clean(fsl_card_T *t);

/**
   Allocates a new cherrypick record instance. The type argument must
   be one of FSL_CHERRYPICK_ADD or FSL_CHERRYPICK_BACKOUT.  target
   must be a valid UUID string. If baseline is not NULL then it also
   must be a valid UUID.

   On success it returns a new record which must eventually be
   passed to fsl_card_Q_free() to free its resources. On
   error (invalid arguments or allocation error) it returns NULL.

   These records are immutable - the API provides no way to change
   them once they are instantiated.
*/
FSL_EXPORT fsl_card_Q * fsl_card_Q_malloc(fsl_cherrypick_type_e type,
                                          fsl_uuid_cstr target,
                                          fsl_uuid_cstr baseline);
/**
   Frees a cherrypick record created by fsl_card_Q_malloc().
   Is a no-op if cp is NULL.
*/
FSL_EXPORT void fsl_card_Q_free( fsl_card_Q * cp );

/**
   Returns true if f is not NULL and f has an opened repo
   which contains a checkin with the given rid, else it returns
   false.

   As a special case, if rid==0 then this only returns true
   if the repository currently has no content in the blob
   table.
*/
FSL_EXPORT bool fsl_rid_is_a_checkin(fsl_cx * f, fsl_id_t rid);

/**
   Fetches the list of all directory names for a given checkin record
   id or (if rid is negative) the whole repo over all of its combined
   history. Each name entry in the list is appended to tgt. The
   results are reduced to unique names only and are sorted
   lexically. If addSlash is true then each entry will include a
   trailing slash character, else it will not. The list does not
   include an entry for the top-most directory.

   If rid is less than 0 then the directory list across _all_
   versions is returned. If it is 0 then the current checkout's RID
   is used (if a checkout is opened, otherwise a usage error is
   triggered). If it is positive then only directories for the
   given checkin RID are returned. If rid is specified, it is
   assumed to be the record ID of a commit (manifest) record, and
   it is impossible to distinguish between the results "invalid
   rid" and "empty directory list" (which is a legal result).

   On success it returns 0 and tgt will have a number of (char *)
   entries appended to it equal to the number of subdirectories in
   the repo (possibly 0).

   Returns non-0 on error, FSL_RC_MISUSE if !tgt, FSL_RC_NOT_A_REPO if
   f has no opened repository. On other errors error tgt might have
   been partially populated and the list contents should not be
   considered valid/complete. Results are undefined if f is NULL.

   Ownership of the returned strings is transfered to the caller,
   who must eventually free each one using
   fsl_free(). fsl_list_visit_free() is the simplest way to free
   them all at once.
*/
FSL_EXPORT int fsl_repo_dir_names( fsl_cx * f, fsl_id_t rid,
                                   fsl_list * tgt, bool addSlash );


/**
   ZIPs up a copy of the contents of a specific version from f's
   opened repository db. sym is the symbolic name for the checkin
   to ZIP. filename is the name of the ZIP file to output the
   result to. See fsl_zip_writer for details and caveats of this
   library's ZIP creation. If vRootDir is not NULL and not empty
   then each file injected into the ZIP gets that directory
   prepended to its name.

   If progressVisitor is not NULL then it is called once just before
   each file is processed, passed the F-card for the file about to be
   zipped and the progressState parameter. If it returns non-0,
   ZIPping is cancelled and that result code is returned. This is
   intended primarily for providing feedback on the zip progress, but
   could also be used to cancel the operation between files.

   As of 2021-09-05 this routine automatically adds the files
   (manifest, manifest.uuid, manifest.tags) to the zip file,
   regardless of repository-level settings regarding those
   pseudo-files (see fsl_ckout_manifest_write()). As there are no
   F-cards associated with those non-files, the progressVisitor is not
   called for those.

   Returns 0 on success. On error returns non-0 and, except for
   FSL_RC_OOM and for FSL_RC_MISUSE when f is NULL, f's error state
   describes the failure, naming the check-in and, where one is
   involved, the file or the output file name.

   A symlink is stored as fossil(1) stores it: an entry with Unix
   mode 0120755 whose content is the link target.

   @see fsl_zip_writer
   @see fsl_card_F_visitor_f()
*/
FSL_EXPORT int fsl_repo_zip_sym_to_filename( fsl_cx * f, char const * sym,
                                             char const * vRootDir,
                                             char const * fileName,
                                             fsl_card_F_visitor_f progressVisitor,
                                             void * progressState);


/**
   Callback state for use with fsl_repo_extract_f() implementations
   to stream a given version of a repository's files, one file at a
   time, to a client. Instances are never created by client code,
   only by fsl_repo_extract() and its delegates, which pass them to
   client-provided fsl_repo_extract_f() functions.
*/
struct fsl_repo_extract_state {
  /**
     The associated Fossil context.
  */
  fsl_cx * f;
  /**
     RID of the checkin version for this file. For a given call to
     fsl_repo_extract(), this number will be the same across all
     calls to the callback function.
  */
  fsl_id_t checkinRid;
  /**
     File-level blob.rid for fc. Can be used with, e.g.,
     fsl_mtime_of_manifest_file().
  */
  fsl_id_t fileRid;
  /**
     Client state passed to fsl_repo_extract(). Its interpretation
     is callback-implementation-dependent.
  */
  void * callbackState;
  /**
     The F-card being iterated over. This holds the repo-level
     metadata associated with the file, other than its RID, which is
     available via this->fileRid.

     Deleted files are NOT reported via the extraction process
     because reporting them accurately is trickier and more
     expensive than it could be. Thus this member's uuid field
     will always be non-NULL.

     Certain operations which use this class, e.g. fsl_repo_ckout()
     and fsl_ckout_update(), will temporarily synthesize an F-card to
     represent the state of a file update, in which case this object's
     contents might not 100% reflect any given db-side state. e.g.
     fsl_ckout_update() synthesizes an F-card which reflects the
     current state of a file after applying an update operation to it.
     In such cases, the fCard->uuid may refer to a repository-side
     file even though the hash of the on-disk file contents may differ
     because of, e.g., a merge.
  */
  fsl_card_F const * fCard;

  /**
     If the fsl_repo_extract_opt object which was used to initiate the
     current extraction has the extractContent member set to false,
     this will be a NULL pointer. If it's true, this member points to
     a transient buffer which holds the full, undelta'd/uncompressed
     content of fc's file record. The content bytes are owned by
     fsl_repo_extract() and are invalidated as soon as this callback
     returns, so the callback must copy/consume them immediately if
     needed.
  */
  fsl_b const * content;

  /**
     These counters can be used by an extraction callback to calculate
     a progress percentage.
  */
  struct {
    /** The current file number, starting at 1. */
    uint32_t fileNumber;
    /** Total number of files to extract. */
    uint32_t fileCount;
  } count;
};
typedef struct fsl_repo_extract_state fsl_repo_extract_state;

/**
   Initialized-with-defaults fsl_repo_extract_state instance, intended
   for const-copy initialization.
*/
#define fsl_repo_extract_state_empty_m {\
  NULL/*f*/, 0/*checkinRid*/, 0/*fileRid*/, \
  NULL/*state*/, NULL/*fCard*/, NULL/*content*/,    \
  {/*count*/0,0} \
}
/**
   Initialized-with-defaults fsl_repo_extract_state instance,
   intended for non-const copy initialization.
*/
FSL_EXPORT const fsl_repo_extract_state fsl_repo_extract_state_empty;

/**
   A callback type for use with fsl_repo_extract(). See
   fsl_repo_extract_state for the meanings of xstate's various
   members.  The xstate memory must be considered invalidated
   immediately after this function returns, thus implementations
   must copy or consume anything they need from xstate before
   returning.

   Implementations must return 0 on success. As a special case, if
   FSL_RC_BREAK is returned then fsl_repo_extract() will stop
   looping over files but will report it as success (by returning
   0). Any other code causes extraction looping to stop and is
   returned as-is to the caller of fsl_repo_extract().

   When returning an error, the client may use fsl_cx_err_set() to
   populate state->f with a useful error message which will
   propagate back up through the call stack.

   @see fsl_repo_extract()
*/
typedef int (*fsl_repo_extract_f)( fsl_repo_extract_state const * xstate );

/**
   Options for use with fsl_repo_extract().
*/
struct fsl_repo_extract_opt {
  /**
     The version of the repostitory to check out. This must be
     the blob.rid of a checkin artifact.
  */
  fsl_id_t checkinRid;
  /**
     The callback to call for each extracted file in the checkin.
     May not be NULL.
  */
  fsl_repo_extract_f callback;
  /**
     Optional state pointer to pass to the callback when extracting.
     Its interpretation is client-dependent.
  */
  void * callbackState;
  /**
     If true, the fsl_repo_extract_state::content pointer passed to
     the callback will be non-NULL and will contain the content of the
     file. If false, that pointer will be NULL. Such extraction is a
     relatively costly operation, so should only be enabled when
     necessary. Some uses cases can delay this decision until the
     callback and only fetch the content for cases which need it.
  */
  bool extractContent;
};

typedef struct fsl_repo_extract_opt fsl_repo_extract_opt;
/**
   Initialized-with-defaults fsl_repo_extract_opt instance, intended
   for intializing via const-copy initialization.
*/
#define fsl_repo_extract_opt_empty_m \
  {0/*checkinRid*/,NULL/*callback*/, \
   NULL/*callbackState*/,false/*extractContent*/}
/**
   Initialized-with-defaults fsl_repo_extract_opt instance,
   intended for intializing new non-const instances.
*/
FSL_EXPORT const fsl_repo_extract_opt fsl_repo_extract_opt_empty;

/**
   Iterates over the file content of a single checkin in a repository,
   sending the appropriate version of each file's contents to a
   client-specified callback.

   For each file in the given checkin, opt->callback() is passed a
   fsl_repo_extract_state instance containing enough information to,
   e.g., unpack the contents to a working directory, add it to a
   compressed archive, or send it to some other destination.

   Returns 0 on success, non-0 on error. It will fail if f has no
   opened repository db.

   If the callback returns any code other than 0 or FSL_RC_BREAK,
   looping over the list of files ends and this function returns
   that value. FSL_RC_BREAK causes looping to stop but 0 is
   returned.

   See fsl_repo_extract_f() for more details about the semantics of
   the callback. See fsl_repo_extract_opt for the documentation of the
   various options.

   Fossil's internal metadata format guarantees that files will be
   passed to the callback in "lexical order" (as defined by fossil's
   manifest format definition). i.e. the files will be passed in
   case-sensitive, alphabetical order, noting that upper-case letters
   sort before lower-case ones.

   Sidebar: this function makes a bitwise copy of the 2nd argument
   before starting its work, just in case the caller gets the crazy
   idea to modify it from the extraction callback. Whether or not
   there are valid/interesting uses for such modification remains to
   be seen. If any are found, this copy behavior may change.
*/
FSL_EXPORT int fsl_repo_extract( fsl_cx * f,
                                 fsl_repo_extract_opt const * opt );

/**
   Equivalent to fsl_tag_an_rid() except that it takes a symbolic
   artifact name in place of an artifact ID as the third
   argumemnt.

   This function passes symToTag to fsl_sym_to_rid(), and on
   success passes the rest of the parameters as-is to
   fsl_tag_an_rid(). See that function the semantics of the other
   arguments and the return value, as well as a description of the
   side effects.
*/
FSL_EXPORT int fsl_tag_sym( fsl_cx * f, fsl_tagtype_e tagType,
                 char const * symToTag, char const * tagName,
                 char const * tagValue, char const * userName,
                 double mtime, fsl_id_t * newId );

/**
   Adds a control record to f's repository that either creates or
   cancels a tag.

   artifactRidToTag is the RID of the record to be tagged.

   tagType is the type (add, cancel, or propagate) of tag.

   tagName is the name of the tag. Must not be NULL/empty.

   tagValue is the optional value for the tag. May be NULL.

   userName is the user's name to apply to the artifact. May not be
   empty/NULL. Use fsl_user_name_guess() to try to figure out a
   proper user name based on the environment. See also:
   fsl_cx_user_get(), but note that the application must first
   use fsl_cx_user_set() to set a context's user name.

   mtime is the Julian Day timestamp for the new artifact. Pass a
   value <=0 to use the current time.

   If newId is not NULL then on success the rid of the new tag control
   artifact is assigned to *newId.

   Returns 0 on success and has about a million and thirteen
   possible error conditions. On success a new artifact record is
   written to the db, its RID being written into newId as described
   above.

   If the artifact being tagged is private, the new tag is also
   marked as private.

*/
FSL_EXPORT int fsl_tag_an_rid( fsl_cx * f, fsl_tagtype_e tagType,
                 fsl_id_t artifactRidToTag, char const * tagName,
                 char const * tagValue, char const * userName,
                 double mtime, fsl_id_t * newId );

/**
    Searches for a repo.tag entry given name in the given context's
    repository db. If found, it returns the record's id. If no record
    is found and create is true then a tag is created and its entry id
    is returned. Returns 0 if it finds no entry, a negative value on
    error, in which case f's error state is updated.
*/
FSL_EXPORT fsl_id_t fsl_tag_id( fsl_cx * f, char const * tag, bool create );

/**
   Returns true if blob rid in f's repository db has an active tag
   with the given id, else returns false.

   Returns false on any sort of error, as well, in which case f's
   error state is updated.
*/
FSL_EXPORT bool fsl_rid_has_tag_id(fsl_cx * f, fsl_id_t rid, fsl_id_t tagId);

/**
   A thin proxy around fsl_rid_has_tag_id() which uses fsl_tag_id() to
   look up the given tag's ID.
*/
FSL_EXPORT bool fsl_rid_has_tag(fsl_cx * f, fsl_id_t rid, char const *zTag);

/**
   Returns true if the checkin with the given rid is a leaf, false if
   not. Returns false if f has no repo db opened, the query fails
   (likely indicating that it is not a repository db), or just about
   any other conceivable non-success case.

   A leaf, by the way, is a commit which has no children in the same
   branch.

   Sidebar: this function calculates whether the RID is a leaf, as
   opposed to checking the "static" (pre-calculated) list of leaves in
   the [leaf] table.
*/
FSL_EXPORT bool fsl_rid_is_leaf(fsl_cx * f, fsl_id_t rid);

/**
   Counts the number of primary non-branch children for the given
   check-in.

   A primary child is one where the parent is the primary parent, not
   a merge parent.  A "leaf" is a node that has zero children of any
   kind. This routine counts only primary children.

   A non-branch child is one which is on the same branch as the parent.

   Returns a negative value on error.
*/
FSL_EXPORT fsl_int_t fsl_count_nonbranch_children(fsl_cx * f,
                                                  fsl_id_t rid);

/**
   Looks for the delta table record where rid==deltaRid, and
   returns that record's srcid via *rv. Returns 0 on success, non-0
   on error. If no record is found, *rv is set to 0 and 0 is
   returned (as opposed to FSL_RC_NOT_FOUND) because that generally
   simplifies the error checking.

   Results are undefined if any pointer argument is NULL.
*/
FSL_EXPORT int fsl_delta_r2s( fsl_cx * f, fsl_id_t deltaRid,
                              fsl_id_t * rv );
/* Deprecated name for fsl_delta_r2s. */
#define fsl_delta_src_id fsl_delta_r2s

/**
   The counterpart of fsl_delta_r2s(): for a given delta.srcid, return
   the associated delta.rid via *rv.  See that function for more
   details.
*/
FSL_EXPORT int fsl_delta_s2r( fsl_cx * f, fsl_id_t deltaRid,
                              fsl_id_t * rv );


/**
   Return true if the given artifact ID should is listed in f's
   shun table or if zUuid is an SHA1 has and f's hash policy
   is set to FSL_HPOLICY_SHUN_SHA1.

   This function has no way to report errors except via the f
   object. If there is an error in this call, f's error state will be
   updated.

   Reminder to self: there is no fsl_is_shunned_rid() because rids
   refer to blob table records and the blob table is not supposed to
   contain shunned artifacts.
*/
FSL_EXPORT bool fsl_is_shunned_uuid(fsl_cx * f, fsl_uuid_cstr zUuid);
/* Old name for fsl_is_shunned_uuid(). */
#define fsl_uuid_is_shunned fsl_is_shunned_uuid


/**
   Compute the "mtime" of the file given whose blob.rid is "fid"
   that is part of check-in "vid".  The mtime will be the mtime on
   vid or some ancestor of vid where fid first appears. Note that
   fossil does not track the "real" mtimes of files, it only
   computes reasonable estimates for those files based on the
   timestamps of their most recent checkin in the ancestry of vid.

   If fid is 0 or less then the D-card time of the artifact with the
   blob.rid == vid is written to pMTime (this is a much less expensive
   operation, by the way).  In this particular case (A) vid may refer
   to any artifact type which has a D-card and (B) FSL_RC_NOT_FOUND is
   returned if vid is not a valid artifact RID.

   On success, if pMTime is not null then the result is written to
   *pMTime.

   Returns 0 on success, non-0 on error. Returns FSL_RC_NOT_FOUND
   if fid is not found in vid.

   This routine is much more efficient if used to answer several
   queries in a row for the same manifest (the vid parameter). It
   is least efficient when it is passed intermixed manifest IDs,
   e.g. (1, 3, 1, 4, 1,...). This is a side-effect of the caching
   used in the computation of ancestors for a given vid.
*/
FSL_EXPORT int fsl_mtime_of_manifest_file(fsl_cx * f, fsl_id_t vid, fsl_id_t fid,
                                          fsl_time_t * pMTime);

/**
   A convenience form of fsl_mtime_of_manifest_file() which looks up
   fc's RID based on its UUID. vid must be the RID of the checkin
   version fc originates from. See fsl_mtime_of_manifest_file() for
   full details - this function simply calculates the 3rd argument
   for that one.
*/
FSL_EXPORT int fsl_mtime_of_F_card(fsl_cx * f, fsl_id_t vid, fsl_card_F const * fc,
                                   fsl_time_t * pMTime);

/**
   Ensures that the given list has capacity for at least n entries. If
   n is 0, li->list and the F-cards it contains are freed and the list
   is zeroed out. Else if the capacity is already at least n, this is
   a no-op. Else li->list is expanded to hold at least n
   elements. Returns 0 on success, FSL_RC_OOM on allocation error.
 */
FSL_EXPORT int fsl_card_F_list_reserve( fsl_card_F_list * li, uint32_t n );

/**
   Frees all memory owned by li and the F-cards it contains. Does not
   free the li pointer.
*/
FSL_EXPORT void fsl_card_F_list_finalize( fsl_card_F_list * li );

/**
   Iterates over all artifacts in f's current repository of the given
   type, passing each one to the given callback. If the callback
   returns non-0, iteration stops and that code is propagated back to
   the caller _unless_ the code is FSL_RC_BREAK, which means to stop
   iteration and return 0.

   The following artifact types are currently supported by this
   operation:

   FSL_SATYPE_CHECKIN, FSL_SATYPE_CONTROL, FSL_SATYPE_WIKI,
   FSL_SATYPE_TICKET, FSL_SATYPE_TECHNOTE, FSL_SATYPE_FORUMPOST

   (CLUSTER and ATTACHMENT are missing only because they're not(?)
   readily findable without parsing every blob in the blob
   table.)

   The decks are iterated over an an unspecified order except for:

   - WIKI and TECHNOTE entries are visited from newest to oldest.

   - TICKET entries are visited from oldest to newest to accommodate
     reconstructing their aggregate state in the callback.

   Each deck is finalized immediately after the callback returns, so
   the callback must not hold any pointers to the deck or its
   contents.

   Returns 0 on success or any number of error codes from lower levels,
   including, but not limited to:

   - FSL_RC_OOM on allocation error
   - FSL_RC_NOT_A_REPO if f has no repository opened.
   - FSL_RC_TYPE if the 2nd argument is invalid or if its type is
     not supported (e.g. FSL_SATYPE_CLUSTER).
   - FSL_RC_MISUSE if the 3rd argument is NULL.

*/
FSL_EXPORT int fsl_deck_foreach(fsl_cx * f, fsl_satype_e type,
                                fsl_deck_visitor_f visitor,
                                void * visitorState);

/**
   Holds options for use with fsl_branch_create().
*/
struct fsl_branch_opt {
  /**
     The checkin RID from which the branch should originate.
  */
  fsl_id_t basisRid;
  /**
     The name of the branch. May not be NULL or empty.
  */
  char const * name;
  /**
     User name for the branch. If NULL, fsl_cx_user_get() will
     be used.
  */
  char const * user;
  /**
     Optional comment (may be NULL). If NULL or empty, a default
     comment is generated (because fossil requires a non-empty
     comment string).
  */
  char const * comment;
  /**
     Optional background color for the fossil(1) HTML timeline
     view.  Must be in \#RRGGBB format, but this API does not
     validate it as such.

     Use of an explicit bgColor is discouraged. This capability
     pre-dates fossil's ability to theme the website via CSS and
     manually-selected colors often visually collide with various
     skins.
  */
  char const * bgColor;
  /**
     The julian time of the branch. If 0 or less, default is the
     current time.
  */
  double mtime;
  /**
     If true, the branch will be marked as private.
  */
  bool isPrivate;
};
typedef struct fsl_branch_opt fsl_branch_opt;
#define fsl_branch_opt_empty_m {                \
    0/*basisRid*/, NULL/*name*/,                \
      NULL/*user*/, NULL/*comment*/,            \
      NULL/*bgColor*/,                          \
      0.0/*mtime*/, 0/*isPrivate*/              \
      }
FSL_EXPORT const fsl_branch_opt fsl_branch_opt_empty;

/**
   Creates a new branch in f's repository. The 2nd paramter holds
   the options describing the branch. The 3rd parameter may be
   NULL, but if it is not then on success the RID of the new
   manifest is assigned to *newRid.

   In Fossil branches are implemented as tags. The branch name
   provided by the client will cause the creation of a tag with
   name name plus a "sym-" prefix to be created (if needed).
   "sym-" denotes that it is a "symbolic tag" (fossil's term for
   "symbolic name applying to one or more checkins,"
   i.e. branches).

   Creating a branch cancels all other branch tags which the new
   branch would normally inherit.

   Returns 0 on success, non-0 on error.

   This function errors with FSL_RC_ALREADY_EXISTS if an open leaf
   with the given branch name already exists. TODO (2026-10-28) is to
   add a fsl_branch_opt flag which tells it to forego that check
   (introduced in [17c0719deb] 2026-10-03).
*/
FSL_EXPORT int fsl_branch_create(fsl_cx * f, fsl_branch_opt const * opt,
                                 fsl_id_t * newRid );

/**
   Checks f's repo db for a setting named 'main-branch'. If
   found. *zOut is set to that string. The mememory is owned by f and
   is retained for later calls to this function, but it may be
   invalidated by certain fsl APIs (namely this very function, if
   forceReload is true, and fsl_cx_finalize()). If forceReload is true
   then any cached value is freed and re-loaded.

   Returns 0 on success. On error, *zOut is not modified. If no such
   setting is found, "trunk" is used.
 */
FSL_EXPORT int fsl_branch_main(fsl_cx *f, char const **zOut, bool forceReload);

/**
   Tries to determine the [filename.fnid] value for the given
   filename.  Returns a positive value if it finds one, 0 if it
   finds none, and some unspecified negative value(s) for any sort
   of error. filename must be a normalized, relative filename (as it
   is recorded by a repo).
*/
FSL_EXPORT fsl_id_t fsl_repo_filename_fnid( fsl_cx * f, char const * filename );

/**
   Resolves client-provided symbol as an artifact's db record ID.
   f must have an opened repository db, and some symbols can only
   be looked up if it has an opened checkout (see the list below).

   Returns 0 and sets *rv to the id if it finds an unambiguous
   match.

   Returns FSL_RC_MISUSE if !sym, !*sym, or !rv.

   Returns FSL_RC_NOT_A_REPO if f has no opened repository.

   Returns FSL_RC_AMBIGUOUS if sym is a partial UUID which matches
   multiple full UUIDs.

   Returns FSL_RC_NOT_FOUND if it cannot find anything.

   Symbols supported by this function:

   - SHA1/3 hash
   - SHA1/3 hash prefix of at least 4 characters
   - Symbolic Name, e.g. branch name
   - "tag:" + symbolic name
   - Date or date-time
   - "date:" + Date or date-time
   - symbolic-name ":" date-time
   - "tip" means the most recent checkin, regardless of its branch
   - "rid:###" resolves to the hash of blob.rid ### if that RID is in
     the database

   The following additional forms are available in local checkouts:

   - "current"
   - "prev" or "previous"
   - "next"

   The following prefix may be applied to the above to modify how
   they are resolved:

   - "root:" prefix resolves to the checkin of the parent branch from
   which the record's branch divered. i.e. the version from which it
   was branched. In the trunk this will always resolve to the first
   checkin.

   - "start:" prefix resolves to the first checkin of the branch to
   which the given checkin belongs. This differs from "root:" by a
   single checkin: the "root:" point is the parent checkin of the
   "start:" point.

   - "merge-in:" TODO - document this once its implications are
   understood.

   If type is not FSL_SATYPE_ANY then it will only match artifacts of
   the specified type. In order to resolve arbitrary UUIDs, e.g.
   those of arbitrary blob content, type needs to be FSL_SATYPE_ANY.
*/
FSL_EXPORT int fsl_sym_to_rid( fsl_cx * f, char const * sym,
                               fsl_satype_e type, fsl_id_t * rv );

/**
   Similar to fsl_sym_to_rid() but on success it returns a UUID string
   by assigning it to *rv (if rv is not NULL). If rid is not NULL then
   on success the db record ID corresponding to the returned UUID is
   assigned to *rid. The caller must eventually free the returned
   string memory by passing it to fsl_free(). Returns 0 if it finds a
   match and one of any number of possible result codes on error, most
   notably FSL_RC_NOT_FOUND if no match is found.
*/
FSL_EXPORT int fsl_sym_to_uuid( fsl_cx * f, char const * sym,
                                fsl_satype_e type, fsl_uuid_str * rv,
                                fsl_id_t * rid );


/**
   Searches f's repo database for the a blob with the given uuid
   (any unique UUID prefix). On success a positive record ID is
   returned. On error one of several unspecified negative values is
   returned. If no uuid match is found 0 is returned.

   Error cases include: uuid is NULL or empty, uuid does not appear
   to be a full or partial UUID (or is too long), uuid is ambiguous
   (try providing a longer one). f's error state is updated for all
   error cases.

   This implementation is more efficient when given a full, valid UUID
   (one for which fsl_is_uuid() returns true).
*/
FSL_EXPORT fsl_id_t fsl_uuid_to_rid( fsl_cx * f, char const * uuid );

/**
   The opposite of fsl_uuid_to_rid(), this returns the UUID string
   of the given blob record ID. Ownership of the string is passed
   to the caller and it must eventually be freed using
   fsl_free(). Returns NULL on error (invalid arguments or f has no
   repo opened) or if no blob record is found. If no record is
   found, f's error state is updated with an explanation of the
   problem.
*/
FSL_EXPORT fsl_uuid_str fsl_rid_to_uuid(fsl_cx * f, fsl_id_t rid);

/**
   Works like fsl_rid_to_uuid() but assigns the UUID to the given
   buffer, re-using its memory, if any. Returns 0 on success,
   FSL_RC_MISUSE if rid is not positive, FSL_RC_OOM on allocation
   error, and FSL_RC_NOT_FOUND if no blob entry matching the given rid
   is found.
*/
FSL_EXPORT int fsl_rid_to_uuid2(fsl_cx * f, fsl_id_t rid, fsl_b *uuid);

/**
   This works identically to fsl_rid_to_uuid() except that it will
   only resolve to a UUID if an artifact matching the given type has
   that UUID. If no entry is found, f's error state gets updated
   with a description of the problem.

   This can be used to distinguish artifact UUIDs from file blob
   content UUIDs by passing the type FSL_SATYPE_ANY. A non-artifact
   blob will return NULL in that case, but any artifact type will
   match (assuming rid is valid).
*/
FSL_EXPORT fsl_uuid_str fsl_rid_to_artifact_uuid(fsl_cx * f, fsl_id_t rid,
                                                 fsl_satype_e type);
/**
   Returns the raw SQL code for a Fossil global config database.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_config(void);

/**
   Returns the raw SQL code for the "static" parts of a Fossil
   repository database. These are the parts which are immutable
   (for the most part) between Fossil versions. They change _very_
   rarely.

   The SQL names the repository's schema with the placeholder
   {{dbname.repo}}, and tables in REFERENCES and index ON clauses with
   {{bare.repo.NAME}}, so it is meant to be passed as the format string
   of fsl_db_exec_multi() or fsl_cx_exec_multi(), which expand them for
   the database or context. Passed as data (e.g. via "%s"), or to plain
   sqlite3, it does not run as is. It does not set the repository db's
   PRAGMA application_id (252006673), which libfossil sets
   separately for a repository db file of its own.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_repo1(void);

/**
   Returns the raw SQL code for the "transient" parts of a Fossil
   repository database - any parts which can be calculated via data
   held in the primary "static" schemas. These parts are
   occassionally recreated, e.g. via a 'rebuild' of a repository.

   Uses the {{dbname.repo}} and {{bare.repo.NAME}} placeholders: see
   fsl_schema_repo1() for how to run it.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_repo2(void);

/**
   Returns the raw SQL code for a Fossil checkout database.

   Uses the {{dbname.ckout}} and {{bare.ckout.NAME}} placeholders: see
   fsl_schema_repo1() for how to run it. It does not set the checkout
   db's PRAGMA application_id (252006674, 'FSLC'), which libfossil
   sets separately for a checkout db file of its own.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_ckout(void);

/**
   Returns the raw SQL code for a Fossil checkout db's
   _default_ core ticket-related tables.

   TODO: add optional (fsl_size_t*) to return the length.

   @see fsl_cx_schema_ticket()
*/
FSL_EXPORT char const * fsl_schema_ticket(void);

/**
   Returns the raw SQL code for the "forum" parts of a Fossil
   repository database.

   Uses the {{dbname.repo}} and {{bare.repo.NAME}} placeholders: see
   fsl_schema_repo1() for how to run it.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_forum(void);

/**
   If f's opened repository has a non-empty config entry named
   'ticket-table', this returns its text via appending it to
   pOut. If no entry is found, fsl_schema_ticket() is appended to
   pOut.

   Returns 0 on success. On error the contents of pOut must not be
   considered valid but pOut might be partially populated.
*/
FSL_EXPORT int fsl_cx_schema_ticket(fsl_cx * f, fsl_b * pOut);

/**
   Returns the raw SQL code for Fossil ticket reports schemas.
   This gets installed as needed into repository databases.

   Uses the {{dbname.repo}} placeholder: see
   fsl_schema_repo1() for how to run it.

   TODO: add optional (fsl_size_t*) to return the length.
*/
FSL_EXPORT char const * fsl_schema_ticket_reports(void);

/**
   This is a wrapper around fsl_cx_hash_buffer() which looks for a
   matching artifact for the given input blob. It first hashes src
   using f's "alternate" hash and then, if no match is found, tries
   again with f's preferred hash.

   On success (a match is found):

   - Returns 0.

   - If ridOut is not NULL, *ridOut is set to the RID of the matching
     blob.

   - If hashOut is not NULL, *hashOut is set to the hash of the
     blob. Its ownership is transferred to the caller, who must
     eventually pass it to fsl_free().

   If no matching blob is found in the repository, FSL_RC_NOT_FOUND is
   returned (but f's error state is not annotated with more
   information). Returns FSL_RC_NOT_A_REPO if f has no repository
   opened. For more serious errors, e.g. allocation error or db
   problems, another (more serious) result code is returned,
   e.g. FSL_RC_OOM or FSL_RC_DB.

   If FSL_RC_NOT_FOUND is returned and hashOut is not NULL, *hashOut
   is set to the value of f's preferred hash and *hashOut's ownership
   is transferred to the caller. *ridOut is only modified if 0 is
   returned, in which case *ridOut will have a positive value.
*/
FSL_EXPORT int fsl_repo_blob_lookup( fsl_cx * f, fsl_b const * src,
                                     fsl_id_t * ridOut,
                                     fsl_uuid_str * hashOut );

/**
   Returns true if the specified file name ends with any reserved
   name, e.g.: _FOSSIL_ or .fslckout.

   For the sake of efficiency, zFilename must be a canonical name,
   e.g. an absolute or checkout-relative path using only forward slash
   ('/') as a directory separator.

   On Windows builds, this also checks for reserved Windows filenames,
   e.g. "CON" and "PRN".

   nameLen must be the length of zFilename. If it is negative,
   fsl_strlen() is used to calculate it.
*/
FSL_EXPORT bool fsl_is_reserved_fn(const char *zFilename,
                                   fsl_int_t nameLen );

/**
   Uses fsl_is_reserved_fn() to determine whether the filename part of
   zPath is legal for use as an in-repository filename. If it is, 0 is
   returned, else FSL_RC_RANGE (or FSL_RC_OOM) is returned and f's
   error state is updated to indicate the nature of the problem. nFile
   is the length of zPath. If negative, fsl_strlen() is used to
   determine its length.

   If relativeToCwd is true then zPath, if not absolute, is
   canonicalized as if were relative to the current working directory
   (see fsl_getcwd()), else it is assumed to be relative to the
   current checkout (if any - falling back to the current working
   directory). This flag is only relevant if zPath is not absolute and
   if f has a checkout opened. An absolute zPath is used as-is and if
   no checkout is opened then relativeToCwd is always treated as if it
   were true.

   This routine does not validate that zPath lives inside a checkout
   nor that the file actually exists. It does only name comparison and
   only uses the filesystem for purposes of canonicalizing (if needed)
   zPath.

   This routine does not require that f have an opened repo, but if it
   does then this routine compares the canonicalized forms of both the
   repository db and the given path and fails if zPath refers to the
   repository db. Be aware that the relativeToCwd flag may influence
   that test.

   This routine also checks fsl_ckout_manifest_setting() and reports
   any of the files represented by that function's results as being
   reserved. It only treats such names as reserved if they are at the
   top level of the repository - those same names in subdirectories are
   not reserved. If f has no checkout opened and relativeToCwd is true
   then those names are considered to be at the "top" if they are in
   the current directory.
*/
FSL_EXPORT int fsl_reserved_fn_check(fsl_cx * f, const char *zPath,
                                     fsl_int_t nFile, bool relativeToCwd);

/**
   Recompute/rebuild the entire repo.leaf table. This is not normally
   needed, as leaf tracking is part of the crosslinking process, but
   "just in case," here it is.

   The result is the same leaf table which crosslinking every
   check-in in a single batch produces: only check-ins which have a
   branch tag (of any type), and the parents of such check-ins, are
   considered, and each of those is a leaf if it has no child in the
   same branch. A check-in with no branch tag which is not the parent
   of one with a branch tag is never a leaf.

   This can supposedly be expensive (in time) for a really large
   repository. Testing implies otherwise.

   Returns 0 on success. On error f's error state may be updated.
   Results are undefined if f is invalid or has no opened repository.
*/
FSL_EXPORT int fsl_repo_leaves_rebuild(fsl_cx * f);

/**
   Flags for use with fsl_leaves_compute().
*/
enum fsl_leaves_compute_e {
/**
   Compute all leaves regardless of the "closed" tag.
*/
FSL_LEAVES_COMPUTE_ALL = 0,
/**
   Compute only leaves without the "closed" tag.
*/
FSL_LEAVES_COMPUTE_OPEN = 1,
/**
   Compute only leaves with the "closed" tag.
*/
FSL_LEAVES_COMPUTE_CLOSED = 2
};
typedef enum fsl_leaves_compute_e fsl_leaves_compute_e;

/**
   Creates a temporary table named "leaves" if it does not already
   exist, else empties it. Populates that table with the RID of all
   check-ins that are leaves which are descended from the checkin
   referred to by vid.

   A "leaf" is a check-in that has no children in the same branch.
   There is a separate permanent table named [leaf] that contains all
   leaves in the tree. This routine is used to compute a subset of
   that table consisting of leaves that are descended from a single
   check-in.

   The leafMode flag determines behavior associated with the "closed"
   tag, as documented for the fsl_leaves_compute_e enum.

   If vid is <=0 then this function, after setting up or cleaning out
   the [leaves] table, simply copies the list of leaves from the
   repository's pre-computed [leaf] table (see
   fsl_repo_leaves_rebuild()).

   @see fsl_leaves_computed_has()
   @see fsl_leaves_computed_count()
   @see fsl_leaves_computed_latest()
   @see fsl_leaves_computed_cleanup()
*/
FSL_EXPORT int fsl_leaves_compute(fsl_cx * f, fsl_id_t vid,
                                  fsl_leaves_compute_e leafMode);

/**
   Requires that a prior call to fsl_leaves_compute() has succeeded,
   else results are undefined.

   Returns true if the leaves list computed by fsl_leaves_compute() is
   not empty, else false. This is more efficient than checking
   against fsl_leaves_computed_count()>0.
*/
FSL_EXPORT bool fsl_leaves_computed_has(fsl_cx * f);

/**
   Requires that a prior call to fsl_leaves_compute() has succeeded,
   else results are undefined.

   Returns a count of the leaves list computed by
   fsl_leaves_compute(), or a negative value if a db-level error is
   encountered. On errors other than FSL_RC_OOM, f's error state will
   be updated with information about the error.
*/
FSL_EXPORT fsl_int_t fsl_leaves_computed_count(fsl_cx * f);

/**
   Requires that a prior call to fsl_leaves_compute() has succeeded,
   else results are undefined.

   Returns the RID of the most recent checkin from those computed by
   fsl_leaves_compute(), 0 if no entries are found, or a negative
   value if a db-level error is encountered. On errors other than
   FSL_RC_OOM, f's error state will be updated with information about
   the error.
*/
FSL_EXPORT fsl_id_t fsl_leaves_computed_latest(fsl_cx * f);

/**
   Cleans up any db-side resources created by fsl_leaves_compute().
   e.g. drops the temporary table created by that routine. Any errors
   are silenty ignored.
*/
FSL_EXPORT void fsl_leaves_computed_cleanup(fsl_cx * f);

/**
   Returns true if f's current repository has the
   forbid-delta-manifests setting set to a truthy value. Results are
   undefined if f has no opened repository. Some routines behave
   differently if this setting is enabled. e.g. fsl_checkin_commit()
   will never generate a delta manifest and fsl_deck_save() will
   refuse to save a delta. This does not affect parsing or deltas or
   those which are injected into the db via lower-level means (e.g. a
   direct blob import or from a remote sync).

   Results are undefined if f has no opened repository.

   Delta manifests ARE NOT RECOMMENDED in practice, as described at
   length at:

   https://fossil-scm.org/home/doc/trunk/www/delta-manifests.md

   As of 2026-09, this setting defaults to on/true (previously
   off/false) in both fossil(1) and libfossil, primarily because delta
   manifests break and/or overly-complicate automated extraction of
   information from manifests, e.g. a list of tags, using shell
   scripts, Tcl, and the like.
*/
FSL_EXPORT bool fsl_repo_forbids_delta_manifests(fsl_cx * f);

/**
   This is a variant of fsl_ckout_manifest_write() which writes data
   regarding the given manifest RID to the given blobs. If manifestRid
   is 0 or less then the current checkout is assumed and
   FSL_RC_NOT_A_CKOUT is returned if no checkout is opened (or
   FSL_RC_RANGE if an empty checkout is opened - a freshly-created
   repository with no checkins).

   For each buffer argument which is not NULL, the corresponding
   checkin-related data are appended to it. All such blobs will end
   in a terminating newline character.

   Returns 0 on success, any of numerious non-0 fsl_rc_e codes on
   error.
*/
FSL_EXPORT int fsl_repo_manifest_write(fsl_cx * f,
                                       fsl_id_t manifestRid,
                                       fsl_b * manifest,
                                       fsl_b * manifestUuid,
                                       fsl_b * manifestTags );


/**
   "Stage" flag for use with fsl_annotate_step and
   fsl_annotate_step_f().
*/
enum fsl_annotate_step_e {
/**
   Indicates that the current fsl_annotate_step_f() call is
   part of the "version dump" stage of the annotation.
*/
FSL_ANNOTATE_STEP_VERSION,
/**
   Indicates that the current fsl_annotate_step_f() call has
   complete version information for the line it is reporting
   about.
*/
FSL_ANNOTATE_STEP_FULL,
/**
   Indicates that the current fsl_annotate_step_f() call has
   only partial version information for the line it is reporting
   about, as a result of a limited-run annotation.
*/
FSL_ANNOTATE_STEP_LIMITED
};
typedef enum fsl_annotate_step_e fsl_annotate_step_e;

/**
   Callback state for use by fsl_annotate_step_f().

   ACHTUNG: this state gets repopulated for each call to the
   fsl_annote_step_f() callback and any pointers it holds must be
   treated as if they are invalidated as soon as the callback returns
   (whether or not that is the case is undefined, though).

   Not all state is set on each call involving this object. See the
   stepType member for details.
*/
struct fsl_annotate_step {
  /**
     Tells the caller the "type" of annotation step this call
     represents. The type of step will determine which fields
     of this object are populated when it is passed to a
     fsl_annotate_step_f() callback:

     Always set:

     stepType, stepNumber (but interpretation varies - see that
     member's docs for details).

     FSL_ANNOTATE_STEP_VERSION: fileHash, versionHash, mtime

     FSL_ANNOTATE_STEP_LIMITED: stepNumber (always 0 for the limited
     case), lineNumber, line, lineNength.

     FSL_ANNOTATE_STEP_FULL: as for FSL_ANNOTATE_STEP_LIMITED plus:
     fileHash, versionHash, mtime, username.
  */
  fsl_annotate_step_e stepType;
  /**
     Step number in this annotation run. When this->stepType is
     FSL_ANNOTATE_STEP_VERSION, this value is the relative number of
     the version, starting at 0 and incremented by 1 on each call. In
     the other modes it is 0-based relative version from which the
     current line is from, or negative if that information is
     incomplete due to a limited annotation run. e.g. a value of 3
     indicates that this line is from 3 versions away from the
     starting version.
  */
  int stepNumber;
  /**
     Line number for the current file.
  */
  uint32_t lineNumber;
  /**
     NUL-terminated current line of the input file, minus any
     newline and/or carriage return.
  */
  char const * line;
  /**
     The number of bytes in this->line.
  */
  uint32_t lineLength;
  /**
     The hash of the file version from which this->line was
     pulled.
  */
  fsl_uuid_cstr fileHash;
  /**
     The hash of the checkin version from which this->line was
     pulled.
  */
  fsl_uuid_cstr versionHash;

  /**
     The mtime field from the [event] table (timeline) entry
     associated with this version. This is a Julian Date and, because
     it is updated by annotations which modify timestamps in the
     [event] table, it reflects any "edited" time (if any).

     @see fsl_julian_to_iso8601()
  */
  double mtime;
  /**
     The user name this change was attributed to, noting that merges
     are attributed to the one who did the merge.
  */
  char const * username;
};

/** Convenience typedef. */
typedef struct fsl_annotate_step fsl_annotate_step;
/** Forward decl and convenience typedef. */
typedef struct fsl_annotate_opt fsl_annotate_opt;

/**
   Callback for use with fsl_annotate(). Implementations receive
   state about each step of an annotation process. They must return 0
   on success. On error, their non-0 result code is propagated back
   to the fsl_annotate() caller.
*/
typedef int (*fsl_annotate_step_f)(void * state,
                                   fsl_annotate_opt const * opt,
                                   fsl_annotate_step const * step);

/**
   A fsl_annotate_step_f() impl. which requires that its first argument
   be a fsl_outputer. It formats each step of the annotation
   in a manner similar to fossil(1) and forwards the result to
   state->out(state->state, ...), returning that function's result code.
*/
int fsl_annotate_step_f_fossilesque(void * state,
                                    fsl_annotate_opt const * opt,
                                    fsl_annotate_step const * step);

/**
   Configuration for use with fsl_annotate().

   This structure holds options for the "annotate" operation and its
   close cousin, "blame" a.k.a. "praise". Annotation takes a given
   file version and builds a line-by-line history, showing when each
   line was last modified. The "blame" a.k.a. "praise" option includes
   *who* modified that line.
*/
struct fsl_annotate_opt {
  /**
     The repository-root-relative NUL-terminated filename to annotate.
  */
  char const * filename;
  /**
     The checkin from which the file's version should be selected. A
     value of 0 or less means the current checkout, if in a checkout,
     and is otherwise an error.
  */
  fsl_id_t versionRid;
  /**
     The origin checkin version. A value of 0 or less means the "root of the
     tree."

     TODO: figure out and explain the difference between versionRid
     and originRid.
  */
  fsl_id_t originRid;
  /**
     The maximum number of versions to search through.
  */
  uint32_t limitVersions;

  /**
     An approximate number of milliseconds of processing time to limit
     the annotation to. Note that this is measured in CPU time, not
     "wall clock" time. This value is rough minimum approximation,
     and the annotation will stop at the first processing step after which
     this limit has been hit or surpassed.

     Even with this limit in place, the annotation engine may impose a
     minimum number of versions to step through before it enforces
     this limit.

     If both this and limitVersions are set to positive values, the
     first limit which is exceeded is applied.
  */
  uint32_t limitMs;
  /**
     - 0 = do not ignore any spaces.
     - <0 = ignore trailing end-of-line spaces.
     - >1 = ignore all spaces
  */
  int16_t spacePolicy;
  /**
     If true, include the name of the user for which each change is
     attributed (noting that merges show whoever merged the change,
     which may differ from the original committer, and amended user
     names will be used over those in the initial commit). If false,
     show only version information.

     This option is alternately known as "blame".

     For reasons lost to history, blame/praise mode does not include
     line numbers. That may change in the future.
  */
  bool praise;
  /**
     Output file blob versions, instead of checkin versions.
  */
  bool fileVersions;

  /**
     If true, annotation output will start with a list of all
     versions analyzed by the annotation process.
  */
  bool dumpVersions;
  /**
     The output channel for the resulting annotation.
  */
  fsl_annotate_step_f out;
  /**
     State for passing as the first argument to this->out().
  */
  void * outState;
};

/** Initialized-with-defaults fsl_annotate_opt structure, intended for
    const-copy initialization. */
#define fsl_annotate_opt_empty_m {\
  NULL/*filename*/, \
  0/*versionRid*/,0/*originRid*/,    \
  0U/*limitVersions*/, 0U/*limitMs*/,\
  0/*spacePolicy*/,                         \
  false/*praise*/, false/*fileVersions*/,     \
  false/*dumpVersions*/,                  \
  NULL/*out*/, NULL/*outState*/               \
}

/** Initialized-with-defaults fsl_annotate_opt structure, intended for
    non-const copy initialization. */
extern const fsl_annotate_opt fsl_annotate_opt_empty;

/**
   Runs an "annotation" of an SCM-controled file and sends the results
   to opt->out().

   Returns 0 on success. On error, returns one of:

   - FSL_RC_OOM on OOM

   - FSL_RC_NOT_A_CKOUT if opt->versionRid<=0 and f has no opened checkout.

   - FSL_RC_NOT_FOUND if the given filename cannot be found in the
     repository OR a given version ID does not resolve to a blob. (Sorry
     about this ambiguity!)

   - FSL_RC_PHANTOM if a phantom blob is encountered while trying to
     annotate.

   - FSL_RC_NOT_A_REPO if f has no opened repository.

   - FSL_RC_MISUSE if opt->out is NULL.

   - FSL_RC_DIFF_BINARY if a version of the file appears to be
     binary.

   - FSL_RC_RANGE if the version of the file being annotated is
     empty.

   - A db-related code if a database operation fails.

   Except for FSL_RC_OOM and codes returned by opt->out(), f's error
   state describes the failure.

   opt->out() may return arbitrary non-0 result codes, in which case
   the returned code is propagated to the caller of this function.

   Results are undefined if either argument is invalid.
*/
FSL_EXPORT int fsl_annotate( fsl_cx * f,
                             fsl_annotate_opt const * opt );


/** Convenience typedef and forward decl. */
typedef struct fsl_rebuild_opt fsl_rebuild_opt;

/**
   Metrics related to a repository rebuild.
*/
struct fsl_rebuild_metrics {
  /**
     The number of phantom artifacts seen during rebuild.
  */
  fsl_size_t phantomCount;
  /**
     Counts of each blob type seen during rebuild.  The FSL_SATYPE_ANY
     slot (0) counts non-artifact blobs.
  */
  fsl_size_t counts[FSL_SATYPE_count];
  /**
     The accumulated sizes of each blob type seen during rebuild. The
     FSL_SATYPE_ANY slot (0) counts non-artifact blobs.
  */
  fsl_size_t sizes[FSL_SATYPE_count];
};
typedef struct fsl_rebuild_metrics fsl_rebuild_metrics;

#define fsl_rebuild_metrics_empty_m { \
    .phantomCount = 0,                \
    .counts = {0,0,0,0,0,0,0,0,0},    \
    .sizes = {0,0,0,0,0,0,0,0,0}      \
  }

/**
   State for use with the fsl_rebuild_f() callback type.
*/
struct fsl_msg_rebuild {
  /**
     Fossil context for which this rebuild is being performed.
  */
  fsl_cx * f;
  /**
     The options object used for this invocation of fsl_repo_rebuild().
  */
  fsl_rebuild_opt const * opt;
  /**
     An _approximate_ upper bound on the number of files
     fsl_repo_rebuild() will process. This number is very likely
     somewhat larger than the number of times which opt->callback()
     will be called, but it is close enough to give some indication of
     how far along a rebuild is.

     This number may be higher than the real value because it's a fast
     approximation. Getting an exact count for the case before a
     rebuild is not always possible: the info needed to get an exact
     count is derived from the result of a rebuild.
  */
  fsl_size_t artifactCount;
  /**
     One-based counter of total artifacts processed so far. After
     rebuilding is finished, opt->callback will be called one final
     time with this value set to 0. The callback may use the value 0
     to recognize that this is post-rebuild step and finalize any
     output or whatever it wants to do.
  */
  fsl_size_t stepNumber;

  /**
     The `blob.rid` value of the just-processed blob. If stepNumber is 0,
     this will be 0.
  */
  fsl_id_t rid;

  /**
     The size of the just-processed blob, -1 if it is a phantom
     blob, or 0 when this object is part of a FSL_MSG_REBUILD_DONE
     message.
  */
  fsl_int_t blobSize;

  /**
     Set to FSL_SATYPE_INVALID if the just-processed blob is _not_ a
     fossil artifact. This will never be set to FSL_SATYPE_ANY.

     (API discrepancy: fsl_rebuild_metrics maps FSL_SATYPE_ANY to
     non-artifact blobs.)
  */
  fsl_satype_e artifactType;

  /**
     This is only non-0 for FSL_MSG_REBUILD_DONE messages, in which
     case it holds the result code of the overall rebuild process.
     This will only be set to non-0 once, if at all, in a given
     rebuild run.
  */
  int errCode;

  /**
     Metrics from the rebuild. On each rebuild step callback call,
     these will contain the updated metrics.
  */
  fsl_rebuild_metrics metrics;
};
/** Convenience typedef. */
typedef struct fsl_msg_rebuild fsl_msg_rebuild;

/** Initialized-with-defaults fsl_msg_rebuild structure, intended for
    const-copy initialization. */
#define fsl_msg_rebuild_empty_m { \
    .f = NULL, .opt = NULL, .artifactCount = 0, \
    .stepNumber = 0, .rid = 0, .blobSize = -1, \
    .artifactType = FSL_SATYPE_INVALID, \
    .errCode = 0, \
    .metrics = fsl_rebuild_metrics_empty_m \
  }

/** Initialized-with-defaults fsl_msg_rebuild structure, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_msg_rebuild fsl_msg_rebuild_empty;

/**
   Callback for use with fsl_repo_rebuild() in order to report
   progress. It must return 0 on success, and any non-0 results will
   abort the rebuild and be propagated back to the caller.

   Each time this is called, state->stepNumber will be incremented, starting
   at 1. After rebuilding is complete, it is called with a stepNumber
   of 0 to give the callback a chance to do any final bookkeeping or output
   cleanup or whatever.

   TODO: replace this with the fsl_msg interface and use
   fsl_msg_listener configured for the being-rebuilt fsl_cx.
*/
typedef int (*fsl_rebuild_f)(fsl_msg_rebuild const * state);

/**
   Options for the rebuild process.
*/
struct fsl_rebuild_opt {
  /**
     Scan artifacts in a random order (generally only of use in testing
     the library's code). This is primarily for testing that the library
     can handle its inputs in an arbitrary order.
  */
  bool randomize;
  /**
     True if clusters should be created.

     NOT YET IMPLEMENTED.
  */
  bool createClusters;
  /**
     If true, the savepoint started by the rebuild process will end in
     a rollback even on success.
  */
  bool dryRun;
  /**
     If true, the rebuild hashes each artifact's full content and
     fails with FSL_RC_CONSISTENCY if it does not match the artifact's
     hash. The rebuild already expands every artifact once, so this
     costs only the hashing. fsl_clone() uses this instead of
     verify-at-commit.
  */
  bool verifyHashes;
};

/** Initialized-with-defaults fsl_rebuild_opt structure, intended for
    const-copy initialization. */
#define fsl_rebuild_opt_empty_m {\
  .randomize=false, .createClusters=false, .dryRun=false, \
  .verifyHashes=false \
}

/** Initialized-with-defaults fsl_rebuild_opt structure, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_rebuild_opt fsl_rebuild_opt_empty;

/**
   "Rebuilds" the current repository database. This involves _at least_
   the following:

   - DROPPING all transient repository tables. ALL tables in the db
     which do not specifically belong to fossil and do not start with
     the name `fx_` _will be dropped_.

   - Recreating all transient tables from immutable state in the
     database.

   - Updating the schema, if needed, from "older" versions of the
     fossil schema to the "current" one. This library does not
     currently check for updates which need to be made to a decade-old
     schema, however! That is, schema changes which were introduced
     10+ years ago are not currently addressed by this library
     because, frankly, it's not expected that anyone using this
     library will be using it with such ancient repositories (and
     those who do can rebuild it once with fossil(1) to update it).

   - Crosslinking all blobs which appear to be artifacts (meaning they
     can be parsed as such). Any crosslink handlers registered via
     fsl_xlink_listener() will be called.

   If opt is NULL then fsl_rebuild_opt_empty is used.

   Returns 0 on success, non-0 on error (with any number of potential
   result codes from the db or crosslinking layers). Returns
   FSL_RC_NOT_A_REPO if f has no opened repository. An error while
   processing an artifact is reported with that artifact's rid and
   hash. A blob which does not parse as an artifact is not an error:
   it is treated as opaque content. It pushes its own
   transaction and will roll that back on non-0, so it "shouldn't"
   leave a mess on error. On error it does _not_ put any higher-level
   transaction into rollback mode.

   If opt->dryRun is true then it also rolls back the transaction but
   it is not treated as an error and the rollback does not affect
   higher levels of the transaction stack

   During the rebuild process, fsl_msg messages of types
   FSL_MSG_REBUILD_STEP and FSL_MSG_REBUILD_DONE may be fired.  The
   latter is only fired if the former is.

   This operation honors interruption via fsl_cx_interrupt() but, due
   to intricacies of timing, it's possible that a triggered interrupt
   gets trumped by another error which happens while the check for the
   interrupt flag is pending. In both cases this function could return
   a non-0 code, though.
*/
FSL_EXPORT int fsl_repo_rebuild(fsl_cx * f, fsl_rebuild_opt const * opt);

/**
   Sets the journal mode of f's repository db to zMode, which must be
   "wal", "delete", "truncate" or "persist". WAL mode is a property of the db
   file and stays set for all later connections from libfossil or fossil(1).

   SQLite commits a WAL db before the dbs in DELETE mode, so a check-in
   interrupted between the two leaves the checkout db behind the repo db. The
   next check-in detects this and fails with FSL_RC_WOULD_FORK, and
   fsl_ckout_update() moves the checkout to the new check-in. At
   synchronous=NORMAL, the in-tree SQLite's default for a WAL db, SQLite does
   not sync the WAL at each commit, so a power loss could instead leave the
   checkout db recording a check-in which the repo db has lost. While a
   checkout db is attached, libfossil sets the repo db to synchronous=FULL,
   which syncs the WAL before the checkout db commit. SQLite can't change 
   synchronous levels inside a transaction.

   Only the repo db can be in WAL mode. If libfossil finds a checkout db
   in WAL mode, libfossil resets the db back to DELETE on opening it. If
   a checkout db was permitted to be in WAL mode, SQLite's lack of atomic
   commit guarantee means that the checkout could commit before the repo,
   resulting in data loss.

   This function must not be called inside a transaction, including one on a
   host db handle (see fsl_cx_host_db()). Returns 0 on success,
   FSL_RC_NOT_A_REPO if f has not opened a repository, FSL_RC_MISUSE
   inside a transaction, for any other zMode, or for a repository
   which is tables of a host's main db (fsl_repo_open_host()), whose
   journal mode is the host's, and FSL_RC_LOCKED if SQLite cannot
   change the mode, e.g. while another connection has the db open.
*/
FSL_EXPORT int fsl_repo_journal_mode_set(fsl_cx * f, char const * zMode);

/**
   Tries to determine the branch name of the given rid, which is
   assumed to refer to a checkin artifact. If it cannot find one and
   doFallback is true then it looks for the `main-branch`
   repository-level config setting and uses that (falling back to
   "trunk" if that setting is not set).

   On success it returns 0 and sets `*zOut` to the branch name,
   transfering ownership of those bytes to the caller (who must
   eventually pass them to fsl_free()). If doFallback is false and no
   direct branch name is found then it sets `*zOut` to NULL. If
   doFallback is true then, on success, `*zOut` will always be set to
   some non-NULL value. On error `*zOut` is not modified.

   On error it may return FSL_RC_NOT_A_REPO, FSL_RC_OOM, or any number
   of db-side error codes.
*/
FSL_EXPORT int fsl_branch_of_rid(fsl_cx * f, fsl_id_t rid,
                                 bool doFallback, char ** zOut );

/** Convenience typedef and obligatory forward declaration. */
typedef struct fsl_cidiff_state fsl_cidiff_state;

/**
   Callback type for use with fsl_cidiff(). It must return 0 on
   success or a value from the fsl_rc_e enum on error.  On error it
   "should" update the error state in the corresponding fsl_cx object
   by passing state->f to fsl_cx_err_set() (or equivalent).
*/
typedef int (*fsl_cidiff_f)(fsl_cidiff_state const *state);

/**
   Options for use with fsl_cidiff().
*/
struct fsl_cidiff_opt {
  /**
     Checkin version (RID) for "version 1".
  */
  fsl_id_t v1;
  /**
     Checkin version (RID) for "version 2". This checkin need not have
     any relationship with version 1, in terms of SCM-side lineage.
  */
  fsl_id_t v2;
  /**
     Callback to call on each iteration step.
  */
  fsl_cidiff_f callback;
  /**
     Opaque state for the callback. It can be accessed
     from the callback via arg->opt->callbackState.
  */
  void * callbackState;
};

/** Convenience typedef. */
typedef struct fsl_cidiff_opt fsl_cidiff_opt;

/** Initialized-with-defaults fsl_cidiff_opt structure, intended for
    const-copy initialization. */
#define fsl_cidiff_opt_empty_m {0,0,0,0}

/** Initialized-with-defaults fsl_cidiff_opt structure, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_cidiff_opt fsl_cidiff_opt_empty;

/**
   Descriptors for the type of information being reported for each
   step of fsl_cidiff() iteration, as reported via the
   fsl_cidiff_state::changes attribute.
*/
enum fsl_cidiff_e {
/**
   Indicates that the v1 and v2 files are the same. Specifically,
   this means:

   - Same current names, compared case-sensitively.
     fsl_card_F::priorName values are ignored for this
   - Same permissions.
   - Same hash.
*/
FSL_CIDIFF_NONE = 0,
/**
   Indicates that the hashes of the v1 and v2 files
   differ.
*/
FSL_CIDIFF_FILE_MODIFIED = 0x0001,
/**
   Indicates that the v2 file was renamed.

   Caveats:

   - If v1 and v2 are not immediate relatives in the SCM DAG
     sense. e.g. when comparing a version X and unrelated version Y,
     or version X and X+30, it is possible that a rename goes
     unreported via fsl_cidiff or that it gets misdiagnosed. e.g. if
     version X renames file A to B and version X+100 renames file C to
     A, it will be reported as a rename. Detecting the true reality of
     such cases is remarkably challenging, requiring going through the
     entire history which links v1 and v2.

   - Pedantically speaking, if v1 and v2 are unrelated in the SCM
     DAG, "renames" are not possible but will be reported as such
     if their names happen to match up.
*/
FSL_CIDIFF_FILE_RENAMED  = 0x0002,
/**
   Indicates that the permissions of the current file
   differ between v1 and v2. This is only set if
   both versions have a given file (by name, as opposed
   to hash).
*/
FSL_CIDIFF_FILE_PERMS    = 0x0004,
/**
   Indicates that the file is in v2 but not v1. If v1 and v2
   are unrelated versions or are not immediate DAG neighbors,
   this might also indicate that a file from v1 was renamed
   in v2.
*/
FSL_CIDIFF_FILE_ADDED    = 0x0010,
/**
   Indicates that the file is in v1 but not v2. If v1 and v2
   are unrelated versions or are not immediate DAG neighbors,
   this might also indicate that a file from v1 was renamed
   in v2.
*/
FSL_CIDIFF_FILE_REMOVED  = 0x0020
};
/** Convenience typedef. */
typedef enum fsl_cidiff_e fsl_cidiff_e;
/**
   Holds the state for a single iteration step of fsl_cidiff.
*/
struct fsl_cidiff_state {
  /**
     The associated fsl_cx instance.
  */
  fsl_cx * f;
  /**
     The options object passed to fsl_cidiff().
  */
  fsl_cidiff_opt const *opt;
  /**
     Denotes the type of this step in the iteration.

     Before fsl_cidiff() starts its loop over F-card changes,
     it calls the callback once with this value set to 0. The intent is to
     give the caller an opporuntity to do any required setup, e.g.
     outputing a report header. The
     fc1 and fc2 members will both be NULL, but the d1 and d2
     members will be set.

     For each step of the F-card iteration, stepType will be set to
     FSL_RC_STEP_ROW.

     After successful difference iteration, fsl_cidiff() calls its
     callback with stepType set to FSL_RC_STEP_DONE. The intent is to
     give the caller an opporuntity to do any required cleanup, e.g.
     outputing a report footer. The fc1 and fc2 members will both be
     NULL, but the d1 and d2 members will be set.
  */
  int stepType;
  /**
     Describes the change(s) being reported by the current
     iteration step, as a bitmask of fsl_cidiff_e values.
  */
  int changes;
  /**
     The file, if any, corresponding to this->v1. This will be NULL
     this->changeType is FSL_CIDIFF_FILE_ADDED.
  */
  fsl_card_F const * fc1;
  /**
     The file, if any, corresponding to this->v2. This will be NULL
     this->changeType is FSL_CIDIFF_FILE_REMOVED.
  */
  fsl_card_F const * fc2;
  /**
     The deck corresponding to this->opt->v1. It is strictly forbidden
     for this->callback to manipulate this object. Specifically, any
     traversal of its F-card list will invalidate the iteration being
     done by fsl_cidiff(). Read-only operations on other state of the
     deck are legal.
  */
  fsl_deck const * d1;
  /**
     The deck corresponding to this->opt->v2. See the docs for
     this->d1 for important details.
  */
  fsl_deck const * d2;
};

/** Initialized-with-defaults fsl_cidiff_state structure, intended for
    const-copy initialization. */
#define fsl_cidiff_state_empty_m {\
    NULL/*f*/,NULL/*opt*/,             \
    0/*stepType*/,FSL_CIDIFF_NONE/*changes*/, \
    NULL/*fc1*/,NULL/*fc2*/,    \
    NULL/*d1*/,NULL/*d2*/     \
  }

/** Initialized-with-defaults fsl_cidiff_state structure, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_cidiff_state fsl_cidiff_state_empty;

/**
   A utility for reporting the differences between the manifests of
   two checkins.

   This loads the fsl_deck instances for each version opt->v1 and
   opt->v2, then calls opt->callback for each step of the
   difference-checking process. It only inspects and reports the
   difference between _exactly_ v1 and _exactly_ v2, not the
   difference between the chain of SCM DAG relatives (if any) between
   the two.

   It is not required that v1 and v2 be related in the SCM DAG but its
   report of differences may be misleading if v1 and v2 are either
   unrelated or separated by more than 1 step in the DAG. See the docs
   for fsl_cidiff_e for cases known to be potentially confusing.

   Returns 0 on success. If the callback returns non-0, that result is
   propagated back to the caller. It may otherwise return any number of
   othe result codes including, but not limited to:

   - FSL_RC_OOM on allocation error

   - FSL_RC_NOT_A_REPO if f has no opened repository.

   - FSL_RC_TYPE if either of the given versions is not a checkin.

   - FSL_RC_NOT_FOUND if either of given versions is not found in the
   repository.


   Potential TODO: add fsl_deck_diff() which takes two decks, instead
   of RIDs, to compare. This function would just be a proxy for that
   one, loading the given RIDs and passing on the decks. That would
   require a significantly larger set of possible change-type values
   and would require much type-specific handling (e.g. maybe reporting
   J-card differences for a pair of ticket decks).
*/
FSL_EXPORT int fsl_cidiff(fsl_cx * f, fsl_cidiff_opt const * opt);


/**
   Configuration parameters for fsl_repo_create().  Always
   copy-construct these from fsl_repo_create_opt_empty
   resp. fsl_repo_create_opt_empty_m in order to ensure proper
   behaviour vis-a-vis default values.

   TODOs:

   - Add project name/description, and possibly other
   configuration bits.

   - Allow client to set password for default user (currently set
   randomly, as fossil(1) does).
*/
struct fsl_repo_create_opt {
  /**
     The file name for the new repository.
  */
  char const * filename;
  /**
     Fossil user name for the admin user in the new repo.  If NULL,
     defaults to the Fossil context's user (see
     fsl_cx_user_get()). If that is NULL, it defaults to
     "root" for historical reasons.
  */
  char const * username;

  /**
     The comment text used for the initial commit. If NULL or empty
     (starts with a NUL byte) then no initial check is
     created. fossil(1) is largely untested with that scenario (but
     it seems to work), so for compatibility it is not recommended
     that this be set to NULL.
  */
  char const * commitMessage;

  /**
     Mime type for the commit message (manifest N-card). Manifests
     support this but fossil(1) has never (as of 2025-07) made use of
     it. It is provided for completeness but should, for
     compatibility's sake, probably not be set, as the fossil UI may
     not honor it. The implied default is text/x-fossil-wiki. Other
     ostensibly legal values include text/plain and text/x-markdown.
     This API will accept any value, but results are technically
     undefined with any values other than those listed above.
  */
  char const * commitMessageMimetype;

  /**
     If not NULL and not empty, fsl_repo_create() will use this
     repository database to copy the configuration, copying over
     the following settings:

     - The reportfmt table, overwriting any existing entries.

     - The user table fields (cap, info, mtime, photo) are copied for
       the "system users": anonymous, nobody, developer, reader.

     - The vast majority of the config table is copied, arguably more
       than it should (e.g. the 'manifest' setting).
  */
  char const * configRepo;

  /**
     If false, fsl_repo_create() will fail if this->filename
     already exists.
  */
  bool allowOverwrite;

  /**
     If true, the new repo will not have a "project-code" config
     entry. Only set this to true when the next operation on the
     new repo will be an inbound clone.
  */
  bool elideProjectCode;

  /**
     If not NULL, the new repository is not a db file but the tables of
     the main db of f's host db handle (fsl_cx_host_db()) whose names
     start with this prefix, as fsl_repo_open_host() describes, and
     filename is not used. f must not be NULL, and allowOverwrite must
     be false (else FSL_RC_MISUSE): to start a repository afresh, drop
     its tables first. The tables are created in one transaction which
     holds the main db's write lock from before its checks, and the
     main db may then have no table, index, trigger or view whose name
     starts with the prefix (ignoring case), else
     FSL_RC_ALREADY_EXISTS. The initial check-in follows in a
     transaction of its own. The main db's application_id is not set.
  */
  char const * hostTablePrefix;
};
typedef struct fsl_repo_create_opt fsl_repo_create_opt;

/** Initialized-with-defaults fsl_repo_create_opt struct, intended
    for in-struct initialization. */
#define fsl_repo_create_opt_empty_m { \
    .filename=NULL,                   \
    .username=NULL,                   \
    .commitMessage=NULL,              \
    .commitMessageMimetype=NULL,      \
    .configRepo=NULL,                 \
    .allowOverwrite=false,            \
    .elideProjectCode=false,          \
    .hostTablePrefix=NULL             \
  }

/** Initialized-with-defaults fsl_repo_create_opt struct, intended
    for copy-initialization. */
FSL_EXPORT const fsl_repo_create_opt fsl_repo_create_opt_empty;

/**
   Creates a new repository database using the options provided in the
   second argument. If f is not NULL, it must be a valid context
   instance, though it need not have an opened checkout/repository. If
   f has an opened repo or checkout, this routine closes them but that
   closing _will fail_ if a transaction is currently active.

   If f is NULL, a temporary context is used for creating the
   repository, in which case the caller will not have access to
   detailed error information (only the result code) if this operation
   fails. In that case, the resulting repository file will, on
   success, be found at the location referred to by opt.filename.

   The opt argument may not be NULL. For opt->hostTablePrefix, see
   that member.

   If opt->allowOverwrite is false (0) and the file exists, it fails
   with FSL_RC_ALREADY_EXISTS, otherwise is creates/overwrites the
   file. This is a destructive operation if opt->allowOverwrite is
   true, so be careful: the existing database will be truncated and
   re-created.

   This operation installs the various "static" repository schemas
   into the db, sets up some default settings, and installs a
   default user.

   This operation always closes any repository/checkout opened by f
   because setting up the new db requires wiring it to f to set up
   some of the db-side infrastructure. The one exception is if
   argument validation fails, in which case f's repo/checkout-related
   state are not modified. Note that closing will fail if a
   transaction is currently active and that, in turn, will cause this
   operation to fail.

   See the fsl_repo_create_opt docs for more details regarding the
   creation options.

   On success, 0 is returned and f (if not NULL) is left with the
   new repository opened and ready for use. On error, f's error
   state is updated and any number of the FSL_RC_xxx codes may be
   returned - there are no less than 30 different _potential_ error
   conditions on the way to creating a new repository.

   If initialization of the repository fails, this routine will
   attempt to remove its partially-initialize corpse from the
   filesystem but will ignore any errors encountered while doing so.

   Example usage:

   ```
   fsl_repo_create_opt opt = fsl_repo_create_opt_empty;
   int rc;
   opt.filename = "my.fossil";
   // ... any other opt.xxx you want to set, e.g.:
   // opt.user = "fred";
   // Assume fsl is a valid fsl_cx instance:
   rc = fsl_repo_create(fsl, &opt);
   if(rc) { ...error... }
   else {
     fsl_db * db = fsl_cx_db_repo(f);
     assert(db); // == the new repo db
   ...
   }
   ```

   @see fsl_repo_open()
   @see fsl_repo_close()
*/
FSL_EXPORT int fsl_repo_create(fsl_cx * f, fsl_repo_create_opt const * opt );

/**
   UNTESTED.

   Returns true if f has an opened repository database which is
   opened in read-only mode, else returns false.
*/
FSL_EXPORT bool fsl_repo_is_readonly(fsl_cx const * f);

/**
   Searches for matching blob records for a fossil ticket ID. (A
   ticket's ID is the value of its K-card.) The given ticket ID must
   be a full-length ticket ID (40 characters of lower-case hex) or an
   unambiguous prefix.

   If at least one match is found, it returns 0 and updates the 3rd
   argument: `*ridList` is assigned to an array of fsl_id_t
   (`blob.rid` values) terminated by an entry with the value
   0. Ownership of the array is passed to the caller, who must
   eventually pass it to fsl_free(). The entries are ordered from
   oldest to newest (based on their `tagxref.mtime` value).

   On error it may return:

   - FSL_RC_OOM on allocation error.
   - FSL_RC_RANGE if the given ticket ID is longer than FSL_STRLEN_SHA1.
   - FSL_RC_AMBIGUOUS if the ticket ID prefix would match multiple distinct
     ticket IDs. This result is not possible if passed a full-length ticket
     ID.
   - FSL_RC_NOT_FOUND if no match is found.
   - FSL_RC_NOT_A_REPO if f has no repository opened.
   - Any number of db-related errors if something goes horribly wrong
     in the db layer.

   On error, the 3rd argument is not modified.
*/
FSL_EXPORT int fsl_tkt_id_to_rids(fsl_cx * f, char const * tktId,
                                  fsl_id_t ** ridList);

/**
   Models user permissions precisely as fossil(1) does. Most of these
   do not apply to the library - they are "app-level" permissions.
   Some very few are honored by the library, namely those relevant for
   sync support.  The app-level permissions are exposed here so that
   app-level code can handle those in ways compatible with fossil(1),
   while leaving the library to handle the permission storage (via the
   `user.cap` repository db field).
*/
struct fsl_uperm {
 bool setup;            /* s: use Setup screens on web interface */
 bool admin;            /* a: administrative permission */
 bool password;         /* p: change password */
 bool write;            /* i: xfer inbound. check-in */
 bool read;             /* o: xfer outbound. check-out */
 bool hyperlink;        /* h: enable the display of hyperlinks */
 bool clone;            /* g: clone */
 bool readWiki;         /* j: view wiki via web */
 bool newWiki;          /* f: create new wiki via web */
 bool appendWiki;       /* m: append to wiki via web */
 bool writeWiki;        /* k: edit wiki via web */
 bool moderateWiki;     /* l: approve and publish wiki content (Moderator) */
 bool readTicket;       /* r: view tickets via web */
 bool newTicket;        /* n: create new tickets */
 bool appendTicket;     /* c: append to tickets via the web */
 bool writeTicket;      /* w: make changes to tickets via web */
 bool moderateTicket;   /* q: approve and publish ticket changes (Moderator) */
 bool attach;           /* b: add attachments */
 bool ticketReport;     /* t: create new ticket report formats */
 bool readAddr;         /* e: read email addresses or other private data */
 bool zip;              /* z: download zipped artifact via /zip URL */
 bool privateContent;   /* x: can send and receive private content */
 bool writeUnversioned; /* y: can push unversioned content */
 bool readForum;        /* 2: Read forum posts */
 bool writeForum;       /* 3: Create new forum posts */
 bool trustedForum;     /* 4: Post to forums not subject to moderation */
 bool moderateForum;    /* 5: Moderate (approve or reject) forum posts */
 bool adminForum;       /* 6: Grant capability 4 to other users */
 bool emailAlert;       /* 7: Sign up for email notifications */
 bool announce;         /* A: Send announcements */
 bool chat;             /* C: read or write the chatroom */
 bool debug;            /* D: show extra Fossil debugging features */
  /* These last two represent capabilities inherited from predefined
     users. */
 bool xReader;          /* u: Inherit all privileges of "reader" */
 bool xDeveloper;       /* v: Inherit all privileges of "developer" */
};

/**
   Helper for mass-handling of fsl_uperm permissions (e.g. generating
   switch/case blocks).  Usage:

   1) #define a macro which takes two argument: the fsl_uperm member
     name (identifier) and its corresponding capabilities character
     (as a char literal).

   2) Invoke fsl_uperm_map_base(THAT_MACRO_NAME).

   The (1) macro will be invoked one time per fsl_uperm member,
   passing it (memberName,aChar). No commas or semicolons are emited
   between calls, so they need to be included in the definition of (1)
   if they're relevant.

   This macro does not include the "inehrits from" permissions
   (xReader, xDeveloper). Use fsl_uperm_map_inherited(M) or
   fsl_uperm_map_all(M) to include those.
*/
#define fsl_uperm_map_base(M)        \
  M(setup,'s') M(admin,'a') M(password,'p')              \
  M(write,'i') M(read,'o') M(hyperlink,'h') M(clone,'g') \
  M(readWiki,'j') M(newWiki,'f') M(appendWiki,'m') M(writeWiki,'k') \
  M(moderateWiki,'l') M(readTicket,'r') M(newTicket,'n') M(appendTicket,'c') \
  M(writeTicket,'w') M(moderateTicket,'q') M(attach,'b') M(ticketReport,'t') \
  M(readAddr,'e') M(zip,'z') M(privateContent,'x') M(writeUnversioned,'y') \
  M(readForum,'2') M(writeForum,'3') M(trustedForum,'4') M(moderateForum,'5') \
  M(adminForum,'6') M(emailAlert,'7') M(announce,'A') M(chat,'C') \
  M(debug,'D')

/**
   Like fsl_uperm_map_base() but only includes the "inherits from"
   members.
*/
#define fsl_uperm_map_inherited(M) \
  M(xReader,'u') M(xDeveloper,'v')

/**
   A combination of fsl_uperm_map_base() and
   fsl_uperm_map_inherited().
*/
#define fsl_uperm_map_all(M) \
  fsl_uperm_map_base(M) fsl_uperm_map_inherited(M)

/** @internal */
#define fsl__uperm_map_init(M,CH) .M=false,

/**
   Const-copy initializer for a fsl_uperm.
*/
#define fsl_uperm_empty_m { fsl_uperm_map_all(fsl__uperm_map_init) }

/**
   A fsl_uperm instance with all members set to false.
*/
extern const fsl_uperm fsl_uperm_empty;
/**
   A fsl_uperm instance with all members set to true except for the
   "inherits from" properties (xReader and xDeveloper), as those
   permissions are already implied in the setting of all other
   permissions to true.
*/
extern const fsl_uperm fsl_uperm_all;

/**
   Adds any permissions specified in zCap to pTgt. It does not
   modify permissions which are not in zCap.

   Returns 0 on success, non-0 on error. If zCap contains any
   unhandled characters it returns FSL_RC_RANGE, with the exception of
   spaces and tabs, which it ignores. It is not an error if zCap is
   empty or contains only spaces/tabs. If f is not NULL, f's error
   state describes the failure.

   If it returns non-0, pTgt's state is not well-defined. It may have
   been partially updated before the failure.

   Any given permission letter may imply other permissions. e.g.  the
   'a' and 's' permissions imply most others.

   f is optional (may be NULL) unless zCap contains 'u' or 'v', in
   which case f is required in order to collect the permissions for
   the the "reader" resp. "developer" user. If f is NULL in those
   cases, FSL_RC_MISUSE is returned. If f has no opened repo in those
   cases, FSL_RC_NOT_A_REPO is returned.
*/
FSL_EXPORT int fsl_uperm_add(fsl_cx * f, fsl_uperm * pTgt, char const *zCap);


/**
   Fetches f's current project code. On success, assigns it to *pOut
   and returns 0. Caches the result for future calls. Each repository
   has a project code which is shared across all of its clones, and
   fossil will not clone between repositories with differing project
   codes.

   The returned memory is owned by f and invalidated any time the
   project code needs to be re-read. Hypothetically that never happens
   within the lifetime of a given context's repository being open, but
   stranger things have happened. i.e. copy it if needed rather than
   relying on a long lifetime.
*/
FSL_EXPORT int fsl_repo_project_code( fsl_cx * f, char const **pOut );


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_REPO_H_INCLUDED */
/* end of file include/fossil-scm/repo.h */
/* start of file include/fossil-scm/checkout.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_CHECKOUT_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_CHECKOUT_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/** @file checkout.h

    fossil-checkout.h declares APIs specifically dealing with
    checkout-side state, as opposed to purely repository-db-side state
    or non-content-related APIs.
*/


#if defined(__cplusplus)
extern "C" {
#endif


/**
   Tries to open a checked-out fossil repository db in the given
   directory (or "." if dirName is NULL). This routine canonicalizes
   its dirName argument using fsl_file_canonical_name(), then passes
   that and checkParentDirs on to fsl_ckout_db_search() to find a
   checkout db, so see that routine for how it searches.

   If this routine finds/opens a checkout, it also tries to open
   the repository database from which the checkout derives, and
   fails if it cannot. The library never allows a checkout to be
   opened without its corresponding repository partner because
   a checkout has hard dependencies on the repo's state.

   Returns 0 on success. If there is an error opening or validating
   the checkout or its repository db, f's error state will be
   updated. Error codes/conditions include:

   - FSL_RC_MISUSE if f is NULL.

   - FSL_RC_ACCESS if f already has an opened checkout.

   - FSL_RC_OOM if an allocation fails.

   - FSL_RC_NOT_FOUND if no checkout is found.

   - FSL_RC_NOT_A_REPO if a checkout is found but its repository db
   is not recorded in it, is not found, or is not a valid
   repository.

   - FSL_RC_RANGE if dirname is not NULL but has a length of 0.

   - Various codes from fsl_getcwd() (if dirName is NULL).

   - Various codes if opening the associated repository DB fails.

   TODO: there's really nothing in the architecture which restricts a
   checkout db to being in the same directory as the checkout, except
   for some historical bits which "could" be refactored. It "might be
   interesting" to eventually provide a variant which opens a checkout
   db file directly. We have the infrastructure, just need some
   refactoring. It "shouldn't" require any trickery or
   incompatibilities with fossil(1).
*/
FSL_EXPORT int fsl_ckout_open_dir( fsl_cx * const f, char const * dirName,
                                   bool checkParentDirs );


/**
   Searches the given directory (or the current directory if dirName
   is 0) for a fossil checkout database file named one of (_FOSSIL_,
   .fslckout).  If it finds one, it returns 0 and appends the file's
   path to pOut if pOut is not 0.  If neither is found AND if
   checkParentDirs is true an then it moves up the path one directory
   and tries again, until it hits the root of the dirPath (see below
   for a note/caveat).

   If dirName is NULL then it behaves as if it had been passed the
   absolute path of the current directory (as determined by
   fsl_getcwd()).

   This function does no normalization of dirName. Because of that...

   Achtung: if dirName is relative, this routine might not find a
   checkout where it would find one if given an absolute path (because
   it traverses the path string given it instead of its canonical
   form). Whether this is a bug or a feature is not yet clear. When in
   doubt, use fsl_file_canonical_name() to normalize the directory
   name before passing it in here. If it turns out that we always want
   that behaviour, this routine will be modified to canonicalize the
   name.

   This routine can return at least the following error codes:

   - FSL_RC_NOT_FOUND: either no checkout db was found or the given
   directory was not found.

   - FSL_RC_RANGE if dirName is an empty string. (We could arguably
   interpret this as a NULL string, i.e. the current directory.)

   - FSL_RC_OOM if allocation of a filename buffer fails.

   TODO?

   - Why was the decision made not to canonicalize dirName from here?
   We might want to change that.

*/
FSL_EXPORT int fsl_ckout_db_search( char const * dirName,
                                    bool checkParentDirs,
                                    fsl_b * const pOut );

/**
   Returns version information for the current checkout.

   If f has an opened checkout then...

   If uuid is not NULL then *uuid is set to the UUID of the opened
   checkout, or NULL if there is no checkout. If rid is not NULL, *rid
   is set to the record ID of that checkout, or 0 if there is no
   checkout (or the current checkout is from an empty repository). The
   returned uuid bytes and rid are owned by f and valid until the
   library updates its checkout state to a newer checkout version
   (essentially unpredictably). When in doubt about lifetime issues,
   copy the UUID immediately after calling this if they will be needed
   later.

   Corner case: a new repo with no checkins has an RID of 0 and a UUID
   of NULL. That does not happen with fossil-generated repositories,
   as those always "seed" the database with an initial commit artifact
   containing no files.
*/
FSL_EXPORT void fsl_ckout_version_info(fsl_cx * f, fsl_id_t * const rid,
                                       fsl_uuid_cstr * const uuid );

/**
   If f has an opened checkout, a copy of its current branch name is returned,
   otherwise f's error state is set to to FSL_RC_NOT_A_CKOUT and 0
   is returned.

   Ownership of the returned string is transfered to the caller, who
   must eventually pass it to fsl_free().

   It may return 0 for various errors, e.g. for a db error or
   OOM. fsl_cx_err_code() and friends can be used to determine what
   failed.
 */
FSL_EXPORT char * fsl_ckout_current_branch(fsl_cx * f);

/**
   Given a fsl_cx with an opened checkout, and a file/directory name,
   this function canonicalizes zOrigName to a form suitable for use as
   an in-repo filename, _appending_ the results to pOut. If pOut is
   NULL, it performs its normal checking but does not write a result,
   other than to return 0 for success.

   As a special case, if zOrigName refers to the top-level checkout
   directory, it resolves to either "." or "./", depending on whether
   zOrigName contains a trailing slash.

   If relativeToCwd is true then the filename is canonicalized
   based on the current working directory (see fsl_getcwd()),
   otherwise f's current checkout directory is used as the virtual
   root.

   If the input name contains a trailing slash, it is retained in
   the output sent to pOut except in the top-dir case mentioned
   above.

   Returns 0 on success, meaning that the value appended to pOut
   (if not NULL) is a syntactically valid checkout-relative path.

   Returns FSL_RC_RANGE if zOrigName points to a path outside
   of f's current checkout root.

   Returns FSL_RC_NOT_A_CKOUT if f has no checkout opened.

   Returns FSL_RC_MISUSE if !zOrigName, FSL_RC_OOM on an allocation
   error.

   This function does not validate whether or not the file actually
   exists, only that its name is potentially valid as a filename
   for use in a checkout (though other, downstream rules might prohibit that, e.g.
   the filename "..../...." is not valid but is not seen as invalid by
   this function). (Reminder to self: we could run the end result through
   fsl_is_simple_pathname() to catch that?)
*/
FSL_EXPORT int fsl_ckout_filename_check( fsl_cx * const f, bool relativeToCwd,
                                         char const * zOrigName, fsl_b * const pOut );

/**
   Convenience typedef and required forward decl.
 */
typedef struct fsl_ckout_manage_opt fsl_ckout_manage_opt;

/**
   State passed to fsl_ckout_manage_f() callback.
*/
struct fsl_ckout_manage_state {
  /**
     The fsl_cx instance for the correspnding fsl_ckout_manage()
     call.
  */
  fsl_cx * f;
  /**
     The options object passed to the corresponding call to
     fsl_ckout_manage(). This is provided primarily for access to
     its callbackState member. The client must never modify any state
     in this opt object other than the callbackState or to use other
     APIs of this->f.
  */
  fsl_ckout_manage_opt const * opt;
  /**
     The name of the file being managed, relative to the root of the
     checkout. fsl_cx_stat2() can be used to transform it to an
     absolute path, if needed. Given a fsl_ckout_manage_state
     named `ms`, that call would look like:

     ```
     fsl_b_reuse(&yourBuffer);
     // ^^^ noting that fsl_cx_stat2() APPENDS to the buffer.
     int rc = fsl_cx_stat2(ms->f, false, ms->filename,
                           NULL, &yourBuffer, true);
     // ^^^ noting that the stat "should not" fail in this case
     // because fsl_ckout_manage() has validated that the file
     // exists.
     ```
  */
  char const * filename;
};

/**
   Convenience typedef.
*/
typedef struct fsl_ckout_manage_state fsl_ckout_manage_state;

/**
   Callback type for use with fsl_ckout_manage_opt(). It should
   inspect the given (`mst->filename`) using whatever criteria it likes, set
   *include to true or false to indicate whether the filename is okay
   to include the current add-file-to-repo operation, and return 0.

   If it returns non-0 the add-file-to-repo process will end and that
   error code will be reported to its caller. Such result codes must
   come from the FSL_RC_xxx family. They may report details of
   the error via fsl_cx_err_set() with the `mst->f` object.

   It will be passed a name which is relative to the top-most checkout
   directory.

   The final argument is not used by the library, but is passed on
   as-is from the fsl_ckout_manage_opt::callbackState pointer which
   is passed to fsl_ckout_manage().
*/
typedef int (*fsl_ckout_manage_f)(fsl_ckout_manage_state const *mst,
                                  bool *include);
/**
   Options for use with fsl_ckout_manage().
*/
struct fsl_ckout_manage_opt {
  /**
     The file or directory name to add. If it is a directory, the add
     process will recurse into it.

     Note that filenames need to be passed in their "proper" case for
     the current platform. fsl_filename_preferred_case() case be used
     to do that, but that functionality is not currently part of the
     fsl_ckout_manage() inner workings (that may change at some
     point). fsl_cx_is_case_sensitive() can be used to determine
     whether or not case-sensitivity is preferred for the current
     repository.
  */
  char const * filename;
  /**
     Whether to evaluate the given name as relative to the current working
     directory or to the current checkout root.

     This makes a subtle yet important difference in how the name is
     resolved. CLI apps which take file names from the user from
     within a checkout directory will generally want to set
     relativeToCwd to true. GUI apps, OTOH, will possibly need it to
     be false, depending on how they resolve and pass on the
     filenames.
  */
  bool relativeToCwd;
  /**
     Whether or not to check the name(s) against the 'ignore-globs'
     config setting (if set).
  */
  bool checkIgnoreGlobs;
  /**
     Optional predicate function which may be called for each
     to-be-added filename. It is only called if:

     - It is not NULL (obviously) and...

     - The file is not already in the checkout database and...

     - The is-internal-name check passes (see
     fsl_reserved_fn_check()) and...

     - If checkIgnoreGlobs is false or the name does not match one of
     the ignore-globs values and...

     - No part of the name's directory part is a symlink or other
     non-directory. As in fossil(1), such files are never added.

     The name it is passed is relative to the checkout root.

     Because the callback is called only if other options have not
     already excluded the file, the client may use the callback to
     report to the user (or otherwise record) exactly which files
     get added.
  */
  fsl_ckout_manage_f callback;

  /**
     State to be passed to this->callback.
  */
  void * callbackState;

  /**
     These counts are updated by fsl_ckout_manage() to report
     what it did.
  */
  struct {
    /**
       Number of files actually added by fsl_ckout_manage().
    */
    uint32_t added;
    /**
       Number of files which were requested to be added but were only
       updated because they had previously been added. An update
       un-deletes the vfile table entry and sets its mtime, but does
       not currently change its executable-bit or is-it-a-symlink
       state. A new entry records both. A symlink is added as a
       symlink if the allow-symlinks setting is on, else as the file
       it points to, as fossil(1) does.
    */
    uint32_t updated;
    /**
       The number of files skipped over for addition. This includes
       files which meet any of these criteria:

       - fsl_reserved_fn_check() fails.

       - If the checkIgnoreGlobs option is true and a filename matches
         any of those globs.

       - Part of the name's directory part is a symlink or other
         non-directory, e.g. "ld/f" where "ld" is a symlink to a
         directory.

       - The client-provided callback says not to include the file.
    */
    uint32_t skipped;
  } counts;
};
/**
   Initialized-with-defaults fsl_ckout_manage_opt instance,
   intended for use in const-copy initialization.
*/
#define fsl_ckout_manage_opt_empty_m {\
    NULL/*filename*/, true/*relativeToCwd*/, true/*checkIgnoreGlobs*/, \
    NULL/*callback*/, NULL/*callbackState*/,                         \
    {/*counts*/ 0/*added*/, 0/*updated*/, 0/*skipped*/}               \
  }
/**
   Initialized-with-defaults fsl_ckout_manage_opt instance,
   intended for use in non-const copy initialization.
*/
FSL_EXPORT const fsl_ckout_manage_opt fsl_ckout_manage_opt_empty;

/**
   Adds the given filename or directory (recursively) to the current
   checkout vfile list of files as a to-be-added file, or updates an
   existing record if one exists.

   This function ensures that opt->filename gets canonicalized and can
   be found under the checkout directory, and fails if no such file
   exists (checking against the canonicalized name). Filenames are all
   filtered through fsl_reserved_fn_check() and may have other filters
   applied to them, as determined by the options object.

   Each filename which passes through the filters is passed to
   the opt->callback (if not NULL), which may perform a final
   filtering check and/or alert the client about the file being
   queued.

   The options object is non-const because this routine updates
   opt->counts when it adds, updates, or skips a file. On each call,
   it updated opt->counts without resetting it (as this function is
   typically called in a loop). This function does not modify any
   other entries of that object and it requires that the object not be
   modified (e.g. via opt->callback()) while it is recursively
   processing. To reset the counts between calls, if needed:

   ```
   opt->counts = fsl_ckout_manage_opt_empty.counts;
   ```

   Returns 0 on success, non-0 on error.

   Files queued for addition this way can be unqueued before they are
   committed using fsl_ckout_unmanage().

   To avoid Significant Grief, this routine automatically skips any
   directories under opt->filename which appear to be fossil checkout
   roots unless that directory is f's current checkout directory, into
   which it will recurse normally.

   @see fsl_ckout_unmanage()
   @see fsl_reserved_fn_check()
*/
FSL_EXPORT int fsl_ckout_manage( fsl_cx * const f,
                                 fsl_ckout_manage_opt * const opt );

/**
   Convenience typedef and required forward decl.
 */
typedef struct fsl_ckout_unmanage_opt fsl_ckout_unmanage_opt;

/**
   State passed to fsl_ckout_unmanage_f() callback.
*/
struct fsl_ckout_unmanage_state {
  /**
     The fsl_cx instance for the correspnding fsl_ckout_unmanage()
     call.
  */
  fsl_cx * f;
  /**
     The options object passed to the corresponding call to
     fsl_ckout_unmanage(). This is provided primarily for access to
     its callbackState member. The client must never modify any state
     in this opt object other than the callbackState or to use other
     APIs of this->f.
  */
  fsl_ckout_unmanage_opt const * opt;
  /**
     The name of the file being unmanaged, relative to the root of the
     checkout. fsl_cx_stat2() can be used to transform it to an
     absolute path, if needed. Given a fsl_ckout_unmanage_state
     named `ums`, that call would look like:

     ```
     fsl_b_reuse(&yourBuffer);
     // ^^^ noting that fsl_cx_stat2() APPENDS to the buffer.
     int rc = fsl_cx_stat2(ums->f, false, ums->filename,
                           NULL, &yourBuffer, true);
     // ^^^ noting that the stat will legitimately and harmlessly
     // fail if the file does not exist, so this error can
     // normally be ignored.
     ```

     Without allow-symlinks, fsl_cx_stat2() follows a symlink, so it
     also fails for a dangling one. A client which wants to unlink
     the file should stat() the link itself instead.
  */
  char const * filename;
};

/** Convenience typedef. */
typedef struct fsl_ckout_unmanage_state fsl_ckout_unmanage_state;


/**
   Callback type for use with fsl_ckout_unmanage(). It is called
   by the removal process, immediately after a file is "removed"
   from SCM management (a.k.a. when the file becomes "unmanaged").

   If it returns non-0 the unmanage process will end and that error
   code will be reported to its caller. Such result codes must come
   from the FSL_RC_xxx family. They may report details of the error
   via fsl_cx_err_set() with the `ums->f` object.

   The object passed to it will hold the name of the file being
   unmanaged, relative to the top-most checkout directory. The client
   is free to unlink the file from the filesystem if they like - the
   library does not do so automatically
*/
typedef int (*fsl_ckout_unmanage_f)(fsl_ckout_unmanage_state const * ums);

/**
   Options for use with fsl_ckout_unmanage().
*/
struct fsl_ckout_unmanage_opt {
  /**
     The file or directory name to add. If it is a directory, the add
     process will recurse into it. See also this->vfileIds.
  */
  char const * filename;
  /**
     An alternative to assigning this->filename is to point
     this->vfileIds to a bag of vfile.id values. If this member is not
     NULL, fsl_ckout_unmanage() will ignore this->filename.

     @see fsl_filename_to_vfile_ids()
  */
  fsl_id_bag const * vfileIds;
  /**
     Whether to evaluate this->filename as relative to the current
     working directory (true) or to the current checkout root
     (false). This is ignored when this->vfileIds is not NULL.

     This makes a subtle yet important difference in how the name is
     resolved. CLI apps which take file names from the user from
     within a checkout directory will generally want to set
     relativeToCwd to true. GUI apps, OTOH, will possibly need it to
     be false, depending on how they resolve and pass on the
     filenames.
  */
  bool relativeToCwd;
  /**
     If true, fsl_vfile_changes_scan() is called to ensure that
     the filesystem and vfile tables agree. If the client code has
     called that function, or its equivalent, since any changes were
     made to the checkout then this may be set to false to speed up
     the rm process.
  */
  bool scanForChanges;
  /**
     Optional predicate function which will be called after each
     file is made unmanaged.

     The name it is passed is relative to the checkout root.
  */
  fsl_ckout_unmanage_f callback;
  /**
     State to be passed to this->callback.
  */
  void * callbackState;
};
/**
   Initialized-with-defaults fsl_ckout_unmanage_opt instance,
   intended for use in const-copy initialization.
*/
#define fsl_ckout_unmanage_opt_empty_m {\
    NULL/*filename*/, NULL/*vfileIds*/,\
    true/*relativeToCwd*/,true/*scanForChanges*/, \
    NULL/*callback*/, NULL/*callbackState*/ \
}
/**
   Initialized-with-defaults fsl_ckout_unmanage_opt instance,
   intended for use in non-const copy initialization.
*/
FSL_EXPORT const fsl_ckout_unmanage_opt fsl_ckout_unmanage_opt_empty;

/**
   The converse of fsl_ckout_manage(), this queues a file for removal
   from the current checkout. Unlike fsl_ckout_manage(), this routine
   does not ensure that opt->filename actually exists - it only
   normalizes zFilename into its repository-friendly form and passes
   it through the vfile table.

   If opt->filename refers to a directory then this operation queues
   all files under that directory (recursively) for removal. In this
   case, it is irrelevant whether or not opt->filename ends in a
   trailing slash.

   Returns 0 on success, any of a number of non-0 codes on error.
   Returns FSL_RC_MISUSE if !opt->filename or !*opt->filename.
   Returns FSL_RC_NOT_A_CKOUT if f has no opened checkout.

   If opt->callback is not NULL, it is called for each
   newly-unamanaged entry. The intention is to provide it the
   opportunity to notify the user, record the filename for later use,
   remove the file from the filesystem, etc. If it returns non-0, the
   unmanaging process will fail with that code and any pending
   transaction will be placed into a rollback state.

   This routine does not actually remove any files from the
   filesystem, it only modifies the vfile table entry so that the
   file(s) will be removed from the SCM by the commit process. If
   opt->filename is an entry which was previously
   fsl_ckout_manage()'d, but not yet committed, or any such entries
   are found under directory opt->filename, they are removed from the
   vfile table. i.e. this effective undoes the add operation.

   @see fsl_ckout_manage()
*/
FSL_EXPORT int fsl_ckout_unmanage( fsl_cx * f,
                                  fsl_ckout_unmanage_opt const * opt );

/**
   Hard-coded range of values of the vfile.chnged db field.
   These values are part of the fossil schema and must not
   be modified.
*/
enum fsl_vfile_change_e {
  /** File is unchanged. */
  FSL_VFILE_CHANGE_NONE = 0,
  /** File edit. */
  FSL_VFILE_CHANGE_MOD = 1,
  /** File changed due to a merge. */
  FSL_VFILE_CHANGE_MERGE_MOD = 2,
  /** File added by a merge. */
  FSL_VFILE_CHANGE_MERGE_ADD = 3,
  /** File changed due to an integrate merge. */
  FSL_VFILE_CHANGE_INTEGRATE_MOD = 4,
  /** File added by an integrate merge. */
  FSL_VFILE_CHANGE_INTEGRATE_ADD = 5,
  /** File became executable but has unmodified contents. */
  FSL_VFILE_CHANGE_IS_EXEC = 6,
  /** File became a symlink whose target equals its old contents. */
  FSL_VFILE_CHANGE_BECAME_SYMLINK = 7,
  /** File lost executable status but has unmodified contents. */
  FSL_VFILE_CHANGE_NOT_EXEC = 8,
  /** File lost symlink status and has contents equal to its old target. */
  FSL_VFILE_CHANGE_NOT_SYMLINK = 9
};
typedef enum fsl_vfile_change_e fsl_vfile_change_e;

/**
   Change-type flags for use with fsl_ckout_changes_visit() and
   friends.

   TODO: consolidate this with fsl_vfile_change_e insofar as possible.
   There are a few checkout change statuses not reflected in
   fsl_vfile_change_e.
*/
enum fsl_ckout_change_e {
/**
   Sentinel placeholder value.
*/
FSL_CKOUT_CHANGE_NONE = 0,
/**
   Indicates that a file was modified in some unspecified way.
*/
FSL_CKOUT_CHANGE_MOD = FSL_VFILE_CHANGE_MOD,
/**
   Indicates that a file was modified as the result of a merge.
*/
FSL_CKOUT_CHANGE_MERGE_MOD = FSL_VFILE_CHANGE_MERGE_MOD,
/**
   Indicates that a file was added as the result of a merge.
*/
FSL_CKOUT_CHANGE_MERGE_ADD = FSL_VFILE_CHANGE_MERGE_ADD,
/**
   Indicates that a file was modified as the result of an
   integrate-merge.
*/
FSL_CKOUT_CHANGE_INTEGRATE_MOD = FSL_VFILE_CHANGE_INTEGRATE_MOD,
/**
   Indicates that a file was added as the result of an
   integrate-merge.
*/
FSL_CKOUT_CHANGE_INTEGRATE_ADD = FSL_VFILE_CHANGE_INTEGRATE_ADD,
/**
   Indicates that the file gained the is-executable trait
   but is otherwise unmodified.
*/
FSL_CKOUT_CHANGE_IS_EXEC = FSL_VFILE_CHANGE_IS_EXEC,
/**
   Indicates that the file has changed to a symlink.
*/
FSL_CKOUT_CHANGE_BECAME_SYMLINK = FSL_VFILE_CHANGE_BECAME_SYMLINK,
/**
   Indicates that the file lost the is-executable trait
   but is otherwise unmodified.
*/
FSL_CKOUT_CHANGE_NOT_EXEC = FSL_VFILE_CHANGE_NOT_EXEC,
/**
   Indicates that the file was previously a symlink but is
   now a plain file.
*/
FSL_CKOUT_CHANGE_NOT_SYMLINK = FSL_VFILE_CHANGE_NOT_SYMLINK,
/**
   Indicates that a file was added.
*/
FSL_CKOUT_CHANGE_ADDED = FSL_CKOUT_CHANGE_NOT_SYMLINK + 1000,
/**
   Indicates that a file was removed from SCM management.
*/
FSL_CKOUT_CHANGE_REMOVED,
/**
   Indicates that a file is missing from the local checkout.
*/
FSL_CKOUT_CHANGE_MISSING,
/**
   Indicates that a file was renamed.
*/
FSL_CKOUT_CHANGE_RENAMED,
/**
   Indicates that the name of a managed file exists in the local
   checkout but is neither a file nor a symlink, e.g. it is a
   directory. With the allow-symlinks setting off, a symlink to a
   directory falls into this category. A dangling symlink is
   reported as FSL_CKOUT_CHANGE_MISSING. This corresponds to
   fossil(1)'s NOT_A_FILE status.
*/
FSL_CKOUT_CHANGE_NOT_A_FILE
};

typedef enum fsl_ckout_change_e fsl_ckout_change_e;

/**
   This is equivalent to calling fsl_vfile_changes_scan() with the
   arguments (f, -1, 0).

   @see fsl_ckout_changes_visit()
   @see fsl_vfile_changes_scan()
*/
FSL_EXPORT int fsl_ckout_changes_scan(fsl_cx * f);

/**
   A typedef for visitors of checkout status information via
   fsl_ckout_changes_visit(). Implementions will receive the
   last argument passed to fsl_ckout_changes_visit() as their
   first argument. The second argument indicates the type of change
   and the third holds the repository-relative name of the file.

   If changes is FSL_CKOUT_CHANGE_RENAMED then origName will hold
   the original name, else it will be NULL.

   Implementations must return 0 on success, non-zero on error. On
   error any looping performed by fsl_ckout_changes_visit() will
   stop and this function's result code will be returned.

   @see fsl_ckout_changes_visit()
*/
typedef int (*fsl_ckout_changes_f)(void * state, fsl_ckout_change_e change,
                                      char const * filename,
                                      char const * origName);

/**
   Compares the changes of f's local checkout against repository
   version vid (checkout version if vid is negative). For each
   change detected it calls visitor(state,...) to report the
   change.  If visitor() returns non-0, that code is returned from
   this function. If doChangeScan is true then
   fsl_ckout_changes_scan() is called by this function before
   iterating, otherwise it is assumed that the caller has called
   that or has otherwise ensured that the checkout db's vfile table
   has been populated.

   If the callback returns FSL_RC_BREAK, this function stops iteration
   and returns 0.

   Returns 0 on success.

   @see fsl_ckout_changes_scan()
*/
FSL_EXPORT int fsl_ckout_changes_visit( fsl_cx * f, fsl_id_t vid,
                                           bool doChangeScan,
                                           fsl_ckout_changes_f visitor,
                                           void * state );
/**
   A bitmask of flags for fsl_vfile_changes_scan().
*/
enum fsl_ckout_sig_e {
/**
   The empty flags set.
*/
FSL_VFILE_CKSIG_NONE = 0,

/**
   Non-file/non-link FS objects trigger an error.
*/
FSL_VFILE_CKSIG_ENOTFILE = 0x001,
/**
   Verify file content using hashing, regardless of whether or not
   file timestamps differ.
*/
FSL_VFILE_CKSIG_HASH = 0x002,
/**
   For unchanged or changed-by-merge files, set the mtime to last
   check-out time, as determined by fsl_mtime_of_manifest_file().
*/
FSL_VFILE_CKSIG_SETMTIME = 0x004,
/**
   Indicates that when populating the vfile table, it should be not be
   cleared of entries for other checkins. Normally we want to clear
   all versions except for the one we're working with, but at least
   a couple of use cases call for having multiple versions in vfile at
   once. Many algorithms generally assume only a single checkin's
   worth of state is in vfile and can get confused if that is not the
   case.
*/
FSL_VFILE_CKSIG_KEEP_OTHERS = 0x008,
/**
   If set and fsl_vfile_changes_scan() is passed a version other than
   the pre-call checkout version, it will, when finished, write the
   given version in the "checkout" setting of the ckout.vvar table,
   effectively switching the checkout to that version. It does not do
   this by default because it is sometimes necessary to have two
   versions in the vfile table at once and the operation doing so
   needs to control which version number is the current checkout.
*/
FSL_VFILE_CKSIG_WRITE_CKOUT_VERSION = 0x010
};

/**
    This function populates (if needed) the vfile table of f's
    checkout db for the given checkin version ID then compares files
    listed in it against files in the checkout directory, updating
    vfile's status for the current checkout version id as its goes. If
    vid is<=0 then the current checkout's RID is used in its place
    (note that 0 is the RID of an initial empty repository!).

    cksigFlags must be 0 or a bitmask of fsl_ckout_sig_e values.

    This is a relatively memory- and filesystem-intensive operation,
    and should not be performed more often than necessary. Many SCM
    algorithms rely on its state being correct, however, so it's
    generally better to err on the side of running it once too often
    rather than once too few times.

    Returns 0 on success, non-0 on error.

    BUG: this does not properly catch one particular corner-case
    change, where a file has been replaced by a same-named non-file
    (symlink or directory).
*/
FSL_EXPORT int fsl_vfile_changes_scan(fsl_cx * const f, fsl_id_t vid,
                                      unsigned cksigFlags);

/**
   If f has an opened checkout which has local changes noted in its
   checkout db state (the vfile table), returns true, else returns
   false. Note that this function does not do the filesystem scan to
   check for changes, but checks only the db state. Use
   fsl_vfile_changes_scan() to perform the actual scan (noting that
   library-side APIs which update that state may also record
   individual changes or automatically run a scan).
*/
FSL_EXPORT bool fsl_ckout_has_changes(fsl_cx * const f);

/**
   Callback type for use with fsl_checkin_queue_opt for alerting a
   client about exactly which files get enqueued/dequeued via
   fsl_checkin_enqueue() and fsl_checkin_dequeue().

   This function gets passed the checkout-relative name of the file
   being enqueued/dequeued and the client-provided state pointer which
   was passed to the relevant API. It must return 0 on success. If it
   returns non-0, the API on whose behalf this callback is invoked
   will propagate that error code back to the caller.

   The intent of this callback is simply to report changes to the
   client, not to perform validation. Thus such callbacks "really
   should not fail" unless, e.g., they encounter an OOM condition or
   some such. Any validation required by the client should be
   performed before calling fsl_checkin_enqueue()
   resp. fsl_checkin_dequeue().
*/
typedef int (*fsl_checkin_queue_f)(const char * filename, void * state);

/**
   Options object type used by fsl_checkin_enqueue() and
   fsl_checkin_dequeue().
*/
struct fsl_checkin_queue_opt {
  /**
     File or directory name to enqueue/dequeue to/from a pending
     checkin.
  */
  char const * filename;
  /**
     If true, filename (if not absolute) is interpreted as relative to
     the current working directory, else it is assumed to be relative
     to the top of the current checkout directory.
  */
  bool relativeToCwd;

  /**
     If not NULL then this->filename and this->relativeToCwd are
     IGNORED and any to-queue filename(s) is/are added from this
     container. It is an error (FSL_RC_MISUSE) to pass an empty bag.
     (Should that be FSL_RC_RANGE instead?)

     The bag is assumed to contain values from the vfile.id checkout
     db field, refering to one or more files which should be queued
     for the pending checkin. It is okay to pass IDs for unmodified
     files or to queue the same files multiple times. Unmodified files
     may be enqueued but will be ignored by the checkin process if, at
     the time the checkin is processed, they are still unmodified.
     Duplicated entries are simply ignored for the 2nd and subsequent
     inclusion.

     @see fsl_ckout_vfile_ids()
  */
  fsl_id_bag const * vfileIds;

  /**
     If true, fsl_vfile_changes_scan() is called to ensure that the
     filesystem and vfile tables agree. If the client code has called
     that function, or its equivalent, since any changes were made to
     the checkout then this may be set to false to speed up the
     enqueue process. This is only used by fsl_checkin_enqueue(), not
     fsl_checkin_dequeue().
  */
  bool scanForChanges;

  /**
     If true, only flagged-as-modified files will be enqueued by
     fsl_checkin_enqueue(). By and large, this should be set to
     true. Setting this to false is generally only intended/useful for
     testing.
  */
  bool onlyModifiedFiles;

  /**
     It not NULL, is pass passed the checkout-relative filename of
     each enqueued/dequeued file and this->callbackState. See the
     callback type's docs for more details.
  */
  fsl_checkin_queue_f callback;

  /**
     Opaque client-side state for use as the 2nd argument to
     this->callback.
  */
  void * callbackState;

  /* TODO (2023-02-02): any state necessary for indicating that this
     checking should be flagged as "private".
   */
};

/** Convenience typedef. */
typedef struct fsl_checkin_queue_opt fsl_checkin_queue_opt;

/** Initialized-with-defaults fsl_checkin_queue_opt structure, intended for
    const-copy initialization. */
#define fsl_checkin_queue_opt_empty_m { \
  NULL/*filename*/,true/*relativeToCwd*/,    \
  NULL/*vfileIds*/,                                 \
  true/*scanForChanges*/,true/*onlyModifiedFiles*/,   \
  NULL/*callback*/,NULL/*callbackState*/      \
}

/** Initialized-with-defaults fsl_checkin_queue_opt structure, intended for
    non-const copy initialization. */
extern const fsl_checkin_queue_opt fsl_checkin_queue_opt_empty;

/**
   Adds one or more files to f's list of "selected" files - those
   which should be included in the next commit (see
   fsl_checkin_commit()).

   Warning: if this function is not called before
   fsl_checkin_commit(), then fsl_checkin_commit() will select all
   modified, fsl_ckout_manage()'d, fsl_ckout_unmanage()'d, or renamed
   files by default.

   opt->filename must be a non-empty NUL-terminated string. The
   filename is canonicalized via fsl_ckout_filename_check() - see that
   function for the meaning of the opt->relativeToCwd parameter. To
   queue all modified files in a checkout, set opt->filename to ".",
   opt->relativeToCwd to false, and opt->onlyModifiedFiles to true.
   "Modified" includes any which are pending deletion, are
   newly-added, or for which a rename is pending.

   The resolved name must refer to either a single vfile.pathname
   value in the current vfile table or to a checkout-root-relative
   directory. All matching filenames which refer to modified files (as
   recorded in the vfile table) are queued up for the next commit.
   If opt->filename is NULL, empty, or ("." and opt->relativeToCwd is false)
   then all files in the vfile table are checked for changes.

   If opt->scanForChanges is true then fsl_vfile_changes_scan() is
   called before starting to ensure that the vfile entries are up to
   date. If the client app has "recently" run that (or its
   equivalent), that (slow) step can be skipped by setting
   opt->scanForChanges to false before calling this

   Note that after this returns, any given file may still be modified
   by the client before the commit takes place, and the changes on
   disk at the point of the fsl_checkin_commit() are the ones which
   get saved (or not).

   For each resolved entry which actually gets enqueued (i.e. was not
   already enqueued and which is marked as modified), opt->callback
   (if it is not NULL) is passed the checkout-relative file name and
   the opt->callbackState pointer.

   Returns 0 on success, FSL_RC_MISUSE if either pointer is NULL, or
   *zName is NUL. Returns FSL_RC_OOM on allocation error. It is not
   inherently an error for opt->filename to resolve to no queue-able
   entries. A client can check for that case, if needed, by assigning
   opt->callback and incrementing a counter in that callback. If the
   callback is never called, no queue-able entries were found.

   On error f's error state might (depending on the nature of the
   problem) contain more details.

   @see fsl_checkin_is_enqueued()
   @see fsl_checkin_dequeue()
   @see fsl_checkin_discard()
   @see fsl_checkin_commit()
*/
FSL_EXPORT int fsl_checkin_enqueue(fsl_cx * f,
                                   fsl_checkin_queue_opt const * opt);

/**
   The opposite of fsl_checkin_enqueue(), this opt->filename,
   which may resolve to a single name or a directory, from the checkin
   queue. Returns 0 on succes. This function does no validation on
   whether a given file(s) actually exist(s), it simply asks the
   internals to clean up matching strings from the checkout's vfile
   table. Specifically, it does not return an error if this operation
   finds no entries to dequeue.

   If opt->filename is empty or NULL then ALL files are unqueued from
   the pending checkin.

   If opt->relativeToCwd is true (non-0) then opt->filename is
   resolved based on the current directory, otherwise it is resolved
   based on the checkout's root directory.

   If opt->filename is not NULL or empty, this functions runs the
   given path through fsl_ckout_filename_check() and will fail if that
   function fails, propagating any error from that function. Ergo,
   opt->filename must refer to a path within the current checkout.

   @see fsl_checkin_enqueue()
   @see fsl_checkin_is_enqueued()
   @see fsl_checkin_discard()
   @see fsl_checkin_commit()
*/
FSL_EXPORT int fsl_checkin_dequeue(fsl_cx * const f,
                                   fsl_checkin_queue_opt const * opt);

/**
   Returns true if the file named by zName is in f's current file
   checkin queue. If NO files are in the current selection queue then
   this routine assumes that ALL files are implicitely selected. As
   long as at least one file is enqueued (via fsl_checkin_enqueue())
   then this function only returns true for files which have been
   explicitly enqueued.

   If relativeToCwd then zName is resolved based on the current
   directory, otherwise it assumed to be related to the checkout's
   root directory.

   This function returning true does not necessarily indicate that
   the file _will_ be checked in at the next commit. If the file has
   not been modified at commit-time then it will not be part of the
   commit.

   This function honors the fsl_cx_is_case_sensitive() setting
   when comparing names.

   Achtung: this does not resolve directory names like
   fsl_checkin_enqueue() and fsl_checkin_dequeue() do. It
   only works with file names.

   Results are undefined if f is NULL.

   @see fsl_checkin_enqueue()
   @see fsl_checkin_dequeue()
   @see fsl_checkin_discard()
   @see fsl_checkin_commit()
*/
FSL_EXPORT bool fsl_checkin_is_enqueued(fsl_cx * const f,
                                        char const * zName,
                                        bool relativeToCwd);

/**
   Discards any state accumulated for a pending checking,
   including any files queued via fsl_checkin_enqueue()
   and tags added via fsl_checkin_T_add().

   @see fsl_checkin_enqueue()
   @see fsl_checkin_dequeue()
   @see fsl_checkin_is_enqueued()
   @see fsl_checkin_commit()
   @see fsl_checkin_T_add()
*/
FSL_EXPORT void fsl_checkin_discard(fsl_cx * const f);

/**
   Parameters for fsl_checkin_commit().

   Checkins are created in a multi-step process:

   - fsl_checkin_enqueue() queues up a file or directory for
   commit at the next commit.

   - fsl_checkin_dequeue() removes an entry, allowing
   UIs to toggle files in and out of a checkin before
   committing it.

   - fsl_checkin_is_enqueued() can be used to determine whether
   a given name is already enqueued or not.

   - fsl_checkin_T_add() can be used to T-cards (tags) to a
   deck. Branch tags are intended to be applied via the
   fsl_checkin_opt::branch member.

   - fsl_checkin_discard() can be used to cancel any pending file
   enqueuings, effectively cancelling a commit (which can be
   re-started by enqueuing another file).

   - fsl_checkin_commit() creates a checkin for the list of enqueued
   files (defaulting to all modified files in the checkout!). It
   takes an object of this type to specify a variety of parameters
   for the check.

   Note that this API uses the terms "enqueue" and "unqueue" rather
   than "add" and "remove" because those both have very specific
   (and much different) meanings in the overall SCM scheme.
*/
struct fsl_checkin_opt {
  /**
     The commit message. May not be empty - the library
     forbids empty checkin messages. It must be valid UTF-8:
     fsl_checkin_commit() fails with FSL_RC_RANGE otherwise.
  */
  char const * message;

  /**
     The optional mime type for the message. Only set
     this if you know what you're doing.
  */
  char const * messageMimeType;

  /**
     The user name for the checkin. If NULL or empty, it defaults to
     fsl_cx_user_get(). If that is NULL, a FSL_RC_RANGE error is
     triggered.
  */
  char const * user;

  /**
     If not NULL, makes the checkin the start of a new branch with
     this name.
  */
  char const * branch;

  /**
     If this->branch is not NULL, this is applied as its "bgcolor"
     propagating property. If this->branch is NULL then this is
     applied as a one-time color tag to the checkin.

     It must be NULL, empty, or in a form usable by HTML/CSS,
     preferably \#RRGGBB form. Length-0 values are ignored (as if
     they were NULL).
  */
  char const * bgColor;

  /**
     If true, the checkin will be marked as private, otherwise it
     will be marked as private or public, depending on whether or
     not it inherits private content.
  */
  bool isPrivate;

  /**
     Whether or not to calculate an R-card. Doing so is very
     expensive (memory and I/O) but it adds another layer of
     consistency checking to manifest files. In practice, the R-card
     is somewhat superfluous and the cost of calculating it has
     proven painful on very large repositories. fossil(1) creates an
     R-card for all checkins but does not require that one be set
     when it reads a manifest.
  */
  bool calcRCard;

  /**
     Tells the checkin to close merged-in branches (merge type of
     0). INTEGRATE merges (type=-4) are always closed by a
     checkin. This does not apply to CHERRYPICK (type=-1) and
     BACKOUT (type=-2) merges.
  */
  bool integrate;

  /**
     If true, allow a file to be checked in if it contains
     fossil-style merge conflict markers, else fail if an attempt is
     made to commit any files with such markers.
  */
  bool allowMergeConflict;

  /**
     A hint to fsl_checkin_commit() about whether it needs to scan the
     checkout for changes. Set this to false ONLY if the calling code
     calls fsl_ckout_changes_scan() (or equivalent,
     e.g. fsl_vfile_changes_scan()) immediately before calling
     fsl_checkin_commit(). fsl_checkin_commit() requires a non-stale
     changes scan in order to function properly, but it's a
     computationally slow operation so the checkin process does not
     want to duplicate it if the application has recently done so.
  */
  bool scanForChanges;

  /**
     NOT YET IMPLEMENTED! TODO!

     If true, files which are removed from the SCM by this checkin
     should be removed from the filesystem.

     Reminder to self: when we do this, incorporate
     fsl_rm_empty_dirs().
  */
  bool rmRemovedFiles;

  /**
     If true, the checkin's db savepoint is rolled back after it's
     complete, effectively meaning that the checkin does not take
     place (but all of the work involved happens). This unfortunately
     has to put any pending transactions into pending-rollback mode,
     too, because of $REASONS.
  */
  bool dryRun;

  /**
     Warning: use of delta manifests is not recommended by Fossil's
     current (2026) primary maintainers, and has not been for many
     years.

     Whether to allow (or try to force) a delta manifest or not. 0
     means no deltas allowed - it will not generate a baseline
     manifest. Greater than 0 forces generation of a delta if
     possible (if one can be readily found) even if doing so would not
     save a notable amount of space. Less than 0 means to
     decide via some heuristics.

     A "readily available" baseline means either the current checkout
     is a baseline or has a baseline. In either case, we can use that
     as a baseline for a delta. i.e. a baseline "should" generally be
     available except on the initial checkin, which has neither a
     parent checkin nor a baseline.

     The current behaviour for "auto-detect" mode is: it will generate
     a delta if a baseline is "readily available" _and_ the repository
     has at least one delta already. Once it calculates a delta form,
     it calculates whether that form saves any appreciable
     space/overhead compared to whether a baseline manifest was
     generated. If so, it discards the delta and re-generates the
     manifest as a baseline. The "force" behaviour (deltaPolicy>0)
     bypasses the "is it too big?" test, and is only intended for
     testing, not real-life use.

     Caveat: if the repository has the "forbid-delta-manifests" set to
     a true value, this option is ignored: that setting takes
     priority. Similarly, it will not create a delta in a repository
     unless a delta has been "seen" in that repository before or this
     policy is set to >0. When a checkin is created with a delta
     manifest, that fact gets recorded in the repository's config
     table.

     CAVEAT: delta manifests have some advantages and may not actually
     save much (if any) repository space because the lower-level delta
     framework already compresses parent versions of artifacts
     tightly. For more information see:

     https://fossil-scm.org/home/doc/tip/www/delta-manifests.md
  */
  int deltaPolicy;

  /**
     Time of the checkin. If 0 or less, the time of the
     fsl_checkin_commit() call is used.
  */
  double julianTime;

  /**
     If false, fsl_checkin_commit() fails with FSL_RC_RANGE if the
     check-in's time (see julianTime) is earlier than that of its
     parent or of any merge parent, as fossil(1) commit does without
     --allow-older. If true, it allows that check-in.
  */
  bool allowOlder;

  /**
     If this is not NULL then the committed manifest will include a
     tag which closes the branch. The value of this string will be
     the value of the "closed" tag, and the value may be an empty
     string. The intention is that this gets set to a comment about
     why the branch is closed, but it is in no way mandatory.
  */
  char const * closeBranch;

  /**
     Tells fsl_checkin_commit() to dump the generated manifest to
     this file. Intended only for debugging and testing. Checking in
     will fail if this file cannot be opened for writing.
  */
  char const * dumpManifestFile;
  /*
    fossil(1) has many more options. We might want to wrap some of
    it up in the "incremental" state (f->ckin.mf).

    TODOs:

    A callback mechanism which supports the user cancelling
    the checkin. It is (potentially) needed for ops like
    confirming the commit of CRNL-only changes.

    2021-03-09: we now have fsl_confirmer for this but currently no
    part of the checkin code needs a prompt.
  */
};

/**
   Empty-initialized fsl_checkin_opt instance, intended for use in
   const-copy constructing.
*/
#define fsl_checkin_opt_empty_m {               \
  .message = NULL,                            \
  .messageMimeType = NULL,                  \
  .user = NULL,                             \
  .branch = NULL,                           \
  .bgColor = NULL,                          \
  .isPrivate = false,                           \
  .calcRCard = true,                           \
  .integrate = false,                           \
  .allowMergeConflict = false,\
  .scanForChanges = true,\
  .rmRemovedFiles = false,\
  .dryRun = false, \
  .deltaPolicy = 0,                        \
  .julianTime = 0.0,                        \
  .allowOlder = false,                      \
  .closeBranch = NULL,                      \
  .dumpManifestFile = NULL               \
}

/**
   Empty-initialized fsl_checkin_opt instance, intended for use in
   copy-constructing. It is important that clients copy this value
   (or fsl_checkin_opt_empty_m) to cleanly initialize their
   fsl_checkin_opt instances, as this may set default values which
   (e.g.) a memset() would not.
*/
FSL_EXPORT const fsl_checkin_opt fsl_checkin_opt_empty;

/**
   This creates and saves a "checkin manifest" for the current
   checkout.

   Its primary inputs is a list of files to commit. This list is
   provided by the client by calling fsl_checkin_enqueue() one or
   more times.  If no files are explicitely selected (enqueued) then
   it calculates which local files have changed vs the current
   checkout and selects all of those.

   Non-file inputs are provided via the opt parameter.

   As in fossil(1), except on Windows, the permissions (executable
   bit or symlink) of each selected file are taken from the
   filesystem. Those of unselected files, and on Windows those of all
   files, are carried over from the current checkout version. With
   the allow-symlinks setting on (fsl_cx_allows_symlinks()), a
   symlink is committed as a symlink, its content being the name it
   points to, and is not checked for merge conflict markers. With the
   setting off, a symlink is followed and committed as the file it
   points to.

   On success, it returns 0 and...

   - If newRid is not NULL, it is assigned the new checkin's RID
   value.

   - If newUuid is not NULL, it is assigned the new checkin's UUID
   value. Ownership of the bytes is passed to the caller, who must
   eventually pass them to fsl_free() to free them.

   Note that the new RID and UUID can also be fetched afterwards by
   calling fsl_ckout_version_info().

   On error non-0 is returned and f's error state may (depending on
   the nature of the problem) contain details about the problem.
   Note, however, that any error codes returned here may have arrived
   from several layers down in the internals, and may not have a
   single specific interpretation here. When possible/practical, f's
   error state gets updated with a human-readable description of the
   problem.

   opt->dryRun: does not work properly, at least partially due to
   stale internal caches.

   ACHTUNG: all pending checkin state is cleared by this function
   unless it fails basic argument validation. This means any queued
   files or tags need to be re-applied if the client wants to try
   again. That is somewhat of a bummer, but this behaviour is the only
   way we can ensure that then the pending checkin state does not get
   garbled on a second use. When in doubt about the state, the client
   should call fsl_checkin_discard() to clear it before try to
   re-commit. (Potential TODO: add a success/fail state flag to the
   checkin state and only clean up on success? OTOH, since something
   in the state likely caused the problem, we might not want to do
   that.)

   Some of the more notable, potentially not obvious, error
   conditions:

   - Trying to commit against a closed leaf: FSL_RC_ACCESS. Doing so
   is not permitted by fossil(1), so we disallow it here.

   - An empty/NULL user name or commit message: FSL_RC_MISSING_INFO.
   In these cases f's error state describes the problem.

   - Only some of the files changed by a pending merge are enqueued:
   FSL_RC_MISUSE.

   - Some resource is not found (e.g. an expected RID/UUID could not
   be resolved): FSL_RC_NOT_FOUND. This would generally indicate
   some sort of data consistency problem. i.e. it's quite possibly
   very bad if this is returned.

   - If no enqueued file actually changed, or the checkin would
   result in no file-level changes vis-a-vis the current checkout,
   FSL_RC_NOOP is returned.

   BUGS:

   - It cannot currently properly distinguish a "no-op" commit, one in
   which no files were modified or only their permissions were
   modifed.

   TODO:

   - Honor the opt->dryRun flag. Getting this working has proven tricky
     because of stale cache issues.

   @see fsl_checkin_enqueue()
   @see fsl_checkin_dequeue()
   @see fsl_checkin_discard()
   @see fsl_checkin_T_add()
*/
FSL_EXPORT int fsl_checkin_commit(fsl_cx * f, fsl_checkin_opt const * opt,
                                  fsl_id_t * newRid, fsl_uuid_str * newUuid);

/**
   Works like fsl_deck_T_add(), adding the given tag information to
   the pending checkin state. Returns 0 on success, non-0 on error. A
   checkin may, in principal, have any number of tags, and this may be
   called any number of times to add new tags to the pending
   commit. This list of tags gets cleared by a successful
   fsl_checkin_commit() or by fsl_checkin_discard(). Decks require
   that each tag be distinct from each other (none may compare
   equivalent), but that check is delayed until the deck is output
   into its final artifact form.

   @see fsl_checkin_enqueue()
   @see fsl_checkin_dequeue()
   @see fsl_checkin_commit()
   @see fsl_checkin_discard()
   @see fsl_checkin_T_add2()
*/
FSL_EXPORT int fsl_checkin_T_add( fsl_cx * f, fsl_tagtype_e tagType,
                                   fsl_uuid_cstr uuid, char const * name,
                                   char const * value);

/**
   Works identically to fsl_checkin_T_add() except that it takes its
   argument in the form of a T-card object.

   On success ownership of t is passed to mf. On error (see
   fsl_deck_T_add()) ownership is not modified.

   Results are undefined if either argument is NULL or improperly
   initialized.
*/
FSL_EXPORT int fsl_checkin_T_add2( fsl_cx * f, fsl_card_T * t );

/**
   Clears all contents from f's checkout database, including the vfile
   table, vmerge table, and some of the vvar table. The tables are
   left intact. Returns 0 on success, non-0 if f has no checkout or for
   a database error.
*/
FSL_EXPORT int fsl_ckout_clear_db(fsl_cx *f);

/**
   Returns the base name of the current platform's checkout database
   file. That is "_FOSSIL_" on Windows and ".fslckout" everywhere
   else. The returned bytes are static.

   TODO: an API which takes a dir name and looks for either name
*/
FSL_EXPORT char const *fsl_preferred_ckout_db_name(void);

/**
   File-overwrite policy values for use with fsl_ckup_opt and friends.
*/
enum fsl_file_overwrite_policy_e {
/** Indicates that an error should be triggered if a file would be
    overwritten. */
FSL_OVERWRITE_ERROR = 0,
/**
   Indicates that files should always be overwritten.
*/
FSL_OVERWRITE_ALWAYS,
/**
   Indicates that files should never be overwritten, and silently
   skipped over. This is almost never what one wants to do.
*/
FSL_OVERWRITE_NEVER
};
typedef enum fsl_file_overwrite_policy_e fsl_file_overwrite_policy_e;

/**
   State values for use with fsl_ckup_state::fileRmInfo.
*/
enum fsl_ckup_rm_state_e {
/**
   Indicates that the file was not removed in a given checkout.
   Guaranteed to have the value 0 so that it is treated as boolean
   false. No other entries in this enum have well-defined values.
*/
FSL_CKUP_RM_NOT = 0,
/**
   Indicates that a file was removed from a checkout but kept
   in the filesystem because it was locally modified.
*/
FSL_CKUP_RM_KEPT,
/**
   Indicates that a file was removed from a checkout and the
   filesystem, with the caveat that failed attempts to remove from the
   filesystem are ignored for Reasons but will be reported as if the
   unlink worked.
*/
FSL_CKUP_RM
};
typedef enum fsl_ckup_rm_state_e fsl_ckup_rm_state_e;

/**
  Under construction. Work in progress...

  Options for "opening" a fossil repository database. That is,
  creating a new fossil checkout database and populating its schema,
  _without_ checking out any files. (That latter part is up for
  reconsideration and this API might change in the future to check
  out files after creating/opening the db.)
*/
struct fsl_repo_open_ckout_opt {
  /**
     Name of the target directory, which must already exist (in the
     context's checkout storage, if one is installed: see
     fsl_cx_ckout_fs()). May be relative to the current directory,
     e.g. ".". May be NULL, in which case the current directory is
     assumed. The current directory is not changed.
  */
  char const * targetDir;

  /**
     The filename, with no directory components, of the desired
     checkout db name, which is resolved relative to targetDir. An
     absolute name is used as is. For the time being, always leave this NULL and
     let the library decide. It "might" (but probably won't) be
     interesting at some point to allow the client to specify a
     different name (noting that that would be directly incompatible
     with fossil(1)).
  */
  char const * ckoutDbFile;

  /**
     Policy for how to handle overwrites of files extracted from a
     newly-opened checkout.

     Potential TODO: replace this with a fsl_confirmer, though that
     currently seems like overkill for this particular case.
  */
  fsl_file_overwrite_policy_e fileOverwritePolicy;

  /**
     fsl_repo_open_ckout() installs the fossil checkout schema. If
     this is true it will forcibly replace any existing relevant
     schema components in the checkout db, otherwise it will fail when
     it tries to overwrite an existing schema and cannot.
  */
  bool dbOverwritePolicy;

  /**
     If true, the checkout-open process will look for an opened
     checkout in the target directory and its parents (recursively)
     and fail with FSL_RC_ALREADY_EXISTS if one is found.
  */
  bool checkForOpenedCkout;

  /**
     If not NULL, the checkout's tables (vvar, vfile, vmerge, stash,
     stashfile, the fsl_undo tables, ...) are not kept in a checkout
     db of their own but are tables of the host's main db whose names
     start with this prefix, e.g. "fslwc_work_" makes
     main.fslwc_work_vfile. Nothing is ATTACHed for the checkout, and
     the host's own tables, including any named like checkout tables
     without the prefix, are not touched. This lets one host db hold
     several working copies, each with a prefix of its own, alongside
     the host's own tables.

     Only for a context bound to a host db handle (fsl_cx_host_db())
     whose repository is opened, and whose main db is a file, so that
     a check-in commits to it and the repository together. Otherwise
     fsl_repo_open_ckout() fails with FSL_RC_MISUSE resp.
     FSL_RC_UNSUPPORTED. ckoutDbFile must then be NULL. The prefix
     must match [A-Za-z_][A-Za-z0-9_]*, so that the prefixed names are
     identifiers without quoting, and must not start with "sqlite_"
     (in any case), else FSL_RC_RANGE.

     The prefix is the working copy's namespace: since some checkout
     table names end in others (fsl_undo_vfile, old_stash), and some
     tables (the stash's and undo's) are only created when first used,
     a prefix may neither be the start of another working copy's or a
     repository's (fsl_repo_open_host()) nor start with one, ignoring
     case (FSL_RC_ALREADY_EXISTS). That holds for the prefixes of other
     contexts on the same handle, for that of this context's
     repository, and for those of the working copies and repositories
     recorded in the main db (each P for which it has tables Pvfile and
     Pvvar, the latter with a 'ckout-root' row, resp. Pblob and Pconfig,
     the latter with a 'content-schema' row).

     If the main db has this prefix's vvar table, the working copy is
     reopened. Its vfile and vmerge tables must exist (else
     FSL_RC_CONSISTENCY), it must belong to this repository by
     project-code, and its version's rid must have the hash it recorded
     there, which a clone (the same project-code, other rids) need not
     (else FSL_RC_REPO_MISMATCH; a repository which was moved reopens,
     and its new file name is recorded, the only write of a reopen),
     and targetDir must be its directory, compared with symbolic links
     resolved and, where file names are case-insensitive
     (fsl_cx_is_case_sensitive()), without regard to case (else
     FSL_RC_MISUSE). targetDir need not be
     empty, nothing is created, and the checkout's state (its version,
     ignore lists, ...) is loaded as for fsl_ckout_open_dir().
     Otherwise a new working copy is created, in one transaction which
     holds the main db's write lock from before its checks, and the
     main db may then have no table, index or trigger whose name
     starts with the prefix (ignoring case), else
     FSL_RC_ALREADY_EXISTS: so it never adopts or drops a table of the
     host's or of another working copy. Its vvar records the
     repository's file name ("repository"; for a repository in the
     host db, see fsl_repo_open_host()) and project-code
     ("project-code") and the checkout's directory ("ckout-root").
     dbOverwritePolicy must be false (else FSL_RC_MISUSE): to start a
     working copy afresh, drop its tables first.

     The checkout's directory is targetDir as given (it is not derived
     from a db file's name), which must exist in the checkout's
     storage (fsl_cx_ckout_fs()). fsl_cx_db_file_ckout() then returns
     the main db's file name, and that file and its -journal, -wal and
     -shm files, however they are spelled through symbolic links, are
     reserved names (fsl_reserved_fn_check()). The main
     db's settings are left as they are: its application_id is not
     set, and its journal mode is not changed. If the repository's
     tables are in the same db (fsl_repo_open_host()), a check-in
     needs no particular journal mode. If the repository is a
     separate db, a check-in fails unless the main db uses a rollback
     journal mode with synchronous on, because SQLite would not commit
     the two dbs together. Closing the checkout drops none of the
     tables.

     The schema's REFERENCES clauses name the prefixed tables, but
     foreign keys are not enforced: libfossil requires PRAGMA
     foreign_keys=OFF on a host's handle.
  */
  char const * hostTablePrefix;
};
typedef struct fsl_repo_open_ckout_opt fsl_repo_open_ckout_opt;

/**
  Empty-initialized fsl_repo_open_ckout_opt const-copy constructer.
*/
#define fsl_repo_open_ckout_opt_m { \
  NULL/*targetDir*/, NULL/*ckoutDbFile*/, \
  FSL_OVERWRITE_ERROR/*fileOverwritePolicy*/, \
  false/*dbOverwritePolicy*/,               \
  -1/*checkForOpenedCkout*/,             \
  NULL/*hostTablePrefix*/                \
}

/**
  Empty-initialised fsl_repo_open_ckout_opt instance. Clients should copy
  this value (or fsl_repo_open_ckout_opt_empty_m) to initialise
  fsl_repo_open_ckout_opt instances for sane default values.
*/
FSL_EXPORT const fsl_repo_open_ckout_opt fsl_repo_open_ckout_opt_empty;

/**
   Opens a checkout db for use with the currently-connected repository
   or creates a new checkout db. If opening an existing one, it gets
   "stolen" from any repository it might have been previously mapped
   to.

   - Requires that f have an opened repository db and no opened
     checkout. Returns FSL_RC_NOT_A_REPO if no repo is opened and
     FSL_RC_MISUSE if a checkout *is* opened.

   - Creates/re-uses a .fslckout DB in the dir opt->targetDir. The
     directory must be NULL or already exist, else FSL_RC_NOT_FOUND is
     returned. If opt->dbOverwritePolicy is false then it fails with
     FSL_RC_ALREADY_EXISTS if that directory already contains a
     checkout db.

   Note that this does not extract any SCM'd files from the
   repository, it only opens (and possibly creates) the checkout
   database.

   Pending:

   - If opening an existing checkout db for a different repo then
   delete the STASH and UNDO entries, as they're not valid for a
   different repo.
*/
FSL_EXPORT int fsl_repo_open_ckout( fsl_cx * const f,
                                    fsl_repo_open_ckout_opt const * opt );

typedef struct fsl_ckup_state fsl_ckup_state;
/**
   A callback type for use with fsl_ckup_state.  It gets called via
   fsl_repo_ckout() and fsl_ckout_update() to report progress of the
   extraction process. It gets called after one of those functions has
   successfully extracted a file or skipped over it because the file
   existed and the checkout options specified to leave existing files
   in place. It must return 0 on success, and non-0 will end the
   extraction process, propagating that result code back to the
   caller. If this callback fails, the checkout's contents may be left
   in an undefined state, with some files updated and others not.  All
   database-side data will be consistent (the transaction is rolled
   back) but filesystem-side changes may not be.
*/
typedef int (*fsl_ckup_f)( fsl_ckup_state const * cState );

/**
   This enum lists the various types of individual file change states
   which can happen during a checkout, update, or merge.
*/
enum fsl_ckup_fchange_e {
/** Sentinel value. */
FSL_CKUP_FCHANGE_INVALID = -1,
/** Was unchanged between the previous and updated-to version,
    so no change was made to the on-disk file. This is the
    only entry in the enum which is guaranteed to have a specific
    value: 0, so that it can be used as a boolean false. */
FSL_CKUP_FCHANGE_NONE = 0,
/**
   Added to SCM in the updated-to version.
*/
FSL_CKUP_FCHANGE_ADDED,
/**
   Added to SCM in the current checkout version and carried over into
   the updated-to version.
*/
FSL_CKUP_FCHANGE_ADD_PROPAGATED,
/**
   Removed from SCM in the updated-to to version OR in the checked-out
   version but not yet committed. a.k.a. it became "unmanaged."

   Do we need to differentiate between those cases?
*/
FSL_CKUP_FCHANGE_RM,
/**
   Removed from the checked-out version but not yet commited,
   so was carried over to the updated-to version.
*/
FSL_CKUP_FCHANGE_RM_PROPAGATED,
/** Updated or replaced without a merge by the checkout/update
    process. */
FSL_CKUP_FCHANGE_UPDATED,
/** Merge was not performed because at least one of the inputs appears
    to be binary. The updated-to version overwrites the previous
    version in this case.
*/
FSL_CKUP_FCHANGE_UPDATED_BINARY,
/** Updated with a merge by the update process. */
FSL_CKUP_FCHANGE_MERGED,
/** Special case of FSL_CKUP_FCHANGE_MERGED. Merge was performed
    and conflicts were detected. The newly-updated file will contain
    conflict markers.

    @see fsl_b_contains_merge_marker()
*/
FSL_CKUP_FCHANGE_CONFLICT_MERGED,
/** Added in the current checkout but also contained in the
    updated-to version. The local copy takes precedence.
*/
FSL_CKUP_FCHANGE_CONFLICT_ADDED,
/**
   Added by the updated-to version but a local unmanaged copy exists.
   The local copy is overwritten, per historical fossil(1) convention
   (noting that fossil has undo support to allow one to avoid loss of
   such a file's contents).

   TODO: use confirmer here to ask user whether to overwrite.
*/
FSL_CKUP_FCHANGE_CONFLICT_ADDED_UNMANAGED,
/** Edited locally but removed from updated-to version. Local
    edits will be left in the checkout tree. */
FSL_CKUP_FCHANGE_CONFLICT_RM,
/** Cannot merge if one or both of the update/updating verions of a
    file is a symlink. The updated-to version overwrites the previous
    version in this case.

    We probably need a better name for this.
*/
FSL_CKUP_FCHANGE_CONFLICT_SYMLINK,
/**
   Indicates that a merge of binary content was requested.

   TODO: figure out why UPDATE uses the target version, instead of
   triggering an error here, and why MERGE does not do the same.
   fossil(1) simply skips over, with a warning, binaries during a
   merge.
*/
FSL_CKUP_FCHANGE_CONFLICT_BINARY,
/** File was renamed in the updated-to version. If a file is both
    modified and renamed, it is flagged as renamed instead
    of modified. */
FSL_CKUP_FCHANGE_RENAMED,
/** Locally modified. This state appears only when
    "updating" a checkout to the same version. */
FSL_CKUP_FCHANGE_EDITED
};
typedef enum fsl_ckup_fchange_e fsl_ckup_fchange_e;

/**
   State to be passed to fsl_ckup_f() implementations via
   calls to fsl_repo_ckout() and fsl_ckout_update().
*/
struct fsl_ckup_state {
  /**
     The core SCM state for the just-extracted file. Note that its
     content member will be NULL: the content is not passed on via
     this interface because it is only loaded for files which require
     overwriting.

     An update process may synthesize content for extractState->fCard
     which do not 100% reflect the file on disk. Of primary note here:

     1) fCard->uuid will refer to the hash of the updated-to
     version, as opposed to the hash of the on-disk file (which may
     differ due to having local edits merged in). 

     2) For the update process, fCard->priorName will be NULL unless
     the file was renamed between the original and updated-to
     versions, in which case priorName will refer to the original
     version's name.
  */
  fsl_repo_extract_state const * extractState;
  /**
     Optional client-dependent state for use in the fsl_ckup_f()
     callback. This is copies from the corresponding
     fsl_ckup_opt::callbackState member.
  */
  void * callbackState;

  /**
     Vaguely describes the type of change the current call into
     the fsl_ckup_f() represents. The full range of values is
     not valid for all operations. Specifically:

     Checkout only uses:

     FSL_CKUP_FCHANGE_NONE
     FSL_CKUP_FCHANGE_UPDATED
     FSL_CKUP_FCHANGE_RM

     For update operations all (or most) values are potentially
     possible.

     If this has a value of FSL_CKUP_FCHANGE_RM,
     this->fileRmInfo will provide a bit more detail.
  */
  fsl_ckup_fchange_e fileChangeType;

  /**
     Indicates whether the file was removed by the process:

     - FSL_CKUP_RM_NOT = Was not removed.

     - FSL_CKUP_RM_KEPT = Was removed from the checked-out version but
     left in the filesystem because the confirmer said to.

     - FSL_CKUP_RM = Was removed from the checkout and the filesystem.

     When this->dryRun is true, this specifies whether the file would
     have been removed.
  */
  fsl_ckup_rm_state_e fileRmInfo;

  /**
     If fsl_repo_ckout()'s or fsl_ckout_update()'s options specified
     that the mtime should be set on each updated file, this holds
     that time. If the file existed and was not overwritten, it is set
     to that file's time. Else it is set to the current time (which
     may differ by a small fraction of a second from the file-write
     time because we avoid stat()'ing it again after writing). If
     this->fileRmInfo indicates that a file was removed, this might
     (depending on availability of the file in the filesystem at the
     time) be set to 0.

     When running in dry-run mode, this value may be 0, as we may not
     have a file in place which we can stat() to get it, nor a db
     entry from which to fetch it.

     This option is ignored for merge operations.
  */
  fsl_time_t mtime;

  /**
     The size of the extracted file, in bytes. If the file was removed
     from the filesystem (or removal was at least attempted) then this
     is set to -1.
  */
  fsl_int_t size;

  /**
     True if the current checkout/update is running in dry-run mode,
     else false. See fsl_ckup_opt::dryRun for details.
  */
  bool dryRun;
};

/**
   Options for use with fsl_repo_ckout() and
   fsl_ckout_update(). i.e. for checkout and update.
*/
struct fsl_ckup_opt {
  /**
     The version of the repostitory to check out or update. This must
     be the blob.rid of a checkin artifact.
  */
  fsl_id_t checkinRid;

  /**
     Gets called once per checked-out or updated file, passed a
     fsl_ckup_state instance with information about the
     checked-out file and related metadata. May be NULL.
  */
  fsl_ckup_f callback;

  /**
     State to be passed to this->callback via the
     fsl_ckup_state::callbackState member.
   */
  void * callbackState;

  /**
     An optional "confirmer" for answering questions about file
     overwrites and deletions posed by the checkout process.
     By default this confirmer of the associated fsl_cx instance
     is used.

     Caveats:

     - This is not currently used by the update process, only
     checkout.

     - If this->setMTime is true, the mtime is NOT set for any files
     which already exist and are skipped due to the confirmer saying
     to leave them in place.

     - Similarly, if the confirmer says to never overwrite files,
     permissions on existing files are not modified. fsl_repo_ckout()
     does not (re)write unmodified files, and thus may leave such
     files with different permissions. That's on the to-fix list.
  */
  fsl_confirmer confirmer;

  /**
     If true, the checkout/update processes will calculate the
     (synthetic) mtime of each extracted file and set its mtime. This
     is a relatively expensive operation which calculates the
     "effective mtime" of each file by calculating it: Fossil does not
     record file timestamps, instead treating files as if they had the
     timestamp of the most recent checkin in which they were added or
     modified.

     It's generally a good idea to let the update process stamp the
     _current_ time on modified files, in order to avoid any hiccups
     with build processes which rely on accurate times
     (e.g. Makefiles). When doing a clean checkout, it's often
     interesting to see the "original" times, though.
  */
  bool setMtime;

  /**
     A hint to fsl_repo_ckout() and fsl_ckout_update() about whether
     it needs to scan the checkout for changes. Set this to false ONLY
     if the calling code calls fsl_ckout_changes_scan() (or
     equivalent, e.g. fsl_vfile_changes_scan()) immediately before
     calling fsl_repo_ckout() or fsl_ckout_update(), as those require
     a non-stale changes scan in order to function properly.
  */
  bool scanForChanges;

  /**
     If true, the extraction process will "go through the motions" but
     will not write any files to disk. It will perform I/O such as
     stat()'ing to see, e.g., if it would have needed to overwrite a
     file.
  */
  bool dryRun;
};
typedef struct fsl_ckup_opt fsl_ckup_opt;

/**
  Empty-initialized fsl_ckup_opt const-copy constructor.
*/
#define fsl_ckup_opt_m {\
  -1/*checkinRid*/, NULL/*callback*/, NULL/*callbackState*/,  \
  fsl_confirmer_empty_m/*confirmer*/,\
  false/*setMtime*/, true/*scanForChanges*/,false/*dryRun*/ \
}

/**
  Empty-initialised fsl_ckup_opt instance. Clients should copy
  this value (or fsl_ckup_opt_empty_m) to initialise
  fsl_ckup_opt instances for sane default values.
*/
FSL_EXPORT const fsl_ckup_opt fsl_ckup_opt_empty;

/**
   A fsl_repo_extract() proxy which extracts the contents of the
   repository version specified by opt->checkinRid to the root
   directory of f's currently-opened checkout. i.e. it performs a
   "checkout" operation.

   For each extracted entry, cOpt->callback (if not NULL) will be
   passed a (fsl_ckup_state const*) which contains a pointer
   to the fsl_repo_extract_state and some additional metadata
   regarding the extraction. The value of cOpt->callbackState will be
   set as the callbackState member of that fsl_ckup_state
   struct, so that the client has a way of passing around app-specific
   state to that callback.

   After successful completion, the process will report (see below)
   any files which were part of the previous checkout version but are
   not part of the current version, optionally removing them from the
   filesystem (depending on the value of opt->rmMissingPolicy). It
   will IGNORE ANY DELETION FAILURE of files it attempts to
   delete. The reason it does not fail on removal error is because
   doing so would require rolling back the transaction, effectively
   undoing the checkout, but it cannot roll back any prior deletions
   which succeeded. Similarly, after all file removal is complete, it
   attempts to remove any now-empty directories left over by that
   process, also silently ignoring any errors. If the cOpt->dryRun
   option is specified, it will "go through the motions" of removing
   files but will not actually attempt filesystem removal. For
   purposes of the callback, however, it will report deletions as
   having happened (but will also set the dryRun flag on the object
   passed to the callback).

   After unpacking the SCM-side files, it may write out one or more
   manifest files, as described for fsl_ckout_manifest_write(), if the
   'manifest' config setting says to do so.

   As part of the file-removal process, AFTER all "existing" files are
   processed, it calls cOpt->callback() (if not NULL) for each removed
   file, noting the following peculiarities in the
   fsl_ckup_state object which is passed to it for those
   calls:

   - It is called after the processing of "existing" files. Thus the
   file names passed during this step may appear "out of order" with
   regards to the others (which are guaranteed to be passed in lexical
   order, though whether it is case-sensitive or not depends on the
   repository's case-sensitivity setting).

   - fileRmInfo will indicate that the file was removed from the
   checkout, and whether it was actually removed or retained in the
   filesystem. This will indicate filesystem-level removal even when
   in dry-run mode, though in that case no filesystem-level removal is
   actually attempted.

   - extractState->fileRid will refer to the file's blob's RID for the
   previous checkout version.

   - extractState->content will be NULL.

   - extractState->callbackState will be NULL.

   - extractState->fCard will refer to the pre-removal state of the
   file. i.e. the state as it was in the checkout prior to this
   function being called.

   Returns 0 on success. Returns FSL_RC_NOT_A_REPO if f has no opened
   repo, FSL_RC_NOT_A_CKOUT if no checkout is opened. If
   cOpt->callback is not NULL and returns a non-0 result code,
   extraction ends and that result is returned. If it returns non-0 at
   any point after basic argument validation, it rolls back all
   changes or sets the current transaction stack into a rollback
   state.

   @see fsl_repo_open_ckout()
*/
FSL_EXPORT int fsl_repo_ckout(fsl_cx * f, fsl_ckup_opt const * cOpt);


/**
   UNDER CONSTRUCTION.

   Performs an "update" operation on f's currenly-opened
   checkout. Performing an update is similar to performing a checkout,
   the primary difference being that an update will merge local file
   modifications into any newly-updated files, whereas a checkout will
   overwrite them.

   TODO?: fossil(1)'s update permits a list of files, in which case it
   behaves differently: it updates the given files to the version
   requested but leaves the checkout at its current version. To be
   able to implement that we either need clients to call this in a
   loop, changing opt->filename on each call (like how we do
   fsl_ckout_manage()) or we need a way for them to pass on the list
   of files/dir in the opt object.

   @see fsl_repo_ckout().
*/
FSL_EXPORT int fsl_ckout_update(fsl_cx * f, fsl_ckup_opt const *opt);


/**
   Tries to calculate a version to update the current checkout version
   to, preferring the tip of the current checkout's branch.

   On success, 0 is returned and *outRid is set to the calculated RID,
   which may be 0, indicating that no errors were encountered but no
   version could be calculated.

   On error, non-0 is returned, outRid is not modified, and f's error
   state is updated.

   Returns FSL_RC_NOT_A_CKOUT if f has no checkout opened and
   FSL_RC_NOT_A_REPO if no repo is opened.

   If it calculates that there are multiple viable descendants it
   returns FSL_RC_AMBIGUOUS and f's error state will contain a list of
   the UUIDs (or UUID prefixes) of those descendants.

   Sidebar: to get the absolute latest version, irrespective of the
   branch, use fsl_sym_to_rid() to resolve the symbolic name "tip".
*/
FSL_EXPORT int fsl_ckout_calc_update_version(fsl_cx * f, fsl_id_t * outRid);

/**
   Bitmask used by fsl_ckout_manifest_setting() and
   fsl_ckout_manifest_write().
*/
enum fsl_cx_manifest_mask_e {
/** Coresponds to the file "manifest". */
FSL_MANIFEST_MAIN = 0x001,
/** Coresponds to the file "manifest.uuid". */
FSL_MANIFEST_UUID = 0x010,
/** Coresponds to the file "manifest.tags". */
FSL_MANIFEST_TAGS = 0x100
};
typedef enum fsl_cx_manifest_mask_e fsl_cx_manifest_mask_e;

/**
   Returns a bitmask representing which manifest files, if any, will
   be written when opening or updating a checkout directory, as
   specified by the repository's 'manifest' configuration setting, and
   sets *m to a bitmask indicating which of those are enabled. It
   first checks for a versioned setting then, if no versioned setting
   is found, a repository-level setting.

   A truthy setting value (1, "on", "true") means to write the
   manifest and manifest.uuid files. A string with any of the letters
   'r', 'u', or 't' means to write the [r]aw, [u]uid, and/or [t]ags
   file(s), respectively.

   If the manifest setting is falsy or not set, *m is set to 0, else
   *m is set to a bitmask representing which file(s) are considered to
   be auto-generated for this repository:

   - FSL_MANIFEST_MAIN = manifest
   - FSL_MANIFEST_UUID = manifest.uuid
   - FSL_MANIFEST_TAGS = manifest.tags

   Any db-related or allocation errors while trying to fetch the
   setting are silently ignored.

   For performance's sake, since this is potentially called often from
   fsl_reserved_fn_check(), this setting is currently cached by this
   routine (in the fsl_cx object), but that ignores the fact that the
   manifest setting can be modified at any time, either in a versioned
   setting file or the repository db, and may be modified from outside
   the library. There's a tiny back-door for working around that: if m
   is NULL, the cache will be flushed and no other work will be
   performed. Thus the following approach can be used to force a fresh
   check for that setting:

   ```
   fsl_ckout_manifest_setting(f, NULL); // clears caches, does nothing else
   fsl_ckout_manifest_setting(f, &myInt); // loads/caches the setting
   ```
*/
FSL_EXPORT void fsl_ckout_manifest_setting(fsl_cx *f, int *m);

/**
   Might write out the files manifest, manifest.uuid, and/or
   manifest.tags for the current checkout to the the checkout's root
   directory. The 2nd-4th arguments are interpreted as follows:

   0: Do not write that file.

   >0: Always write that file.

   <0: Use the value of the "manifest" config setting (see
   fsl_ckout_manifest_setting()) to determine whether or not to write
   that file.

   As each file is written, its mtime is set to that of the checkout
   version. (Forewarning: that behaviour may change if it proves to be
   problematic vis a vis build processes.)

   Returns 0 on success, non-0 on error:

   - FSL_RC_NOT_A_CKOUT if no checkout is opened.

   - FSL_RC_RANGE if the current checkout RID is 0 (indicating a fresh,
   empty repository).

   - Various potential DB/IO-related error codes.

   If the final argument is not NULL then it will be updated to
   contain a bitmask representing which files, if any, were written:
   see fsl_ckout_manifest_setting() for the values. It is updated
   regardless of success or failure and will indicate which file(s)
   was/were written before the error was triggered.

   Each file implied by the various manifest settings which is NOT
   written by this routine and is also not part of the current
   checkout (i.e. not listed in the vfile table) will be removed from
   disk, but a failure while attempting to do so will be silently
   ignored.

   @see fsl_repo_manifest_write()
*/
FSL_EXPORT int fsl_ckout_manifest_write(fsl_cx * const f,
                                        int manifest,
                                        int manifestUuid,
                                        int manifestTags,
                                        int * const wroteWhat );

/**
   Returns true if f has an opened checkout and the given absolute
   path is rooted in that checkout, else false. As a special case, it
   returns false if the path _is_ the checkout root unless zAbsPath
   has a trailing slash. (The checkout root is always stored with a
   trailing slash because that simplifies its internal usage.)

   Note that this is strictly a string comparison, not a
   filesystem-level operation.
*/
FSL_EXPORT bool fsl_is_rooted_in_ckout(fsl_cx * const f, char const * const zAbsPath);

/**
   Works like fsl_is_rooted_in_ckout() except that it returns 0 on
   success, and on error updates f with a description of the problem
   and returns non-0: FSL_RC_RANGE or (if updating the error state
   fails) FSL_RC_OOM.
 */
FSL_EXPORT int fsl_is_rooted_in_ckout2(fsl_cx * const f, char const * const zAbsPath);

/**
   Change-type values for use with fsl_ckout_revert_f() callbacks.
*/
enum fsl_ckout_revert_e {
/** Sentinel value. */
FSL_REVERT_NONE = 0,
/**
   File was previously queued for addition but unqueued
   by the revert process.
*/
FSL_REVERT_UNMANAGE,
/**
   File was previously queued for removal but unqueued by the revert
   process. If the file's contents or permissions were also reverted
   then the file is reported as FSL_REVERT_PERMISSIONS or
   FSL_REVERT_CONTENTS instead.
*/
FSL_REVERT_REMOVE,
/**
   File was previously scheduled to be renamed, but the rename was
   reverted. The name reported to the callback is the original one.
   If a file was both modified and renamed, it will be flagged as
   renamed instead of modified, for consistency with the usage of
   fsl_ckup_fchange_e's FSL_CKUP_FCHANGE_RENAMED.

   FIXME: this does not mean that the file on disk was actually
   renamed (if needed). That is TODO, pending addition of code to
   perform renames.
*/
FSL_REVERT_RENAME,
/** File's permissions (only) were reverted. */
FSL_REVERT_PERMISSIONS,
/**
   File's contents reverted. This value trumps any others in this
   enum. Thus if a file's permissions and contents were reverted,
   or it was un-renamed and its contents reverted, it will be
   reported using this enum entry.
*/
FSL_REVERT_CONTENTS
};
typedef enum fsl_ckout_revert_e fsl_ckout_revert_e;
/**
   Callback type for use with fsl_ckout_revert(). For each reverted
   file it gets passed the checkout-relative filename, type of change,
   and the callback state pointer which was passed to
   fsl_ckout_revert(). If it returns non-0, the revert process will
   end in an error and that code will be propagated back to the
   caller.  In such cases, any files reverted up until that point will
   still be reverted on disk but the reversion in the database will be
   rolled back. A change scan (e.g. fsl_ckout_changes_scan()) will
   restore balance to that equation, but these callbacks should only
   return non-0 in for catastrophic failure.
*/
typedef int (*fsl_ckout_revert_f)( char const *zFilename,
                                   fsl_ckout_revert_e changeType,
                                   void * callbackState );

/**
   Options for passing to fsl_ckout_revert().
*/
struct fsl_ckout_revert_opt {
  /**
     File or directory name to revert. See also this->vfileIds.
  */
  char const * filename;
  /**
     An alternative to assigning this->filename is to point
     this->vfileIds to a bag of vfile.id values. If this member is not
     NULL, fsl_ckout_revert() will ignore this->filename.

     @see fsl_filename_to_vfile_ids()
  */
  fsl_id_bag const * vfileIds;
  /**
     Interpret filename as relative to cwd if true, else relative to
     the current checkout root. This is ignored when this->vfileIds is
     not NULL.
  */
  bool relativeToCwd;
  /**
     If true, fsl_vfile_changes_scan() is called to ensure that
     the filesystem and vfile tables agree. If the client code has
     called that function, or its equivalent, since any changes were
     made to the checkout then this may be set to false to speed up
     the revert process.
  */
  bool scanForChanges;

  /**
     Optional callback to notify the client of what gets reverted.
  */
  fsl_ckout_revert_f callback;
  /**
     State for this->callback.
  */
  void * callbackState;
};
typedef struct fsl_ckout_revert_opt fsl_ckout_revert_opt;
/**
   Initialized-with-defaults fsl_ckout_revert_opt instance,
   intended for use in const-copy initialization.
*/
#define fsl_ckout_revert_opt_empty_m { \
  NULL/*filename*/,NULL/*vfileIds*/,true/*relativeToCwd*/,true/*scanForChanges*/, \
  NULL/*callback*/,NULL/*callbackState*/      \
}
/**
   Initialized-with-defaults fsl_ckout_revert_opt instance,
   intended for use in non-const copy initialization.
*/
FSL_EXPORT const fsl_ckout_revert_opt fsl_ckout_revert_opt_empty;

/**
   Reverts changes to checked-out files, replacing their
   on-disk versions with the current checkout's version.

   If zFilename refers to a directory, all managed files under that
   directory are reverted (if modified). If zFilename is NULL or
   empty, all modifications in the current checkout are reverted.

   If a file has been added but not yet committed, the add
   is un-queued but the file is otherwise untouched. If the
   file has been queued for removal, this removes it from
   that queue as well as restores its contents.

   If a rename is pending for the given filename, the name may match
   either its original name or new name. Whether or not that will
   actually work when file A is renamed to B and file C is renamed to
   A is anyone's guess. (Noting that (fossil mv) won't allow that
   situation to exist in the vfile table for a single checkout
   version, so it seems safe enough.)

   If the 4th argument is not NULL then it is called for each revert
   (_after_ the revert happens) to report what was done with that
   file. It gets passed the checkout-relative name of each reverted
   file. The 5th argument is not interpreted by this function but is
   passed on as-is as the final argument to the callback. If the
   callback returns non-0, the revert process is cancelled, any
   pending transaction is set to roll back, and that error code is
   returned. Note that cancelling a revert mid-process will leave file
   changes made by the revert so far in place, and thus the checkout
   db and filesystem will be in an inconsistent state until
   fsl_vfile_changes_scan() (or equivalent) is called to restore
   balance to the world.

   Files which are not actually reverted because their contents or
   permissions were not modified on disk are not reported to the
   callback unless the reversion was the un-queuing of an ADD or
   REMOVE operation.

   Returns 0 on success, any number of non-0 results on error.

   [tag:bug:revert-merge-hiccup] (2024-09-13): it is possible, via
   merging and copying modified files between multiple checkouts of
   the same repo, to get the tree into a state where this function has
   no files to revert and therefore does not clear the merge
   state. This condition is very tricky to trigger, and has only been
   seen once in the wild. "The problem" with fixing that is that
   whether or not we need to do a _full_ wipe of the merge state (as
   opposed to just wiping merge state of individual files) depends
   largely on information which (A) this function does have and (B) is
   onerous for the caller to figure out and provide (namely, whether
   it's a full revert or not). As this bug is so rare, we'll leave it
   for now and ponder potential solutions. As of 2024-09-13, this bug
   is believed to have been adequately resolved, but exactly how it
   was initially triggered is unclear, so we don't have a test which
   proves it is resolved.
*/
FSL_EXPORT int fsl_ckout_revert( fsl_cx * const f,
                                 fsl_ckout_revert_opt const * opt );

/**
   Expects f to have an opened checkout and zName to be the name of
   an entry in the vfile table where vfile.vid == vid. If vid<=0 then
   the current checkout RID is used. This function does not do any
   path resolution or normalization on zName and checks only for an
   exact match (honoring f's case-sensitivity setting - see
   fsl_cx_case_sensitive_set()).

   On success it returns 0 and assigns *vfid to the vfile.id value of
   the matching file.  If no match is found, 0 is returned and *vfile
   is set to 0. Returns FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_RANGE if zName is not a simple path (see
   fsl_is_simple_pathname()), and any number of codes for db-related
   errors.

   This function matches only vfile.pathname, not vfile.origname,
   because it is possible for a given name to be in both fields (in
   different records) at the same time.
*/
FSL_EXPORT int fsl_filename_to_vfile_id( fsl_cx * const f, fsl_id_t vid,
                                         char const * zName,
                                         fsl_id_t * const vfid );

/**
   Searches the `vfile` table where `vfile.vid=vid` for a name which
   matches `zName` or all `vfile` entries found under a subdirectory
   named `zName` (with no trailing slash). `zName` must be relative to
   the checkout root. As a special case, if `zName` is `NULL`, empty,
   or `"."` then all files in `vfile` with the given `vid` are
   selected. For each entry it finds, it adds the `vfile.id` to
   `dest`. If `vid<=0` then the current checkout RID is used.

   If `changedOnly` is `true` then only entries which have been marked
   in the `vfile` table as having some sort of change are included, so
   if `true` then fsl_ckout_changes_scan() (or equivalent) must have
   been "recently" called to ensure that state is up to do. This routine
   only checks the `vfile` table for "is changed" state, it does not
   do filesystem-level checks on the files.

   This search honors the context-level case-sensitivity setting (see
   fsl_cx_case_sensitive_set()).

   Returns 0 on success. Not finding anything is not treated as an
   error, though we could arguably return `FSL_RC_NOT_FOUND` for the
   cases which use this function. In order to determine whether or not
   any results were actually found, compare `dest->entryCount` before
   and after calling this.

   This function matches only `vfile.pathname`, not `vfile.origname`,
   because it is possible for a given name to be in both fields (in
   different records) at the same time.

   @see fsl_ckout_vfile_ids()
*/
FSL_EXPORT int fsl_filename_to_vfile_ids( fsl_cx * const f, fsl_id_t vid,
                                          fsl_id_bag * const dest,
                                          char const * zName,
                                          bool changedOnly);

/**
   This is a variant of fsl_filename_to_vfile_ids() which accepts
   filenames in a more flexible form than that routine. This routine
   works exactly like that one except for the following differences:

   1) The given filename and the relativeToCwd arguments are passed to
   by fsl_ckout_filename_check() to canonicalize the name and ensure
   that it points to someplace within f's current checkout.

   2) Directory names passed to it may optionally end in an trailing
   slash.

   3) Because of (1), zName may not be NULL or empty. To fetch all of
   the vfile IDs for the current checkout, pass a zName of "."  and
   relativeToCwd=false.

   Returns 0 on success, else:

   - FSL_RC_MISUSE if zName is NULL or empty.
   - FSL_RC_OOM on allocation error.
   - FSL_RC_NOT_A_CKOUT if f has no opened checkout.
   - FSL_RC_RANGE if the given name points outside of the checkout.
*/
FSL_EXPORT int fsl_ckout_vfile_ids( fsl_cx * const f, fsl_id_t vid,
                                    fsl_id_bag * const dest, char const * zName,
                                    bool relativeToCwd, bool changedOnly );


/**
   This "mostly internal" routine (re)populates f's checkout vfile
   table with all files from the given checkin manifest. If
   manifestRid is 0 or less then the current checkout's RID is
   used. If vfile already contains any content for the given checkin,
   it is left intact (and several processes rely on that behavior to
   keep it from nuking, e.g., as-yet-uncommitted queued add/rm
   entries).

   Returns 0 on success, any number of codes on any of many potential
   errors.

   f must not be NULL and must have opened checkout and repository
   databases. In debug builds it will assert that that is so.

   If the 3rd argument is true, any entries in vfile for checkin
   versions other than the one specified in the 2nd argument are
   cleared from the vfile table. That is _almost_ always the desired
   behavior, but there are rare cases where vfile needs to temporarily
   (for the duration of a single transaction) hold state for multiple
   versions.

   If the 4th argument is not NULL, it gets assigned the number of
   blobs from the given version which are currently missing from the
   repository due to being phantoms (as opposed to being shunned).

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_OOM on allocation error, FSL_RC_DB for db-related problems,
   et.al.

   Misc. notes:

   - This does NOT update the "checkout" vvar table entry because this
   routine is sometimes used in contexts where we need to briefly
   maintain two vfile versions and keep the previous checkout version.

   - Apps must take care to not leave more than one version in the
   vfile table for longer than absolutely needed. They "really should"
   use fsl_vfile_unload() to clear out any version they load with this
   routine.

   @see fsl_vfile_unload()
   @see fsl_vfile_unload_except()
*/
FSL_EXPORT int fsl_vfile_load(fsl_cx * const f, fsl_id_t manifestRid,
                              bool clearOtherVersions,
                              uint32_t * missingCount);

/**
   Clears out all entries in the current checkout's vfile table with
   the given vfile.vid value. If vid<=0 then the current checkout RID
   is used (which is never a good idea from client-side code!).

   ACHTUNG: never do this without understanding the consequences. It
   can ruin the current checkout state.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if f has no checkout
   opened, FSL_RC_DB on any sort of db-related error (in which case
   f's error state is updated with a description of the problem).

   @see fsl_vfile_load()
   @see fsl_vfile_unload_except()
*/
FSL_EXPORT int fsl_vfile_unload(fsl_cx * const f, fsl_id_t vid);

/**
   A counterpart of fsl_vfile_unload() which removes all vfile
   entries where vfile.vid is not the given vid. If vid is <=0 then
   the current checkout RID is used.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if f has no checkout
   opened, FSL_RC_DB on any sort of db-related error (in which case
   f's error state is updated with a description of the problem).

   @see fsl_vfile_load()
   @see fsl_vfile_unload()
*/
FSL_EXPORT int fsl_vfile_unload_except(fsl_cx * const f, fsl_id_t vid);


/**
   Performs a "fingerprint check" between f's current checkout and
   repository databases. Returns 0 if either there is no checkout, no
   mismatch, or it is impossible to determine because the checkout is
   missing a fingerprint (which is legal for "older" checkout
   databases).

   If a mismatch is found, FSL_RC_REPO_MISMATCH is returned. Returns
   some other non-0 code on a lower-level error (db access, OOM,
   etc.).

   As a special case, this is a no-op for a newly-created repo, as
   those cannot yet have a fingerprint.

   A mismatch can happen when the repository to which a checkout
   belongs is replaced, either with a completely different repository
   or a copy/clone of that same repository. Each repository copy may
   have differing blob.rid values, and those are what the checkout
   database uses to refer to repository-side data. If those RIDs
   change, then the checkout is left pointing to data other than what
   it should be.

   TODO: currently the library offers no automated recovery mechanism
   from a mismatch, the only remedy being to close the checkout
   database, destroy it, and re-create it. fossil(1) is able, in some cases,
   to automatically recover from this situation.
*/
FSL_EXPORT int fsl_ckout_fingerprint_check(fsl_cx * const f);

/**
   Looks for the given file in f's current checkout. If relativeToCwd
   then the name is resolved from the current directory, otherwise it is
   assumed to be relative to the checkout root or an absolute path
   with the checkout dir as a prefix of that path.

   On success, 0 is returned and dest's gets populated with the
   content of the file.

   On error, non-0 is returned and, depending on the error type, dest
   might be partially populated. f's error state will be updated to
   describe the error.

   Results are undefined if any pointer argument is NULL.

   This function currently resolves symlinks on its way to the
   content, but that behaviour may change in the future to reflect f's
   symlink preferences.
*/
FSL_EXPORT int fsl_ckout_file_content(fsl_cx * const f, bool relativeToCwd,
                                      char const * zName,
                                      fsl_b * const dest);

/**
   Fetches the timestamp of the given F-card's name against the
   filesystem and/or the most recent checkin in which it was modified
   (as reported by fsl_mtime_of_manifest()). vid is the checkin
   version to look at. If it's <=0, the current checkout will be used.

   On success, returns 0 and:

   - If repoMtime is not NULL then (*repoMtime) is assigned to the
   result of fsl_mtime_of_manifest_file() for the given file.

   - If localMtime is not NULL then (*localMtime) is assigned to
   the checkout-local timestamp of the file.

   Returns non-0 on error. Some of the potential results include:

   - FSL_RC_NOT_A_CKOUT.

   - FSL_RC_NOT_FOUND if the filename cannot be resolved in the
     requested version or cannot be stat()'d. This can happen if,
     e.g. fc's file has been renamed, but not yet checked in, in the
     current checkout. A _potential_ TODO is to check for a
     (`vfile.origname=fc->name`) record and use `vfile.pathname` for
     the stat() call.

   - FSL_RC_OOM.
*/
FSL_EXPORT int fsl_card_F_ckout_mtime(fsl_cx * const f, fsl_id_t vid,
                                      fsl_card_F const * const fc,
                                      fsl_time_t * const repoMtime,
                                      fsl_time_t * const localMtime);

/**
   File change types for use with fsl_merge_state::fileChangeType.

   Terminology used in some of the descriptions:

   - (P) is the "pivot" - the common ancestor for the merge.
   - (M) is the version being merged in to...
   - (V) is current checkout version into which (M) is being merged.

   Maintenance reminder: this enum's values must start at 0 and
   increment sequentially, and FSL_MERGE_FCHANGE_count must be the
   final entry. This is to enable the creation of arrays, e.g. for
   keeping track (client-side) of how many times a given change type
   has been seen during a given merge run.
*/
enum fsl_merge_fchange_e {
/**
    Not currently used. Merge does not (and cannot without some
    surgery) report state of files unaffected by a merge. This entry
    exists for the case that that changes. This is the only entry in
    the enum which is guaranteed to have a specific value: 0, so that
    it can be used as a boolean false. */
FSL_MERGE_FCHANGE_NONE = 0,
/**
   File was added to (V) from (M).
*/
FSL_MERGE_FCHANGE_ADDED,
/**
   File content was copied as-is from (M) to (V).
*/
FSL_MERGE_FCHANGE_COPIED,
/**
   File was removed from (V) via (M). a.k.a. it became "unmanaged."
*/
FSL_MERGE_FCHANGE_RM,
/**
   Content from (M) was merged into (V).
*/
FSL_MERGE_FCHANGE_MERGED,
/**
   Special case of FSL_MERGE_FCHANGE_MERGED. Merge was performed from
   (M) to (V) and conflicts were detected. The newly-updated file will
   contain conflict markers.

    @see fsl_b_contains_merge_marker()
*/
FSL_MERGE_FCHANGE_CONFLICT_MERGED,
#if 0
/** Added in the current checkout but also contained in the
    updated-to version. The local copy takes precedence.
*/
FSL_MERGE_FCHANGE_CONFLICT_ADDED,
#endif
/**
   Added to (V) by (M) but a local unmanaged copy exists.
   The local copy is overwritten, per historical fossil(1) convention
   (noting that fossil has undo support to allow one to avoid loss of
   such a file's contents).
*/
FSL_MERGE_FCHANGE_CONFLICT_ADDED_UNMANAGED,
#if 0
/*
  Fossil deletes merged-over removed files, regardless of whether
  they're locally edited, so we'll do the same for now (noting that
  fossil has undo support which can hypothetically save that case
  from data loss). fsl_ckout_update() does not do so, but has extra
  infastructure to deal with this. */
/** Edited locally but removed from merged-in version. Local
    edits will be left in the checkout tree. */
FSL_MERGE_FCHANGE_CONFLICT_RM,
#endif
/**
   Cannot merge if one or both of the update/updating versions of a
   file is a symlink.

   This case needs re-thinking. fossil(1) simply skips such merges
   with a warning but no error. This library has no warning mechanism
   other than to pass this code on to the fsl_merge_f() callback,
   so that's what we do.

   For UPDATE ops, the updated-to version overwrites the previous
   version in this case. Why merge doesn't do that isn't clear, but
   it's probably because we can have any number of merge parents and
   choosing which one to use in the merge/replace case would be
   impossible.
*/
FSL_MERGE_FCHANGE_CONFLICT_SYMLINK,
/**
   Indicates that a merge of binary content was requested. We
   cannot merge binaries, so this indicates that the file in question
   was skipped over for merge purposes.

   fossil(1) simply skips over, with a warning, binaries during a
   merge, so we do the same (for lack of a better option).
*/
FSL_MERGE_FCHANGE_CONFLICT_BINARY,
/**
   File was renamed in the updated-to version. If a file is both
   modified and renamed, it will be reported twice: once for each type
   of change. The new name is reported via fsl_merge_state::filename
   and the previous name via fsl_merge_state::priorName.
*/
FSL_MERGE_FCHANGE_RENAMED,
/**
   This is the number of entries in this enum, for purposes of creating,
   e.g. arrays of counters. This entry is never reported via a
   fsl_merge_state::fileChangeType.
*/
FSL_MERGE_FCHANGE_count
};
typedef enum fsl_merge_fchange_e fsl_merge_fchange_e;

/** Reqired forward decl. */
typedef struct fsl_merge_opt fsl_merge_opt;

/**
   UNDER CONSTRUCTION! INCOMPLETE!

   A type for passing state to fsl_merge_f callbacks during
   fsl_ckout_merge() processing.

   For each step of a merge operation which affects a file,
   state reflecting that change is set in one of these objects
   and it is passed to the fsl_merge_f implementation supplied by
   the caller.

   Unlike fsl_ckout_update(), fsl_ckout_merge() reports only files
   which are affected by a merge, not unmodified files.  Whether
   that's a bug or a feature is not yet clear, but the merge algorithm
   does not, as is, support reporting unaffected files.

   Due to the complexity and intricacy of the merge operation, it is
   possible that any given file will get passed to the fsl_merge_f()
   callback more than once with a different
   fsl_merge_state::fileChangeType value. Most notably, a file which
   has been modified and renamed may be passed on one with
   FSL_MERGE_FCHANGE_COPIED and once with FSL_MERGE_FCHANGE_RENAMED.
   Whether that's a bug or a feature is as-yet undecided, but
   (A) fossil(1) does it that way and (B) _not_ doing that would
   require some rearchitecting.
*/
struct fsl_merge_state {
  /**
     The fsl_cx object for which the current merge is running.
   */
  fsl_cx * f;
  /**
     The options object which drives the current fsl_ckout_merge()
     run.
  */
  fsl_merge_opt const * opt;

  /**
     The checkout-relative name of the file affected by the merge.
     These bytes are invalidated after the fsl_merge_f() callback
     returns, so must be copied if the client requires them for later.
  */
  char const * filename;

  /**
     If this->fileChangeType is FSL_MERGE_FCHANGE_RENAMED then
     this is the previous name of the file, else it is NULL.
  */
  char const * priorName;
  
  /**
     Indicates the state of the file currently being merged.  Merge
     does not support the full range fo fsl_ckup_fchange_e
     values. TODO: list which it does or create a new enum which
     enumerates only merge-specific change types.
  */
  fsl_merge_fchange_e fileChangeType;

  /**
     Indicates whether the current file was removed. A state of
     FSL_CKUP_RM_KEPT and fileChangeType of FSL_MERGE_FCHANGE_RM
     indicates that the file has become unmanaged but the local
     copy was retained because it was flagged as locally modified.
  */
  fsl_ckup_rm_state_e fileRmInfo;
};
typedef struct fsl_merge_state fsl_merge_state;

/**
   Callback type for use with fsl_merge_opt and fsl_ckout_merge().
*/
typedef int (*fsl_merge_f)(fsl_merge_state const * const);

/**
   Merge type enum for use with fsl_merge_opt::mergeType.

   The values of these entries are fossil-magic values for the
   `vmerge.id` db field and must stay in sync with fossil's
   definition.
*/
enum fsl_merge_type_e {
/**
   Indicates a normal merge.
*/
FSL_MERGE_TYPE_NORMAL = 0,
/**
   Indicates an "integrate" merge, which tells the next checkin
   operation to apply a "closed" tag to the checkin from which this
   merge is performed (effectively closing its branch).

   Certain merge-time state will force this merge type to silently
   behave like FSL_MERGE_TYPE_NORMAL:

   - If the being-merged-in content is marked as private.
   - If the being-merged-in content is not a leaf.
*/
FSL_MERGE_TYPE_INTEGRATE = -4,
/**
   Indicates a cherrypick merge, pulling in only the changes made to a
   specific checkin without otherwise inheriting its lineage.
*/
FSL_MERGE_TYPE_CHERRYPICK = -1,
/**
   Indicates a backout merge, a reverse cherrypick, backing out any
   changes which were added by the corresponding
   fsl_merge_opt::mergeRid.
*/
FSL_MERGE_TYPE_BACKOUT = -2
};
typedef enum fsl_merge_type_e fsl_merge_type_e;

/**
   UNDER CONSTRUCTION.

   Options for use with fsl_ckout_merge().
*/
struct fsl_merge_opt {
  /**
     The version of the repostitory to merge into the current
     checkout. This must be the `blob.rid` of a checkin artifact.
  */
  fsl_id_t mergeRid;
  /**
     The version of the most recent common ancestor. Must normally be
     0. The default is calculated automatically based on
     this->mergeRid and this->mergeType.

     This corresponds to fossil(1)'s `--baseline` merge flag.

     fsl_ckout_merge() will fail if this is >0 and it does not refer
     to a checkin version or if this->mergeType is
     FSL_MERGE_TYPE_CHERRYPICK.
  */
  fsl_id_t baselineRid;
  /**
     Specifies the merge type to perform. Certain merge-internal logic
     may override this. Specifically, integrate-merges may be treated
     as regular merges, as documented for FSL_MERGE_TYPE_INTEGRATE.
  */
  fsl_merge_type_e mergeType;
  /**
     Gets called once per merge-updated file, passed a fsl_ckup_state
     instance with information about the merged file and related
     metadata. May be NULL, in which case the merge process will do as
     much work as it can, even if that means doing certain
     questionable things (such as skipping updates of binary files or
     symlinks because it refuses to merge them). As a rule of thumb,
     if fossil(1) performs a given "questional" merge features without
     generating an error, fsl_ckout_merge() does as well. This
     callback gives clients a chance to decide that certain states
     _Simply Will Not Stand_ and cancel the merge by returning non-0
     (preferably after calling fsl_cx_err_set() on the passed-in
     fsl_merge_state::f object).

     The callback is called after any on-disk changes are made to
     the file, e.g. merging, file permissions, renaming, etc. However,
     when this->dryRun is true, filesystem-level changes are skipped.
  */
  fsl_merge_f callback;
  /**
     Client-defined state for use with this->callback.
  */
  void * callbackState;
  /**
     A hint to fsl_ckout_merge() about whether it needs to scan the
     checkout for changes. Set this to false ONLY if the calling code
     calls fsl_ckout_changes_scan() (or equivalent,
     e.g. fsl_vfile_changes_scan()) immediately before calling
     fsl_ckout_merge(), as that function requires a non-stale changes
     scan in order to function properly.
  */
  bool scanForChanges;
  /**
     If true, the extraction process will "go through the motions" but
     will not write any files to disk. It may still perform I/O such
     as stat()'ing to see, e.g., if it would have needed to overwrite
     a file. When in dry-run, this->callback is still called as if
     dry-run mode were not in effect. Thus the on-disk state may not
     actually reflect what the callback sees when dry-run mode is
     active.
  */
  bool dryRun;
  /**
     This flag is not part of the public API and will be removed
     once the merge operation's development has settled down.
  */
  unsigned short debug;
  /**
     TODO:

     - How to handle fossil's --binary GLOBPATTERN flag. Plain string
     or a glob list object or a stateful predicate function or... ?

     We currently rely entirely on the global `binary-glob` setting.
  */
};
/** Initialized-with-defaults fsl_merge_opt structure, intended for
    const-copy initialization. */
#define fsl_merge_opt_empty_m \
  {-1/*mergeRid*/,0/*baselineRid*/, \
   FSL_MERGE_TYPE_NORMAL/*mergeType*/, \
   NULL/*callback*/, NULL/*callbackState*/, \
   true/*scanForChanges*/, \
   false/*dryRun*/,0/*debug*/}
/** Initialized-with-defaults fsl_merge_opt structure, intended for
    non-const copy initialization. */
extern const fsl_merge_opt fsl_merge_opt_empty;

/**
   UNDER CONSTRUCTION and not yet well-tested.

   Performs a "merge" operation on the current checkout, merging in
   version opt->mergeRid. If that version has already been merged,
   this call has no SCM-related side effects.

   Returns 0 on success, any number of non-0 codes on error,
   including, _but not limited to_:

   - FSL_RC_NOT_A_CKOUT if f has no opened checkout.

   - FSL_RC_OOM on allocation error.

   - FSL_RC_TYPE if opt->mergeRid or opt->baselineRid do to refer to
     a checkin.

   - FSL_RC_PHANTOM if a file participating in the merge is
     a phantom.

   - FSL_RC_RANGE if the to-be-merged-in RID is the same as the
     current checkout RID or the same as the pivot/baseline of
     the merge.

   - FSL_RC_NOT_FOUND if no common ancestor can be found for use as a
     basis for the merge.

   - FSL_RC_MISUSE if the current checkout is empty (has an RID of 0).

   - Any number of DB- or I/O-related codes, as well as codes from
     underlying APIs such as fsl_vfile_changes_scan().

   For all but the most trivial argument validation errors or
   allocation errors, f's error state will be updated with a
   description of the problem.

   TODOs and potential TODOs:

   - There are certain illegal combinations of merge state which may
     require adding new result codes for. e.g. a no-op merge.

   - Empty directories may be left behind when a merge removes all
     files in a directory. fsl_ckout_update() handles that case but
     fsl_ckout_merge() currently does not.

*/
FSL_EXPORT int fsl_ckout_merge(fsl_cx * const f, fsl_merge_opt const * const opt);

/**
   If zDirName is a directory name which contains what appears to
   be a fossil checkout database (noting that only a cursory check is done - the
   db is not opened and validated), the name of that database file (minus
   the directory part) is returned, else NULL is returned. The returned bytes
   are static.

   @see fsl_ckout_dbnames()
*/
FSL_EXPORT char const * fsl_is_top_of_ckout(char const *zDirName);

/**
   Returns an array of strings with the base names of valid fossil checkout
   databases. The array is terminated by a NULL element.

   As of this writing, and for the foreseeable future, the list is
   comprised of only 3 elements, {".fslckout", "_FOSSIL_", NULL}, but
   the order of the non-NULL elements is unspecified by the interface.
*/
FSL_EXPORT char const ** fsl_ckout_dbnames(void);

/** Convenience typedef. */
typedef struct fsl_ckout_rename_opt fsl_ckout_rename_opt;
/**
   Callback type for use with fsl_ckout_rename(). It gets called once per
   iteration of a rename operation, along with the original options object
   for the rename and:

   - zSrcName is the checkout-relative original name of the file.
   - zDestname is the checkout-relative new name of the file.

   Both strings are owned by the calling operation and will be freed
   soon after this call returns. If the client needs them, they must
   make copies.

   It must returns 0 on success. If it returns non-0 then the current
   renaming op is cancelled (rolled back) and the result code is
   propagated back to the caller of fsl_ckout_rename().

   This gets called immediately after the associated db record is
   modified and before the filesystem move (if any) is performed.

   Design note: ideally the callback would be called after the
   filesystem move, but the way the moves are currently processed (as
   a batch after the db updates, noting that those updates may trigger
   variou error conditions) precludes that. Alternately, we could
   delay the callback until the file-move phase (noting that the
   file-move step is optional), and that might be a sensible change to
   make.
*/
typedef int (*fsl_ckout_rename_f)(fsl_cx *, fsl_ckout_rename_opt const *,
                                  char const * zSrcName, char const *zDestName);

/**
   Options object for use with fsl_ckout_rename().
*/
struct fsl_ckout_rename_opt {
  /**
     The source filename(s) or directory name(s) to rename. The
     contents of this list _must not_ be modified while
     fsl_ckout_rename() is running (e.g. via a callback function).
  */
  fsl_list const * src;
  /**
     The target filename or directory name to rename to.
  */
  char const * dest;
  /**
     If true, src and dest are resolved/normalized based on the current
     working directory, else they must be relative to the top of the
     checkout.
  */
  bool relativeToCwd;
  /**
     If true fsl_ckout_rename() will attempt to move files within the
     filesystem. If false, it will only do the db-side renaming.
  */
  bool doFsMv;
  /**
     If true, fsl_ckout_rename() will not perform any lasting
     operations but will "go through the motions" with the exception
     of actually attempting to move files on disk (if doFsMv is
     true). It will still report errors in this mode, with the
     exception that filesystem-level moving is not attempted so
     potential failures there cannot be detected.

     Achtung: in dry-run mode it will trigger a rollback of any
     pending transaction which is opened before fsl_ckout_rename() is
     called.
  */
  bool dryRun;
  /** Optional callback. May be NULL. */
  fsl_ckout_rename_f callback;
  /** Optional state for the callback. */
  void * callbackState;
};

/** Initialized-with-defaults fsl_ckout_rename_opt structure, intended for
    const-copy initialization. */
#define fsl_ckout_rename_opt_empty_m {NULL,NULL,true,false,false,NULL,NULL}

/** Initialized-with-defaults fsl_ckout_rename_opt structure, intended for
    non-const copy initialization. */
extern const fsl_ckout_rename_opt fsl_ckout_rename_opt_empty;

/**
   This routine renames one or more SCM-managed files matching all
   entries in opt->src to opt->dest within the current checkout. This
   updates the current checkout's vfile table with the changes, and
   optionally attempts to move the files within the filesystem, but
   does not commit anything, so the change may still be reverted later
   on.

   If an entry in opt->src matches an existing directory name within
   the SCM-managed file list, this function assumes that all files
   under that directory are to be moved.

   If opt->relativeToCwd is true then the destination name and all
   opt->src names are canonicalized based on the current working
   directory (see fsl_getcwd()), otherwise they are assumed to be
   relative to f's current checkout directory.

   If opt->dest refers to an _existing_ directory, when an opt->src
   entry refers to a directory then that whole directory, including the
   directory name part, is renamed. If opt->dest does not exist in the
   filesystem and if opt->src resolves to multiple inputs, opt->dest is
   assumed to be a new target directory but the renaming behavior of
   the opt->src files differs. Examples:

   - Case 1: opt->dest refers to an existing directory: moving
     directory foo/bar to baz will result in baz/bar.

   - Case 2: opt->dest does not refer to an existing directory: moving
   directory foo/bar to baz results in baz with the previous contents
   of foo/bar.

   Why? Because that's how fossil(1) does it.

   This function matches opt->src entries only against
   `vfile.pathname`, not `vfile.origname`.

   If opt->doFsMv is true then the final operation this function
   attempts is to rename source files to their new destination. It
   will only attempt this in cases where (A) the original file exists
   and (B) the destination file does _not_ exist. Any errors generated
   during this filesystem-level rename/move step _are ignored_ for two
   reasons: 1) fossil(1) does it that way and (2) after moving any
   files, trying to roll back and undo the filesystem-level operations
   would add a significant amount of complexity and new errror cases
   (what happens when a try-to-undo-rename fails?).

   Returns 0 on succcess. Potential errors include:

   - FSL_RC_OOM on allocation error.

   - FSL_RC_NOT_A_CKOUT if f has no opened checkout.

   - FSL_RC_MISUSE: opt->src contains multiple entries but the
   destination is not an _existing_ directory.

   - FSL_RC_ALREADY_EXISTS: cannot rename because the destination name
   is already in use by another record.

   - FSL_RC_TYPE: opt->dest refers to a non-directory and an opt->src
   entry refers to a directory.

   - Any potential DB-related errors.

   BUGS/Shortcomings:

   - If it fails moving files in the filesystem, it might have
   successfully already moved one or more source files, and those
   moves are not undone.

   - Depending on the case-sensitivity of the repo and the filesystem,
   it might (UNTESTED) fail to rename a file if the new name differs
   only in its case (e.g. `README.TXT` to `README.txt`). Those
   relavant code renames such vfile entries but leaves the filesystem
   entries intact because fossil(1) does it that way.

   - If it moves a whole directory full of files it leaves any
   original directories intact. Improving this is on the TODO list.
   Often, such directories have contents (e.g. compiled/generated/temp
   files) and cannot be removed.
*/
FSL_EXPORT int fsl_ckout_rename(fsl_cx * const f,
                                fsl_ckout_rename_opt const * opt);

/**
   Undoes a rename scheduled by fsl_ckout_rename(). zNewName is the
   current (renamed) name of the file.

   If relativeToCwd is true then zNewName is canonicalized based on
   the current working directory (see fsl_getcwd()), otherwise it is
   assumed to be relative to f's current checkout directory.

   On success, or if no such pending rename is found, it returns 0.
   If it actually performs a db-level rename then it sets
   `*didSomething` to true if didSomething is not NULL. It should
   arguably return FSL_RC_NOT_FOUND (or some such) if no matching
   rename is pending, but that currently feels overly-pedantic.

   If doFsMv is true and a db entry is renamed and a file with the
   new name exists in the filesystem then this function will
   _delete_ any file which has the original name and rename the zNewName
   file to its reverted name. If that fails, the operation as a
   whole will fail and the db changes will be rolled back. Note,
   however, that a file deleted by this operation cannot be recovered
   and that the deletion must be done before the rename is attempted.

   On error, returns any of a wide array of non-0 result codes, only
   two of which can come directly from this function: FSL_RC_OOM or
   FSL_RC_NOT_A_CKOUT. Any other non-zero result codes are propagated
   errors from lower-level code.
*/
FSL_EXPORT int fsl_ckout_rename_revert(fsl_cx * const f,
                                       char const * zNewName,
                                       bool relativeToCwd, bool doFsMv,
                                       bool *didSomething);

/**
    Fetches the vfile.pathname value for the given vfile.id
    entry. Results are undefined if f does not have an opened
    checkout. On success returns 0 and sets `*zOut` to the name,
    transfering ownership to the caller (who must eventually pass it
    to fsl_free()). If absolute is true then the returned name has the
    checkout dir prepended to it, else it is relative to the top of
    the repo.

    Potential TODO: this routine is in no way optimized for heavy use
    within an app, expecting to be only rarely used, e.g. in
    conjunction with fsl_ckout_rename()-like ops. If it sees any
    significant use it should be refactored to use a cached statement.
*/
FSL_EXPORT int fsl_vfile_pathname(fsl_cx * const f, fsl_id_t vfid,
                                  bool absolute, char **zOut);


/**
   Callback type for fsl_ckout_fs::xDirList(). It is called once per
   entry of the listed directory, with the entry's name (no directory
   part, not "." or ".."). If it returns non-0, the listing stops and
   xDirList() must return that value.
*/
typedef int (*fsl_ckout_fs_dir_f)(void * cbState, char const * zEntry);

/**
   Storage for a checkout's files: a set of operations through which
   the library's checkout code (checkout, update, merge, revert,
   stash, undo, commit and the change scan) reads and writes the
   files of the working copy, installed per context with
   fsl_cx_ckout_fs(). The default, fsl_ckout_fs_os, is the
   filesystem.

   It covers the working copy's files only. The checkout, repository
   and config databases are SQLite's business, and the current
   directory is still the filesystem's.

   All names are absolute, UTF-8, with '/' as the separator and no
   trailing '/', as the library builds them from the checkout
   directory. Each operation
   returns 0 on success or a FSL_RC_xxx code. Every operation which
   looks up a name (xStat(), xRead(), xUnlink(), xRename()'s source)
   must return FSL_RC_NOT_FOUND for a name which does not exist,
   because the library's callers branch on it.

   A storage with no symlinks (xSymlinkRead and xSymlinkCreate NULL)
   holds a link as a regular file containing the link's target, as
   the filesystem does on platforms without symlinks.

   Members other than xExecSet, xMtimeSet, xSymlinkRead,
   xSymlinkCreate, xCopy, xHash and xWriteBlob are required.
*/
struct fsl_ckout_fs {
  /**
     The version of this struct the implementation was written
     against: 1 or 2. Version 2 added xWriteBlob. Later versions may
     add members at the end. The library reads no member a struct's
     version does not have, so a version 1 struct may be allocated
     without the later members.
  */
  int iVersion;
  /**
     Populates *tgt with the type, size, mtime and permissions of
     zName. If derefLinks is true and zName is a symlink, it describes
     the link's target. Storage which has no symlinks ignores
     derefLinks.
  */
  int (*xStat)(void * state, char const * zName, fsl_fstat * tgt,
               bool derefLinks);
  /**
     Replaces tgt's contents with the full contents of file zName.
  */
  int (*xRead)(void * state, char const * zName, fsl_b * tgt);
  /**
     Creates or replaces file zName with the n bytes at src. zName's
     directory is created first by the library, via xMkdir().

     A storage wrapping another one (e.g. one from
     fsl_cx_ckout_fs_get() with some members replaced) to see every
     write must wrap xWriteBlob too, if the wrapped storage has one:
     the library writes the files of a checked-out version through
     xWriteBlob, not xWrite, when it is not NULL.
  */
  int (*xWrite)(void * state, char const * zName, void const * src,
                fsl_size_t n);
  /** Removes file zName. */
  int (*xUnlink)(void * state, char const * zName);
  /** Renames file zFrom to zTo, replacing zTo if it exists. */
  int (*xRename)(void * state, char const * zFrom, char const * zTo);
  /** Creates directory zName, whose parent exists. */
  int (*xMkdir)(void * state, char const * zName);
  /** Removes directory zName if it is empty, else fails. */
  int (*xRmdir)(void * state, char const * zName);
  /** Calls cb() for each entry of directory zDir. */
  int (*xDirList)(void * state, char const * zDir,
                  fsl_ckout_fs_dir_f cb, void * cbState);
  /**
     Sets or clears file zName's executable bit. May be NULL, in which
     case setting it does nothing.
  */
  int (*xExecSet)(void * state, char const * zName, bool isExec);
  /**
     Sets file zName's mtime, in seconds since the Unix epoch. May be
     NULL, in which case setting it does nothing.
  */
  int (*xMtimeSet)(void * state, char const * zName, fsl_time_t mtime);
  /**
     Replaces tgt's contents with the target of symlink zName. May be
     NULL if the storage has no symlinks, in which case xSymlinkCreate
     must be NULL too.
  */
  int (*xSymlinkRead)(void * state, char const * zName, fsl_b * tgt);
  /**
     Creates symlink zName pointing to zTarget. zName does not exist,
     and its directory does. May be NULL if the storage has no
     symlinks, in which case xSymlinkRead must be NULL too.
  */
  int (*xSymlinkCreate)(void * state, char const * zTarget,
                        char const * zName);
  /**
     Copies file zFrom to zTo as fsl_file_copy() does: creating zTo's
     directory and carrying over the executable bit. May be NULL, in
     which case the library reads zFrom whole and writes it to zTo. A
     storage which can copy without holding the whole file in memory
     should provide it.
  */
  int (*xCopy)(void * state, char const * zFrom, char const * zTo);
  /**
     Replaces tgt's contents with the lower-case hex SHA3-256 hash of
     file zName's contents if sha3 is true, else its SHA1 hash. May be
     NULL, in which case the library reads the file whole and hashes
     it. A storage which can hash without holding the whole file in
     memory should provide it.
  */
  int (*xHash)(void * state, char const * zName, bool sha3, fsl_b * tgt);
  /** Opaque state passed as the first argument of every member. */
  void * state;
  /**
     Version 2. Creates or replaces file zName with the content of
     blob rid of the context's repository, as the checkout code does
     to write a file of a checked-out version (checkout, update,
     revert, merge, and the manifest file). zName's directory is
     created first by the library, via xMkdir(), as for xWrite(). The
     library sets the executable bit and mtime afterwards, as after
     xWrite(). May be NULL, in which case the library reads the blob
     (fsl_content_get()) and passes it to xWrite(). A storage which
     can record the reference instead of copying the bytes, reading
     the blob only when the file is read, should provide it. It is
     given no fsl_cx: a storage which needs the context, e.g. to read
     the blob later, keeps it in its state.
  */
  int (*xWriteBlob)(void * state, char const * zName, fsl_id_t rid);
};
typedef struct fsl_ckout_fs fsl_ckout_fs;

/**
   The current version of struct fsl_ckout_fs, for its iVersion: what
   a storage written against this header sets, and what a caller sets
   in the struct it passes to fsl_cx_ckout_fs_get() or as
   fsl_cx_ckout_fs()'s pPrev, so that the copy has every member.
*/
#define FSL_CKOUT_FS_VERSION 2

/** Initialized-with-defaults fsl_ckout_fs instance, intended for
    const-copy initialization. Its iVersion is 0, which as f's
    storage means "none installed" and as a destination of
    fsl_cx_ckout_fs_get() means version 1: set iVersion to
    FSL_CKOUT_FS_VERSION before using it as one. */
#define fsl_ckout_fs_empty_m {0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL}
/** Initialized-with-defaults fsl_ckout_fs instance, intended for
    non-const copy initialization. */
FSL_EXPORT const fsl_ckout_fs fsl_ckout_fs_empty;

/**
   The filesystem as a fsl_ckout_fs, which every context uses unless
   another storage is installed: each member calls the fs.c function
   the checkout code always used (fsl_stat(), fsl_b_fill_from_filename(),
   fsl_b_to_filename(), fsl_file_unlink(), ...). A storage which keeps
   only some files elsewhere can delegate the rest to these members.
*/
FSL_EXPORT const fsl_ckout_fs fsl_ckout_fs_os;

/**
   Installs a bitwise copy of *pNew as f's checkout file storage (see
   fsl_ckout_fs). If pNew is NULL, the storage reverts to the
   filesystem, fsl_ckout_fs_os. If pPrev is not NULL, the previous
   storage is copied to it first, as fsl_cx_ckout_fs_get() copies it,
   so that a caller can restore it later: the caller sets
   pPrev->iVersion first, or the copy lacks xWriteBlob:

   ```
   fsl_ckout_fs prev = fsl_ckout_fs_empty;
   prev.iVersion = FSL_CKOUT_FS_VERSION;
   rc = fsl_cx_ckout_fs(f, &mine, &prev);
   ... // f uses mine
   rc = fsl_cx_ckout_fs(f, &prev, NULL); // back to what it was
   ```

   Only the members of pNew->iVersion are read: those a later version
   added are NULL in f's copy.

   Returns 0 on success, FSL_RC_MISUSE if pNew->iVersion is not 1 or
   2, or a required member is NULL, or exactly one of xSymlinkRead and
   xSymlinkCreate is NULL, or if a transaction is open on f, since
   files would then be split between two storages mid-operation. On
   error f's storage is unchanged.

   @see fsl_cx_ckout_fs_get()
*/
FSL_EXPORT int fsl_cx_ckout_fs(fsl_cx * const f, fsl_ckout_fs const * pNew,
                               fsl_ckout_fs * pPrev);

/**
   Stores a bitwise copy of f's checkout file storage into *dest:
   fsl_ckout_fs_os unless another one is installed. The caller sets
   dest->iVersion first to the version of the struct dest points to,
   which may have been allocated without the members of later
   versions: if it is 0 or 1, only the version 1 members are written
   (a storage's xWriteBlob is then not copied), and dest->iVersion is
   set to 1; if it is 2 or more, the whole struct is written.
   Installing a version 1 copy gives up the storage's xWriteBlob, so
   the library then writes those files through xWrite.

   @see fsl_cx_ckout_fs()
*/
FSL_EXPORT void fsl_cx_ckout_fs_get(fsl_cx const * const f,
                                    fsl_ckout_fs * dest);


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_CHECKOUT_H_INCLUDED */
/* end of file include/fossil-scm/checkout.h */
/* start of file include/fossil-scm/stash.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_STASH_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_STASH_H_INCLUDED
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/** @file stash.h

    stash.h declares the checkout stash: uncommitted changes saved in
    the checkout db so that they can be reverted and applied again
    later, as with (fossil stash).

    The stash uses fossil(1)'s own "stash" and "stashfile" tables, so
    stashes saved by fossil(1) can be applied with these APIs and vice
    versa. The port follows fossil(1)'s src/stash.c, with Mark
    Jamsek's stash implementation in client/fnc/fnc.c as the guide to
    the equivalent libfossil APIs.

    Not yet supported: fossil(1)'s undo of stash operations, as
    libfossil does not yet have undo.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   Change types reported by fsl_stash_apply() for each stashed
   file.
*/
enum fsl_stash_e {
/** Sentinel value. */
FSL_STASH_NONE = 0,
/** An added file was written and queued for adding. */
FSL_STASH_ADD,
/** A removed file was deleted from the checkout. */
FSL_STASH_DELETE,
/**
   A file which was unchanged since the stash's baseline was
   overwritten with the stashed version.
*/
FSL_STASH_UPDATE,
/**
   A file which was changed since the stash's baseline was merged with
   the stashed version without conflicts.
*/
FSL_STASH_MERGE,
/**
   As for FSL_STASH_MERGE, but the merge had conflicts, which are
   marked in the file.
*/
FSL_STASH_CONFLICT,
/**
   A file which was changed since the stash's baseline could not be
   merged because it is binary or a symlink. It is left unchanged.
*/
FSL_STASH_UNMERGEABLE,
/**
   The file's name is not safe to write: it is outside the checkout,
   or a part of its path which should be a directory is not one. It
   was skipped.
*/
FSL_STASH_UNSAFE
};
typedef enum fsl_stash_e fsl_stash_e;

/**
   Callback type for fsl_stash_apply(). It is called once for
   each stashed file, after that file is handled. zName is the file's
   checkout-relative name, as it will be at the next check-in. If the
   stash renamed the file, zOrigName is its original name, else it is
   the same as zName. nConflicts is the number of merge conflicts for
   FSL_STASH_CONFLICT, else 0. state is the callbackState member of
   the options object.

   If it returns non-0, applying stops and that result is returned,
   noting that files written so far stay written.
*/
typedef int (*fsl_stash_f)(char const * zName,
                                 char const * zOrigName,
                                 fsl_stash_e change,
                                 unsigned nConflicts,
                                 void * state);

/**
   Options for fsl_stash_save().
*/
struct fsl_stash_save_opt {
  /**
     The stash's comment. May be NULL.
  */
  char const * comment;
  /**
     A NULL-terminated list of file or directory names to stash. If
     this is NULL or its first entry is NULL, all changes in the
     checkout are stashed.
  */
  char const * const * filenames;
  /**
     If true, this->filenames are relative to the current working
     directory, else to the checkout root.
  */
  bool relativeToCwd;
  /**
     If false (the default), the stashed changes are reverted after
     they are saved, as with (fossil stash save). If true, they are
     kept, as with (fossil stash snapshot).
  */
  bool keepChanges;
  /**
     Optional callback for the revert which follows the save. Ignored
     if this->keepChanges is true.
  */
  fsl_ckout_revert_f revertCallback;
  /**
     State for this->revertCallback.
  */
  void * revertCallbackState;
};
typedef struct fsl_stash_save_opt fsl_stash_save_opt;

/** Initialized-with-defaults fsl_stash_save_opt instance,
    intended for use in const-copy initialization. */
#define fsl_stash_save_opt_empty_m { \
  NULL/*comment*/, NULL/*filenames*/, true/*relativeToCwd*/, \
  false/*keepChanges*/, NULL/*revertCallback*/, NULL/*revertCallbackState*/ \
}

/** Initialized-with-defaults fsl_stash_save_opt instance,
    intended for use in non-const copy initialization. */
FSL_EXPORT const fsl_stash_save_opt fsl_stash_save_opt_empty;

/**
   Saves the checkout's uncommitted changes as a new stash, then
   reverts them unless opt->keepChanges is true. See
   fsl_stash_save_opt for the options.

   The stash records, for each changed file, whether it is added or
   removed, its executable and symlink state, its original and new
   names, and its content: a delta from the checkout's version for a
   modified file, the whole content for an added file, and nothing
   for a removed one.

   If stashId is not NULL, the new stash's ID is written to it on
   success.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOOP if there were no changes to stash, or none in the
   files named by opt->filenames (in which case no stash is created),
   or any number of db or I/O errors.

   The stash is saved in its own transaction, which is committed
   before the revert, as fossil(1) does, so that a failed revert
   cannot lose changes it already reverted on disk. If the revert
   fails, the stash is still saved and *stashId is still set, but
   the revert's error is returned. If the caller has a transaction
   open, the save joins it and the caller's commit decides.
*/
FSL_EXPORT int fsl_stash_save(fsl_cx * const f,
                              fsl_stash_save_opt const * opt,
                              fsl_id_t * stashId);

/**
   Options for fsl_stash_apply().
*/
struct fsl_stash_apply_opt {
  /**
     The stash to apply, or 0 for the most recent one.
  */
  fsl_id_t stashId;
  /**
     If true, the stash is dropped after it is applied, as with
     (fossil stash pop).
  */
  bool pop;
  /**
     If true, the checkout is first updated to the stash's baseline
     version, as with (fossil stash goto).
  */
  bool gotoBaseline;
  /**
     Optional per-file callback.
  */
  fsl_stash_f callback;
  /**
     State for this->callback.
  */
  void * callbackState;
};
typedef struct fsl_stash_apply_opt fsl_stash_apply_opt;

/** Initialized-with-defaults fsl_stash_apply_opt instance,
    intended for use in const-copy initialization. */
#define fsl_stash_apply_opt_empty_m { \
  0/*stashId*/, false/*pop*/, false/*gotoBaseline*/, \
  NULL/*callback*/, NULL/*callbackState*/ \
}

/** Initialized-with-defaults fsl_stash_apply_opt instance,
    intended for use in non-const copy initialization. */
FSL_EXPORT const fsl_stash_apply_opt fsl_stash_apply_opt_empty;

/**
   Applies a stash to the current checkout. For each stashed file:

   - An added file is written and queued for adding.
   - A removed file is deleted from the disk.
   - A modified file which is unchanged on disk since the stash's
     baseline is overwritten with the stashed version.
   - A modified file which was changed on disk since then is merged
     with the stashed version, three-way, with the stash's baseline
     version as the common ancestor. Conflicts are marked in the
     file. A binary file or symlink cannot be merged and is left
     unchanged.
   - A renamed file is moved to its new name.

   If nConflicts is not NULL, the number of files which had merge
   conflicts or could not be merged is written to it, as fossil(1)
   counts them, including, for gotoBaseline, files the update left in
   conflict. The callback gets each file's own conflict count.

   Returns 0 on success, even if there were conflicts. Returns
   FSL_RC_NOT_A_CKOUT if no checkout is opened, FSL_RC_NOT_FOUND if
   the stash does not exist or there are no stashes, or any number of
   db or I/O errors.

   The db side runs in a transaction, but files written before an
   error stay written.
*/
FSL_EXPORT int fsl_stash_apply(fsl_cx * const f,
                               fsl_stash_apply_opt const * opt,
                               unsigned * nConflicts);

/**
   Deletes the given stash, or every stash if stashId is negative.
   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOT_FOUND if stashId is positive and no such stash exists,
   or a db error.
*/
FSL_EXPORT int fsl_stash_drop(fsl_cx * const f, fsl_id_t stashId);

/**
   Changes the comment of the given stash. Unlike
   fsl_stash_apply(), a stashId of 0 does not mean the most
   recent stash. Returns 0 on success, FSL_RC_NOT_A_CKOUT if no
   checkout is opened, FSL_RC_NOT_FOUND if no such stash exists, or a
   db error.
*/
FSL_EXPORT int fsl_stash_rename(fsl_cx * const f, fsl_id_t stashId,
                                char const * zComment);

/**
   Writes the ID of the most recent stash to *stashId, or 0 if there
   are no stashes. Returns 0 on success, FSL_RC_NOT_A_CKOUT if no
   checkout is opened, or a db error.
*/
FSL_EXPORT int fsl_stash_latest(fsl_cx * const f, fsl_id_t * stashId);

/**
   Reconstructs the stashed content of one file and appends it to
   tgt, which is first reset. zName is the file's name at the next
   check-in, as stored in the stash. If baseline is not NULL, the
   file's content in the stash's baseline version is written to it,
   or it is left empty for an added file.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOT_FOUND if the stash or the file is not found, FSL_RC_TYPE
   if the file was removed in the stash (it has no content), or a db
   or delta error.

   Clients can use this to show a stash, e.g. as a diff between
   baseline and tgt. The stash's file list is in the checkout db's
   stashfile table.
*/
FSL_EXPORT int fsl_stash_content(fsl_cx * const f, fsl_id_t stashId,
                                 char const * zName, fsl_b * const tgt,
                                 fsl_b * const baseline);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_STASH_H_INCLUDED */
/* end of file include/fossil-scm/stash.h */
/* start of file include/fossil-scm/undo.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_UNDO_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_UNDO_H_INCLUDED
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/** @file undo.h

    undo.h declares one level of undo and redo for the operations
    which change a checkout's files: fsl_ckout_update(),
    fsl_ckout_merge(), fsl_ckout_revert(), fsl_stash_apply() and
    fsl_stash_drop(), as with (fossil undo) and (fossil redo).

    Unlike fossil(1), which saves each file just before an operation
    writes it, libfossil records the state before an operation as a
    stash snapshot of the local changes, plus the checkout version and
    copies of the vfile and vmerge tables (as fossil(1)'s undo_vfile
    and undo_vmerge). Undo reverts, goes back to that version, writes
    each snapshot file back exactly, and restores vfile and vmerge.
    Redo does the same in the other direction.

    The undo state lives in the checkout db's fsl_undo* tables, apart
    from fossil(1)'s own undo tables, so (fossil undo) and
    fsl_undo() do not see each other's state.

    Differences from fossil(1):

    - Undo does not restore an unmanaged file which the update or
      merge overwrote, as the snapshot holds only managed changes.
      (Redo does restore unmanaged files at paths the undo took over,
      e.g. one left behind by an update which dropped a rename.)

    - Undo refuses if the checkout is no longer on the version the
      operation left it on (e.g. after a commit), and, unless forced,
      if its local changes or merge state changed after the
      operation, because restoring the earlier state would discard
      those changes. fossil(1) restores only the files the operation
      wrote, and a commit clears its undo state.

    - Undo of only some files, (fossil undo FILE...), is not
      supported.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   What fsl_undo_state() reports is available.
*/
enum fsl_undo_e {
/** Nothing can be undone or redone. */
FSL_UNDO_NONE = 0,
/** The most recent operation can be undone. */
FSL_UNDO_UNDO,
/** The most recent undo can be redone. */
FSL_UNDO_REDO
};
typedef enum fsl_undo_e fsl_undo_e;

/**
   Reports what can be undone or redone in f's checkout. *state is
   set to one of the fsl_undo_e values. If zLabel is not NULL, it is
   set to a description of the operation, e.g. "update", which the
   caller must pass to fsl_free(), or to NULL if *state is
   FSL_UNDO_NONE.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   or a db error.
*/
FSL_EXPORT int fsl_undo_state(fsl_cx * const f, fsl_undo_e * state,
                              char ** zLabel);

/**
   Undoes the most recent undoable operation, or, if redo is true,
   redoes the most recent undo.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOT_FOUND if there is nothing to undo (or redo),
   FSL_RC_MISUSE if called while another checkout operation is
   running on f, or FSL_RC_CONFLICT if the checkout is no longer on
   the version the operation left it on (e.g. after a commit), or if
   its local changes or merge state changed after the operation and
   force is false. force does not override a version change. On
   FSL_RC_CONFLICT nothing is changed.

   It runs in a transaction, but files it has written stay written if
   it fails partway.
*/
FSL_EXPORT int fsl_undo(fsl_cx * const f, bool redo, bool force);

/**
   Forgets any undo or redo state. Returns 0 on success,
   FSL_RC_NOT_A_CKOUT if no checkout is opened, or a db error.
*/
FSL_EXPORT int fsl_undo_reset(fsl_cx * const f);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_UNDO_H_INCLUDED */
/* end of file include/fossil-scm/undo.h */
/* start of file include/fossil-scm/confdb.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_CONFDB_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_CONFDB_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/** @file confdb.h

    fossil-confdb.h declares APIs dealing with fossil's various
    configuration option storage backends.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   A flag type for specifying which configuration backend a given API
   should be applied to. Used by most of the fsl_config_XXX() APIS,
   e.g. fsl_config_get_int32() and friends.

   This type is named fsl_confdb_e (not the "db" part) because 3 of
   the 4 fossil-supported config storage backends are databases. The
   "versioned setting" backend, which deals with non-db local files,
   was encapsulated into this API long after the db-related options
   were
*/
enum fsl_confdb_e {
/** Sentinel value. Not for use with public APIs. */
FSL_CONFDB_NONE = 0,
/**
   Signfies the global-level (per system user) configuration area.

   Note that fsl_config_... APIs which use this do not currently open
   that database on demand due to the potential for downstream
   locking-related issues when the config db is left open, as well as
   locking-related issues here when a separate client or instance is
   holding that db open. That behaviour may change in the future.
*/
FSL_CONFDB_GLOBAL = 1,
/**
   Signfies the repository-level configuration area.
*/
FSL_CONFDB_REPO = 2,
/**
   Signfies the checkout-level (a.k.a. "local") configuration area.
*/
FSL_CONFDB_CKOUT = 3,

/**
   The obligatory special case...

   Versionable settings are stored directly in SCM-controlled files,
   each of which has the same name as the setting and lives in the
   .fossil-settings directory of a checkout. Though versionable
   settings _can_ be read from a non-checked-out repository, doing so
   requires knowning which version to fetch and is horribly
   inefficient, so there are currently no APIs for doing so.

   Note that the APIs which read and write versioned settings do not
   care whether those settings are valid for fossil(1).

   Reminder to self: SQL to find the checkins in which a versioned
   settings file was added or modified (ignoring renames and branches
   and whatnot).

   ```
select strftime('%Y-%m-%d %H:%M:%S',e.mtime) mtime,
b.rid, b.uuid from mlink m, filename f, blob b, event e
where f.fnid=m.fnid
and m.mid=b.rid
and b.rid=e.objid
and f.name='.fossil-settings/ignore-glob'
order by e.mtime desc
;
   ```

*/
FSL_CONFDB_VERSIONABLE = 4
};
typedef enum fsl_confdb_e fsl_confdb_e;

/**
   Returns the name of the db table associated with the given
   mode. Results are undefined if mode is an invalid value. The
   returned bytes are static and constant.

   Returns NULL for the role FSL_CONFDB_VERSIONABLE.
*/
FSL_EXPORT char const * fsl_config_table_for_role(fsl_confdb_e mode);

/**
   Returns a handle to the db associates with the given fsl_confdb_e
   value. Returns NULL if !f or if f has no db opened for that
   configuration role. Results are undefined if mode is an invalid
   value.

   For FSL_CONFDB_VERSIONABLE it returns the results of fsl_cx_db(),
   even though there is no database-side support for versionable files
   (which live in files in a checkout).
*/
FSL_EXPORT fsl_db * fsl_config_for_role(fsl_cx * const f, fsl_confdb_e mode);

/**
   Returns the int32 value of a property from one of f's config
   dbs, as specified by the mode parameter. Returns dflt if !f, f
   does not have the requested config db opened, no entry is found,
   or on db-level errors.
*/
FSL_EXPORT int32_t fsl_config_get_int32( fsl_cx * const f, fsl_confdb_e mode,
                                         int32_t dflt, char const * key );
/**
   int64_t counterpart of fsl_config_get_int32().
*/
FSL_EXPORT int64_t fsl_config_get_int64( fsl_cx * const f, fsl_confdb_e mode,
                                         int64_t dflt, char const * key );

/**
   fsl_id_t counterpart of fsl_config_get_int32().
*/
FSL_EXPORT fsl_id_t fsl_config_get_id( fsl_cx * const f, fsl_confdb_e mode,
                                       fsl_id_t dflt, char const * key );
/**
   double counterpart of fsl_config_get_int32().
*/
FSL_EXPORT double fsl_config_get_double( fsl_cx * const f, fsl_confdb_e mode,
                                         double dflt, char const * key );


/**
   Boolean countertpart of fsl_config_get_int32().

   fsl_str_bool() is used to determine the booleanness (booleanity?)
   of a given config option.
*/
FSL_EXPORT bool fsl_config_get_bool( fsl_cx * const f, fsl_confdb_e mode,
                                     bool dflt, char const * key );

/**
   A convenience form of fsl_config_get_buffer().  If it finds a
   config entry it returns its value. If *len is not NULL then *len is
   assigned the length of the returned string, in bytes (and is set to
   0 if NULL is returned). Any errors encounters while looking for
   the entry are suppressed and NULL is returned.

   The returned memory must eventually be freed using fsl_free(). If
   len is not NULL then it is set to the length of the returned
   string. Returns NULL for any sort of error or for a NULL db value.

   If capturing error state is important for a given use case, use
   fsl_config_get_buffer() instead, which provides the same features
   as this one but propagates any error state.

   Achtung: because this is intended only for fossil config data, some
   of which supports #-style single-line comments, this function
   strips such content from its value (as of 2026-08-29, in order to
   resolve a discrepancy between libfossil and fossil(1)).
*/
FSL_EXPORT char * fsl_config_get_text( fsl_cx * const f, fsl_confdb_e mode,
                                       char const * key,
                                       fsl_size_t * len );

/**
   The fsl_b-type counterpart of fsl_config_get_int32().

   Replaces the contents of the given buffer (re-using any memory it
   might have) with a value from a config region. Returns 0 on
   success, FSL_RC_NOT_FOUND if no entry was found or the requested db
   is not opened, FSL_RC_OOM on allocation errror.

   If mode is FSL_CONFDB_VERSIONABLE, this operation requires
   a checkout and returns (if possible) the contents of the file
   named {CHECKOUT_ROOT}/.fossil-settings/{key}.

   This strips out #-style comment lines as described for
   fsl_config_get_text().

   On any sort of error, including the inability to find or open
   a versionable-settings file, non-0 is returned:

   - FSL_RC_OOM on allocation error

   - FSL_RC_NOT_FOUND if either the database referred to by mode is
   not opened or a matching setting cannot be found.

   - FSL_RC_ACCESS is a versionable setting file is found but cannot
   be opened for reading.

   - FSL_RC_NOT_A_CKOUT if mode is FSL_CONFDB_VERSIONABLE and no
   checkout is opened.

   - Potentially one of several db-related codes if reading a
   non-versioned setting fails.

   In the grand scheme of things, the inability to load a setting is
   not generally an error, so clients are not expected to treat it as
   fatal unless perhaps it returns FSL_RC_OOM, in which case it likely
   is.
*/
FSL_EXPORT int fsl_config_get_buffer( fsl_cx * const f, fsl_confdb_e mode,
                                      char const * key, fsl_b * const b );


/**
   If f has an opened checkout, this replaces b's contents (re-using
   any existing memory) with an absolute path to the filename for that
   setting: {CHECKOUT_ROOT}/.fossil-settings/{key}

   This routine neither verifies that the given key is a valid
   versionable setting name nor that the file exists: it's purely a
   string operation.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if f has no checkout
   opened, FSL_RC_MISUSE if key is NULL, empty, or if
   fsl_is_simple_pathname() returns false for the key, and FSL_RC_OOM
   if appending to the buffer fails.
 */
FSL_EXPORT int fsl_config_versionable_filename(fsl_cx *f, char const * key, fsl_b *b);

/**
   Sets a configuration variable in one of f's config databases, as
   specified by the mode parameter. Returns 0 on success.  val may
   be NULL. Returns FSL_RC_MISUSE if f does not have that database
   opened or key is NULL, FSL_RC_RANGE if key is empty, and
   FSL_RC_NOT_A_CKOUT if mode is FSL_CONFDB_VERSIONABLE and f has no
   opened checkout. On error, f's error state gives the setting name
   and the database or file it was being written to.

   If mode is FSL_CONFDB_VERSIONABLE, it attempts to write/overwrite
   the corresponding file in the current checkout.

   If mem is NULL and mode is not FSL_CONFDB_VERSIONABLE then an SQL
   NULL is bound instead of an empty blob. For FSL_CONFDB_VERSIONABLE
   an empty file will be written for that case.

   If mode is FSL_CONFDB_VERSIONABLE, this does NOT queue any
   newly-created versionable setting file for inclusion into the
   SCM. That is up to the caller. See
   fsl_config_versionable_filename() for info about an additional
   potential usage error case with FSL_CONFDB_VERSIONABLE.

   Pedantic side-note: the input text is saved as-is. No trailing
   newline is added when saving to FSL_CONFDB_VERSIONABLE because
   doing so would require making a copy of the input bytes just to add
   a newline to it. The non-text fsl_config_set_XXX() APIs add a
   newline when writing to their values out to a versionable config
   file because it costs them nothing to do so and text files "should"
   have a trailing newline.

   Potential TODO: if mode is FSL_CONFDB_VERSIONABLE and the key
   contains directory components, e,g, "app/x", we should arguably use
   fsl_mkdir_for_file() to create those components. As of this writing
   (2021-03-14), no such config keys have ever been used in fossil.

   @see fsl_config_versionable_filename()
*/
FSL_EXPORT int fsl_config_set_text( fsl_cx * const f, fsl_confdb_e mode,
                                    char const * key, char const * val );

/**
   The blob counterpart of fsl_config_set_text(). If len is
   negative then fsl_strlen(mem) is used to determine the length of
   the memory.

   If mem is NULL and mode is not FSL_CONFDB_VERSIONABLE then an SQL
   NULL is bound instead of an empty blob. For FSL_CONFDB_VERSIONABLE
   an empty file will be written for that case.
*/
FSL_EXPORT int fsl_config_set_blob( fsl_cx * const f, fsl_confdb_e mode, char const * key,
                                    void const * mem, fsl_int_t len );
/**
   int32 counterpart of fsl_config_set_text().
*/
FSL_EXPORT int fsl_config_set_int32( fsl_cx * const f, fsl_confdb_e mode,
                                     char const * key, int32_t val );
/**
   int64 counterpart of fsl_config_set_text().
*/
FSL_EXPORT int fsl_config_set_int64( fsl_cx * const f, fsl_confdb_e mode,
                                     char const * key, int64_t val );
/**
   fsl_id_t counterpart of fsl_config_set_text().
*/
FSL_EXPORT int fsl_config_set_id( fsl_cx * const f, fsl_confdb_e mode,
                                  char const * key, fsl_id_t val );
/**
   fsl_double counterpart of fsl_config_set_text().
*/
FSL_EXPORT int fsl_config_set_double( fsl_cx * const f, fsl_confdb_e mode,
                                      char const * key, double val );
/**
   Boolean counterpart of fsl_config_set_text().

   For compatibility with fossil conventions, the value will be saved
   in the string form "on" or "off". When mode is
   FSL_CONFDB_VERSIONABLE, that value will include a trailing newline.
*/
FSL_EXPORT int fsl_config_set_bool( fsl_cx * const f, fsl_confdb_e mode,
                                    char const * key, bool val );

/**
   "Unsets" (removes) the given key from the given configuration database.
   It is not considered to be an error if the config table does not
   contain that key.

   Returns FSL_RC_MISUSE if key is NULL or empty or f does not have
   the database for mode opened.

   Returns FSL_RC_UNSUPPORTED, changing no setting, if mode is
   FSL_CONFDB_VERSIONABLE. It "could" hypothetically remove a
   checked-out copy of a versioned setting, then queue the file for
   removal in the next checkin, but it does not do so. It might, in
   the future, be changed to do so, or at least to remove the local
   settings file.
*/
FSL_EXPORT int fsl_config_unset( fsl_cx * const f, fsl_confdb_e mode,
                                 char const * key );

/**
   Begins (or recurses) a transaction on the given configuration
   database.  Returns 0 on success, non-0 on error. On success,
   fsl_config_transaction_end() must eventually be called with the
   same parameters to pop the transaction stack. Returns
   FSL_RC_MISUSE if no db handle is opened for the given
   configuration mode. Assuming all arguments are valid, this
   returns the result of fsl_db_txn_begin() and propagates
   any db-side error into the f object's error state.

   This is primarily intended as an optimization when an app is
   making many changes to a config database. It is not needed when
   the app is only making one or two changes.

   @see fsl_config_transaction_end()
   @see fsl_db_txn_begin()
*/
FSL_EXPORT int fsl_config_transaction_begin(fsl_cx * const f, fsl_confdb_e mode);

/**
   Pops the transaction stack pushed by
   fsl_config_transaction_begin(). If rollback is true then the
   transaction is set roll back, otherwise it is allowed to
   continue (if recursive) or committed immediately (if not
   recursive).  Returns 0 on success, non-0 on error. Returns
   FSL_RC_MISUSE if no db handle is opened for the given
   configuration mode. Assuming all arguments are valid, this
   returns the result of fsl_db_txn_end() and propagates
   any db-side error into the f object's error state.

   @see fsl_config_transaction_begin()
   @see fsl_db_txn_end()
*/
FSL_EXPORT int fsl_config_transaction_end(fsl_cx * const f, fsl_confdb_e mode, bool rollback);

/**
   Populates li as a glob list from the given configuration key.
   Uses (versionable/repo/global) config settings, in that order.
   It is not an error if one or more of those sources is missing -
   they are simply skipped.

   Note that gets any new globs appended to it, as per
   fsl_glob_list_append(), as opposed to replacing any existing
   contents.

   Returns 0 on success, but that only means that there were no
   errors, not that any entries were necessarily added to li.

   Arguably a bug: this function does not open the global config if
   it was not already opened, but will use it if it is opened. This
   function should arbuably open and close it in that case. That said,
   there are cases which prohibit closing of the config db and this
   function cannot know if one of those cases is active.
*/
FSL_EXPORT int fsl_config_globs_load(fsl_cx * const f, fsl_list * const li, char const * key);

/**
   Fetches the preferred name of the "global" db file for the current
   user by assigning it to *zOut. Returns 0 on success, in which case
   *zOut is updated and non-0 on error, in which case *zOut is not
   modified.  On success, ownership of *zOut is transferred to the
   caller, who must eventually free it using fsl_free().

   Errors include:

   - FSL_RC_OOM on allocation error
   - FSL_RC_NOT_FOUND if no relevant environment variables are set
     from which to form the db path. On Unix-like systems that means
     none of FOSSIL_HOME, HOME, or XDG_CONFIG_HOME.
   - FSL_RC_TYPE (Unix-like systems) if neither FOSSIL_HOME nor
     XDG_CONFIG_HOME is set and $HOME is not a directory.

   This function has no fsl_cx and sets no error message;
   fsl_config_open() reports these failures in its context's error
   state.

   The locations searched for the database file are
   platform-dependent...

   Unix-like systems are searched in the following order:

   1) If the FOSSIL_HOME environment var is set, use
   $FOSSIL_HOME/.fossil.

   2) If $HOME/.fossil already exists, use that.

   3) If XDG_CONFIG_HOME environment var is set, use
   $XDG_CONFIG_HOME/fossil.db.

   4) If $HOME/.config is a directory, use $HOME/.config/fossil.db

   5) Fall back to $HOME/.fossil (historical name).

   Windows:

   1) If $FOSSIL_HOME is set, use that directory.
   2) If $LOCALAPPDATA is set, use that directory.
   3) If $APPDATA is set, use that directory.
   4) If $USERPROFILE is set, use that directory.
   5) If $HOMEDRIVE and $HOMEPATH are set, use that directory.

   If none of the above are set, FSL_RC_NOT_FOUND is returned.

   The name `_fossil` is appended to the first of the above-listed
   locations which is set in the environment.

   All platforms:

   Except where listed above, this function does not check whether the
   file already exists or is a database.
*/
FSL_EXPORT int fsl_config_global_preferred_name(char ** zOut);

/**
   A variant of fsl_config_get_int32() which can search through multiple
   config sources in an order specified by the caller.

   zCfg must be a NUL-terminated list of case-sensitive letters
   corresponding to config sources: any of (c, r, v, g) for checkout,
   repo, versionable, and global, respectively. Each source, if
   available, is searched, in the order provided, until either the
   given key is found in that source or no more sources are available,
   in which case dflt is returned. Any missing sources are silently
   skipped over (e.g. if 'c' is provided but no checkout is opened,
   that is not considered an error by this function).

   Errors are silently ignored and cause dflt to be returned.

   @see fsl_configs_get_int64()
   @see fsl_configs_get_id()
   @see fsl_configs_get_bool()
   @see fsl_configs_get_text()
*/
FSL_EXPORT int32_t fsl_configs_get_int32(fsl_cx * const f, char const * zCfg, int32_t dflt, char const * key);

/**
   The int64_t counterpart of fsl_configs_get_int32().
*/
FSL_EXPORT int64_t fsl_configs_get_int64(fsl_cx * const f, char const * zCfg, int64_t dflt, char const * key);

/**
   The fsl_id_t counterpart of fsl_configs_get_int32().
*/
FSL_EXPORT fsl_id_t fsl_configs_get_id(fsl_cx * const f, char const * zCfg, fsl_id_t dflt, char const * key);

/**
   The bool counterpart of fsl_configs_get_int32().
*/
FSL_EXPORT bool fsl_configs_get_bool(fsl_cx * const f, char const * zCfg, bool dflt, char const * key);

/**
   The double counterpart of fsl_configs_get_int32().
*/
FSL_EXPORT double fsl_configs_get_double(fsl_cx * const f, char const * zCfg, double dflt, char const * key);

/**
   The buffer counterpart of fsl_configs_get_int32(). This variant
   collects, if found, its results in the given buffer (its memory, if
   any, is reused by this routine). It returns 0 if an entry is found,
   FSL_RC_OOM on buffer allocation error, and FSL_RC_NOT_FOUND if no
   match is found in any of the listed sources (noting that missing
   sources are silently skipped). The full range of errors reported by
   fsl_config_get_buffer() is not supported here: only FSL_RC_OOM and
   FSL_RC_NOT_FOUND are reported.

   @see fsl_configs_get_text()
*/
FSL_EXPORT int fsl_configs_get_buffer( fsl_cx * const f, char const *zCfg,
                                       char const * key, fsl_b * const b );

/**
   The C-string counterpart of fsl_configs_get_int32(). If the final
   argument is not NULL then if a match is found then its length (in
   bytes) is assigned to (*len). Returns NULL if no match is found.

   If non-NULL is returned, ownership is transfered to the caller, who
   must eventually pass the value to fsl_free().

   Note that this function silently ignores any errors,
   e.g. allocation failure for the result string will be reported by
   returning NULL (which is indistinguishable from it not finding a
   match).

   @see fsl_configs_get_buffer()
*/
FSL_EXPORT char * fsl_configs_get_text(fsl_cx * const f, char const * zCfg, char const * key,
                                       fsl_size_t * len);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_CONFDB_H_INCLUDED */
/* end of file include/fossil-scm/confdb.h */
/* start of file include/fossil-scm/vpath.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_VPATH_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_VPATH_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).

  *****************************************************************************
  This file declares public APIs relating to calculating paths via
  Fossil SCM version history.
*/

#if defined(__cplusplus)
extern "C" {
#endif

typedef struct fsl_vpath_node fsl_vpath_node;
typedef struct fsl_vpath fsl_vpath;

/**
   Holds information for a single node in a path of checkin versions.

   @see fsl_vpath
*/
struct fsl_vpath_node {
  /** ID for this node */
  fsl_id_t rid;
  /** True if pFrom is the parent of rid */
  bool fromIsParent;
  /** True if primary side of common ancestor */
  bool isPrimary;
  /* HISTORICAL: Abbreviate output in "fossil bisect ls" */
  bool isHidden;
  /** Node this one came from. */
  fsl_vpath_node *pFrom;
  union {
    /** List of nodes of the same generation */
    fsl_vpath_node *pPeer;
    /** Next on path from beginning to end */
    fsl_vpath_node *pTo;
  } u;
  /** List of all nodes */
  fsl_vpath_node *pAll;
};

/**
   A utility type for collecting "paths" between two checkin versions.
*/
struct fsl_vpath{
  /** Current generation of nodes */
  fsl_vpath_node *pCurrent;
  /** All nodes */
  fsl_vpath_node *pAll;
  /** Nodes seen before */
  fsl_id_bag seen;
  /** Number of steps from first to last. */
  int nStep;
  /** Earliest node in the path. */
  fsl_vpath_node *pStart;
  /** Common ancestor of pStart and pEnd */
  fsl_vpath_node *pPivot;
  /** Most recent node in the path. */
  fsl_vpath_node *pEnd;
};

/**
   An empty-initialize fsl_vpath object, intended for const-copy
   initialization.
*/
#define fsl_vpath_empty_m {0,0,fsl_id_bag_empty_m,0,0,0,0}

/**
   An empty-initialize fsl_vpath object, intended for copy
   initialization.
*/
FSL_EXPORT const fsl_vpath fsl_vpath_empty;


/**
   Returns the first node in p's path.

   The returned node is owned by path may be invalidated by any APIs
   which manipulate path.
*/
FSL_EXPORT fsl_vpath_node * fsl_vpath_first(fsl_vpath *p);

/**
   Returns the last node in p's path.

   The returned node is owned by path may be invalidated by any APIs
   which manipulate path.
*/
FSL_EXPORT fsl_vpath_node * fsl_vpath_last(fsl_vpath *p);

/**
   Returns the next node p's path.

   The returned node is owned by path may be invalidated by any APIs
   which manipulate path.

   Intended to be used like this:

   ```
   for( p = fsl_vpath_first(path) ;
   p ;
   p = fsl_vpath_next(p)){
   ...
   }
   ```
*/
FSL_EXPORT fsl_vpath_node * fsl_vpath_next(fsl_vpath_node *p);

/**
   Returns p's path length.
*/
FSL_EXPORT int fsl_vpath_length(fsl_vpath const * p);

/**
   Frees all nodes in path (which must not be NULL) and resets all
   state in path. Does not free path.
*/
FSL_EXPORT void fsl_vpath_clear(fsl_vpath *path);

/**
   Find the mid-point of the path.  If the path contains fewer than 2
   steps, returns 0. The returned node is owned by path and may be
   invalidated by any APIs which manipulate path.
*/
FSL_EXPORT fsl_vpath_node * fsl_vpath_midpoint(fsl_vpath * path);


/**
   Computes the shortest path from checkin versions ridFrom to ridTo
   (inclusive), storing the result state in path. If path has
   state before this is called, it is cleared by this call.

   ridFrom and ridTo must both be valid checkin version RIDs.

   If directOnly is true, then use only the "primary" links from
   parent to child.  In other words, ignore merges.

   On success, returns 0 and path->pStart will point to the
   beginning of the path (the ridFrom node). If pStart is 0 then no
   path could be found but 0 is still returned.

   Elements of the path can be traversed like so:

   ```
   fsl_vpath path = fsl_vpath_empty;
   fsl_vpath_node * n = 0;
   int rc = fsl_vpath_shortest(f, &path, versionFrom, versionTo, 1, 0);
   if(rc) { ... error ... }
   for( n = fsl_vpath_first(&path); n; n = fsl_vpath_next(n) ){
   ...
   }
   fsl_vpath_clear(&path);
   ```

   On error, f's error state may be updated with a description of the
   problem.
*/
FSL_EXPORT int fsl_vpath_shortest( fsl_cx * const f, fsl_vpath * const path,
                                   fsl_id_t ridFrom, fsl_id_t ridTo,
                                   bool directOnly, bool oneWayOnly );

/**
   This variant of fsl_vpath_shortest() stores the shortest direct
   path from version ridFrom to version ridTo in the ANCESTOR temporary
   table using f's current repo db handle. That table gets created, if
   needed, else cleared by this call.

   The ANCESTOR temp table has the following interface:

   ```
   rid INT UNIQUE
   generation INTEGER PRIMARY KEY
   ```

   Where [rid] is a checkin version RID and [generation] is the
   1-based number of steps from ridFrom, including ridFrom (so
   ridFrom's own generation is 1).

   On error returns 0 and, if pSteps is not NULL, assigns *pSteps to
   the number of entries added to the ancestor table. On error, pSteps
   is never modifed, any number of various non-0 codes may be
   returned, and f's error state will, if possible (not an OOM), be
   updated to describe the problem.

   This function's name is far too long and descriptive. We might want
   to consider something shorter.

   Maintenance reminder: this impl swaps the 2nd and 3rd parameters
   compared to fossil(1)'s version!
*/
FSL_EXPORT int fsl_vpath_shortest_store_in_ancestor(fsl_cx * const f,
                                                    fsl_id_t ridFrom,
                                                    fsl_id_t ridTo,
                                                    uint32_t *pSteps);

/**
   Computes a list of direct (non-merge) ancestors of the given
   checkin RID and stores it in the TEMP table [ancestor], which it
   creates if needed or clears if it currently exists.

   The [ancestor] schema is described in
   fsl_vpath_shortest_store_in_ancestor(). The [generation] value of
   the record corresponding to rid is 1, increasing by 1 for each
   generation back in the history.

   Returns 0 on success, FSL_RC_NOT_A_REPO if f has no repo db opened,
   and any number of lower-level result codes if something goes wrong.
*/
FSL_EXPORT int fsl_compute_direct_ancestors(fsl_cx * const f, fsl_id_t rid);

/**
   Reconstructs path from path->pStart to path->pEnd, reversing its
   order by fiddling with the u->pTo fields.

   Unfortunately does not reverse after the initial creation/reversal
   :/.
*/
FSL_EXPORT void fsl_vpath_reverse(fsl_vpath * path);


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_VPATH_H_INCLUDED */
/* end of file include/fossil-scm/vpath.h */
/* start of file include/fossil-scm/bisect.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_BISECT_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_BISECT_H_INCLUDED
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/** @file bisect.h

    bisect.h declares a bisect session, as with (fossil bisect): mark
    check-ins good or bad, and step the checkout to the midpoint of the
    path between the innermost good and bad ones until one check-in is
    left.

    The session lives in the checkout db's vvar table under fossil(1)'s
    own names (bisect-good, bisect-bad, bisect-log, bisect-complete and
    the bisect-OPTION settings), so a session started with fossil(1) can
    be continued with these APIs and vice versa.

    The path between good and bad is computed as fossil(1) 2.29's
    path_shortest() does, including its priority queue's ordering of
    equally short paths and its "skip" (hidden) check-ins, so that each
    step picks the same check-in fossil(1) would. That is a separate
    implementation from fsl_vpath_shortest(), which predates those
    changes in fossil(1).
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   Verdicts for fsl_bisect_mark().
*/
enum fsl_bisect_e {
/** The check-in does not have the problem. */
FSL_BISECT_GOOD = 1,
/** The check-in has the problem. */
FSL_BISECT_BAD,
/** The check-in cannot be tested, e.g. it does not build. */
FSL_BISECT_SKIP
};
typedef enum fsl_bisect_e fsl_bisect_e;

/**
   Records a verdict for check-in rid, or the current checkout's
   version if rid is 0, in the bisect log. A good or bad verdict
   replaces the session's good or bad check-in, unless rid already is
   that check-in, in which case nothing is logged, as in fossil(1).
   Like fossil(1), a skip is logged only once the log has a good or bad
   entry.

   This does not move the checkout: call fsl_bisect_next() for that,
   as (fossil bisect) does when its auto-next option is on.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_RANGE for an invalid verdict, or a db error.
*/
FSL_EXPORT int fsl_bisect_mark(fsl_cx * const f, fsl_bisect_e verdict,
                               fsl_id_t rid);

/**
   Removes the most recent good, bad or skip entry from the bisect log
   and recomputes the good and bad check-ins from what remains, as
   (fossil bisect undo) does, except that skip entries are passed over
   (fossil(1) 2.29 takes a skip entry for a good check-in of 0).

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOT_FOUND if the log is empty, or a db error.
*/
FSL_EXPORT int fsl_bisect_undo(fsl_cx * const f);

/**
   Ends the bisect session: forgets the good and bad check-ins, the
   log and whether the session is complete. Options are kept, except
   the linear option, which fossil(1) also resets. Returns 0 on
   success, FSL_RC_NOT_A_CKOUT if no checkout is opened, or a db error.
*/
FSL_EXPORT int fsl_bisect_reset(fsl_cx * const f);

/**
   Session state, as reported by fsl_bisect_state() and
   fsl_bisect_next().
*/
struct fsl_bisect_state_t {
  /** The innermost good check-in, or 0. */
  fsl_id_t good;
  /** The innermost bad check-in, or 0. */
  fsl_id_t bad;
  /**
     For fsl_bisect_next(): the check-in the checkout was (or would be)
     updated to, or 0 if the bisect is complete.
  */
  fsl_id_t next;
  /**
     The number of steps on the path between good and bad, not
     counting skipped check-ins.
  */
  int span;
  /**
     An estimate of the steps remaining: the base-2 logarithm of span,
     rounded up, as fossil(1) reports it.
  */
  int stepsLeft;
  /**
     For fsl_bisect_state(): true if the session has finished. For
     fsl_bisect_next(): true if this step found nothing left to test.
  */
  bool complete;
};
typedef struct fsl_bisect_state_t fsl_bisect_state_t;

/** Initialized-with-defaults fsl_bisect_state_t instance. */
FSL_EXPORT const fsl_bisect_state_t fsl_bisect_state_t_empty;

/**
   Reports the session's good and bad check-ins and whether it is
   complete. The next, span and stepsLeft members are left 0.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   or a db error.
*/
FSL_EXPORT int fsl_bisect_state(fsl_cx * const f, fsl_bisect_state_t * st);

/**
   Picks the next check-in to test: the midpoint of the path between
   the good and bad check-ins, skipping skipped ones, or, with the
   linear option on, the check-in next to the good one. If uOpt is not
   NULL, the checkout is then updated to it with fsl_ckout_update(),
   using uOpt with its checkinRid member replaced. If there is no such
   check-in, the session is marked complete instead.

   On success st, if not NULL, describes the result.

   Returns 0 on success (including when the bisect is complete),
   FSL_RC_NOT_A_CKOUT if no checkout is opened, FSL_RC_MISUSE if
   neither a good nor a bad check-in has been marked, FSL_RC_NOT_FOUND
   if there is no path between them, or a db or update error.
*/
FSL_EXPORT int fsl_bisect_next(fsl_cx * const f, fsl_ckup_opt const * uOpt,
                               fsl_bisect_state_t * st);

/**
   Computes the path between the session's good and bad check-ins
   into path, from the good one to the bad one, with isHidden set on
   skipped check-ins. If only one of them is set, the path is that
   one check-in. path is cleared first and must eventually be passed
   to fsl_vpath_clear().

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_MISUSE if neither a good nor a bad check-in has been
   marked, FSL_RC_NOT_FOUND if there is no path between them, or a db
   error.
*/
FSL_EXPORT int fsl_bisect_path(fsl_cx * const f, fsl_vpath * const path);

/**
   Gets, and if zNewValue is not NULL first sets, the bisect option
   zName: "auto-next", "direct-only", "display" or "linear", which
   are kept as fossil(1) keeps them. If zValue is not NULL, *zValue
   is set to the option's value, or its default, which the caller must
   pass to fsl_free().

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_NOT_FOUND for an unknown option, or a db error.
*/
FSL_EXPORT int fsl_bisect_option(fsl_cx * const f, char const * zName,
                                 char const * zNewValue, char ** zValue);

/**
   Returns true if the bisect option zName, which must be one of the
   boolean ones, is on, as fossil(1) decides it: a value of "on",
   "yes" or "true" (in any case) or a non-zero number is on, "off",
   "no", "false" or "0" is off, and anything else, or no checkout,
   means the option's default.
*/
FSL_EXPORT bool fsl_bisect_option_is_on(fsl_cx * const f,
                                        char const * zName);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_BISECT_H_INCLUDED */
/* end of file include/fossil-scm/bisect.h */
/* start of file include/fossil-scm/patch.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_PATCH_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_PATCH_H_INCLUDED
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/** @file patch.h

    patch.h declares APIs for fossil(1)-compatible binary patches, as
    with (fossil patch). A patch is a single file which captures all
    of the uncommitted changes of a checkout so that they can be
    applied to another checkout of the same repository, typically on
    another machine.

    A patch file is an SQLite database with these tables, as defined
    by fossil(1)'s src/patch.c:

    - cfg(key,value): metadata. See fsl_patch_info.

    - chng(pathname,origname,hash,isexe,islink,delta): one row per
      changed file. pathname is the file's name at the next check-in
      and origname its name before a rename, else NULL. hash is the
      baseline version's hash of the file, or NULL for a new file.
      delta is NULL for a removed file, the compressed full content
      for a new file, else a compressed fossil delta from the baseline
      content, with a length of 0 if the content is unchanged.

    - patchmerge(type,mhash): optional. One row per pending merge,
      where type is one of "merge", "cherrypick", "backout" or
      "integrate".

    Patches created by these APIs can be applied by fossil(1) and vice
    versa.

    Not yet supported: undo of an applied patch.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   Options for fsl_patch_create().
*/
struct fsl_patch_create_opt {
  /**
     The file to write the patch to. If this is NULL, the patch is
     passed to this->out instead.
  */
  char const * filename;
  /**
     If true and this->filename already exists, it is overwritten,
     else fsl_patch_create() fails with FSL_RC_ALREADY_EXISTS.
  */
  bool overwrite;
  /**
     Output channel for the patch if this->filename is NULL. The
     patch is binary and is passed to it in one or more calls.
  */
  fsl_output_f out;
  /**
     State for this->out.
  */
  void * outState;
  /**
     The name of the machine the patch is created on, recorded in the
     patch for informational purposes only. May be NULL, in which
     case it is not recorded. The library does not look this up
     itself.
  */
  char const * hostname;
};
typedef struct fsl_patch_create_opt fsl_patch_create_opt;

/** Initialized-with-defaults fsl_patch_create_opt instance,
    intended for use in const-copy initialization. */
#define fsl_patch_create_opt_empty_m { \
  NULL/*filename*/, false/*overwrite*/, NULL/*out*/, \
  NULL/*outState*/, NULL/*hostname*/ \
}

/** Initialized-with-defaults fsl_patch_create_opt instance,
    intended for use in non-const copy initialization. */
FSL_EXPORT const fsl_patch_create_opt fsl_patch_create_opt_empty;

/**
   Creates a patch of all uncommitted changes in f's checkout,
   including pending merges, as with (fossil patch create). See
   fsl_patch_create_opt for the options.

   The checkout is scanned for changes first, so the caller need not
   do so.

   Unlike fossil(1), each file's executable bit and symlink state are
   taken from the file itself. fossil(1) takes them from the checkout
   db, which a changes scan does not update when only they change, so
   its patches lose such a change.

   The patch is built in memory and written only once it is complete,
   so an error does not leave a partial patch file behind. It is
   written even if there are no changes, as fossil(1) does.

   Returns 0 on success, FSL_RC_NOT_A_CKOUT if no checkout is opened,
   FSL_RC_MISUSE if opt->filename and opt->out are both NULL,
   FSL_RC_ALREADY_EXISTS if opt->filename exists and opt->overwrite
   is false, FSL_RC_TYPE if opt->filename exists but is not a file,
   any result code returned by opt->out, or any number of db or I/O
   errors.
*/
FSL_EXPORT int fsl_patch_create(fsl_cx * const f,
                                fsl_patch_create_opt const * opt);

/**
   Opaque handle to an opened patch. It is created by
   fsl_patch_open_file() or fsl_patch_open_mem() and freed by
   fsl_patch_close(). It must not outlive the fsl_cx it was opened
   with.
*/
typedef struct fsl_patch fsl_patch;

/**
   Opens the patch file zFile, read-only, and assigns *pOut to a new
   handle to it, which the caller must eventually pass to
   fsl_patch_close(). Neither a repository nor a checkout need be
   opened.

   The patch is validated before it is accepted: it must be a
   well-formed SQLite database which passes SQLite's quick_check and
   has the tables and columns described in this file's docs. Note
   that a patch is untrusted input, so the database is opened in
   SQLite's defensive mode with untrusted-schema handling. The file
   names in it are not checked here but by fsl_patch_apply().

   Returns 0 on success, FSL_RC_NOT_FOUND if zFile does not exist,
   FSL_RC_SYNTAX if it is not a valid patch, FSL_RC_OOM, or a db
   error. On error *pOut is not modified.
*/
FSL_EXPORT int fsl_patch_open_file(fsl_cx * const f, char const * zFile,
                                   fsl_patch ** pOut);

/**
   Works like fsl_patch_open_file() but reads the patch from the n
   bytes of memory at src, e.g. a patch read from stdin or from a
   remote command. The memory is copied, so the caller still owns
   src and need not keep it alive.

   In addition to the errors fsl_patch_open_file() can return, this
   returns FSL_RC_SYNTAX if n is less than 512, the smallest possible
   SQLite database.
*/
FSL_EXPORT int fsl_patch_open_mem(fsl_cx * const f, void const * src,
                                  fsl_size_t n, fsl_patch ** pOut);

/**
   Frees all resources owned by p. A no-op if p is NULL.
*/
FSL_EXPORT void fsl_patch_close(fsl_patch * p);

/**
   Metadata from a patch's cfg table. Any member may be NULL if the
   patch does not have that entry. All strings are owned by the
   fsl_patch they come from and are valid until it is closed.
*/
struct fsl_patch_info {
  /** Hash of the check-in the patch's changes are relative to. */
  char const * baseline;
  /** The repository's project code. */
  char const * projectCode;
  /** The repository's project name. */
  char const * projectName;
  /** The user who created the patch. */
  char const * user;
  /** The machine the patch was created on. */
  char const * hostname;
  /** The absolute path of the checkout the patch was created in. */
  char const * ckoutDir;
  /** The absolute path of the repository it was created in. */
  char const * repoDb;
  /** When the patch was created, as a Julian day, or 0 if unknown. */
  double date;
};
typedef struct fsl_patch_info fsl_patch_info;

/**
   Returns p's metadata. It is read when p is opened, so this cannot
   fail. The result is owned by p.
*/
FSL_EXPORT fsl_patch_info const * fsl_patch_info_get(fsl_patch const * p);

/**
   One changed file in a patch, as passed to fsl_patch_each_f.
*/
struct fsl_patch_entry {
  /** The file's checkout-relative name at the next check-in. */
  char const * name;
  /** The file's name before it was renamed, or NULL if it was not
      renamed. */
  char const * origName;
  /** The file's hash in the baseline version, or NULL if the file is
      new. */
  char const * baselineHash;
  /** True if the file is new (not in the baseline). */
  bool isNew;
  /** True if the file is removed. */
  bool isDeleted;
  /** True if an existing file's content changed. Always false for a
      new or removed file, and for one which is only renamed or whose
      permissions changed. */
  bool isModified;
  /** True if the file is executable. */
  bool isExe;
  /** True if the file is a symlink. */
  bool isLink;
};
typedef struct fsl_patch_entry fsl_patch_entry;

/**
   Callback type for fsl_patch_each(). e and the memory it points to
   are valid only for the duration of the call. If it returns non-0,
   iteration stops and that result is returned from fsl_patch_each(),
   except that FSL_RC_BREAK stops iteration and fsl_patch_each()
   returns 0.
*/
typedef int (*fsl_patch_each_f)(fsl_patch_entry const * e, void * state);

/**
   Callback type for fsl_patch_each_merge(), passed the type and hash
   of one pending merge. It works as fsl_patch_each_f does.
*/
typedef int (*fsl_patch_merge_f)(fsl_merge_type_e type,
                                 char const * zHash, void * state);

/**
   Calls cb once for each changed file in p, ordered by name, passing
   it state. Returns 0 on success, the result of cb as described for
   fsl_patch_each_f, or a db error.
*/
FSL_EXPORT int fsl_patch_each(fsl_patch * const p, fsl_patch_each_f cb,
                              void * state);

/**
   Calls cb once for each pending merge recorded in p, in the order in
   which they are recorded, passing it state. Entries with an unknown
   merge type or a malformed hash are skipped, as fossil(1) does.
   Returns 0 on success, including if p has no merges, the result of
   cb as described for fsl_patch_each_f, or a db error.
*/
FSL_EXPORT int fsl_patch_each_merge(fsl_patch * const p,
                                    fsl_patch_merge_f cb, void * state);

/**
   Reconstructs one file of patch p, for example to show the patch as a
   diff, as (fossil patch diff) does. p's context must have a
   repository opened, which must hold the patch's baseline versions.
   zName is the file's name as fsl_patch_entry::name has it.

   If tgt is not NULL, it is reset, then the file's content as the
   patch leaves it is written to it: empty for a removed file, and
   the baseline content for a file which is only renamed or whose
   permissions changed.

   If baseline is not NULL, it is reset, then the file's content in
   the patch's baseline is written to it: empty for a new file. Unlike
   fossil(1), which shows a removed file as an empty diff because its
   patches record no hash for it, a removed file's baseline content
   is looked up in the baseline check-in.

   Returns 0 on success, FSL_RC_NOT_A_REPO if no repository is opened,
   FSL_RC_NOT_FOUND if p has no file named zName or a baseline version
   which is needed is not in the repository, FSL_RC_SYNTAX for a
   malformed hash or file content, FSL_RC_DELTA_INVALID_xxx for a
   malformed delta, or a db error.
*/
FSL_EXPORT int fsl_patch_content(fsl_patch * const p, char const * zName,
                                 fsl_b * const tgt, fsl_b * const baseline);

/**
   The steps reported by fsl_patch_apply()'s callback.
*/
enum fsl_patch_apply_e {
/** Sentinel value. */
FSL_PATCH_APPLY_NONE = 0,
/**
   A pre-existing local change was reverted, because
   fsl_patch_apply_opt::force was true. The name is that of the
   reverted file.
*/
FSL_PATCH_APPLY_REVERT,
/**
   The checkout was updated to the patch's baseline. The name is the
   baseline's hash.
*/
FSL_PATCH_APPLY_BASELINE,
/**
   A pending merge was re-done. The name is the merged version's
   hash.
*/
FSL_PATCH_APPLY_MERGE,
/**
   A file which a merge changed but the patch does not mention was
   reverted, as fossil(1) does.
*/
FSL_PATCH_APPLY_UNMERGE,
/** A file was removed. */
FSL_PATCH_APPLY_DELETE,
/** A file was renamed. origName is its former name. */
FSL_PATCH_APPLY_RENAME,
/** A file's content or permissions were changed. */
FSL_PATCH_APPLY_EDIT,
/** A new file was written and queued for adding. */
FSL_PATCH_APPLY_NEW
};
typedef enum fsl_patch_apply_e fsl_patch_apply_e;

/**
   Callback type for fsl_patch_apply(). It is called after each step
   is done, or in place of doing it in a dry run. zName is the
   checkout-relative file name or a hash, as documented for each
   fsl_patch_apply_e value. zOrigName is the file's former name for
   FSL_PATCH_APPLY_RENAME, else NULL.

   If it returns non-0, applying stops and that result is returned,
   noting that files written so far stay written.
*/
typedef int (*fsl_patch_apply_f)(fsl_patch_apply_e step,
                                 char const * zName,
                                 char const * zOrigName,
                                 void * state);

/**
   Options for fsl_patch_apply().
*/
struct fsl_patch_apply_opt {
  /**
     If true and the checkout has uncommitted changes, they are
     reverted, and permanently lost, before the patch is applied. If
     false, a checkout with changes is an error.
  */
  bool force;
  /**
     If true, nothing is changed, but the callback is told what
     would have been done.
  */
  bool dryRun;
  /**
     Optional per-step callback.
  */
  fsl_patch_apply_f callback;
  /**
     State for this->callback.
  */
  void * callbackState;
};
typedef struct fsl_patch_apply_opt fsl_patch_apply_opt;

/** Initialized-with-defaults fsl_patch_apply_opt instance,
    intended for use in const-copy initialization. */
#define fsl_patch_apply_opt_empty_m { \
  false/*force*/, false/*dryRun*/, NULL/*callback*/, \
  NULL/*callbackState*/ \
}

/** Initialized-with-defaults fsl_patch_apply_opt instance,
    intended for use in non-const copy initialization. */
FSL_EXPORT const fsl_patch_apply_opt fsl_patch_apply_opt_empty;

/**
   Applies patch p to f's checkout, as with (fossil patch apply), in
   this order:

   1. If the checkout has changes and opt->force is true, they are
      reverted.

   2. If the checkout is not at the patch's baseline, it is updated
      to it.

   3. The patch's pending merges, if any, are re-done, then any file
      which they changed but which the patch does not mention is
      reverted. That follows fossil(1) (2024-12-16): such changes were
      not part of the original checkout's state.

   4. Removed files are removed, renamed files are renamed, and
      changed and new files are written, with new ones queued for
      adding.

   Unlike fossil(1), a new empty file is added, and a change to only a
   file's executable or symlink state is applied. fossil(1) drops both.

   Before anything is changed, the patch is checked: a file name which
   is not a simple relative path or is a reserved name, a hash which
   is not a full artifact hash, or a baseline (of the patch or of any
   file) which is not in the repository causes the whole patch to be
   rejected. When a file is written, removed or renamed, its path is
   also checked against symlinked or non-directory parent directories
   at that time.

   In a dry run, the callback is not told which files step 3 would
   revert, as that depends on the outcome of merges which are not
   done.

   Returns 0 on success. Returns FSL_RC_NOT_A_CKOUT if no checkout is
   opened, FSL_RC_REPO_MISMATCH if the patch's project code differs
   from the repository's, FSL_RC_CONFLICT if the checkout has changes
   and opt->force is false, FSL_RC_NOT_FOUND or FSL_RC_PHANTOM if the
   baseline or a file's baseline version is not in the repository
   (it may need to be synced first), FSL_RC_RANGE for an unsafe file
   name, FSL_RC_SYNTAX for a malformed hash or file content,
   FSL_RC_DELTA_INVALID_xxx for a malformed delta, the result of
   opt->callback, or any number of db or I/O errors.

   The db side runs in a transaction, which is rolled back on error
   or in a dry run, but files written before an error stay written.
*/
FSL_EXPORT int fsl_patch_apply(fsl_cx * const f, fsl_patch * const p,
                               fsl_patch_apply_opt const * opt);

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_PATCH_H_INCLUDED */
/* end of file include/fossil-scm/patch.h */
/* start of file include/fossil-scm/auth.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_AUTH_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_AUTH_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).

  ******************************************************************************
  This file declares public APIs for handling fossil
  authentication-related tasks.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   If f has an opened repository, this function forms a hash from:

   "zProjectCode/zLoginName/zPw"

   (without the quotes)

   where zProjectCode is typically a repository-dependent series of
   random bytes. If zProjCode is 0 then fsl_repo_project_code() is
   used to fetch it. (The project code is stored in the repository's
   config table under the key 'project-code'.)

   The returned string is owned by the caller, who must eventually
   fsl_free() it.

   Returns NULL if zProjCode is 0 and fsl_repo_project_code() fails,
   in which case f's error state holds that function's result
   (FSL_RC_NOT_FOUND if the repository has no project-code), or on
   allocation error.

   All arguments except zProjCode must be non-NULL or behavior is
   undefined.

   Potential TODO:

   - in fossil(1), this function generates a different result (it
   returns a copy of zPw) if the project code is not set, under
   the assumption that this is "the first xfer request of a
   clone."  Whether or not that will apply at this level to
   libfossil remains to be seen.
*/

FSL_EXPORT char * fsl_sha1_shared_secret2( fsl_cx * const f, char const * zLoginName,
                                           char const * zPw, char const * zProjCode );

/**
   Equivalent to fsl_sha1_shared_secret2(f,zLoginName,zPw,NULL).
*/
FSL_EXPORT char * fsl_sha1_shared_secret( fsl_cx * const f, char const * zLoginName,
                                          char const * zPw );

/**
   Fetches the login group name (if any) for the given context's
   current repositorty db. If f has no opened repo, 0 is returned.

   If the repo belongs to a login group, its name is returned in the
   form of a NUL-terminated string. The returned value (which may be
   0) is owned by the caller, who must eventually fsl_free() it. The
   value (unlike in fossil(1)) is not cached because it may change
   via modification of the login group.
*/
FSL_EXPORT char * fsl_repo_login_group_name(fsl_cx * const f);

/**
   Fetches the login cookie name associated with the current repository
   db, or 0 if no repository is opened.

   The returned (NUL-terminated) string is owned by the caller, who
   must eventually fsl_free() it. The value is not cached in f because
   it may change during the lifetime of a repo (if a login group is
   set or removed).

   The login cookie name is a string in the form "fossil-XXX", where
   XXX is the first 16 hex digits of either the repo's
   'login-group-code' or 'project-code' config values (in that order).
*/
FSL_EXPORT char * fsl_repo_login_cookie_name(fsl_cx * const f);

/**
   Searches for a user ID (from the repo.user.uid DB field) for a given
   username and password. The password may be either its hashed form or
   non-hashed form (if it is not exactly 40 bytes long, that is!).

   On success, 0 is returned and *pId holds the ID of the
   user found (if any).  *pId will be set to 0 if no match for the
   name/password was found, or positive if a match was found.

   If any of the arguments are NULL, or zUsername is empty,
   FSL_RC_MISUSE is returned. f must have an opened repo, else
   FSL_RC_NOT_A_REPO is returned. If the repo has no project-code,
   FSL_RC_NOT_FOUND is returned. On a db error, that error is
   reported via f's error state.

*/
FSL_EXPORT int fsl_repo_login_search_uid(fsl_cx * const f, char const * zUsername,
                                         char const * zPasswd, fsl_id_t * pId);

/**
   Clears all login state for the given user ID. If the ID is negative
   then ALL logins are cleared. Has no effect on the built-in
   pseudo-users.

   Returns non-0 on error, and not finding a matching user ID is not
   considered an error.

   Returns FSL_RC_MISUSE if f is NULL. f must have an opened repo, or
   FSL_RC_NOT_A_REPO is returned. On a db error, that error is
   reported via f's error state.

   TODO: there are currently no APIs for _setting_ the state this
   function clears! As of mid-2026 they are managed by the sync layer.
*/
FSL_EXPORT int fsl_repo_login_clear( fsl_cx * const f, fsl_id_t userId );


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_AUTH_H_INCLUDED */
/* end of file include/fossil-scm/auth.h */
/* start of file include/fossil-scm/forum.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_FORUM_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_FORUM_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).

  ******************************************************************************
  This file declares public APIs for working with fossil-managed forum
  content.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   If the given fossil context has a db opened, this function
   installs, if needed, the forum-related schema and returns 0 on
   success (or if no installation was needed). If f has no repository
   opened, FSL_RC_NOT_A_REPO is returned. Some other FSL_RC_xxx value
   is returned if there is a db-level error during installation.
*/
int fsl_repo_install_schema_forum(fsl_cx *f);


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_FORUM_H_INCLUDED */
/* end of file include/fossil-scm/forum.h */
/* start of file include/fossil-scm/sync.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_SYNC_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_SYNC_H_INCLUDED
/*
  Copyright 2025 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2025 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/** @file sync.h

    sync.h declares APIs dealing with fossil repository
    synchronization.
*/


#if defined(__cplusplus)
extern "C" {
#endif

typedef struct fsl_sc fsl_sc;

/**
   Callback for xfer-layer debugging messages. TODO consolidate this
   with the fsl_msg system.
*/
typedef void (*fsl_xfer_dbg_f)(fsl_xfer *xf, char const * zMsg);

/**
   Internal part of fsl_sc, uplifted into its own struct to simplify
   proper intialization of them in downstream fsl_sc implementations.
*/
struct fsl_xfer_dbg {
  /**
     This optional method is intended to be set by client-level code,
     not the sync channel implementor.

     If not NULL, the library or fsl_sc implementations may emit
     debugging output via this function.

     For output channel legibility, zMsg should always end with a
     newline (fsl_xfer_debug() and friends will automatically add one
     if needed).

     Implementations are free to mangle or emit the message in any
     form they like.

     Design note: its return type is void, but experience with binding
     C to Java and C++ shows that such bindings may need to propagate
     unexpected exceptions (e.g. resource acquisition failure, logging
     failure, etc.) somehow through the C API, and the conventional
     generic way to do that is to have a result code.  In normal use,
     it is never expected that a debugging function fails in a way
     which impacts the non-debugging functionality, but if an
     implementation absolutely must report an error, they should call
     fsl_xfer_error(), and that will be propagated back from this
     call. Channels, however, are _not_ required to check that after
     every debug call - they may assume success when the debug
     function is called, as the debug channel should not interfere
     with the sync channel's operation. That said, most of the
     fsl_xfer APIs become no-ops when its error state is set, causing
     the error to be implicitly propagated.

     @see fsl_xfer_debug_f_FILE()
     @see fsl_xfer_debug_f_buffer()
  */
  fsl_xfer_dbg_f callback;

  /**
     Available in callback() implementations via ch->debug.state.

     This memory is not owned by this object. It's owned by whoever
     set this member to non-NULL.
  */
  void * state;

  /**
     This is a scratch buffer solely for internal use by:

     1) library APIs like fsl_xfer_debugf()

     2) fsl_sc method implementations which do not themselves call
        into (1) while using this buffer.

     Without this, fsl_xfer_debug() becomes unduly memory-costly. This
     memory is owned by the library and gets cleared by
     fsl_sc_cleanup().  fsl_sc::cleanup() implementations may clean it
     up but are not required to.
  */
  fsl_b b;
};

typedef struct fsl_xfer_dbg fsl_xfer_dbg;

/** Empty-initialized fsl_xfer_dbg instance for use in cleanly
    const-copy initializing objects. */
#define fsl_xfer_dbg_empty_m {.callback=0, .state=0, .b=fsl_b_empty_m}

/** Empty-initialized instance for use in cleanly initializing
    objects. */
extern const fsl_xfer_dbg fsl_xfer_dbg_empty;

/**
   Frees any memory which may be owned by p but does not free p (which
   is typically stack-allocated).
*/
FSL_EXPORT void fsl_xfer_dbg_cleanup( fsl_xfer_dbg * p );

/**
   Flags for use with fsl_sc::flags. The top-most 8 bits are reserved
   for use by common library-level flags which a fsl_sc implementation
   may choose to support or may be required to support.
*/
enum fsl_sc_F_lib_e {
  /**
     Tells the fsl_sc impl that it should post data using the HTTP
     Content-Type value of "application/x-fossil" instead of
     "application/x-fossil-uncompressed". The former will have a
     fossil-compressed response payload[^1] whereas the latter will
     have an uncompressed response. Compressed payloads require far
     more memory to process but can save considerable network
     bandwidth.

     fsl_sc implementations are required to honor this flag, in that
     they must set the appropriate Content-Type request header, so
     that the library can Do The Right Thing without requiring that
     each fsl_sc implementation know whether to stream or buffer the
     content.

     This is a _hint_ for the remote, but the remote may override
     that, sending uncompressed responses instead of compressed.
     The remote will never do the opposite, converting a request for
     an uncompressed response to a compressed one.

     Compression may be handled differently for certain sync response
     types. e.g., a protocol-version-3 clone request will _not_ emit a
     fully-compressed response because most of the response body is
     already compressed in that case. The fsl_sc implementations need
     not concern themselves with that, however.

     Similarly, when fossil is operated via its "test-http" facility,
     as it does for non-networked/file-level sync, it does not
     compress responses.

     When this flag is set, the sync process will read all of the
     response content from the fsl_sc instance and then take over
     reading of the response from there so that fsl_sc implementations
     do not have to deal with those details.

     Because compression support is so memory-hungry, it is opt-in
     flag instead of an opt-out. Compression will save network
     bandwidth but costs the client application and the remote fossil
     instance boatloads of RAM.

     [^1]: zlib compress() with a 4-byte big-endian header encoding
           the decompressed size.
  */
  FSL_SC_F_COMPRESSED = 0x40000000,

  /**
     For impls with this flag set, the library will populate their
     fsl_sc::requestHeaders immediately before calling the impl's
     submit() method. Some impls generate their own headers or feed
     them into a proxy application in a different way, so don't need
     this. e.g. the curl-binary-based impl passes headers to curl
     in the form of CLI flags.
  */
  FSL_SC_F_REQUEST_HEADERS = 0x20000000,

  /**
     Impls which use temp files must honor this flag by _not_ deleting
     those files, so that they can be examined for testing and
     debugging.

     Implementations are recommended to send a fsl_cx_emit()
     message with the type FSL_MSG_TMPFILE and the name of the
     file in the message at the time when they would have otherwise
     been deleted, to facilitate matching temp files to their purpose.
  */
  FSL_SC_F_LEAVE_TEMP_FILES = 0x10000000,

  /**
     Impls which might, due to shelling out, emit info to stderr are
     expected to honor this flag and redirect stderr to /dev/null (or
     equivalent) if at all possible.
  */
  FSL_SC_F_SUPPRESS_STDERR = 0x08000000,

  /**
     Impls which use TLS must honor this flag by accepting any server
     certificate, without verifying its chain or its host name. The
     connection is then open to a man-in-the-middle attack. It
     corresponds to fossil(1)'s --accept-any-cert flag.
  */
  FSL_SC_F_TLS_ACCEPT_ANY_CERT = 0x04000000,

  /**
     For channels which do not speak HTTP. The library does not parse
     HTTP headers from the reply, so submit() must not make read()
     return any. Instead, submit() sets fsl_sc::reply to describe the
     reply body, which read() then returns from its first byte. The
     flag says nothing about the request: it may be combined with
     FSL_SC_F_REQUEST_HEADERS, for a channel which speaks HTTP to its
     peer but delimits the reply itself, and the library then builds
     fsl_sc::requestHeaders as it does without this flag. Without
     FSL_SC_F_REQUEST_HEADERS the channel carries the login card
     passed to submit() in whatever way it likes.
  */
  FSL_SC_F_NO_HTTP = 0x02000000,

  /**
     The mask of FSL_SC_F_... bits which are reserved for use by
     library-level options.
  */
  FSL_SC_F_lib_mask = 0x7FFF0000,

  /**
     The mask of FSL_SC_F_... bits which are reserved for use by
     client-level options.
  */
  FSL_SC_F_client_mask = ~FSL_SC_F_lib_mask
};

/**
   Indicates that fsl_sc::read() must read exactly 1 line of
   input. Its precise value is not well-defined but it is guaranteed
   to be of the same type as fsl_sc::read()'s final parameter. It is
   not an enum entry because we cannot (in C99) portably make an enum
   be precisely of a specific integer type.
*/
#define FSL_SC_READ_LINE ((fsl_int_t)-1)

/**
   Indicates that fsl_sc::read() must transfer or copy all of its
   input into the result buffer. See FSL_SC_READ_LINE for more
   details. It does _not_ have a well-defined value beyond that it is
   guaranteed to be negative and distinct from FSL_SC_READ_LINE, but
   must not be changed willy-nilly because it gets baked into all
   client code.
*/
#define FSL_SC_READ_ALL ((fsl_int_t)-2147483648)

/**
   Initialization modes for use with fsl_sc::init() implementations.
*/
enum fsl_sc_init_e {
  /**
     Indicates that the fsl_sc instance should initialize any core
     resources but not necessarily any request/response resources.

     See fsl_sc::init() for more details.
  */
  FSL_SC_INIT_INITIAL = 0x01,

  /**
     Indicates that the object must (re)initialize any state needed
     for constructing a request. e.g. initializing a buffer or temp
     file. The xfer layer may use this to compose a follow-up response
     while it is still reading a remote's response.

     See fsl_sc::init() for more details.

     Design note: there is no FSL_SC_INIT_RESPONSE counterpart because
     that role is effectively filled by fsl_sc::submit(), which
     initiates the processing of any response.
  */
  FSL_SC_INIT_REQUEST = 0x02
};

/**
   The fsl_sc class encapsulates a streamable (as opposed to
   random-access) I/O channel intended solely for use in implementing
   fossil(1)'s sync protocol in libfossil in a synchronous,
   I/O-channel-agnostic manner.  (The name "sc" is an abbreviation of
   "sync channel".)  The idea is that we can hook up arbitrary
   streamable I/O channels via this interface, e.g. HTTP-, SSH-, and
   file-driven channels.

   Each instance must be fully populated to set up its fsl_cx, I/O
   methods, and non-NULL values for all required methods (init(),
   cleanup(), etc.). Each instance may have arbitrary state associated
   with it, but whether such state must be provided by the user, or is
   created/initialized by the open() implementation, is
   implementation-defined.

   A channel's lifecycle, in terms of its API, goes something like:

   - User populates a state object of the type required by the
     channel.

   - User cleanly initializes a fsl_sc instance by copy-initializing
     it from a known-good starting point, e.g. fsl_sc_empty or
     fsl_sc_popen. We'll call this object "sc".

   - User sets sc.state.p if necessary for the implementation.
     e.g. fsl_sc_popen requires that its state pointer refer to a
     properly-populated fsl_sc_popen_state object, e.g. a copy of
     fsl_sc_popen_state_curl.

   - User passes it off to the library for handling. A bit of vague
     hand-waving there.

   - Its init() method is called.

   - Its append() method will be called an arbitrary number of times
     to populate it with a fossil sync request payload.

   - Its submit() method is called to finalize the request payload
     and send it wherever it needs to go.

   - Its read() method is used to read the response payload. Sync
     protocol "cards" are read line-by-line and card-level payloads
     are read in their-payload-sized chunks.

   - For a multi-round-trip sync, its init() method is called once per
     round trip, starting the process over.

   - Its cleanup() method is called to clean it up.


   A client applies a channel of its own to a sync or a clone through
   fsl_xfer_config::channel. What the library requires of it:

   - init(), append(), submit() and read() must not be NULL and
     impl.p must not be NULL. A channel which lacks any of them is
     refused with FSL_RC_MISUSE and a message which names what it
     lacks. cleanup() is optional, and self() defaults to
     fsl_sc_self().

   - A method has failed if it returns non-0 or if it set the
     transfer's error state with fsl_xfer_error() or one of its
     siblings. If it set that state, the library reports that error as
     it is, whatever the method returned, so a method which fails
     should set a message and return the same code. If it returned
     non-0 without setting it, the library sets it to that code with a
     message which names the channel and the method. A read() which
     reaches the end of its input returns FSL_RC_BREAK, which is not a
     failure.

   - A read() asked for a positive number of bytes must append exactly
     that many, and a read() asked for FSL_SC_READ_LINE must append at
     least one byte. If it returns 0 having appended anything else
     the library fails the transfer with FSL_RC_MISUSE and a message
     which names the channel and says how many bytes were asked for
     and how many were appended.
*/
struct fsl_sc {
  /**
     The "transfer context" for this channel. This is set by the
     library and is needed by many related APIs.
  */
  fsl_xfer * xfer;

  /**
     A debugging-purposes name for this channel,
     e.g. "http-socket". The bytes are considered to be static, and
     must outlive any instance of this class which uses them.
  */
  char const * name;

  /**
     The remote fossil URL.

     It is up to the client to either set up the URL before passing
     this object on to the library or to ensure that the
     "last-sync-url" repository config entry (a URL string) is of a
     schema compatible with this instance.

     It is also up to the client to ensure that the URL scheme matches
     the fsl_sc implementation. How best to do that is still TBD.

     This memory is owned by this object.

     Recall that fsl_b_external() is a convenient way to wrap a (const
     char *) in this without having to allocate.
  */
  fsl_url url;

  /**
     Flags for customizing certain behaviors. See fsl_sc_F_lib_e.
  */
  fsl_flag32_t flags;

  /**
     Implementation-dependent state.
  */
  struct {
    /**
       Arbitrary state for implementations. Its ownership is
       implementation-defined, as is whether this object's init()
       method will populate this or whether the client must provide
       it. If this object owns it, its cleanup() method must free the
       memory and clear this member. If this object does not own this
       memory, whether it should clear this member is
       implementation-defined (but normally they should unless it
       points to static/global memory).
    */
    void * p;
    /**
       An optional value which uniquely identifies a specific
       type. Intended as a semi-type-safety measure for this->state.p.
       i.e. don't assume p is of the desired type unless this matches
       some well-defined value (which need not, and probably should
       not, be public).
    */
    void const * type;
  } impl;

  /**
     this->init()'s responsibility is to initialize and validate any
     resources which may be implied via this->impl.

     The second argument tells the implementation what type of
     initialization is required, as per the fsl_sc_init_e docs.

     FSL_SC_INIT_INITIAL is only ever passed one time per object and
     is guaranteed to be called before FSL_SC_INIT_REQUEST is. If the
     channel needs to perform any validation, that is the time to do
     it.

     FSL_SC_INIT_REQUEST is called each time a new request body needs
     to be generated, including the initial request. Implementations
     must discard any prior request-specific state when initialized
     with this value.

     ch->flags must be set before calling this and must not be
     modified afterwards. The library will set the ch->xfer member.

     It is up to the direct users of this API to ensure that their
     fsl_sc instances contain no randomly-initialized state before the
     initial call to this function. i.e. cleanly initialize _all_
     member state.

     This call may, depending on the impl, initialize ch->impl,
     whereas some channel implementations may require that the caller
     populate ch->impl with an implementation-defined "something".
     Those details are to be documented for each concrete
     implementation. The former strategy is of course preferred but
     some channels may require inputs which the library cannot account
     for.

     Implementations must return 0 on success. On error they must
     return a fsl_rc_e value and should ideally call fsl_xfer_error()
     on ch->xfer to report an error message and return its result.

     Regardless of success or failure, clients are required to
     eventually call the cleanup() method if they call init(). On a
     failed init() call, it is not generically knowable whether it's
     okay to call init() again, and clients should not do so.

     Whether or not this step will initialize any network and/or FILE
     and/or RPC connections is left to the implementation. It may do
     so here, if needed, or it may delay such things until submit().
  */
  int (*init)(fsl_sc *ch, enum fsl_sc_init_e mode);

  /**
     this->append() must append the first n bytes of pIn to the
     outbound sync request payload. The library calls this an
     arbitrary number of times to generate a sync body payload.

     Implementations are free to buffer, or not, the payload,
     depending on their requirements, but practical considerations may
     make buffering unavoidable. e.g. an HTTP implementation will
     require the full payload before sending, so that the Content-Size
     header can be set and the headers pushed before the payload is. A
     streaming-to-(FILE*) implementation, however, has no such
     requirements, so could avoid an extra buffering step (unless,
     perhaps, that file's contents are intended for further processing
     by, e.g., netcat(1), in which case HTTP headers would need to be
     prepended).

     Achtung: calling this API directly from client code will
     effectively corrupt the output. The library internals funnel all
     fsl_sc output traffic through a single point so that the size of
     the request and its SHA1 hash can be kept track of (both are
     needed for sending authenticated requests). Calling this API
     directly will bypass that and result in request bodies whose
     hashes do not match fossil's authentication expectations.
  */
  int (*append)(fsl_sc *ch, void const * pIn, fsl_size_t n);

  /**
     this->submit() tells the channel that the library is done
     building the request payload and it should be submitted.

     If this method buffers its response, it may close (if still
     opened) any channel opened by init() but should retain any state
     which might be needed for reestablishing that connection. If it
     does not buffer the response, it may keep the channel open for
     downstream read() calls.

     This is never called before init() is passed FSL_SC_INIT_REQUEST
     and is never called after any call to init() fails.

     If loginCard is not NULL, it contains the full content of a login
     card for the request. A channel which uses
     FSL_SC_F_REQUEST_HEADERS must not add it to the request: the
     library has put it in requestHeaders already, in the Cookie
     header shown below. Any other channel must carry these bytes to
     the remote. An HTTP channel emits them as a header in this form:

     ```
     Cookie: x-f-l-c=UrlEncodedValueOfTheCard
     ```

     Which, in C, might look something like:

     ```
     char * z = fsl_mprintf("Cookie: x-f-l-c=%t\r\n",
                             cmpp_b_cstr(loginCard));
     ...
     fsl_free(z);
     ```

     A channel which uses FSL_SC_F_NO_HTTP and does not use
     FSL_SC_F_REQUEST_HEADERS carries the card in whatever way suits
     its transport, and its peer must present it to the remote as that
     header.

     (Sidebar: that approach to authentication only works with fossil
     versions newer than 2025-07-27, so the library cannot log in
     to older fossil versions but can otherwise speak to them.)

     Implementations must return 0 on success. On error,
     implementations must return a non-FSL_RC_OK value from the
     fsl_rc_e enum, and are strongly encouraged to set an error
     message using the fsl_xfer_error() family of functions, passing
     ch->xfer to it.
  */
  int (*submit)(fsl_sc *ch, fsl_b const *loginCard);

  /**
     this->read() must read, or consume from its buffer, the requested
     amount of data and append it to tgt.  It must only append to the
     target buffer, not reset or otherwise manipulate it, as the
     buffer may already contain state when this is called.

     If howMuch is greater than zero, it's a number of bytes which are
     expected to be appended to tgt. A non-0 result code must be
     returned if exactly that many bytes cannot be consumed.

     If howMuch is FSL_SC_READ_LINE then:

     1) One newline-separated (0x0A) line must be consumed from the
        input source and be append to tgt, including the newline
        character.  Aside from interpretation of that one character,
        implementations must treat the preceeding data (if any) as
        opaque. i.e. it must not be otherwise parsed and empty lines
        must not be skipped.

     2) If no newline is found, return FSL_RC_BREAK if at EOF and no
        data precedes the EOF, else some other non-0 error code
        (e.g. FSL_RC_IO). The library will interpret FSL_RC_BREAK as a
        non-error EOF condition.

     If howMuch is FSL_SC_READ_ALL then the library must read the
     whole response into the target buffer. (This is used by the
     library to handle fossil-compressed response bodies on behalf of
     fsl_sc implementations.) If the implementation internally stores
     the response in a fsl_b, it should use fsl_b_swap() to
     transfer it to tgt, rather than copy it.  If it uses a file,
     fsl_stream() can be used to transfer it, e.g.:

     ```
     fsl_stream(fsl_input_f_FILE, responseFile,
                fsl_output_f_b, tgt);
     // or:
     fsl_stream(fsl_input_f_fd, &myFileDescriptor,
                fsl_output_f_b, tgt);
     ```

     When howMuch is FSL_SC_READ_ALL, the library will not read any
     more from the channel until/unless ch->submit() is called again,
     so the implementation may free up any related resources at that
     point if it likes.

     The library will never pass a howMuch value of 0 to this
     function, but it reserves the option of eventually using 0 as a
     way of communicating that we are done reading, if such a
     capability ever becomes useful. For future compatibility's sake,
     it's legal to simply return 0 if howMuch is 0, but it's also
     legal to assert(howMuch!=0) until that happens.

     How the end of a reply body is determined. The library never
     tells read() the length of the body and does not stop reading
     once it has read that many bytes, so read() must end the body
     itself, in HTTP mode and in FSL_SC_F_NO_HTTP mode alike. The
     length the library knows is the Content-Length header in HTTP
     mode and fsl_sc::reply.length in FSL_SC_F_NO_HTTP mode. It is
     used afterwards, to check what was read:

     - If the reply is not compressed, the library reads cards with
       FSL_SC_READ_LINE and with sized reads, and the body ends
       where a FSL_SC_READ_LINE read returns FSL_RC_BREAK. So read()
       must return FSL_RC_BREAK right after the last byte of the
       body and must not return any byte which follows it, as that
       belongs to the next reply. When the body has ended, the library
       fails the transfer with "truncated" or "longer than its
       Content-Length" if it read another number of bytes than the
       length.

     - If the reply is compressed, the library calls read() once, with
       FSL_SC_READ_ALL, which must append the whole body and no more:
       the library fails the transfer if that is not the length. It
       then decompresses the body and serves the cards from memory
       without calling read() again before the next submit().

     Must return 0 on success, non-0 on error, and should use one of
     the fsl_xfer_error() family of functions to to provide any error
     message and propagate the error through the library.
  */
  int (*read)(fsl_sc *ch, fsl_b * tgt, fsl_int_t howMuch);

  /**
     Must free up all dynamically-allocated resources owned by ch and
     ch->impl.

     Finalizing must, if appropriate, free up any resources it uses,
     but must not free the object passed to it (which might be
     stack-allocated or part of a larger struct). If this connection
     is still open, it must close it.

     It is up to the implementation to set ch->impl.p to 0 if that's
     appropriate for them - the library does not do so. Some
     implementations may use static state and not need to reset
     ch->impl.

     In the wisdom of "destructors must not throw," the library
     provides no way to report a failure to close a channel (nor does
     it really care, at that point - by then the channel will have
     either already failed or served its purpose). If, after this
     call, ch->f has error state, the library has the option, at its
     developers' discretion, of emitting a warning to the client (this
     is unspecified and currently unimplemented, but warning and/or
     debug channels may be added at some point).

     The library will never pass NULL to this function.

     This method must never be called directly from client
     code. Instead, pass the object to fsl_sc_cleanup(), as that will
     free up the common fsl_sc members, leaving clean() impls to only
     concern themselves with their own private state.
  */
  void (*cleanup)(fsl_sc *ch);

  /**
     This is internal-use tooling to support adding "shim" layers of
     fsl_sc between the library and the "real" fsl_sc. The default
     impl (fsl_sc_self()) is suitable for all non-proxying channels
     and simply returns its argument. The impl for the tracer channel
     returns the object it's tracing. This distinction is relevant for
     handling of fsl_sc internals such as ch->url and ch->flags, in
     that (A) the internals always want those values to come from the
     "real" implementation, not the shim, and (B) they don't want code
     which is using a shim to have to know it's using a shim.  Calling
     ch->self(ch)->url will return the "correct" URL object.

     Implementation code of a fsl_sc, unless that channel is itself a
     proxy for another, should not use this - it's simply not needed
     there.  It's used by library code which wants to avoid having to
     know there's a shim/proxy channel in place. Implementors of proxy
     channels must provide a self() implementation which looks
     something like the following (taken from the tracer channel):

     ```
     // Custom channel state, set in fsl_sc::impl.p of channels
     // of this subtype.
     struct my_channel_state {
       fsl_sc * proxied; // proxied channel
       ... any other necessary state ...
     };
     typedef struct my_channel_state my_channel_state;

     fsl_sc * my_self(fsl_sc *ch){
       my_channel_state * const st = ch->impl.p;
       fsl_sc * const orig = st->proxied;
       return orig->self(orig); // call self() in case orig is a proxy!
     }
     ```
  */
  fsl_sc * (*self)(fsl_sc *ch);

  /**
     If this->flags contains FSL_SC_F_REQUEST_HEADERS, the library
     will populate this with raw HTTP headers for the request,
     including a trailing `\r\n` line, immediately before calling
     submit().  Implementations' submit() methods must, unless they do
     their own header generation, emit this before the body.  See
     FSL_SC_F_REQUEST_HEADERS.
  */
  fsl_b requestHeaders;
  /**
     A general-purpose scratchpad buffer for use by the channel object
     and the library internals.
  */
  fsl_b scratch;
  /**
     For channels with FSL_SC_F_NO_HTTP: what submit() must set to
     describe the reply, in place of the Content-Length and
     Content-Type headers. A length of 0 is an error.
  */
  struct {
    /** Size of the reply body in bytes. */
    fsl_size_t length;
    /** True if the body is fossil-compressed, as for FSL_SC_F_COMPRESSED. */
    bool compressed;
  } reply;
}/*fsl_sc*/;

/**
   An implementation for fsl_xfer::debug::callback which requires
   that the associated state be a (FILE*) handle opened for output.
   Each call sends zMsg to that FILE handle via fprintf(), without
   additional decoration.
*/
FSL_EXPORT void fsl_xfer_debug_f_FILE(fsl_xfer *xf, char const * zMsg);

/**
   An implementation for fsl_xfer::debug::callback which requires
   that the associated state be a (fsl_b*). On each call zMsg is
   appended as-is to that buffer, without additional decoration.
*/
FSL_EXPORT void fsl_xfer_debug_f_buffer(fsl_xfer *xf, char const * zMsg);

/**
   The default implementation of fsl_sc::self(). Simply returns
   ch.
*/
FSL_EXPORT fsl_sc * fsl_sc_self(fsl_sc *ch);

/** Empty-initialized fsl_sc instance, intended for const-copy
    initialization. */
#define fsl_sc_empty_m {        \
    .xfer=0, .name="unnamed",   \
    .url=fsl_url_empty_m,       \
    .flags = 0,                 \
    .impl = {.p = 0,.type = 0}, \
    .init=0, .append = 0,       \
    .submit=0,                  \
    .read=0, .cleanup=0,        \
    .self=fsl_sc_self,          \
    .requestHeaders = fsl_b_empty_m, \
    .scratch = fsl_b_empty_m     \
}

/** Empty-initialized fsl_sc instance, intended for copy
    initialization. */
extern const fsl_sc fsl_sc_empty;

/**
   Flags regarding which configuration options to sync.
*/
enum fsl_config_sync_e {
  FSL_CFG_SYNC_NONE         = 0,
  FSL_CFG_SYNC_CSS          = 1<<0, /* Style sheet only */
  FSL_CFG_SYNC_SKIN         = 1<<1, /* WWW interface appearance */
  FSL_CFG_SYNC_TKT          = 1<<2, /* Ticket configuration */
  FSL_CFG_SYNC_PROJ         = 1<<3, /* Project name */
  FSL_CFG_SYNC_SHUN         = 1<<4, /* Shun settings */
  FSL_CFG_SYNC_USER         = 1<<5, /* The USER table */
  FSL_CFG_SYNC_ADDR         = 1<<6, /* The CONCEALED table */
  FSL_CFG_SYNC_XFER         = 1<<7, /* Transfer configuration */
  FSL_CFG_SYNC_ALIAS        = 1<<8, /* URL Aliases */
  FSL_CFG_SYNC_SUBSCRIBER   = 1<<9, /* Email subscribers */
  FSL_CFG_SYNC_IWIKI        = 1<<10, /* Interwiki codes */
  FSL_CFG_SYNC_ALL          = 0x0000ffff, /* Everything */
  FSL_CFG_SYNC_OVERWRITE    = 0x10000000 /* Causes overwrite instead of merge */
};

typedef struct fsl_xfer_config fsl_xfer_config;

/**
   Synchronizes the repository currently opened by f with the peer
   selected by config. config->op.pull and config->op.push select the
   transfer direction. At least one must be true and config->op.clone
   must be false.

   This function requires an opened repository.

   Each protocol round runs in its own transaction, which is committed
   before the next request goes out, as fossil(1)'s client does. That
   keeps the repository's write lock free while waiting on the network,
   so other connections can write between rounds. If the caller has a
   transaction open, the rounds are savepoints nested in it, and
   nothing reaches the disk until the caller commits.

   If a reply holds an error card, or a card or body which cannot be
   handled, then processing of that reply stops there, what was
   received before that point is kept, and further rounds follow if
   the session still has work to do, as sections 5.2 and 10.1 of the
   sync draft require, though no further batches of local artifacts
   are pushed. The session then keeps everything it received and
   returns the first such error. A second such error ends the session
   at once, likewise keeping what was received and returning the
   first error. On any other error (e.g. out of memory, a db error, a
   project code mismatch, or received content which does not match its
   hash), the session ends at once: the current round is rolled back,
   and rounds which were already committed are kept. Like fossil(1), a
   later sync picks up where it stopped.

   On success, returns 0. On error it returns a non-0 fsl_rc_e value
   and propagates error information through err (if not NULL), or
   through f when err is NULL.
*/
FSL_EXPORT int fsl_sync_client(fsl_cx * f,
                               fsl_xfer_config const * config,
                               fsl_error * err);

#if 0
/**
   Resets ch's buffers for re-use and then calls ch->submit().

   This is prefered to calling ch->submit() directly because this
   ensures that ch's buffers are accounted for.
*/
FSL_EXPORT void fsl_sc_close(fsl_sc * const ch);
#endif

/**
   Calls fsl_sc_close() then, if ch->cleanup is not NULL, it is
   called. Then it frees all of ch's buffers. Does not free ch.

   This is prefered to calling ch->cleanup() directly because this
   ensures that ch's buffers are accounted for.
*/
FSL_EXPORT void fsl_sc_cleanup(fsl_sc * ch);

/**
   If xf has a debug channel installed, the given
   fsl_appendf()-compatible arguments are posted to it in string
   form. The output may be prefixed with other information.

   If xf has no debugging channel then this function has no
   side-effects.

   This function adds a newline to the result if it does not end in
   one.

   Returns 0 on success and the only error case is a formatting buffer
   allocation error, which causes FSL_RC_OOM to be returned. Such
   results should not be propagated by client code - an OOM is
   innocuous in the context of debugging output.

   This function requires allocating memory, and re-uses a buffer
   dedicated to that purpose. In ideal cases, it won't have to
   allocate more than once during the lifetime of a given fsl_xf
   instance.

   WARNING: fsl_xfer_config::debug-bound logging functions must not
   call this, else there will be an endless loop and eventual stack
   overflow.
*/
FSL_EXPORT int fsl_xfer_debugf(fsl_xfer * xf, char const * zFmt, ...);

/** va_list variant of fsl_xfer_debugf(). */
FSL_EXPORT int fsl_xfer_debugfv(fsl_xfer * xf, char const * zFmt, va_list args);

/**
   Equivalent to fsl_xfer_debugf(ch,"%s",zMsg) but is more efficient
   than that.
*/
FSL_EXPORT void fsl_xfer_debug(fsl_xfer * xf, char const * zMsg);

/**
   Returns xf's fsl_cx context. This is used in fsl_sc callback
   implementations.
*/
FSL_EXPORT fsl_cx * fsl_xfer_cx(fsl_xfer * xf);

/**
   Returns the most bytes xf's transfer accepts in one reply body,
   compressed or uncompressed: fsl_xfer_config::maxResponseBytes if it
   is positive, else 256 MiB. The library checks a reply against it
   when it knows its length. A channel which reads a reply of unknown
   length should stop and fail when the reply gets longer.

   xf may be NULL, as for a channel used outside of a transfer, and
   then the result is the default.

   fsl_sc::xfer is set before fsl_sc::init() is first called, so
   this may be used from there.
*/
FSL_EXPORT fsl_size_t fsl_xfer_max_response(fsl_xfer const * xf);

/**
   Returns the number of seconds a channel should let a read or write
   make no progress before failing the transfer:
   fsl_xfer_config::socketTimeoutSeconds if it is positive, else 120.
   The library does not enforce this itself: it is for channels which
   do their own I/O, as the native socket channel does.

   xf may be NULL, as for fsl_xfer_max_response(), and fsl_sc::xfer is
   set before fsl_sc::init() is first called.
*/
FSL_EXPORT int fsl_xfer_socket_timeout(fsl_xfer const * xf);

/**
   Sets xf's (persistent) error state to the given information
   and propagates it through to xf's fsl_cx. After this,
   further calls to fsl_xf-taking APIs will fail.

   This is intended to only be used from fsl_sc implementations
   and this library's own internals.

   This function prefixes the message with some form of ch->name and
   the fsl_rc_cstr() value of the given result code.

   The format is fsl_appendf()'s, not the C library's. In it %z is not
   a size modifier: it prints a (char *) like %s and then frees it, as
   in SQLite, so "%zu" with a size_t crashes. Print sizes with
   FSL_SIZE_T_PFMT, e.g. "%" FSL_SIZE_T_PFMT.

   Returns the given code, or FSL_RC_ERROR if code is 0. i.e.
   it never returns 0. A code value of 0 is semantically illegal in
   this context.
*/
FSL_EXPORT int fsl_xfer_errorf(fsl_xfer *xf, int code, char const * zFmt,
                               ...);

/** va_list variant of fsl_xfer_errorf(). */
FSL_EXPORT int fsl_xfer_errorfv(fsl_xfer *xf, int code, char const * zFmt,
                              va_list args);

/**
   Equivalent to fsl_xfer_errorf(ch,code,"%s",zMsg) unless code is
   FSL_RC_OOM, in which case zMsg is disregarded.
*/
FSL_EXPORT int fsl_xfer_error(fsl_xfer *xf, int code, char const * zMsg);

/**
   Policies for use with fsl_sc_popen indicating how to fetch the
   response from invoking an external command to transport fossil sync
   requests. This is all internal experimentation, not part of the
   public API.
*/
enum fsl_sc_popen_e {
  /**
     Directs the binary's stdout to a temp file bound to
     fsl_sc_popen_state::response::fp using fopen().

     This "should" work the same as fsl_sc_popen_e_direct but this one
     works where that one doesn't, for reasons unknown.

     Measurements show, somewhat surprisingly, this to be
     significantly faster than fsl_sc_popen_e_membuf (anywhere from
     30% to twice as fast, depending on the test run), as well as far
     memory-lighter: 410kb peak RAM vs 9.4MB peak ram for the same
     clone of fossil's canonical repository.
  */
  fsl_sc_popen_e_filebuf = 1,

  /**
     Don't use this except for experimentation.

     Slurp whole response into a fsl_b at
     fsl_sc_popen_state::response. This works but can use a huge
     amount of memory.

     This is slower than fsl_sc_popen_e_filebuf and much more
     memory-hungry.  The main speed culprit seems to be
     fsl_b_stream_lines(), which takes up some 25% of the test
     run's CPU instructions (as reported by callgrind).
  */
  fsl_sc_popen_e_membuf = 2,

  /**
     Does not work!

     Don't buffer: read response from the binary's stdout, bound to
     fsl_sc_popen_state::process::fdStdOut.

     This mode is currently failing with curious read failures: for
     _some_ cards, reading the payload leaves (apparently) pieces
     which are then read by the next read-line op and of course don't
     parse as a card. The cause is as-yet unknown but it's got to be a
     bug somewhere in this code.
  */
  fsl_sc_popen_e_direct = 3,

  /**
     Does not work!

     Read the binary's stdout using an unbuffered file descriptor
     open()ed on fsl_sc_popen_state::response::fd.

     This is is known to fail with "not found" for the output file
     after fsl_popen2()'ing the command (at which point we expect the
     output to be there). This "should" fail in the same way as
     fsl_sc_popen_e_direct, as we're doing the same thing just with
     another file of indirection.
  */
  fsl_sc_popen_e_fd = 4,

  /**
     Mode used by fsl_sc_popen_state_empty.
  */
  fsl_sc_popen_e_default = fsl_sc_popen_e_filebuf
};

typedef struct fsl_sc_popen_state fsl_sc_popen_state;

/**
   State for use with the fsl_sc_popen fsl_sc impl. fsl_sc_popen
   requires that its state member point to an instance of this class.

   This type acts as a base implemtation for channels which
   "shell out" to an external binary to provide the transport
   layer. e.g. curl can be used for HTTP(S) and fossil(1)'s own
   "test-http" mechanism can be used this way.
*/
struct fsl_sc_popen_state {
  /**
     State for "subclasses". Not really subclasses, but "concrete
     implementations" gets unwieldy after a while.
  */
  struct {
    /**
       This optional method gets called as part of the
       FSL_SC_INIT_INITIAL phase of fsl_sc::init() to give subclasses
       a way to perform any validation they may need. It may also
       perform any one-time initialization it may need to do.

       If it returns non-0, channel initialization fails.
    */
    int (*init)(fsl_sc *ch);

    /**
       Command arguments initializer. Must be set by concrete
       implementations and it gets invoked via
       fsl_sc::submit(). Implementations must populate b using
       ((fsl_sc_popen_state*)ch->impl.p)'s state, namely the
       request.filename and response.filename members, which are names
       of temporary files which will eventually contain the request
       payload and response payloads.

       Implementations must use fsl_b_escape_arg() and friends to
       append a complete command line to b. They must return 0 on
       success.

       When this is called (early on in the fsl_sc::submit() process):

       - this->bin.location will be set to the command to invoke. It
         must be prepended to the command line (or may it may be
         proxied via a separate command known only to the concrete
         implementation).

       - this->url will be set to the remote fossil URL.

       - this->request.filename is a file which the
         command is expected to read the fossil sync request body
         payload from.

       - If this->response.filename is not NULL then it is a file
         which the command is expected to write the fossil sync
         response to, minus any transport-layer metadata like HTTP
         headers. If it is NULL, the process is expected to write to
         stdout.

       - None of the other this->request and this->response members
         will be set up.

       - If bLoginCard is not NULL then it will hold the content for a
         fossil sync login card. Implementations must emit an HTTP
         header in the form "Cookie: x-f-x-l=XYZ" where XYZ is the
         URL-encoded content of bLoginCard.  For fsl_sc impls which
         use the FSL_SC_F_REQUEST_HEADERS flag, the library will have
         populated ch->requestHeaders before this is called, including
         the login card.
    */
    int (*buildCommandLine)(fsl_sc * ch, fsl_b * b,
                            fsl_b const * bLoginCard);

    /**
       May be set for subclasses in order to clean up any dynamic
       state owned by this object in this->impl.state. It will be
       called early in the fsl_sc::cleanup() step, before st's base
       class state are cleaned.

       Whether or not it must free st is implementation-defined.
    */
    void (*cleanup)( fsl_sc_popen_state * st );

    /**
       Subclass-specific state. Owned by this object's cleanup()
       method.
    */
    void * state;
  } impl;

  /** Info about the binary. */
  struct {
    /**
       The name of the program binary, e.g. "curl". It is expected to
       be findable via the $PATH.
    */
    char const * name;
    /**
       Location where the binary was found. If NULL, it defaults to a
       $PATH search of this->bin.name. Clients may set this before
       use, but (A) it must be allocated using a libfossil API,
       e.g. fsl_mprintf(), and (B) this memory is owned by this
       object.

       If the client does not set this, the library will search in the
       $PATH for this->name and assign that value here.
    */
    char * location;
  } bin;
  /** State for/around fsl__popen2(). */
  struct {
    /** The external process's stdin, i.e. a write-only stream. */
    FILE *fStdIn;
    /** The external process's stdout, i.e. a read-only stream. */
    int fdStdOut;
    /** The external process's PID. */
    int pid;
  } process;

  /**
     State for the sync request payload.
  */
  struct {
    /** Filename of this->fp. */
    char *filename;
    /** Request payload temp file. */
    FILE *fp;
    /** Number of initiated requests. */
    unsigned count;
  } request;

  /**
     State for the sync response payload.
  */
  struct {
    /**
       How to read the response. This should never be set by clients.
       It's for library-internal experimentation. If it must be set as
       part of a struct initialization, set it to
       fsl_sc_popen_e_default.
    */
    enum fsl_sc_popen_e mode;
    /**
       Response temp file when this->response.mode is
       fsl_sc_popen_e_filebuf or fsl_sc_popen_e_fd.
    */
    char *filename;
    /**
       Response source file when this->mode is fsl_sc_popen_e_filebuf.
       This file is opened in "w+b" mode.
    */
    FILE * fp;
    /**
       Response input source when this->mode is fsl_sc_popen_e_fd.
    */
    int fd;
    /** Number of initiated response-reads. */
    unsigned count;
    /**
       Response body when this->mode is fsl_sc_popen_e_membuf.
    */
    fsl_b b;
  } response;

  /**
     Flag(s).
  */
  struct {
    /**
       Internal implementation detail. Tells fsl_sc_popen's
       cleanup() impl whether or not to free() this object.
    */
    void * allocStamp;

    /**
       A random prefix for temp file names. Memory is owned by this
       object. All request and response temp files are prefixed with
       this and get a predictable suffix. We generate a random prefix,
       rather than a new random name on each call, to simplify
       grouping of the files for development and debugging purposes.
    */
    char * tmpfilePrefix;
  } misc;

  /**
     The command line to invoke. This is intended to be set up by
     this->impl.buildCommandLine.
  */
  fsl_b cmd;
};

/**
   Initializer for a fsl_sc_popen_state object which sets
   obj.bin.name=BinName, obj.impl.buildCommandLine=XCmdInit, and
   obj.impl.cleanup=XCleanup.

   The object is intended only for use as the fsl_sc::state pointer of
   a copy of fsl_sc_popen.
*/
#define fsl_sc_popen_state_init(BinName,xInit,XCmdInit,XCleanup) {  \
  .impl = {                                                  \
    .init=xInit,                                             \
    .buildCommandLine=XCmdInit,                              \
    .cleanup=XCleanup, .state = 0                            \
  },                                                         \
  .bin = { .name = BinName, .location = 0 },                 \
  .process = {                                               \
    .fStdIn = 0, .fdStdOut = -1, .pid = 0                    \
  },                                                         \
  .request = {                                               \
    .filename = 0, .fp = 0, .count=0                         \
  },                                                         \
  .response = {                                              \
    .mode = fsl_sc_popen_e_default,                          \
    .filename = 0, .fp = 0, .fd = -1,                        \
    .count=0, .b = fsl_b_empty_m                        \
  },                                                         \
  .misc = {                                                  \
    .allocStamp = 0,                                         \
    .tmpfilePrefix = 0                                       \
  },                                                         \
  .cmd = fsl_b_empty_m                                  \
}

//#define fsl_sc_popen_state_empty_m fsl_sc_popen_state_init("unnamed",0,0)

/**
   An empty base fsl_sc_popen_state instance intended to be
   copied to intialize fsl_sc_popen_state implementations.
   Implementations must set the bin.name and
   impl.buildCommandLine members to whatever is appropriate for the
   object's external binary.
*/
extern const fsl_sc_popen_state fsl_sc_popen_state_empty;

/**
   An empty base fsl_sc instance for use with fsl_sc_popen_state
   implementations.

   To use it:

   1. Bitwise-copy it over a fsl_sc instance.

   2. Set its state.p member to point to a valid fsl_sc_popen_state
      instance.

   3. Do not modify its state.type member.

   Nuances of this implementation:

   - Its state.p _must_ be a (fsl_sc_popen_state*) and state.type must
     be &fsl_sc_popen. This initializer does that latter part.

   - If state->flag.allocStamp is not 0, it must point to state->p.
     This indicates that this object owns its state pointer and will
     free it via this object's cleanup() method.
*/
extern const fsl_sc fsl_sc_popen;

/**
   An empty state object of the type expected by fsl_sc_popen,
   configured to use the system's "curl" binary as the fossil sync
   communication channel.

   This class is not needed if libfossil is built with libssl, in
   which case it can talk HTTP(s) via that.
*/
extern const fsl_sc_popen_state fsl_sc_popen_state_curl;

/**
   Like fsl_sc_popen but may include different fsl_sc::flags defaults.
   The state.p member _must_ point to a fsl_sc_popen_state instance
   initialized by bitwise copying from fsl_sc_popen_state_curl.

   Example usage:

   ```
   fsl_sc_popen_state pst = fsl_sc_popen_state_curl;
   fsl_sc st = fsl_sc_popen_curl;
   st.state.p = &pst;
   ```
*/
extern const fsl_sc fsl_sc_popen_curl;

/**
   Works like fsl_sc_popen_curl but uses "fossil test-http" for the
   transport layer. The fsl_sc::state::p pointer of these objects MUST be a
   pointer to an fsl_sc_popen_state object which was initialized by
   copying it from fsl_sc_popen_state_fth. Example:

   ```
   fsl_sc sc = fsl_sc_popen_fth;
   fsl_sc_popen_state st = fsl_sc_popen_state_fth;
   sc.state.p = &sc;
   ```
*/
extern const fsl_sc fsl_sc_popen_fth;
/**
   State type for use with fsl_sc_popen_fth.
*/
extern const fsl_sc_popen_state fsl_sc_popen_state_fth;

/**
   Works like fsl_sc_popen_curl but uses "ssh ... fossil test-http" for the
   transport layer. The fsl_sc::state::p pointer of these objects MUST be a
   pointer to an fsl_sc_popen_state object which was initialized by
   copying it from fsl_sc_popen_state_ssh. Example:

   ```
   fsl_sc sc = fsl_sc_popen_ssh;
   fsl_sc_popen_state st = fsl_sc_popen_state_ssh;
   sc.state.p = &sc;
   ```

   By default it assumes that fossil(1) is in the remote's $PATH, but
   it can be explicitly told the path by providing a query argument to
   the URL: fossil=/path/to/remote/fossil (URL-encoded if it contains
   anything which needs to be).

   Peculiarities of this implementation:

   - The user in the URL is the ssh login, and ssh does the
     authentication. We copy fossil(1): no fossil login card is sent,
     and any password supplied in the URL is ignored.
*/
extern const fsl_sc fsl_sc_popen_ssh;

/**
   State type for use with fsl_sc_popen_ssh.
*/
extern const fsl_sc_popen_state fsl_sc_popen_state_ssh;

/**
   A native socket-based sync channel for http:// and https:// URLs. It
   is a drop-in peer of fsl_sc_popen_curl which removes the dependency
   on an external curl binary by speaking HTTP over a TCP socket
   directly (and, when built with FSL_NATIVE_TLS_OPENSSL, TLS for
   https://). It uses the library-generated HTTP headers
   (FSL_SC_F_REQUEST_HEADERS), as the "fossil test-http" channel does.

   A client copy-initializes an fsl_sc from this value, calls
   fsl_sc_socket_state_init() on it to allocate per-channel private
   state, then hands it to the sync machinery, e.g.:

   ```
   fsl_sc ch = fsl_sc_socket;
   fsl_url_parse(&ch.url, zUrl);
   fsl_sc_socket_state_init(&ch);
   ```

   See doc/sync-native-channel.md.
*/
extern const fsl_sc fsl_sc_socket;

/**
   Allocates and installs the private state for an fsl_sc_socket
   instance. Call after copy-initializing an fsl_sc from fsl_sc_socket
   and before its init(). Returns 0 on success, FSL_RC_OOM on
   allocation failure. The state is freed by the channel's cleanup().
*/
FSL_EXPORT int fsl_sc_socket_state_init(fsl_sc *ch);

/**
   What read() returns when no byte arrived within
   fsl_xfer_socket_timeout() seconds. See fsl_sc_stream_ops.
*/
#define FSL_SC_STREAM_TIMEOUT ((fsl_int_t)-2)

/**
   What read() returns at the end of a stream which was not closed
   cleanly, as when a TLS peer closes the connection without a
   close_notify alert. See fsl_sc_stream_ops.
*/
#define FSL_SC_STREAM_UNCLEAN ((fsl_int_t)-3)

/**
   The callbacks of a stream channel, which gives a caller who has
   only a byte stream (a TCP or TLS connection, a Unix socket, a
   tunnel) the library's HTTP handling, so that the caller writes none
   of it: the request line and headers, the HTTP/1.1 upgrade with
   "Connection: close", replies with a Content-Length, close-delimited
   replies, chunked replies, the reply size limit and the timeout.
   The library's own http: and https: channel is this same channel
   with sockets and OpenSSL as its callbacks.

   The channel makes one request per connection. For each round
   trip it calls connect(), then write() until the request is sent,
   then read() until it returns 0 and then close(). It also calls
   close() when the transfer ends with the connection open, as after
   a failed write(). The calls all come from the thread which runs the
   transfer.

   Every callback which can fail receives the transfer, xf, to report
   the failure to. A failing callback sets the error state with
   fsl_xfer_errorf() or one of its siblings, naming what failed, and
   returns as described below. The channel then fails the transfer
   with that error, as for the methods of fsl_sc. If a callback fails
   without setting one, the channel sets a message which names the
   channel and the callback.

   The callbacks must make progress or fail: the library cannot
   interrupt a blocked callback.
*/
struct fsl_sc_stream_ops {
  /**
     Opens the connection to the host in url: url->host, url->port
     (0 if the URL has none), url->scheme and url->path. The library
     does not interpret the scheme, so a caller may use any. If it
     does TLS, it also does all of its certificate handling. Returns
     0 on success. The callback should not let a later read() or
     write() wait longer than fsl_xfer_socket_timeout(xf) seconds
     for progress.
  */
  int (*connect)(void * state, fsl_url const * url, fsl_xfer * xf);

  /**
     Reads up to n bytes into dest and returns how many it read. It
     returns at least one byte, waiting for it if need be, unless the
     stream has ended, when it returns 0 if the peer closed the
     connection cleanly, with a TCP FIN or a TLS close_notify, and
     FSL_SC_STREAM_UNCLEAN if it did not, as a TLS peer which just
     closes the connection. Both end the reply, and the library
     checks it against its Content-Length. A reply which has neither a
     Content-Length nor chunks ends where the connection does, and is
     accepted only after a clean close, as it could otherwise be cut
     short. If no byte arrives within
     fsl_xfer_socket_timeout(xf) seconds it returns
     FSL_SC_STREAM_TIMEOUT. The library treats that as the end of the
     reply if the peer had already sent some of it, and otherwise
     fails with "No response from HOST within N seconds". Any other
     negative result is a failure.
  */
  fsl_int_t (*read)(void * state, void * dest, fsl_size_t n,
                    fsl_xfer * xf);

  /**
     Writes up to n bytes from src and returns how many it wrote,
     which is at least one, or a value less than 1 on failure.
     The library calls it again for the rest.
  */
  fsl_int_t (*write)(void * state, void const * src, fsl_size_t n,
                     fsl_xfer * xf);

  /**
     Closes the connection and releases whatever connect() acquired.
     It is optional.
  */
  void (*close)(void * state);

  /**
     The first argument of all of the callbacks. It is the caller's.
  */
  void * state;
};
typedef struct fsl_sc_stream_ops fsl_sc_stream_ops;

/**
   Initializes ch as a stream channel which calls ops, ready to be
   assigned to fsl_xfer_config::channel. ops must have its connect(),
   read() and write() set, and it and what its state points to must
   outlive every transfer which uses ch, because ch points to ops
   until a transfer starts and copies it. Each transfer takes its own
   copy of ch, which allocates and frees the buffers it needs, so
   nothing has to be cleaned up afterwards and ch may serve any number
   of transfers one after another.

   The URL of the transfer is parsed into the channel's copy and
   passed to ops->connect(). Its scheme, such as https, has no
   meaning to the channel.

   ch->name is "stream", which prefixes the channel's error
   messages. A caller may change it after this returns.

   Returns 0 on success and FSL_RC_MISUSE if ch or ops is NULL or ops
   lacks a required callback.
*/
FSL_EXPORT int fsl_sc_stream_init(fsl_sc * ch, fsl_sc_stream_ops const * ops);

/**
   Expands to a mapping of all fsl_sc_tracer_e types by invoking
   E(NAME,VALUE) for each one. NAME is the suffix part of the name,
   e.g. init instead of FSL_SC_TRACER_init. VALUE is its integer
   value.
*/
#define fsl_sc_tracer_map(E)              \
  E(none,0)                               \
  E(init,1) E(read, 1<<1) E(append, 1<<2) \
  E(cleanup, 1<<3) E(submit, 1<<4) E(self, 1<<5) \
  E(debug, 1<<6)

/**
   Flags for use with fsl_sc_tracer_init().
*/
enum fsl_sc_tracer_e {
#define E(NAME,FLAG) FSL_SC_TRACER_ ## NAME = FLAG,
  fsl_sc_tracer_map(E)
#undef E

  FSL_SC_TRACER_all = 0
#define E(NAME,FLAG) | FSL_SC_TRACER_ ## NAME
  fsl_sc_tracer_map(E),
#undef E

  FSL_SC_TRACER_default = FSL_SC_TRACER_init
  | FSL_SC_TRACER_cleanup
  | FSL_SC_TRACER_submit
  | FSL_SC_TRACER_self
};

/**
   An fsl_sc implementation which proxies another, which must be
   set as its state member.

   This proxy calls fsl_sc_debug() with the name of each called fsl_sc
   method before passing the method on to the proxied changed.

   The exception is: the fsl_sc::debug.callback method is passed that
   through directly because calling fsl_sc_debug() on itself leads to
   an endless loop.

   The out argument is where debug output should be written
   to. Neither out nor out->out may be NULL.

   Example:

   ```
   fsl_outputer out = ...;
   fsl_sc orig = ...another sc...;
   fsl_sc tracer = fsl_sc_tracer_empty;
   fsl_sc * const sc = fsl_sc_tracer_init(
       &tracer, &orig, FSL_SC_TRACER_all, &out
   );
   assert( !sc || sc==&tracer );
   ```

   Then use tracer in place of orig with the downstream APIs.  Calling
   tracer.cleanup(&tracer) will also cleanup orig.
*/
extern const fsl_sc fsl_sc_tracer_empty;

/**
   Initializes chTrace as a copy of fsl_sc_tracer_empty then directs
   chTrace's state to point to ch. Returns chTrace on success.  On
   error it returns NULL.
*/
FSL_EXPORT fsl_sc * fsl_sc_tracer_init(fsl_sc *chTrace, fsl_sc *ch,
                                       fsl_flag32_t traceFlags,
                                       fsl_outputer * out);

/** @internal

   Pass the name of a macro which takes 2 arguments to this
   macro. Macro E will be called with (NAME,LENGTH) of each sync card
   type. NAME is the unquoted name. LENGTH is strlen(#NAME) (which we
   need in a compile-time form).

   !!! Keep these sorted by name and edit code which uses these to
   !!! match. Internals require them to be sorted by name. Actually...
   !!! maybe not anymore.
*/
#define fsl_xfcard_map(E) \
  /* KEEP */   E(cfile,5) E(clone,5) E(clone_seqno,11) E(config,6)   \
  /* THESE */  E(cookie,6) E(error,5) E(file,4) E(gimme,5) E(igot,4) \
  /* SORTED */ E(login,5) E(uvfile,6) E(message,7) E(pragma,6)       \
  /* BY */     E(private,7) E(pull,4) E(push,4) E(reqconfig,9)       \
  /* NAME */   E(uvgimme,7) E(uvigot,6)

/** @internal

   Ids for fossil sync protocol card types.

   This is only exposed in the public API for use with
   fsl_xfer_metrics. It is otherwise an internal type.
*/
enum fsl_xfcard_e {
  /* MUST BE FIRST. Reminder to self: this has to be outside of
     fsl_xfcard_map() because of how fsl__xfcard_search() is set up. */
  fsl_xfcard_e_unknown,

#define E(T,LEN) fsl_xfcard_e_ ## T,
  fsl_xfcard_map(E)
#undef E

  /* Sentinel entry */
  fsl_xfcard_e_COUNT
};
typedef enum fsl_xfcard_e fsl_xfcard_e;
/**
   A comma-separated list of zeroes: one for each entry in
   fsl_xfcard_e.
*/
#define fsl_xfcard_zeroes \
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

/**
   Metrics for use with the library's "xfer" (sync) subsystem.
*/
struct fsl_xfer_metrics {
  /** Number of connections made to the remote. */
  fsl_size_t trips;
  /** Number of "igot" cards sent */
  fsl_size_t iGotSent;
  /** Number of private "igot" cards */
  fsl_size_t privIGot;
  /** Number of gimme cards sent */
  fsl_size_t gimmeSent;
  /** Number of files sent */
  fsl_size_t fileSent;
  /** Number of deltas sent */
  fsl_size_t deltaSent;
  /** Number of files received */
  fsl_size_t fileRcvd;
  /** Number of deltas received */
  fsl_size_t deltaRcvd;
  /** Number of dangling deltas received */
  fsl_size_t danglingFile;
  /** Total received artifacts */
  fsl_size_t rcvdArtifacts;
  /** Largest card payload size */
  fsl_size_t largestCardPayload;
  /**
     Buffer capacity allocated for the latest single
     fossil-compressed response.
  */
  fsl_size_t largestDecompressedResponse;
  /**
     Number of compressed response bytes via fsl__xfer_submit().
     This counts only compressed response bodies, not the compressed
     content of cfile cards.
  */
  fsl_size_t bytesReadCompressed;
  /** Number of uncompressed response bytes via fsl__xfer_read() and
      fsl_xfer_readln(). */
  fsl_size_t bytesReadUncompressed;
  /**
     Number of response body bytes as received from the peer,
     before any decompression.
  */
  fsl_size_t bytesReadWire;
  /** Number of bytes via fsl__xfer_append() and friends. */
  fsl_size_t bytesWritten;
  /** Counts of each card type seen in the response(s). */
  fsl_size_t cardsRx[fsl_xfcard_e_COUNT];
  /**
     Counts of each card type sent in request(s).

     TODO: replace most of the card-specific members with this.  We
     first need to change how fsl__xfer_appendln() works.
  */
  fsl_size_t cardsTx[fsl_xfcard_e_COUNT];

  /** Various timing metrics. */
  struct {
    /** Time spent waiting on fsl_sc::read(), but only via
        fsl__xfer_read(), fsl__xfer_readln(), and (when reading
        compressed responses) fsl__xfer_submit(). */
    fsl_timer read;
    /** Time spent waiting on fsl_sc::submit(). */
    fsl_timer submit;
    /**
       Time taken to decompress cfile card payloads.
    */
    fsl_timer uncompress;
    /**
       Time taken to decompress cfile card payloads.
    */
    fsl_timer process;
  } timer;
};

typedef struct fsl_xfer_metrics fsl_xfer_metrics;

/**
   Payload type for FSL_MSG_XFER messages, sent after each round trip
   of a sync or clone and once more when it completes.
*/
struct fsl_msg_xfer {
  /** The running metrics. */
  fsl_xfer_metrics const * metrics;
  /** Number of completed round trips. */
  fsl_size_t trips;
  /** NULL until the final message, then "Pull", "Push", "Sync" or
      "Clone" (fossil(1)'s labels). */
  char const * zDone;
  /** The remote's host name, or NULL if it has none (e.g. file:). */
  char const * zRemote;
};
typedef struct fsl_msg_xfer fsl_msg_xfer;

/**
   Empty-initialized fsl_xfer_metrics instance intended for
   const-copy initialization.
*/
#define fsl_xfer_metrics_empty_m { \
    .trips = 0, \
    .iGotSent = 0, \
    .privIGot = 0, \
    .gimmeSent = 0, \
    .fileSent = 0, \
    .deltaSent = 0, \
    .fileRcvd = 0, \
    .deltaRcvd = 0, \
    .danglingFile = 0, \
    .rcvdArtifacts = 0, \
    .largestCardPayload = 0, \
    .largestDecompressedResponse = 0, \
    .bytesReadCompressed = 0, \
    .bytesReadUncompressed = 0, \
    .bytesReadWire = 0, \
    .bytesWritten = 0, \
    .cardsRx = {fsl_xfcard_zeroes},  \
    .cardsTx = {fsl_xfcard_zeroes},  \
    .timer = {                       \
      .read = fsl_timer_empty_m, \
      .submit = fsl_timer_empty_m, \
      .uncompress = fsl_timer_empty_m,    \
      .process = fsl_timer_empty_m \
    } \
  }

/**
   Empty-initialized fsl_xfer_metrics instance intended for
   non-const copy initialization.
*/
extern const fsl_xfer_metrics fsl_xfer_metrics_empty;

/**
   A callback for use with the libfossil sync transfer subsystem.
   Implementations are passed the sync-related metrics, their state
   object, and the result code of the sync (so that they can choose
   whether or not to skip any display on error).
*/
typedef void (*fsl_xfer_metrics_f)(fsl_xfer_metrics const *, void*,
                                   int theRc);

/**
   A fsl_xfer_metrics_f implementation which requires that its second
   argument be a (fsl_xfer_metrics*). It copies the first argument
   bitwise over the second. The final argument is ignored.
*/
void fsl_xfer_metrics_f_dup(fsl_xfer_metrics const *, void*, int theRc);

/**
   A fsl_xfer_metrics_f implementation which requires its second
   argument to be a (fsl_outputer*). It sends all output to that
   channel. If theRc is non-0 then this is a no-op.
*/
void fsl_xfer_metrics_f_outputer(fsl_xfer_metrics const * m,
                                 void *state, int theRc);

/**
   This typedef describes a callback used by the library for fetching
   passwords when needed for remote synchronization.

   Its first two arguments are current fsl_cx and the URL the password
   is being requested for. The final argument is
   implementation-dependent state.

   Implementations must somehow collect a password for the given URL,
   append a copy of it to bOut, and return 0 on success. On error
   they must return non-0, preferably the result of passing f to
   fsl_cx_err_set(). If appending the result to the buffer fails, it's
   caused (barring invalid arguments) by an OOM, in which case that
   code can be returned directly.

   It is legal for implementations to use bOut for construct their
   input prompt, so long as they pass it to fsl_b_reuse() before
   appending the password to it.

   To indicate a non-error when no password is available, return 0 and
   do not modify bOut (or pass it to fsl_b_reuse() before
   returning). In such cases the library will continue as if no
   credentials are available, which might trigger an error later on if
   credentials are required.

   bOut is owned by the library. The state argument is owned by
   whoever put it there.

   Design notes:

   Sync passwords are stored, if at all, in f's global config
   database.  Each has a key of "libfossil-sync-pw:" + the URL shorn
   of any password part. Thus saving a password for
   "http://foo:bar@baz/bar" will leave a config entry named
   "libfossil-sync-pw:http://foo@baz/bar". The passwords are stored as
   conventionally-fossil-hashed passwords.

   Passwords are specific to a given repository "project-code", so
   attempting to sync to the same URL for multiple project codes will
   leave the sync unable to log in to any but the most recent one for
   which the password was saved.

   This password storage is different from fossil(1)'s. The thinking
   is "separate apps, separate passwords", though the passwords all go
   in the same database. That's subject to change, though.
*/
typedef int (*fsl_pw_f)(fsl_cx * f, char const * zUrl,
                        fsl_b * bOut, void * state);

#if 0
/**
   A fsl_pw_f() implementation which uses unistd.h's
   obsolete/deprecated getpass(2). This implementation exists
   primarily for testing.

   Warning: getpass(2) uses static state, so this function must not be
   used if multiple threads might need to use getpass(2).

   This function works only for terminal applications, not GUI apps or
   those which cannot read from stdin.

   This implementation ignores the final argument.


   TODO: implement a getpass()-free alternative like the one
   demonstrated at:

   https://www.gnu.org/software/libc/manual/html_node/getpass.html

   Ah, fossil(1) has one in its user.c as well.
*/
int fsl_pw_f_getpass(fsl_cx * f, char const * zUrl,
                     fsl_b * bOut, void * state);
#endif

/**
   Various configuration pieces for libfossil sync transfer subsystem.

   Instances of this class are invariably stack-allocated but may own
   memory and must be cleaned up using fsl_xfer_config_cleanup().

   As of 2026-11-03: do not bitwise-copy these!
*/
struct fsl_xfer_config {
  /**
     The URL or filename to sync with. If this is empty then the
     library will try to determine it from the currently-opened
     repository. Its memory is owned by this object.
  */
  fsl_b url;

  /**
     Reserved for a response time limit. fsl_sync_client() returns
     FSL_RC_NYI if this is set to a non-negative value.
  */
  int8_t maxResponseSeconds;

  /**
     For fsl_sync_client() and fsl_clone(), the hard maximum
     compressed and uncompressed response size, in bytes. Values less
     than 1 mean 256 MiB. A fossil(1) server stops adding artifacts to
     a reply once the reply reaches its max-download setting (default
     5000000 bytes), so a reply can be max-download + 1 artifact.
     Replies from a fossil(1) server should be smaller than FSL_BLOB_MAX_SIZE.

     The native socket channel and the popen channels stop reading a
     reply once the reply is longer than:

        maxResponseBytes + (the formula in src/sc.c:fsl__sc_reply_max)

     It is also the approximate maximum outbound request payload size,
     which may also be exceeded by one artifact. Values less than 1 apply a
     built-in default to the outbound payload size.

     A channel supplied through channel reads the effective value with
     fsl_xfer_max_response().
  */
  int32_t maxResponseBytes;

  /**
     Seconds the HTTP socket channel waits for each read of a reply (or
     write of a request) to make progress before failing the
     transfer. Values less than 1 mean the default of 120. A channel
     supplied through channel reads the effective value with
     fsl_xfer_socket_timeout() and must apply it itself.
  */
  int32_t socketTimeoutSeconds;

  /**
     Verbosity level (higher is more verbose).
  */
  short verbosity;

  /**
     A hint for fsl_sc channels which support it. See
     FSL_SC_F_LEAVE_TEMP_FILES.
  */
  bool leaveTempFiles;

  /**
     If true, request zlib-compressed responses using the
     application/x-fossil Content-Type. Otherwise use
     application/x-fossil-uncompressed. This is a hint to the server,
     which may respond as it likes.
  */
  bool compressTraffic;

  /**
     If true, set FSL_SC_F_TLS_ACCEPT_ANY_CERT on the channel, so that
     an https connection accepts any server certificate.
  */
  bool acceptAnyCert;

  /**
     TODO (2026-08-30): add dryRun flag now that we can sync in a
     transaction.  That was historically not possible because we
     shelled out to fossil(1) and our transaction locked the db.
  */

  /**
     Receives messages emitted by this transfer. If its callback is
     NULL, fsl_sync_client() inherits the listener configured on its
     fsl_cx.
  */
  fsl_msg_listener listener;

  /** Optional debug message callback. */
  fsl_xfer_dbg debug;

  /**
     fsl_sc API tracing hook.
  */
  struct {
    /**
       If non-zero, a tracing channel is installed with the given mask
       of fsl_sc_tracer_e flags. If it is zero, no tracer is
       installed.
    */
    fsl_flag32_t mask;
    /**
       The tracing output sink.
    */
    fsl_outputer outputer;
  } trace;

  /**
     Members which are set to true will activate specific aspects of
     sync.
  */
  struct {
    /* Clone with protocol version 1, 2, or 3. 0 = do not clone. */
    short clone;
    /* Push content. */
    bool push;
    /* Pull content. */
    bool pull;
    /* Transfer private content, subject to peer authorization. */
    bool privateContent;
    /* Reserved. fsl_sync_client() returns FSL_RC_NYI when true. */
    bool autosync;
    /* Request all igot cards from the server. */
    bool verily;
  } op;

  struct {
    /**
       If not NULL, fsl_xfer's cleanup routine will call this,
       passing it the metrics, this->state, and the final result code
       of the sync process.
    */
    fsl_xfer_metrics_f callback;
    /**
       Optional state for the 2nd argument to this->callback(). It is
       owned by whoever assigns it to non-NULL.
    */
    void * state;
  } metrics;

  struct {
    /**
       Callback to use to fetch passwords.
    */
    fsl_pw_f callback;
    /**
       State for the password callback. It must match that
       implementation's expectations. It is owned by whoever set this
       property.
    */
    void * state;
    /**
       If true:

       - If the URL contains a password, then on successful sync
         the hashed password is saved for future use with that same
         URL (excluding the password part).

       This does not govern whether a saved password is used: see
       ignoreSaved.
    */
    bool save;
    /**
       If true and the URL has no password, saved passwords are not
       looked up: the password comes from this->callback, which may
       then be saved as governed by this->save. Without a callback,
       a sync which needs a password fails.
    */
    bool ignoreSaved;
  } password;

  /**
     If not NULL, a copy of this channel is used for the transfer,
     instead of one chosen from the URL scheme. The caller initializes
     it from fsl_sc_empty and sets its methods, flags and impl state
     (see fsl_sc for what it must provide; the library refuses a
     channel which lacks a required member). The library sets the
     copy's xfer member and parses the URL, which is still required,
     into the copy's url, so that the channel can read its host and
     path. The caller keeps ownership of what impl.p points to, which
     must outlive the transfer, and of the original, which the library
     does not clean up.
  */
  fsl_sc const * channel;
};


/**
   Empty-initialized fsl_xfer_config instance intended for const-copy
   initialization.
*/
#define fsl_xfer_config_empty_m {    \
  .url = fsl_b_empty_m,              \
  .maxResponseSeconds = -1,          \
  .maxResponseBytes = 0,             \
  .socketTimeoutSeconds = 0,         \
  .verbosity = 0,                    \
  .compressTraffic=true,             \
  .acceptAnyCert=false,              \
  .listener = fsl_msg_listener_empty_m, \
  .debug = fsl_xfer_dbg_empty_m,     \
  .trace = {                         \
    .mask = 0,                       \
    .outputer = fsl_outputer_FILE_m  \
  },                                 \
  .op = {                            \
    .clone = 0,                      \
    .push = false,                   \
    .pull = false,                   \
    .privateContent  = false,        \
    .autosync = false                \
  },                                 \
  .metrics = {                       \
    .callback = NULL, .state = NULL  \
  },                                 \
  .password = {                      \
    .callback = NULL,                \
    .state = NULL,                   \
    .save = false,                   \
    .ignoreSaved = false             \
  },                                 \
  .channel = NULL                    \
}

/**
   Flags for use with fsl_xfer_config_from_flags(). This is a bit of a
   holdover from fcli rather than an integral part of the sync
   interface.
*/
enum fsl_sync_flags_e {
  /**
     Only perform one of the request operations if the fossil config
     setting "fcli.autosync" or "autosync" is set, preferring the
     former. "autosync" is fossil(1) standard flag for this, but clients
     may use "fcli.autosync" to trump that without changing fossil's
     behavior. With neither setting, autosync is on, as in fossil(1).
     "pullonly" and the "dont-push" setting drop FSL_SYNC_PUSH. If
     neither FSL_SYNC_PULL nor FSL_SYNC_PUSH is set, both are
     assumed.
  */
  FSL_SYNC_AUTO     =     0x01,
  /** Perform a pull (read-only) sync. */
  FSL_SYNC_PULL     =     0x02,
  /** Perform a push (write-only) sync. */
  FSL_SYNC_PUSH     =     0x04,
  /** Perform a full (read/write) sync. */
  FSL_SYNC_FULL     =     FSL_SYNC_PULL | FSL_SYNC_PUSH,
  /** Perform a full sync, but only if autosync is enabled. */
  FSL_SYNC_FULLAUTO =     FSL_SYNC_AUTO | FSL_SYNC_FULL,
  /** Legacy flag - no longer used (we don't shell out anymore). */
  FSL_SYNC_NO_STDOUT =    0x10,
  /**
     Elide all sync-related messages, including metrics.
  */
  FSL_SYNC_NO_OUTPUT =    0x20,

  /**
     Do not save a password. By default it will be saved.
  */
  FSL_SYNC_NO_PW_SAVE =   0x80,
  /**
     Do not use a saved password. A password from the URL or the
     password callback may still be saved, as governed by
     FSL_SYNC_NO_PW_SAVE.
  */
  FSL_SYNC_NO_SAVED_PASSWORD = 0x100
};
typedef enum fsl_sync_flags_e fsl_sync_flags_e;

/**
   Given flags from the fsl_sync_flags_e enum, this function derives
   options to set on xc and sets them.

   It returns flags, possibly modified for autosync-related flags.

   If f does not have an opened repository, or on any error involving
   fetching state from f, -1 is returned and f's error state is
   updated.

   It may modify:

   - xc->op.pull, xc->op.push: depending on both the flags and, if
   applicable, autosync settings.

   - xc->listener.callback is set to a dummy no-op impl if the
   FSL_SYNC_NO_OUTPUT flag is used.

   - xc->password.save = false if FSL_SYNC_NO_PW_SAVE is used,
   else true.

   - xc->password.ignoreSaved = true if FSL_SYNC_NO_SAVED_PASSWORD is
   used, else false.

   - IFF xc->url is empty then it may be populated from the
     most recent sync-url for the current repo.
*/
fsl_flag32_t fsl_xfer_config_from_flags(fsl_cx * f,
                                        fsl_xfer_config *xc,
                                        fsl_flag32_t flags);

/**
   Empty-initialized fsl_xfer_config instance intended for
   non-const-copy initialization.
*/
extern const fsl_xfer_config fsl_xfer_config_empty;

/**
   Frees any memory which may be owned by p but does not
   free p.
*/
FSL_EXPORT void fsl_xfer_config_cleanup( fsl_xfer_config * p );

/**
   Tries to find a saved password for xf's URL. If found, it's
   assigned to xf->user.passwordToFree and xf->user.password, else
   xf->user.passwordToFree will be 0 and xf->user.password will be
   unmodified. It ignores db-level and search errors, except that
   failure to open the global config db is reported via xf's error
   state. A saved password which is empty is treated as not found.

   If no saved password is found and xf's config->password.callback is
   not 0, the callback is used to collect the password.

   If usePrompt is true then:

   a) If xf's config->password.callback is not 0 then it is used to collect
   the password, else

   b) xf's error state is set to FSL_RC_ACCESS, with a message which
   includes the user and the URL.

   Not finding a password is not an error here. When the sync itself
   finds no password for a URL whose user is not "anonymous" or
   "nobody", and has no callback, it fails with FSL_RC_ACCESS.
*/
FSL_EXPORT void fsl_xfer_pw_lookup(fsl_xfer * xf, bool usePrompt);

/**
   Options for use with fsl_clone(). Because its children
   may own memory, these must be cleaned up using
   fsl_clone_config_cleanup().
*/
struct fsl_clone_config {
  /** Options for fsl_repo_create(). */
  fsl_repo_create_opt repo;
  /**
     Options related to the transfer subsystem.
  */
  /**
     Core sync subsystem options.
  */
  fsl_xfer_config xfer;
};

typedef struct fsl_clone_config fsl_clone_config;

/**
   Empty-initialized fsl_clone_config instance intended for const-copy
   initialization.
*/
#define fsl_clone_config_empty_m {      \
  .repo = fsl_repo_create_opt_empty_m,  \
  .xfer = fsl_xfer_config_empty_m       \
}

/**
   Empty-initialized fsl_clone_config instance intended for
   non-const-copy initialization.
*/
extern const fsl_clone_config fsl_clone_config_empty;

/**
   Cleans up any memory owned by c and its members, but does
   not free c.
*/
void fsl_clone_config_cleanup(fsl_clone_config *c);

/**
   Clones a fossil repository using the given configuration
   and optional error object. The configuration bits are
   documented in the fsl_clone_config struct.

   This function uses a call-local savepoint so that all repository
   changes made by every protocol round are committed atomically. On
   any error, including a later round, the repository is restored to
   its pre-sync state. In the first reply, though, an error card is
   ignored, and a card or body which cannot be handled only ends
   processing of that reply; either way the clone goes on to its
   second round, as sections 8.3 and 10.1 of the sync draft require.
   A bad clone_seqno card, a project code mismatch, or content which
   does not match its hash is always an error.

   On success it will have created a new clone at the file specified
   by cc->repo.filename.

   On error non-0 is returned and, if `err` is not NULL, it will be
   populated with any available error information.
*/
FSL_EXPORT int fsl_clone( fsl_clone_config const * cc, fsl_error * err );

#if 0
/**
   Untested, incomplete, and it open design question remain regarding
   handling of the channel's state object's memory.

   Attempts to find a fsl_sc class capable of handling the given
   fossil URL.

   Currently handled:

   - http and https: uses fsl_sc_popen

   On success, returns a new instance, which the caller must
   eventually pass to fsl_sc_cleanup() and then to fsl_free().
*/
int fsl_sc_for_url( char const * zUrl, fsl_sc **pOut,  );
#endif

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_SYNC_H_INCLUDED */
/* end of file include/fossil-scm/sync.h */
/* start of file include/fossil-scm/pages.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_PAGES_H_INCLUDED)
#define ORG_FOSSIL_SCM_PAGES_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).

  *****************************************************************************
  This file contains only Doxygen-format documentation, split up into
  Doxygen "pages", each covering some topic at a high level.  This is
  not the place for general code examples - those belong with their
  APIs.
*/

/** @mainpage libfossil

    Forewarning: this API assumes one is familiar with the Fossil SCM,
    ideally in detail. The Fossil SCM can be found at:

    https://fossil-scm.org

    libfossil is an experimental/prototype library API for the Fossil
    SCM. This API concerns itself only with the components of fossil
    which do not need user interaction or the display of UI components
    (including HTML and CLI output). It is intended only to model the
    core internals of fossil, off of which user-level applications
    could be built.

    The project's repository and additional information can be found at:

    https://fossil.wanderinghorse.net/r/libfossil/

    This code is 100% hypothetical/potential, and does not represent
    any Official effort of the Fossil project. It is up for any amount
    of change at any time and does not yet have a stable API.

    All Fossil users are encouraged to participate in its development,
    but if you are reading this then you probably already knew that
    :).

    This effort does not represent "Fossil Version 2", but provides an
    alternate method of accessing and manipulating fossil(1)
    repositories. Whereas fossil(1) is a monolithic binary, this API
    provides library-level access to (some level of) the fossil(1)
    feature set (that level of support grows approximately linearly
    with each new commit).

    Current status: alpha. Some bits are basically finished but there
    is a lot of work left to do. The scope is pretty much all
    Fossil-related functionality which does not require a user
    interface or direct user interaction, plus some range of utilities
    to support those which require a UI/user.
*/

/** @page page_terminology Fossil Terminology

    See also: https://fossil-scm.org/home/doc/trunk/www/concepts.wiki

    The libfossil API docs normally assume one is familiar with
    Fossil-internal terminology, which is of course a silly assumption
    to make. Indeed, one of libfossil's goals is to make Fossil more
    accessible, partly be demystifying it. To that end, here is a
    collection of terms one may come across in the API, along with
    their meanings in the context of Fossil...


    - REPOSITORY (a.k.a. "repo) is an sqlite database file which
    contains all content for a given "source tree." (We will use the
    term "source tree" to mean any tree of "source" (documents,
    whatever) a client has put under Fossil's supervision.)

    - CHECKOUT (a.k.a. "local source tree" or "working copy") refers
    to (A) the action of pulling a specific version of a repository's
    state from that repo into the local filesystem, and (B) a local
    copy "checked out" of a repo. e.g. "he checked out the repo," and
    "the changes are in his [local] checkout."

    - ARTIFACT is the generic term for anything stored in a repo. More
    specifically, ARTIFACT refers to "control structures" Fossil uses
    to internally track changes. These artifacts are stored as blobs
    in the database, just like any other content. For complete details
    and examples, see:
    https://fossil-scm.org/home/doc/tip/www/fileformat.wiki

    - A MANIFEST is a specific type of ARTIFACT - the type which
    records all metadata for a COMMIT operation (which files, which
    user, the timestamp, checkin comment, lineage, etc.). For
    historical reasons, MANIFEST is sometimes used as a generic term
    for ARTIFACT because what the fossil(1)-internal APIs originally
    called a Manifest eventually grew into other types of artifacts
    but kept the Manifest naming convention. In Fossil developer
    discussion, "manifest" most often means what this page calls
    ARTIFACT (probably because that how the C code is modelled).  The
    libfossil API calls uses the term "deck" instead of "manifest" to
    avoid ambiguity/confusion (or to move the confusion somewhere
    else, at least).

    - CHECKIN is the term libfossil prefers to use for COMMIT
    MANIFESTS. It is also the action of "checking in"
    (a.k.a. "committing") file changes to a repository.  A CHECKIN
    ARTIFACT can be one of two types: a BASELINE MANIFEST (or BASELINE
    CHECKIN) contains a list of all files in that version of the
    repository, including their file permissions and the UUIDs of
    their content. A DELTA MANFIEST is a checkin record which derives
    from a BASELINE MANIFEST and it lists only the file-level changes
    which happened between the baseline and the delta, recording any
    changes in content, permisions, or name, and recording
    deletions. Note that this inheritance of deltas from baselines is
    an internal optimization which has nothing to do with checkin
    version inheritance - the baseline of any given delta is normally
    _not_ its direct checkin version parent.

    - BRANCH, FORK, and TAG are all closely related in Fossil and are
    explained in detail (with pictures!) at:
    https://fossil-scm.org/home/doc/trunk/www/concepts.wiki
    In short: BRANCHes and FORKs are two names for the same thing, and
    both are just a special-case usage of TAGs.

    - MERGE or MERGING: the process of integrating one version of
    source code into another version of that source code, using a
    common parent version as the basis for comparison. This is
    normally fully automated, but occasionally human (and sometimes
    Divine) intervention is required to resolve so-called "merge
    conflicts," where two versions of a file change the same parts of
    a common parent version.

    - RID (Record ID) is a reference to the blob.rid field in a
    repository DB. RIDs are used extensively throughout the API for
    referencing content records, but they are transient values local
    to a given copy of a given repository at a given point in
    time. They _can_ change, even for the same content, (e.g. a
    rebuild can hypothetically change them, though it might not, and
    re-cloning a repo may very well change some RIDs). Clients must
    never rely on them for long-term reference to SCM'd data - always use
    the full UUID of such data. Even though they normally appear to be
    static, they are most explicitly NOT guaranteed to be. Nor are
    their values guaranteed to imply any meaning, e.g. "higher is
    newer" is not necessarily true because synchronization can import
    new remote content in an arbitrary order and a rebuild might
    import it in random order. The API uses RIDs basically as handles
    to arbitrary blob content and, like most C-side handles, must be
    considered transient in nature. That said, within the db, records
    are linked to each other exclusively using RIDs, so they do have
    some persistence guarantees for a given db instance.
*/


/** @page page_APIs High-level API Overview

    The primary end goals of this project are to eventually cover the
    following feature areas:

    - Provide embeddable SCM to local apps using sqlite storage.
    - Provide a network layer on top of that for synchronization.
    - Provide apps on top of those to allow administration of repos.

    To those ends, the fossil APIs cover the following categories of
    features:

    Filesystem:

    - Conversions of strings from OS-native encodings to UTF.
    fsl_utf8_to_unicode(), fsl_filename_to_utf8(), etc. These are
    primarily used internally but may also be useful for applications
    working with files (as most clients will). Actually... most of
    these bits are only needed for portability across Windows
    platforms.

    - Locating a user's home directory: fsl_find_home_dir()

    - Normalizing filenames/paths. fsl_file_canonical_name() and friends.

    - Checking for existence, size, and type (file vs directory) with
    fsl_is_file() and fsl_dir_check(), or the more general-purpose
    fsl_stat().


    Databases (sqlite):

    - Opening/closing sqlite databases and running queries on them,
    independent of version control features. See fsl_db_open() and
    friends. The actual sqlite-level DB handle type is abstracted out
    of the public API, largely to simplify an eventual port from
    sqlite3 to sqlite4 or (hypothetically) to other storage back-ends
    (not gonna happen - too much work).

    - There are lots of utility functions for oft-used operations,
    e.g. fsl_config_get_int32() and friends to fetch settings from one
    of several different configuration areas (global, repository,
    checkout, and "versionable" settings).

    - Pseudo-recusive transactions: fsl_db_txn_begin() and
    fsl_db_txn_end(). sqlite does not support truly nested
    transactions, but they can be simulated quite effectively so long
    as certain conventions are adhered to.

    - Cached statements (an optimization for oft-used queries):
    fsl_db_prepare_cached() and friends.


    The DB API is (as Brad Harder put so well) "very present" in the
    public API. While the core API provides access to the underlying
    repository data, it cannot begin to cover even a small portion of
    potential use cases. To that end, it exposes the DB API so that
    clients who want to custruct their own data can do so. It does
    require research into the underlying schemas, but gives
    applications the ability to do _anything_ with their repositories
    which the core API does not account for. Historically, the ability
    to create ad-hoc data structures as needed, in the form of SQL
    queries, has accounted for much of Fossil's feature flexibility.


    Deltas:

    - Creation and application of raw deltas, using Fossil's delta
    format, independent of version control features. See
    fsl_delta_create() and friends. These are normally used only at
    the deepest internal levels of fossil, but the APIs are exposed so
    that clients can, if they wish, use them to deltify their own
    content independently of fossil's internally-applied
    deltification. Doing so is remarkably easy, but completely
    unnecessary for content which will be stored in a repo, as Fossil
    creates deltas as needed.


    SCM:

    - A "context" type (fsl_cx) which manages a repository db and,
    optionally, a checkout db. Read-only operations on the DB are
    working and write functionality (adding repo content) is
    ongoing. See fsl_cx, fsl_cx_init(), and friends.

    - The fsl_deck class assists in parsing, creating, and outputing
    "artifacts" (manifests, control (tags), events, etc.). It gets its
    name from it being container for "a collection of cards" (which is
    what a Fossil artifact is).

    - fsl_content_get() expands a (possibly) deltified blob into its
    full form, and fsl_content_blob() can be used to fetch a raw blob
    (possibly a raw delta).

    - A number of routines exist for converting symbol names to RIDs
    (fsl_sym_to_rid()), UUIDs to RIDs (fsl_uuid_to_rid(),
    and similar commonly-needed lookups.


    Input/Output:

    - The API defines several abstractions for i/o interfaces, e.g.
    fsl_input_f() and fsl_output_f(), which allow us to accept/emit
    data from/to arbitrary streamable (as opposed to random-access)
    sources/destinations. A fsl_cx instance is configured with an
    output channel, the intention being that all clients of that
    context should generate any output through that channel, so that
    all compatible apps can cooperate more easily in terms of i/o. For
    example, the s2 script binding for libfossil routes fsl_output()
    through the script engine's i/o channels, so that any output
    generated by libfossil-using code it links to can take advantage
    of the script-side output features (such as output buffering,
    which is needed for any non-trivial CGI output). That said: the
    library-level code does not actually generate output to that
    channel, but higher-level code like fcli does, and clients are
    encouraged to in order to enable their app's output to be
    redirected to an arbitrary UI element, be it a console or UI
    widget.


    Utilities:

    - fsl_b, a generic buffer class, is used heavily by the
    library.  See fsl_b and friends.

    - fsl_appendf() provides printf()-like functionality, but sends
    its output to a callback function (optionally stateful), making it
    the one-stop-shop for string formatting within the library.

    - The fsl_error class is used to propagate error information
    between the libraries various levels and the client.

    - The fsl_list class acts as a generic container-of-pointers, and
    the API provides several convenience routines for managing them,
    traversing them, and cleaning them up.

    - Hashing: there are a number of routines for calculating SHA1,
    SHA3, and MD5 hashes. See fsl_sha1_cx, fsl_sha3_cx, fsl_md5_cx,
    and friends.

    - zlib compression is used for storing artifacts. See
    fsl_data_is_compressed(), fsl_b_compress(), and friends.
    These are never needed at the client level, but are exposed "just
    in case" a given client should want them.
*/

/** @page page_is_isnot Fossil is/is not...

    Through porting the main fossil application into library form,
    the following things have become very clear (or been reinforced)...

    Fossil is...

    - _Exceedingly_ robust. Not only is sqlite literally the single
    most robust application-agnostic container file format on the
    planet, but Fossil goes way out of its way to ensure that what
    gets put in is what gets pulled out. It cuts zero corners on data
    integrity, even adding in checks which seem superfluous but
    provide another layer of data integrity (i'm primarily talking
    about the R-card here, but there are other validation checks). It
    does this at the cost of memory and performance (that said, it's
    still easily fast enough for its intended uses). "Robust" doesn't
    mean that it never crashes nor fails, but that it does so with
    (insofar as is technically possible) essentially zero chance of
    data loss/corruption.

    - Long-lived: the underlying data format is independent of its
    storage format. It is, in principal, usable by systems as yet
    unconceived by the next generation of programmers. This
    implementation is based on sqlite, but the model can work with
    arbitrary underlying storage.

    - Amazingly space-efficient. The size of a repository database
    necessarily grows as content is modified. However, Fossil's use of
    zlib-compressed deltas, using a very space-efficient delta format,
    leads to tremendous compression ratios. As of this writing (March,
    2021), the main Fossil repo contains approximately 5.36GB of
    content, were we to check out every single version in its
    history. Its repository database is only 64MB, however, equating
    to a 83:1 compression ration. Ratios in the range of 20:1 to 40:1
    are common, and more active repositories tend to have higher
    ratios. The TCL core repository, with just over 15 years of code
    history (imported, of course, as Fossil was introduced in 2007),
    is (as of September 2013) only 187MB, with 6.2GB of content and a
    33:1 compression ratio.

    Fossil is not...

    - Memory-light. Even very small uses can easily suck up 1MB of RAM
    and many operations (verification of the R card, for example) can
    quickly allocate and free up hundreds of MB because they have to
    compose various versions of content on their way to a specific
    version. To be clear, that is total RAM usage, not _peak_ RAM
    usage. Peak usage is normally a function of the content it works
    with at a given time, often in direct relation to (but
    significantly more than) the largest single file processed in a
    given session. For any given delta application operation, Fossil
    needs the original content, the new content, and the delta all in
    memory at once, and may go through several such iterations while
    resolving deltified content. Verification of its 'R-card' alone
    can require a thousand or more underlying DB operations and
    hundreds of delta applications. The internals use caching where it
    would save us a significant amount of db work relative to the
    operation in question, but relatively high memory costs are
    unavoidable. That's not to say we can't optimize a bit, but first
    make it work, then optimize it. The library takes care to re-use
    memory buffers where it is feasible (and not too intrusive) to do
    so, but there is yet more RAM to be optimized away in this regard.
*/

/** @page page_threading Threads and Fossil

    It is strictly illegal to use a given fsl_cx instance from more
    than one thread. Period.

    It is legal for multiple contexts to be running in multiple
    threads, but only if those contexts use different
    repository/checkout databases. Though access to the storage is,
    through sqlite, protected via a mutex/lock, this library does not
    have a higher-level mutex to protect multiple contexts from
    colliding during operations. So... don't do that. One context, one
    repo/checkout.

    Multiple application instances may each use one fsl_cx instance to
    share repo/checkout db files, but must be prepared to handle
    locking-related errors in such cases. e.g. db operations which
    normally "always work" may suddenly pause for a few seconds before
    giving up while waiting on a lock when multiple applications use
    the same database files. sqlite's locking behaviours are
    documented in great detail at https://sqlite.org.
 */

/** @page page_artifacts Creating Artifacts

    A brief overview of artifact creating using this API. This is targeted
    at those who are familiar with how artifacts are modelled and generated
    in fossil(1).

    Primary artifact reference:

    https://fossil-scm.org/home/doc/trunk/www/fileformat.wiki

    In fossil(1), artifacts are generated via the careful crafting of
    a memory buffer (large string) in the format described in the
    document above. While it's relatively straightforward to do, there
    are lots of potential gotchas, and a bug can potentially inject
    "bad data" into the repo (though the verify-before-commit process
    will likely catch any problems before the commit is allowed to go
    through). The libfossil API uses a higher-level (OO) approach,
    where the user describes a "deck" of cards and then tells the
    library to save it in the repo (fsl_deck_save()) or output it to
    some other channel (fsl_deck_output()). The API ensures that the
    deck's cards get output in the proper order and that any cards
    which require special treatment get that treatment (e.g. the
    "fossilize" encoding of certain text fields). The "deck" concept
    is equivalent to Artifact in fossil(1), but we use the word deck
    because (A) Artifact is highly ambiguous in this context and (B)
    deck is arguably the most obvious choice for the name of a type
    which acts as a "container of cards."

    Ideally, client-level code will never have to create an artifact
    via the fsl_deck API (because doing so requires a fairly good
    understanding of what the deck is for in the first place,
    including the individual Cards). The public API strives to hide
    those levels of details, where feasible, or at least provide
    simpler/safer alternatives for basic operations. Some operations
    may require some level of direct work with a fsl_deck
    instance. Likewise, much read-only functionality directly exposes
    fsl_deck to clients, so some familiarity with the type and its
    APIs will be necessary for most clients.

    The process of creating an artifact looks a lot like the following
    code example. We have elided error checking for readability
    purposes, but in fact this code has undefined behaviour if error
    codes are not checked and appropriately reacted to.

    ```
    fsl_deck deck = fsl_deck_empty;
    fsl_deck * d = &deck ; // for typing convenience.
    // Doxygen bug ^^^^^^^ requires space before semicolon!
    fsl_deck_init( fslCtx, d, FSL_SATYPE_CONTROL ); // must come first
    fsl_deck_D_set( d, fsl_julian_now() );
    fsl_deck_U_set( d, "your-fossil-name", -1 );
    fsl_deck_T_add( d, FSL_TAGTYPE_ADD, "...uuid being tagged...",
                   "tag-name", "optional tag value");
    ...
    // Now output it to stdout:
    fsl_deck_output( f, d, fsl_output_f_FILE, stdout );
    // See also: fsl_deck_save(), which stores it in the db and
    // "crosslinks" it.
    fsl_deck_finalize(d);
    ```

    The order the cards are added to the deck is irrelevant - they
    will be output in the order specified by the Fossil specs
    regardless of their insertion order. Each setter/adder function
    knows, based on the deck's type (set via fsl_deck_init()), whether
    the given card type is legal, and will return an error (probably
    FSL_RC_TYPE) if an attempt is made to add a card which is illegal
    for that deck type. Likewise, fsl_deck_output() and
    fsl_deck_save() confirm that the decks they are given contain (A)
    only allowed cards and (B) have all required
    cards. fsl_deck_output() will "unshuffle" the cards, making sure
    they're in the correct order.

    Sidebar: normally outputing a structure can use a const form of
    that structure, but the traversal of F-cards in a deck requires
    (for the sake of delta manifests) using a non-const cursor. Thus
    outputing a deck requires a non-const instance. If it weren't for
    delta manifests, we could be "const-correct" here.
*/

/** @page page_transactions DB Transactions

    The fsl_db_txn_begin() and fsl_db_txn_end()
    functions implement a basic form of recursive transaction,
    allowing the library to start and end transactions at any level
    without having to know whether a transaction is already in
    progress (sqlite3 does not natively support nested
    transactions). A rollback triggered in a lower-level transaction
    will propagate the error back through the transaction stack and
    roll back the whole transaction, providing us with excellent error
    recovery capabilities (meaning we can always leave the db in a
    well-defined state).

    It is STRICTLY ILLEGAL to EVER begin a transaction using "BEGIN"
    or end a transaction by executing "COMMIT" or "ROLLBACK" directly
    on a fsl_db instance. Doing so bypasses internal state which needs
    to be kept abreast of things and will cause Grief and Suffering
    (on the client's part, not mine).

    Begin a transaction which will write the repository or checkout db
    with fsl_cx_txn_begin_write(), which takes those dbs' write locks
    before the transaction reads them. A transaction begun with
    fsl_cx_txn_begin() or fsl_db_txn_begin() takes a write lock at its
    first write. If it has read that db by then and another connection
    holds the lock, SQLite reports the db as locked at once, without
    waiting for the busy timeout.

    Tip: implementing a "dry-run" mode for most fossil operations is
    trivial by starting a transaction before performing the
    operations. Many operations run in a transaction, but if the
    client starts one of his own they can "dry-run" any op by simply
    rolling back the transaction he started. Abstractly, that looks
    like this pseudocode:

    ```
    db.begin();
    fsl.something();
    fsl.somethingElse();
    if( dryRun ) db.rollback();
    else db.commit();
    ```
*/

/** @page page_code_conventions Code Conventions

    Project and Code Conventions...

    Foreword: all of this more or less evolved organically or was
    inherited from fossil(1) (where it evolved organically, or was
    inherited from sqilte (where it evol...)), and is written up here
    more or less as a formality. Historically i've not been a fan of
    coding conventions, but as someone else put it to me, "the code
    should look like it comes from a single source," and the purpose
    of this section is to help orient those looking to hack in the
    sources. Note that most of what is said below becomes obvious
    within a few minutes of looking at the sources - there's nothing
    earth-shatteringly new nor terribly controversial here.

    The Rules/Suggestions/Guidelines/etc. are as follows...


    - C99 is the basis. It was C89 until 2021-02-12.

    - The canonical build environment uses the most restrictive set of
    warning/error levels possible. It is highly recommended that
    non-canonical build environments do the same. Adding -Wall -Werror
    -pedantic does _not_ guaranty that all C compliance/portability
    problems can be caught by the compiler, but it goes a long way in
    helping us to write clean code. The clang compiler is particularly
    good at catching subtle foo-foo's such as uninitialized variables.

    - API docs (as you may have already noticed), does not (any
    longer) follow Fossil's comment style, but instead uses
    Doxygen-friendly formatting. Each comment block MUST start with
    two or more asterisks, or '*!', or doxygen apparently doesn't
    understand it
    (https://www.stack.nl/~dimitri/doxygen/manual/docblocks.html). When
    adding code snippets and whatnot to docs, please use doxygen
    conventions if it is not too much of an inconvenience. All public
    APIs must be documented with a useful amount of detail. If you
    hate documenting, let me know and i'll document it (it's what i do
    for fun).

    - Public API members have a fsl_ or FSL_ prefix (fossil_ seems too
    long). For private/static members, anything goes. Optional or
    "add-on" APIs (e.g. ::fcli) may use other prefixes, but are
    encouraged use an "f-word" (as it were), simply out of deference
    to long-standing software naming conventions.

    - Internal APIs, especially non-static ones, start with `fsl__` or
    `FSL__`, with two underscores. Such APIs must never be used in
    client-side code.

    - Public-API structs and functions use lower_underscore_style().
    Static/internal APIs may use different styles. It's not uncommon
    to see UpperCamelCase for file-scope structs.

    - Function parameters and function-scope vars have no set
    conventions - implementors are free to name those however they
    like.

    - Overall style, especially scope blocks and indentation, should
    follow Fossil's.  We are _not at all_ picky about whether or not
    there is a space after/before parens in if( foo ), and similar
    small details, just the overall code pattern and two-space
    indentation. Hard tabs are verboten.

    - Structs and enums all get the optional typedef so that they do
    not need to be qualified with 'struct' resp. 'enum' when
    used. Because of how doxygen tracks those, the typedef should be
    separate from the struct declaration, rather than combinding
    those into a single declaration.

    - Function typedefs are named fsl_XXX_f. Implementations of such
    typedefs/interfaces are typically named fsl_XXX_f_SUFFIX(), where
    SUFFIX describes the implementation's
    specialization. e.g. fsl_output_f() is a callback
    typedef/interface and fsl_output_f_FILE() is a concrete
    implementation for FILE handles.

    - Enums tend to be named fsl_XXX_e.

    - Functions follow the naming pattern prefix_NOUN_VERB(), rather
    than the more C-conventional prefix_VERB_NOUN(),
    e.g. fsl_foo_get() and fsl_foo_set() rather than fsl_get_foo() and
    fsl_get_foo(). The primary reasons are (A) sortability for
    document processors and (B) they more naturally match with OO API
    conventions, e.g. `noun.verb()`. A few cases knowingly violate
    this convention for the sake of readability or sorting of several
    related functions (e.g. fsl_db_get_TYPE() instead of
    fsl_db_TYPE_get()).

    - Structs intended to be creatable on the stack are accompanied by
    a const instance named fsl_STRUCT_NAME_empty, and possibly by a
    macro named fsl_STRUCT_NAME_empty_m, both of which are
    "default-initialized" instances of that struct. This is superiour
    to using `memset()` for struct initialization because we can
    define (and document) arbitrary default values and all clients who
    copy-construct them are unaffected by many types of changes to the
    struct's signature (though they may need a recompile). The
    intention of the fsl_STRUCT_NAME_empty_m macro is to provide a
    struct-embeddable form for use in other structs or
    copy-initialization of const structs, and the `_m` macro is always
    used to initialize its const struct counterpart. e.g. the library
    guarantees that fsl_cx_empty_m (a macro representing an empty
    fsl_cx instance) holds the same default values as fsl_cx_empty (a
    const fsl_cx value).

    - Returning int vs fsl_int_t vs fsl_size_t: int is used as a
    conventional result code. fsl_int_t is often used as a signed
    length-style result code (e.g. printf() semantics). Unsigned
    ranges use fsl_size_t. Ints are (also) used as a "triplean" (3
    potential values, e.g. <0, 0, >0). fsl_int_t also guarantees that
    it will be 64-bit if available, so can be used for places where
    large values are needed but a negative value is legal (or handy),
    e.g. the final arguments for fsl_strndup() and
    fsl_b_append(). The use of the fsl_xxx_t typedefs, rather
    than (unsigned) int, is primarily for readability/documentation,
    e.g. so that readers can know immediately that the function uses a
    given argument or return value following certain API-wide
    semantics. It also allows us to better define platform-portable
    printf/scanf-style format modifiers for them (analog to C99's
    PRIi32 and friends), which often come in handy.

    - Signed vs. unsigned types for size/length arguments: use the
    fsl_int_t (signed) argument type when the client may legally pass
    in a negative value as a hint that the API should use fsl_strlen()
    (or similar) to determine a byte array's length. Use fsl_size_t
    when no automatic length determination is possible (or desired),
    to "force" the client to pass the proper length. Internally
    fsl_int_t is used in some places where fsl_size_t "should" be used
    because some ported-in logic relies on loop control vars being
    able to go negative. Additionally, fossil internally uses negative
    blob lengths to mark phantom blobs, and care must be taken when
    using fsl_size_t with those.

    - Functions taking elipses (...) are accompanied by a va_list
    counterpart named the same as the (...) form plus a trailing
    'v'. e.g. fsl_appendf() and fsl_appendfv(). We do not use the
    printf()/vprintf() convention because that hoses sorting of the
    functions in generated/filtered API documentation.

    - Error handling/reporting: please keep in mind that the core code
    is a library, not an application.  The main implication is that
    all lib-level code needs to check for errors whereever they can
    happen (e.g. on every single memory allocation, of which there are
    many) and propagate errors to the caller, to be handled at his
    discretion. The app-level code (::fcli) is not particularly strict
    in this regard, and installs its own allocator which abort()s on
    allocation error, which simplifies app-side code somewhat
    vis-a-vis lib-level code. When reporting an error can be improved
    by the inclusion of an error string, functions like
    fsl_cx_err_set() can be used to report the error. Several of the
    high-level types in the API have fsl_error object member which
    contains such error state. The APIs which use that state take care
    to use-use the error string memory whenever possible, so setting
    an error string is often a non-allocating operation.
*/


/** @page page_fossil_arch Fossil Architecture Overview

    An introduction to the Fossil architecture. These docs
    are basically just a reformulation of other, more detailed,
    docs which can be found via the main Fossil site, e.g.:

    - https://fossil-scm.org/home/doc/trunk/www/concepts.wiki

    - https://fossil-scm.org/home/doc/trunk/www/fileformat.wiki

    Fossil's internals are fundamentally broken down into two basic
    parts. The first is a "collection of blobs."  The simplest way to
    think of this (and it's not far from the full truth) is a
    directory containing lots of files, each one named after a hash of
    its contents. This pool contains ALL content required for a
    repository - all other data can be generated from data contained
    here. Included in the blob pool are so-called Artifacts. Artifacts
    are simple text files with a very strict format, which hold
    information regarding the idententies of, relationships involving,
    and other metadata for each type of blob in the pool. The most
    fundamental Artifact type is called a Manifest, and a Manifest
    tells us, amongst other things, which of the hash-based file names
    has which "real" file name, which version the parent (or parents!)
    is (or are), and other data required for a "commit" operation.

    The blob pool and the Manifests are all a Fossil repository really
    needs in order to function. On top of that basis, other forms of
    Artifacts provide features such as tagging (which is the basis of
    branching and merging), wiki pages, and tickets. From those
    Artifacts, Fossil can create/calculate all sorts of
    information. For example, as new Artifacts are inserted it
    transforms the Artifact's metadata into a relational model which
    sqlite can work with. That leads us to what is conceptually the
    next-higher-up level, but is in practice a core-most component...

    Storage. Fossil's core model is agnostic about how its blobs are
    stored, but libfossil and fossil(1) both make heavy use of sqlite
    to implement many of their features. These include:

    - Transaction-capable storage. It's almost impossible to corrupt a
    Fossil db in normal use. sqlite3 offers literally the most robust
    general-purpose file format on the planet.

    - The storage of the raw blobs.

    - Artifact metadata is transformed into various DB structures
    which allow libfossil to traverse historical data much more
    efficiently than would be possible without a db-like
    infrastructure (and everything that implies). These structures are
    kept up to date as new Artifacts are stored in a repository,
    either via local edits or synching in remote content. These data
    are incrementally updated as changes are made to a repo.

    - A tremendous amount of the "leg-work" in processing the
    repository state is handled by SQL queries, without which the
    library would easily require 5-10x more code in the form of
    equivalent hard-coded data structures and corresponding
    functionality. The db approach allows us to ad-hoc structures as
    we need them, providing us a great deal of flexibility.

    All content in a Fossil repository is in fact stored in a single
    database file. Fossil additionally uses another database (a
    "checkout" db) to keep track of local changes, but the repo
    contains all "fossilized" content. Each copy of a repo is a
    full-fledged repo, each capable of acting as a central copy for
    any number of clones or checkouts.

    That's really all there is to understand about Fossil. How it does
    its magic, keeping everything aligned properly, merging in
    content, how it stores content, etc., is all internal details
    which most clients will not need to know anything about in order
    to make use of fossil(1). Using libfossil effectively, though,
    does require learning _some_ amount of how Fossil works. That will
    require taking some time with _other_ docs, however: see the
    links at the top of this section for some starting points.


    Sidebar:

    - The only file-level permission Fossil tracks is the "executable"
    (a.k.a. "+x") bit. It internally marks symlinks as a permission
    attribute, but that is applied much differently than the
    executable bit and only does anything useful on platforms which
    support symlinks.

*/

#endif
/* ORG_FOSSIL_SCM_PAGES_H_INCLUDED */
/* end of file include/fossil-scm/pages.h */
/* start of file include/fossil-scm/cli.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(_ORG_FOSSIL_SCM_FCLI_H_INCLUDED_)
#define _ORG_FOSSIL_SCM_FCLI_H_INCLUDED_
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).

  *****************************************************************************
  This file provides a basis for basic libfossil-using apps. It
  attempts to provide basic services required by a wide variety of
  fossil-using apps, with the intent of simplifying their creation.
*/

#include <stdlib.h> /* EXIT_SUCCESS and friends */
#include <assert.h>

/** @page page_fcli fcli (formerly FossilApp)

    ::fcli (formerly FossilApp) provides a small framework for
    bootstrapping simple libfossil applications which only need a
    single fsl_cx instance managing a single checkout and/or
    repository. It is primarily intended for use with CLI apps
    implementing features similar to those in fossil(1), but can also
    be used with GUI apps. It provides the following basic services to
    applications:

    - The global ::fcli struct holds global state.

    - fcli_setup_v2() bootstraps the environment. This must be the
    first call made into the API, as this replaces the libfossil
    memory allocator with a fail-fast variant to simplify app-level
    code a bit (by removing the need to check for OOM errors). This
    also registers an atexit(3) handler to clean up fcli-owned
    resources at app shutdown.

    - Automatically tries to open a checkout (and its associated
    repository) under the current directory, but not finding one
    is not an error (the app needs to check for this if it should
    be an error: use fsl_cx_db_repo() and fsl_cx_db_ckout()).

    - fcli_flag(), fcli_next_arg(), and friends provide uniform access
    to CLI arguments.

    - A (very) basic help subsystem, triggered by the --help or -? CLI
    flags, or if the first non-flag argument is "help".  Applications
    may optionally assign fcli.appHelp to a function which outputs
    app-specific help.

    - Basic error reporting mechanism. See fcli_err_report().

    The source tree contains several examples of using fcli
    in the files named f-apps/f-*.c.
*/

/**
   Outputs the given fsl_appendf()-compatible formatting expression
   (2nd arg) to fcli_printf() if fcli.verbose>=N, else it does
   nothing.

   Reminder: this uses a while(0) loop so that the macro can end
   with a semicolon without triggering a warning.
*/
#define FCLI_VN(N,pfexp)                        \
  if(fcli.config.verbose>=(N)) do {        \
      fcli_printf("VERBOSE %d: ", (int)(N));    \
      fcli_printf pfexp;                        \
  } while(0)

/**
   Convenience form of FCLI_VN for level-2 verbosity.
*/
#define FCLI_V2(pfexp) FCLI_VN(2,pfexp)

/**
   Convenience form of FCLI_VN for level-1 verbosity. Levels 1 and 2
   are intended for application-level use. Levels 3+ are intended for
   fcli use.
*/
#define FCLI_V(pfexp) FCLI_VN(1,pfexp)

#if defined(__cplusplus)
extern "C" {
#endif

/**
   Result codes specific to the fcli API.
*/
enum fcli_rc_e {
/**
   For use with fcli_flag_callback_f() implementations to indicate
   that the flag processor should check for that flag again.
*/
FCLI_RC_FLAG_AGAIN = FSL_RC_end + 1,
/**
   Returned from fcli_dispatch_commands() when the string returned
   from fcli_next_arg() does not match any fcli_command in the list.
*/
FCLI_RC_NO_CMD,
/**
   Returned from fcli_setup() if flag processing invokes the help
   system. This is an indication that the app should exit immediately
   with a 0 result code.
*/
FCLI_RC_HELP
};
/**
   Types for use with the fcli_cliflag::flagType field.  The value of
   that field determines how the CLI flag handling interprets the
   fcli_cliflag::flagValue void pointer.
*/
enum fcli_cliflag_type_e {
/** Sentinel placeholder. */
FCLI_FLAG_TYPE_INVALID = 0,
/** Represents bool. */
FCLI_FLAG_TYPE_BOOL,
/** Represents bool, but gets set to false if the flag is set. */
FCLI_FLAG_TYPE_BOOL_INVERT,
/** Works like FCLI_FLAG_TYPE_BOOL but toggles the target
    boolean each time it's seen. */
FCLI_FLAG_TYPE_BOOL_TOGGLE,
/** Represents int32_t. */
FCLI_FLAG_TYPE_INT32,
/** Represents int64_t. */
FCLI_FLAG_TYPE_INT64,
/** Represents fsl_id_t, which might be either int32_t or int64_t. */
FCLI_FLAG_TYPE_ID,
/** Represents double. */
FCLI_FLAG_TYPE_DOUBLE,
/** Represents (char const *). */
FCLI_FLAG_TYPE_CSTR
};

typedef struct fcli_cliflag fcli_cliflag;
/**
   Callback handler for CLI flag handling. It is passed the flag in
   question, containing its state after fcli has processed its
   flagValue part.

   If the callback returns FCLI_RC_FLAG_AGAIN, the flag handler will
   check for that flag again (for as long as the handler keeps
   returning that value and as long as the flag repeats in the
   argument list). This can be used to implement repeatable flags.

   If it returns any other non-0 value, fcli_setup()
   resp. fcli_process_flags() will fail with that result code.

   Achtung: during fcli_setup(), at the time these are processed, fcli
   will not yet have opened up a repository or checkout, so the
   callback will not have access to things like symbolic-name-to-UUID
   conversion at this level. Apps which need to do such work on their
   arguments must first queue up the input and process it after
   fcli_setup() returns. Apps which process the flags using
   fcli_process_flags() after setup is complete will have access to
   such features.
*/
typedef int (*fcli_flag_callback_f)(fcli_cliflag const *);

/**
   Models a single CLI flag. Its relative complexity is largely to
   support generation of help text.

   @see fcli_process_flags()
*/
struct fcli_cliflag {
  /**
     "Short-form" for this flag, noting that there's no restriction on
     its length. Either of flagShort and flagLong, but not both, may be
     NULL.
  */
  const char * flagShort;
  /**
     "Long-form" for this flag, noting that there's no restriction on
     its length.
  */
  const char * flagLong;

  /**
     Specifies how to interpret the data pointed to by
     this->flagValue. See that member for details.
  */
  enum fcli_cliflag_type_e flagType;

  /**
     If not NULL, the member is the target of the flag's value.
     Its exact interpretation depends on the value of this->flagType:

     - FCLI_FLAG_TYPE_BOOL: a pointer to a bool. Existence
     of the flag causes it to be set to true.

     - FCLI_FLAG_TYPE_BOOL_INVERT: a pointer to a bool, but
     existence of the flag causes it to be set to false.

     - FCLI_FLAG_TYPE_BOOL_TOGGLE: works like the other BOOL
     varants and it toggles that value on each invocation.

     - FCLI_FLAG_TYPE_INT32: a pointer to an int32_t. The flag's
     value must be an optionally signed base-10 integer in the range
     of int32_t.

     - FCLI_FLAG_TYPE_INT64: a pointer to an int64_t. The flag's
     value must be an optionally signed base-10 integer in the range
     of int64_t.

     - FCLI_FLAG_TYPE_ID: a pointer to a fsl_id_t, which
     can be either int32_t or int64_t. The flag's value must be a
     non-negative base-10 integer in the range of fsl_id_t.

     - FCLI_FLAG_TYPE_DOUBLE: a pointer to a double. The flag's
     value is converted using strtod() and must contain nothing
     after the number.

     A numeric value which does not meet those rules causes
     fcli_process_flags() to fail with FSL_RC_RANGE and an error
     message naming the flag and the value.

     - FCLI_FLAG_TYPE_CSTR: a pointer to a (const char *). The flag's
     value will be assigned on without further interpretation.

     If this member is not NULL: If the flag is set, this value will
     be assigned to. If the flag is not set in the CLI args, this
     value is not written to.

     If this member is NULL then fcli_process_flags() will simply skip
     over it, but the help-text generator will process it. This can be
     used to set up flags which will appear in the --help text but
     which are processed separately (or outright ignored) by the app.

     The underlying flag value's string memory is owned by fcli and is
     valid until the app exits.
  */
  void * flagValue;

  /**
     Optional descriptive label to be used when rendering help text:

     -x|--x-flag=ABCD

     If it is NULL, the --help text generator will choose a value of
     the ABCD part which depends on this->flagType.

     This is only used if this->flagType is not one of
     (FCLI_FLAG_TYPE_BOOL, FCLI_FLAG_TYPE_BOOL_INVERT,
     FCLI_FLAG_TYPE_BOOL_TOGGLE). For those types (which have no
     client-given values), this member is ignored when generating help
     text.
  */
  const char * flagValueLabel;

  /**
     Optional callback which gets passed the flag, if it is set, after
     fcli has assigned the flagValue entry (if it is not NULL).
     See this data type's docs for more details.
  */
  fcli_flag_callback_f callback;

  /**
     Help text for the flag. Intended to be displayed in the context
     of a --help listing of flags.
  */
  const char * helpText;
};
#define fcli_cliflag_empty_m {\
    0/*flagShort*/,0/*flagLong*/,\
    FCLI_FLAG_TYPE_INVALID/*flagType*/,\
    NULL/*flagValue*/,\
    NULL/*flagValueLabel*/,NULL/*callback*/,NULL/*helpText*/}
/** Non-const-copyable counterpart of fcli_cliflag_empty_m. */
FSL_EXPORT const fcli_cliflag fcli_cliflag_empty;

/** @def FCLI_FLAG_xxx

   The various FCLI_FLAG_xxx macros are convenience-form initializers
   for fcli_cliflag instances for use in initializing a fcli_cliflag
   array. Example usage:

   ```
   bool flag1 = true, flag2 = false;
   int32_t flag3 = 0;
   const char * flag4 = 0;
   const fcli_cliflag cliFlags[] = {
     FCLI_FLAG_BOOL("x","xyz",&flag1,"Flag 1."),
     FCLI_FLAG_BOOL_INVERT(NULL,"yzx",&flag2,"Flag 2."),
     FCLI_FLAG_INT32("z",NULL,"value",&flag3,"Flag 3"),
     FCLI_FLAG("f","file","filename",&flag4,
               "Input file. May optionally be passed as the first "
               "non-flag argument."),
     fcli_cliflag_empty_m // list MUST end with this (or equivalent)
   };
   fcli_help_info const appHelp = {...};

   int rc = fcli_setup_v2(argc, argv, cliFlags, &appHelp);
   ```

   BE CAREFUL with the data types, as we're using (void*) to access
   data of an arbitrary type, the type being defined by a separate
   field in the fcli_cliflag object.
*/
#define FCLI_FLAG_xxx /* for doc purposes only */
//Members:
//{short, long, type, tgt, valueDescr., callback, help}
/** Bool-type flag. */
#define FCLI_FLAG_BOOL(S,L,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_BOOL,TGT,NULL,NULL,HELP}
/** Bool-type flag, but set to false if flag is set. */
#define FCLI_FLAG_BOOL_INVERT(S,L,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_BOOL_INVERT,TGT,NULL,NULL,HELP}
/** Bool-type flag toggled for each flag instance. */
#define FCLI_FLAG_BOOL_TOGGLE(S,L,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_BOOL_TOGGLE,TGT,NULL,NULL,HELP}
/** Bool-type flag with a callback. */
#define FCLI_FLAG_BOOL_X(S,L,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_BOOL,TGT,NULL,CALLBACK,HELP}
/** Bool-type flag with a callback, but set to false if the flag is set. */
#define FCLI_FLAG_BOOL_INVERT_X(S,L,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_BOOL_INVERT,TGT,NULL,CALLBACK,HELP}
/** String-type flag. */
#define FCLI_FLAG_CSTR(S,L,LBL,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_CSTR,TGT,LBL,NULL,HELP}
#define FCLI_FLAG FCLI_FLAG_CSTR
/** String-type flag with a callback. */
#define FCLI_FLAG_CSTR_X(S,L,LBL,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_CSTR,TGT,LBL,CALLBACK,HELP}
#define FCLI_FLAG_X FCLI_FLAG_CSTR_X
/** int32-type flag. */
#define FCLI_FLAG_I32(S,L,LBL,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_INT32,TGT,LBL,NULL,HELP}
/** int32-type flag with a callback. */
#define FCLI_FLAG_I32_X(S,L,LBL,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_INT32,TGT,LBL,CALLBACK,HELP}
/** int64-type flag. */
#define FCLI_FLAG_I64(S,L,LBL,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_INT64,TGT,LBL,NULL,HELP}
/** int64-type flag with a callback. */
#define FCLI_FLAG_I64_X(S,L,LBL,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_INT64,TGT,LBL,CALLBACK,HELP}
/** fsl_id_t-type flag. */
#define FCLI_FLAG_ID(S,L,LBL,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_ID,TGT,LBL,NULL,HELP}
/** fsl_id_t-type flag with a callback. */
#define FCLI_FLAG_ID_X(S,L,LBL,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_ID,TGT,LBL,CALLBACK,HELP}
/** double-type flag. */
#define FCLI_FLAG_DBL(S,L,LBL,TGT,HELP) \
  {S,L,FCLI_FLAG_TYPE_DOUBLE,TGT,LBL,NULL,HELP}
/** double-type flag with a callback. */
#define FCLI_FLAG_DBL_X(S,L,LBL,TGT,CALLBACK,HELP) \
  {S,L,FCLI_FLAG_TYPE_DOUBLE,TGT,LBL,CALLBACK,HELP}

/**
   Structure for holding app-level --help info.
*/
struct fcli_help_info {
  /** Brief description of what the app does. */
  char const * briefDescription;
  /** Brief usage text. It will be prefixed by the app's name and
      "[options]". e.g. "file1 ... fileN".
  */
  char const * briefUsage;
  /**
     If not 0 then this is called after outputing any flags' help.
     It should output any additional help text using f_out().
  */
  void (*callback)(void);
};
typedef struct fcli_help_info fcli_help_info;

/**
   The fcli_t type, accessed by clients via the ::fcli
   global instance, contains various data for managing a basic
   Fossil SCM application build using libfossil.

   Usage notes:

   - All non-const pointer members are owned and managed by the
   fcli API. Clients may reference them but must be aware of
   lifetimes if they plan to hold the reference for long.

*/
struct fcli_t {
  /**
     The shared fsl_cx instance. It gets initialized by
     fcli_setup() and cleaned up post-main().

     this->f is owned by this object and will be cleaned up at app
     shutdown (post-main).
  */
  fsl_cx * f;
  /**
     The current list of CLI arguments. This list gets modified by
     fcli_flag() and friends. Its memory is owned by fcli.
  */
  char ** argv;
  /**
     Current number of items in this->argv.
  */
  int argc;
  /**
     Application's name. Currently argv[0] but needs to be adjusted
     for Windows platforms. Gets set by fcli_setup_v2() and may
     optionally be set by the client before calling that.
  */
  char const * appName;
  /**
     The flags in this struct are "public," meaning that client
     applications may query and safely manipulate them directly if
     they know what they're doing.

     However, some of this state is only be legally modified
     _before_ calling fcli_setup() (or equivalent).
  */
  struct {
    /**
       If not NULL, it must be a pointer to fcli_help_info holding help
       info for the app.  It will be formated and output when --help
       is triggered.

       Should be set by client applications BEFORE calling fcli_setup()
       so that the ::fcli help subsystem can integrate the
       app. fcli.appName will be set by the time this is used.
    */
    fcli_help_info const * appHelp;

    /**
       May be set to an array of CLI flag objects, which fcli_setup()
       will use for parsing the CLI flags. The array MUST end with an
       entry which has NULL values for its (flagShort, flagLong)
       members. When creating the array it is simplest to use
       fcli_cliflag_empty_m as the initializer for that sentinel entry.

       The elements in this array are traversed in the order they are
       provided, and any which have a callback which returns
       FCLI_RC_FLAG_AGAIN will be traversed repeatedly before moving on
       to the next flag. This ordering may have side-effects on how the
       app sets up its flag handling. In particular, this arrangement
       makes the common cases easy to implement but makes certain more
       complicated situations effectively impossible to implement. For
       example:

       ```
       -x=1 -y=2 -x=3 -y=4
       ```

       Assuming the definition of the -y flag is first in this array and
       has a callback which returns FCLI_RC_FLAG_AGAIN, the two -x flags
       will be processed before either of the -y flags. Thus it is
       impossible (using this method of traversal) to change the
       behavior of the -y flags based on the left-closest -x value.

       We "could," but probably never will, instead walk the input argv
       looking for things which look like flags, then looking back into
       this list for a match, rather than the other way around. That
       would require a new args processing implementation, though, for
       relatively little benefit.
    */
    const fcli_cliflag * cliFlags;

    /**
       If not NULL then fcli_setup() will attempt to open the
       checkout for the given dir, including its associated repo
       db. By default this is "." (the current directory).

       Applications can set this to NULL _before_ calling
       fcli_setup() in order to disable the automatic attemp to
       open a checkout under the current directory.  Doing so is
       equivalent to using the --no-checkout flag. The global
       --checkout-dir flag will trump that setting, though.
    */
    char const * checkoutDir;

    /**
       A verbosity level counter. Starts at 0 (no verbosity) and goes
       up for higher verbosity levels. Currently levels 1 and 2 are
       intended for app-level use and level 3 for library-level use.
    */
    unsigned short verbose;

    /**
       Whether or not to enable fossil's SQL tracing.  This should
       start with a negative value, which helps fcli_setup() process
       it. Setting this after initialization has no effect.
    */
    int traceSql;
    /**
       This output channel is used when initializing the context
       object. The default implementation uses fsl_outputer_FILE to
       output to stdout.
    */
    fsl_outputer outputer;

    /**
       Listener for fsl_msg-published messages. The default listener
       sends all of its output via this->outputer.
    */
    fsl_msg_listener listener;
  } config;

  /**
     Transient settings and flags set in response to global/shared CLI
     flags. These are bits which are used during (or very shortly
     after) fcli_setup() but generally have no effect if modified
     after that (and should not be modified, in any case).

     TODO (2026-07-30): move this into static state in cli.c.

     TOOD (2026-10-16): see previous TODO.
  */
  struct {
    /**
       repo db name string from -R/--repo CLI flag.
    */
    const char * repoDbArg;
    /**
       User name from the --user CLI flag.
    */
    const char * userArg;
    /**
       Incremented if fcli_setup() detects -? or --help in the
       argument list, or if the first non-flag argument is "help".
       This is an int, rather than a bool, to support multiple levels
       of help verbosity via multiple --help flags.
    */
    short helpRequested;
    /**
       True if the --lib-version CLI flag was used. This causes
       fcli setup to exit as if --help had been invoked.
    */
    bool versionRequested;

    /**
       If true then fcli_sync() will emit verbose sync metrics. If it's
       false, it won't.

       CLI flag: -SM|--sync-metrics sets this to the opposite of
       whatever the build-time default is. i.e. it turns it off if
       it's on by default and on if it's off by default.
    */
    bool reportSyncMetrics;

    /**
       If true then fcli will dump various cache metrics

       CLI flag: -CU|--cache-metrics.
    */
    bool reportCacheMetrics;

    /**
       If true (the default) then fcli installs the
       fcli.config.listener in its fsl_cx instance, which means that
       it will provide progress of, e.g., clone or rebuild via its
       output channel. If false then it does not do so.

       CLI flag: --no-lib-events
    */
    bool libEvents;
  } globalFlags;
  /**
     For holding pre-this->f-init error state. Once this->f is
     initialized, all errors reported via fcli_err_set() are stored in
     that object's error state.
  */
  fsl_error err;
};
typedef struct fcli_t fcli_t;

/** @var fcli

    This fcli_t instance is intended to act as a singleton.  It holds
    all fcli-related global state.  It gets initialized with
    default/empty state at app startup and gets fully initialized via
    fcli_setup(). See that routine for an example of how it is
    typically initialized.

    fcli_cx() returns the API's fsl_cx instance. It will be non-NULL
    (but might not have an opened checkout/repository) if fsl_setup()
    succeeds.
*/
FSL_EXPORT fcli_t fcli;

/**
   Initializes fcli's state and CLI flags processing.

   MUST BE CALLED BEFORE fsl_malloc() and friends are used, as this
   swaps out the allocator with one which aborts on OOM. (But see
   fcli_pre_setup() for a workaround for that.)

   Should be called early on in main(), passed the arguments passed to
   main(). Returns 0 on success. This sets up the ::fcli instance and
   opens any checkout found in/above the current dir by default. To
   disable the automatic search for a checkout, assign
   `fcli.config.checkoutDir` to `NULL` before calling this.

   If the 3rd argument is not NULL, this sets `fcli.config.cliFlags` to its
   value. If the 4th argument is not NULL, this sets `fcli.config.appHelp` to
   that value.

   If argument processing finds either of the (`--help`, `-?`) flags,
   or the first non-flag argument is "help", it calls fcli_help(), and
   returns FCLI_RC_HELP, in which case the application should
   exit/return from main with code 0 immediately (see example
   below). It behaves similar when it finds the `--lib-version` flag.

   This function behaves significantly differently if its 3rd argument
   is not NULL or if fcli.config.cliFlags has been set before it is
   called. In that case, it parses the CLI flags using that type's
   rules and sets up fcli_help() to use those flags for generating the
   help. It parses the global flags first, then the app-specific flags
   (this means that global flags will be consumed from the argv array
   before app-specific flags with the same names).

   Returns 0 on success. Results other than FCLI_RC_HELP should be
   treated as fatal to the app, and fcli.f's error state _might_
   contain info about the error. If this function returns non-0, the
   convention is that the app immediately returns the result of
   fcli_end_of_main(THE_RESULT_CODE) from main(). That function will
   treat FCLI_RC_HELP as a non-error and will report any error state
   pending in the fcli_cx() object.

   Example of intended basic usage:

   ```
   int main(int argc, char const * const * argv){
     ...
     // Optional fcli_cliflag setup:
     fcli_cliflag const cliFlags[] = {
       ...,
       fcli_cliflag_empty_m // empty trailing entry required
     };
     // Optional fcli_help_info setup:
     fcli_help_info const help = {
       "Fnoobs the borts and rustles the feathers.",
       "file1 [... fileN]",
       NULL // optional callback to display extra help
     };
     // Initialize...
     int rc = fcli_setup_v2(argc, argv, cliFlags, &help);
     if(rc) goto end; // might be from --help

     ... app logic ...

     end:
     return fcli_end_of_main(rc);
   }
   ```

   @see fcli_pre_setup()
   @see fcli_setup()
   @see fcli_end_of_main()
*/
FSL_EXPORT int fcli_setup_v2(int argc, char const * const * argv,
                             fcli_cliflag const * const cliFlags,
                             fcli_help_info const * const helpInfo );

/**
   The first time this is called, it swaps out libfossil's default
   allocator with a fail-fast one which abort()s on allocation
   error. This is normally called by fcli_setup(), but that also means
   that it's illegal to use fsl_malloc() and friends before calling
   that routine. If an application really needs to use fsl_malloc()
   before calling fcli_setup(), it must call this first in order to
   get the allocator initialization out of the way.

   Calls after the first are no-ops, but the check for that is not
   thread-safe. Neither is fcli, though, so that's okay.
*/
FSL_EXPORT void fcli_pre_setup(void);

/**
   Returns the libfossil context associated with the fcli API.
   This will be NULL until fcli_setup() is called.
*/
FSL_EXPORT fsl_cx * fcli_cx(void);

/**
   Works like printf() but sends its output to fsl_outputf() using
   the fcli.f fossil conext (if set) or fsl_fprintf() (to
   stdout).
*/
FSL_EXPORT void fcli_printf(char const * fmt, ...)
#if 0
/* Would be nice, but complains about our custom format options: */
  __attribute__ ((__format__ (__printf__, 1, 2)))
#endif
  ;

/**
   f_out() is a shorthand for fcli_printf().
*/
#define f_out fcli_printf

/**
   Returns the verbosity level set via CLI args. 0 is no verbosity,
   and one level is added each time the --verbose/-V CLI flag is
   encountered by fcli_setup().
*/
FSL_EXPORT unsigned short fcli_is_verbose(void);

/**
   Searches fcli.argv for the given flag (pass it without leading
   dashes). If found, this function returns true, else it returns
   false. If value is not NULL then the flag, if found, is assumed to
   have a value, otherwise the flag is assumed to be a boolean. A flag
   with a value may take either one of these forms:

   -flag=value
   -flag value

   *value gets assigned to a COPY OF the value part of the first form
   or a COPY OF the subsequent argument for the second form (copies
   are required in order to avoid trickier memory management
   here). That copy is owned by fcli and will be cleaned up at app
   exit. On success it removes the flag (and its value, if any) from
   fcli.argv.  Thus by removing all flags early on, the CLI arguments
   are left only with non-flag arguments to sift through.

   Flags may start with either one or two dashes - they are
   equivalent.

   This function may update the fcli error state. Specifically, if
   passed a non-NULL 2nd argument and the flag is found at the end of
   the argument list or the value immediately after the flag starts
   with '-' then the error state will be updated and false will be
   returned. Apps don't normally need to be quite that picky with
   their error checking after looking for a flag, but the state is
   there if needed. It may get reset by any future calls into the API,
   though. fcli_process_flags() does check this state and will fail if
   such an error is triggered.
*/
FSL_EXPORT bool fcli_flag(char const * opt, const char ** value);

/**
   Works like fcli_flag() but tries two argument forms, in order. It
   is intended to be passed short and long forms, but can be passed
   two aliases or similar. It accepts NULL for either form.

   ```
   const char * v = NULL;
   fcli_flag2("n", "limit", &v);
   if(v) { ... }
   ```
*/
FSL_EXPORT bool fcli_flag2(char const * opt1, char const * opt2,
                           const char ** value);

/**
   Works similarly to fcli_flag2(), but if no flag is found and
   value is not NULL then *value is assigned to the return value of
   fcli_next_arg(true). In that case:

   - The return value will specify whether or not fcli_next_arg()
   returned a value or not.

   - If it returns true then *value is owned by fcli and will be
   cleaned up at app exit.

   - If it returns false, *value is not modified.

   The opt2 parameter may be NULL, but op1 may not.
*/
FSL_EXPORT bool fcli_flag_or_arg(char const * opt1, char const * opt2,
                                 const char ** value);


/**
   Clears any error state in fcli.f.
*/
FSL_EXPORT void fcli_err_reset(void);

/**
   Sets fcli.f's error state, analog to fsl_cx_err_set().
   Returns the code argument on success, some other non-0 value on
   a more serious error (e.g. FSL_RC_OOM when formatting the
   string).
*/
FSL_EXPORT int fcli_err_set(int code, char const * fmt, ...);

/**
   Returns the internally-used fsl_error instance which is used for
   propagating errors.  The object is owned by ::fcli and MUST NOT
   be freed or otherwise abused by clients. It may, however, be
   passed to routines which take a fsl_error parameter to report
   errors (e.g. fsl_deck_output().

   Returns NULL if fcli_setup() has not yet been called or after
   fcli has been cleaned up (post-main()).

*/
FSL_EXPORT fsl_error * fcli_error(void);

/**
   If ::fcli has any error state, this outputs it and returns the
   error code, else returns 0. If clear is true the error state is
   cleared/reset, otherwise it is left in place. Returns 0 if
   ::fcli has not been initialized. The 2nd and 3rd arguments are
   assumed to be the __FILE__ and __LINE__ macro values of the call
   point. See fcli_err_report() for a convenience form of this
   function.

   If fcli_cx() has no error state but fsl_cx_db(fcli_cx()) does,
   then that error state is moved into the fsl_cx object and
   reported here.

   The format of the output depends partially on fcli_is_verbose(). In
   verbose mode, the file/line info is included, otherwise it is
   elided.

   @see fcli_err_report()
*/
FSL_EXPORT int fcli_err_report2(bool clear, char const * file, int line);

/**
   Convenience macro for using fcli_err_report2().
*/
#define fcli_err_report(CLEAR) fcli_err_report2((CLEAR), __FILE__, __LINE__)

/**
   Peeks at or takes the next argument from the CLI args. If the
   argument is true, it is removed from the args list. It is owned by
   fcli and will be freed when the app exits.

   Returns NULL if the args list is empty.
*/
FSL_EXPORT const char * fcli_next_arg(bool remove);

/**
   If fcli.argv contains what looks like any flag arguments, this
   updates the fossil error state and returns FSL_RC_MISUSE, else
   returns 0. A "-" by itself is not considered to be a flag, as it
   conventionally names stdin or stdout. If outputError is true and an
   unused flag is found then
   the error state is immediately output (but not cleared).  If
   outputError is false then the next call to fcli_err_report2() will
   emit it the error, typically indirectly via fcli_end_of_main().
*/
FSL_EXPORT int fcli_has_unused_flags(bool outputError);
/**
   If fcli.argv contains any entries, returns FSL_RC_MISUSE and
   updates the error state with a message about unusued extra
   arguments, else returns 0. outputError is interpreted as for
   fcli_has_unused_flags().
*/
FSL_EXPORT int fcli_has_unused_args(bool outputError);

typedef struct fcli_command fcli_command;
/**
   Typedef for general-purpose fcli call-by-name commands.

   It gets passed its own command definition, primarily for each of
   access to the flags member for CLI flags processing.

   @see fcli_dispatch_commands()
*/
typedef int (*fcli_command_f)(fcli_command const *);

/**
   Describes a named callback command.

   @see fcli_dispatch_commands()
*/
struct fcli_command {
  /** The name of the command. */
  char const * name;
  /**
     NUL-delimited string containing optional aliases of the above command
     name. This string _must_ be double-NUL terminated (e.g., "alias\0\al\0").
  */
  char const * aliases;
  /** Brief description, for use in generating help text. */
  char const * briefDescription;
  /** The callback for this command. */
  fcli_command_f f;
  /** Optional usage callback for this command. */
  void (*usage)(void);
  /**
     Must be NULL or an array compatible with fcli_process_flags().
     Can be used from within this->f for command-specific flag
     dispatching, as well as help text generation.
  */
  fcli_cliflag const * flags;
};

/**
   Expects an array of fcli_commands which contain a trailing
   sentry entry with a NULL name and callback. It searches the list
   for a command matching fcli_next_arg(). If found, it
   removes that argument from the list, calls the callback, and
   returns its result. If no command is found FCLI_RC_NO_CMD is
   returned, the argument list is not modified, and the error state
   is updated with a description of the problem and a list of all
   command names in cmdList.

   The distinct FCLI return code aims to help clients distinguish
   between fcli_dispatch_commands() failure and failures propagated
   by successfully dispatched fcli_command fcli_command_f callbacks.

   If reportErrors is true then on error this function outputs
   the error result but it keeps the error state in place
   for the downstream use.

   As a special case: when a command matches the first argument and
   that object has a non-NULL flags member, this function checks the
   _next_ argument, and if it is "help" then this function passes
   that flags member to fcli_command_help() to output help, then
   returns 0.
*/
FSL_EXPORT int fcli_dispatch_commands( fcli_command const * cmdList,
                                       bool reportErrors);

/**
   Parse cmd->aliases for an alias (i.e., NUL-terminated string semantically
   equivalent to cmd->name) matching arg. Return 0 if a match is found, else 1.
   Note that cmd->aliases _must_ be double-NUL terminated.
*/
FSL_EXPORT int fcli_cmd_aliascmp( fcli_command const * cmd, char const * arg );

/**
   A minor helper function intended to be passed the pending result
   code of the main() routine. This function outputs any pending
   error state in fcli. Returns one of EXIT_SUCCESS if mainRc is 0
   and fcli had no pending error report, otherwise it returns
   EXIT_FAILURE. This function does not clean up fcli - that is
   handled via an atexit() handler.

   It is intended to be called once at the very end of main:

   ```
   int main(){
   int rc;

   ...set up fcli...assign rc...

   return fcli_end_of_main(rc);
   }
   ```

   As a special case, if mainRc is FCLI_RC_HELP, it is assumed to
   be the result of the fcli --help flag handling, and is treated as
   if it were 0.

   If mainRc is non-0 but fcli has no error state, the report names
   mainRc and lists any arguments the app left unconsumed (see
   fcli_next_arg()), since an unconsumed argument often shows which
   argument the app misread.

   @see fcli_error()
   @see fcli_err_set()
   @see fcli_err_report()
   @see fcli_err_reset()
*/
FSL_EXPORT int fcli_end_of_main(int mainRc);

/**
   If mem is not NULL, this routine appends mem to a list of pointers
   which will be passed to fsl_free() during the atexit() shutdown
   phase of the app. Because fcli uses a fail-fast allocator, failure
   to append the entry will itself cause a crash. This is only useful
   for values for which fsl_free() suffices to clean them up, not
   complex values like multi-dimensional arrays.

   "fax" is short for "free at exit."

   Results are undefined if the same address or overlapping addresses
   are queued more than once. Once an entry is in this queue, there is
   no way to remove it.

   Returns its argument so that it can be used like:

   ```
   char * x = fcli_fax( fsl_strdup("...") );
   ```
*/
FSL_EXPORT void * fcli_fax(void * mem);

/**
   Requires an array of fcli_cliflag objects terminated with an
   instance with NULL values for the (flagShort, flagLong) members
   (fcli_cliflag_empty_m is an easy way to get that).

   If fcli.config.cliFlags is set before fcli_setup() is called, this routine
   is called and passed those flags. Thus most apps can simply assign
   their flags there and let setup() do the work. Apps which have
   multiple dispatch paths, each with differing flags, may find it
   easier to use this.

   As a special case, if a given entry has NULL values for both of its
   (flagValue, callback) members, it is assumed to exist purely for
   use with the help-generating mechanisms and the flag is NOT
   processed or consumed by fcli_process_flags(). That can be used
   when the client needs to process the flag in ways beyond what is
   capable via this routine. In such cases, add an appropriate entry
   to the fcli_cliflag array for --help purposes and then process the
   flag using fcli_flag() (or similar) either before or after calling
   this.

   Returns 0 on success. On error it sets the fcli error state
   (fcli_error()) and returns non-0:

   - FSL_RC_MISUSE if a flag which requires a value has none.

   - FSL_RC_RANGE if a numeric flag's value is not a valid number
     of that flag's type.

   - FSL_RC_MISUSE if an entry has an unknown flagType.

   - The result of a callback() member which returns a value other
     than 0 or FCLI_RC_FLAG_AGAIN. The callback is responsible for
     setting the error message.
*/
FSL_EXPORT int fcli_process_flags( fcli_cliflag const * defs );

/**
   Requires an array of fcli_cliflag objects as described for
   fcli_process_flags(). This routine outputs their flags
   and help text in a framework-conventional manner.

   If fcli.config.cliFlags is set before fcli_setup() is called, this
   routine is called and passed those flags. Thus most apps can simply
   assign their flags there and let fcli_setup() do the work. Apps
   which have multiple dispatch paths, each with differing flags, may
   find it easier to use this.

   Such apps, in order to get the full help listing for all dispatch
   paths, may need to assign fcli.config.appHelp to a helper which
   dispatches to an app-local help routine which, in turn, passes each
   of their separate fcli_cliflag lists to this routine.
*/
FSL_EXPORT void fcli_cliflag_help(fcli_cliflag const *defs);

/**
   Requires that cmd be an array of fcli_command objects with a
   trailing entry which has a NULL name. This function iterates over
   them and outputs help text based on each one's (name,
   briefDescription, flags) members.

   If the 2nd argument is true AND the cmd->usage() callback has been
   set, it will be called for each object in the cmd array after
   outputting the cmd->flags help text.

   If the 3rd argument is true, only the help for the single given
   object is output, not any adjacent array members (if any).
*/
FSL_EXPORT void fcli_command_help(fcli_command const * cmd, bool showUsage, bool onlyOne);

/**
   Pretty print fcli_command->aliases like: " (aliases: cmd, com)".
*/
FSL_EXPORT void fcli_help_show_aliases(char const * aliases);

/**
   If fcli has a checkout opened, this dumps various info about it
   to its output channel. Returns 0 on success, FSL_RC_NOT_A_CKOUT
   if no checkout is opened, or some other non-0 code on error.

   If the useUtc argument is true, it uses UTC timestamps, else
   localtime. (Potential TODO: add an fcli-level CLI flag for that
   instead?)
*/
FSL_EXPORT int fcli_ckout_show_info(bool useUtc);

/**
   Given a hash prefix, lists (via f_out()) all blob table entries
   which have this prefix. This is intended to be used by apps which
   accept a from a user and fsl_sym_to_rid() returns FSL_RC_AMBIGUOUS.

   The first argument is an optional output label/header to output.
   If it is NULL, a default is used. If it is "" then no header is
   output.
*/
FSL_EXPORT void fcli_list_ambiguous_artifacts(char const * label, char const *prefix);

/**
   If fcli has an opened checkout, that db handle is returned, else NULL
   is returned.
*/
FSL_EXPORT fsl_db * fcli_db_ckout(void);

/**
   If fcli has an opened repository, that db handle is returned, else
   NULL is returned.
*/
FSL_EXPORT fsl_db * fcli_db_repo(void);

/**
   If fcli has an opened checkout, that db handle is returned, else NULL
   is returned and fcli's error state is updated with a description
   of the problem.
*/
FSL_EXPORT fsl_db * fcli_needs_ckout(void);

/**
   If fcli has an opened repository, that db handle is returned, else NULL
   is returned and fcli's error state is updated with a description
   of the problem.
*/
FSL_EXPORT fsl_db * fcli_needs_repo(void);

/**
   Processes all remaining CLI arguments as potential file or directory
   names, collects their vfile.id values, and stores them in the given
   target bag. It requires an opened checkout.

   vid is the vfile.vid value to filter on. If vid<=0 then the current
   checkout version is used. (Unless the app has explicitly loaded
   another version, that will be the only option available.)

   If relativeToCwd is true then each argument is resolved as if
   referenced from the current working directory, else each is assumed
   to be relative to the top of the checkout directory. (For CLI apps,
   a value of true is almost always the right choice.)

   If changedFilesOnly is true then only files which are "changed",
   according to the vfile table (as opposed to a filesystem check) are
   considered for addition. For that to work, vfile must be up to
   date, so fsl_vfile_changes_scan() must have been recently called to
   update that state. This function does not call it automatically
   because it's relatively slow and many apps already have to call it
   on their own.

   This function matches only vfile.pathname, not vfile.origname,
   because it is possible for a given name to be in both fields (in
   different records) at the same time.

   Returns 0 on success. If there are no more CLI arguments when it is
   called then it returns FSL_RC_MISUSE and updates the fcli error
   state with a description of the problem. It may return any number
   of non-0 codes from the underlying operations.

   Sidebar: fsl_filename_to_vfile_ids() requires that directory names
   passed to it have no trailing slashes, and this routine strips
   trailing slashes from its arguments before passing them on to that
   routine, so they may be entered with slashes without ill effect.

   @see fsl_filename_to_vfile_ids()
*/
FSL_EXPORT int fcli_args_to_vfile_ids(fsl_id_bag * const tgt,
                                      fsl_id_t vid,
                                      bool relativeToCwd,
                                      bool changedFilesOnly);

/**
   Performs a "fingerprint check" on the current checkout/repo
   combination, as per fsl_ckout_fingerprint_check(). If the check
   fails and reportImmediately is true then an error report is
   immediately output. Returns 0 if the fingerprint check is okay,
   else a non-0 value as per fsl_ckout_fingerprint_check().

   Passing true here may output more information than the underlying
   fsl_cx-level error state provides. e.g. it may provide a hint about
   how to recover.
*/
FSL_EXPORT int fcli_fingerprint_check(bool reportImmediately);

/**
   Returns the "tail" part of the argv[0] string which was passed to
   fcli_setup(), or NULL if neither of those have yet been called. The
   "tail" part is the part immediately after the final '/' or '\\'
   character.
*/
FSL_EXPORT char const * fcli_progname(void);

/**
   Color theme IDs for use with fcli_diff_colors.
 */
enum fcli_diff_colors_e{
/**
   Tells fcli_diff_colors() to NULL out the ANSI color state of its
   target object.
*/
FCLI_DIFF_COLORS_NONE = 0,
/**
   Basic red (deletion) and green (insertion) diff colors.
*/
FCLI_DIFF_COLORS_RG,
FCLI_DIFF_COLORS_DEFAULT = FCLI_DIFF_COLORS_RG
};
typedef enum fcli_diff_colors_e fcli_diff_colors_e;

/**
   Populates the given fsl_dibu_opt::ansiColors state with values
   dependend on the second argument.
*/
FSL_EXPORT void fcli_diff_colors(fsl_dibu_opt * const tgt,
                                 fcli_diff_colors_e theme);

/**
   Uses the library's sync API to run a sync operation, optionally
   either or both of push and pull operations. 

   Its argument may be a mask of any values from the fsl_sync_flags_e
   enum.

   Returns 0 if it does not sync.  Returns FSL_RC_NOT_A_REPO if no
   repo is opened. If the repo is opened but has no "syncwith:"
   entries in its config table, no sync is attempted and 0 is
   returned.

   If fossil cannot be found, returns FSL_RC_NOT_FOUND, else returns
   as documented for fsl_system().

   TODO (2026-09-30): consolidate fcli_sync_e with lib-level code
   (where is TBD).
*/
FSL_EXPORT int fcli_sync( int ops );


/** @internal

   This function is intented for use in development of libfossil. It
   dumps the current state of cached SQL statements to fcli_printf().

   Normally its output detail level is determined by
   fcli_is_verbose(), but if forceVerbose is true then it cranks the
   detail all the way up.
 */
FSL_EXPORT void fcli_dump_stmt_cache(bool forceVerbose);

/** @internal

    This pseudo-internal function causes fcli to dump any
    library-level caching metrics it knows about. This function exists
    primarily to keep fcli client code from having to access the
    related internal members directly. This is a no-op if fcli has
    not been initialized.
*/
FSL_EXPORT void fcli_dump_cache_metrics(void);

/**
   A fsl_msg_f() implementation intended for use with CLI apps.  It
   emits all output via fcli_printf(). This is the default message
   listener. Clients may replace the default by setting up
   fcli.config.listener before calling fcli_setup_v2(), and simple
   client apps may use this for other fsl_cx instances. This
   implementation ignores its state argument.
*/
FSL_EXPORT int fsl_msg_f_fcli(fsl_msg const *msg, void *state);

#if defined(__cplusplus)
} /*extern "C"*/
#endif

#endif
/* _ORG_FOSSIL_SCM_FCLI_H_INCLUDED_ */
/* end of file include/fossil-scm/cli.h */
/* start of file include/fossil-scm/deprecated.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(FSL_OMIT_DEPRECATED)
#if !defined(ORG_FOSSIL_SCM_LIBFOSSIL_DEPRECATED_H_INCLUDED)
#define ORG_FOSSIL_SCM_LIBFOSSIL_DEPRECATED_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/** @file deprecated.h

  This file holds APIs which are deprecated or otherwise "on the chopping
  block." The libfossil public API has gathered a good deal of cruft
  over the years.
*/

/**
   @deprecated fsl_db_role_name() is easier to deal with.

   Similar to fsl_cx_db_file_ckout() and friends except that it
   applies to DB name (as opposed to DB _file_ name) implied by the
   specified role (2nd parameter). If no such role is opened, or the
   role is invalid, NULL is returned.

   If the 3rd argument is not NULL, it is set to the length, in bytes,
   of the returned string. The returned strings are NUL-terminated and
   are either static or owned by the db handle they correspond to.

   If the client does not care whether the db in question is
   actually opened, the name for the corresponding role can be
   fetched via fsl_db_role_name().

   This is the "easiest" way to figure out the DB name of the given
   role, independent of what order f's databases were opened
   (because the first-opened DB is always called "main").

   The Fossil-standard names of its primary databases are: "localdb"
   (checkout), "repository", and "configdb" (global config DB), but
   libfossil uses "ckout", "repo", and "cfg", respective. So long as
   queries use table names which unambiguously refer to a given
   database, the DB name is normally not needed. It is needed when
   creating new non-TEMP db tables and views. By default such
   tables/views would go into the "main" DB, and which one is the
   "main" db is dependent on the order the DBs are opened, so it's
   important to use the correct DB name when creating such constructs.

   Note that the role of FSL_DBROLE_TEMP is invalid here.
*/
char const * fsl_cx_db_name_for_role(fsl_cx const * const f,
                                     fsl_dbrole_e r,
                                     fsl_size_t * len);

/**
   Equivalent to `fcli_setup_v2(argc,argv,fcli.cliFlags,fcli.appHelp)`.

   @see fcli_pre_setup()
   @see fcli_setup_v2()
   @see fcli_end_of_main()
   @deprecated Its signature will change to fcli_setup_v2()'s at some point.
*/
int fcli_setup(int argc, char const * const * argv );

/** @deprecated fsl_close_scm_dbs()

   As of 2021-01-01, this functions identically to
   fsl_close_scm_dbs(). Prior to that...

   If fsl_repo_open_xxx() has been used to open a respository db,
   perhaps indirectly via opening of a checkout, this call closes that
   db and any corresponding checkout db.

   Returns 0 on success or if no repo/checkout db is opened. It may
   propagate an error from the db layer if closing/detaching the db
   fails.

   @see fsl_repo_open()
   @see fsl_repo_create()
*/
int fsl_repo_close( fsl_cx * const f );


/** @deprecated use fsl_close_scm_dbs() instead

   As of 2021-01-01, this functions identically to
   fsl_close_scm_dbs(). Prior to that...

   If fsl_ckout_open_dir() (or similar) has been used to open a
   checkout db, this call closes that db, as well as any
   corresponding repository db.

   Returns 0 on success or if no checkout db is opened. It may
   propagate an error from the db layer if closing/detaching the db
   fails. Returns FSL_RC_MISUSE if f has any transactions pending.

   This also closes the repository which was implicitly opened for the
   checkout.
*/
int fsl_ckout_close( fsl_cx * const f );

#endif /* ORG_FOSSIL_SCM_LIBFOSSIL_DEPRECATED_H_INCLUDED */
#endif /* FSL_OMIT_DEPRECATED */
/* end of file include/fossil-scm/deprecated.h */
#if defined(FSL_EXPOSE_INTERNAL_APIS)
/* FSL_EXPOSE_INTERNAL_APIS is a compatibility crutch for fnc! */
/* Do not use FSL_EXPOSE_INTERNAL_APIS unless you know you need it! */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#if !defined(ORG_FOSSIL_SCM_FSL_INTERNAL_H_INCLUDED)
#define ORG_FOSSIL_SCM_FSL_INTERNAL_H_INCLUDED
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).

  *****************************************************************************
  This file declares library-level internal APIs which are shared
  across the library.
*/


#if defined(_WIN32) && !defined(WIN32_LEAN_AND_MEAN)
/* Keep <windows.h> from including the old <winsock.h>, which
   conflicts with the <winsock2.h> the native sync channel uses. */
#  define WIN32_LEAN_AND_MEAN
#endif

/**
   Determine whether fsl__mutex_enter() and friends are no-ops.  If
   we'd require C11 then we could use C11's mutexes instead of
   sqlite3's, but we have those handy so we might as well use them.
*/
#if !defined(FSL_ENABLE_MUTEX)
#  if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
#    define FSL_ENABLE_MUTEX 1
#  else
#    define FSL_ENABLE_MUTEX 0
#  endif
#endif

/**
   A few places lock SQLite's own mutexes even when FSL_ENABLE_MUTEX
   is 0. A SQLite built with SQLITE_THREADSAFE=0 (e.g. its wasm
   builds) omits sqlite3_mutex_xxx() altogether, so in that build
   these are no-ops. fsl__sq3_mutex_alloc() then returns a non-NULL
   dummy because fsl__libinit() treats a NULL result as OOM.
*/
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
#  define fsl__sq3_mutex_alloc(ID) ((sqlite3_mutex*)8)
#  define fsl__sq3_mutex_enter(M) (void)(M)
#  define fsl__sq3_mutex_leave(M) (void)(M)
#else
#  define fsl__sq3_mutex_alloc(ID) sqlite3_mutex_alloc(ID)
#  define fsl__sq3_mutex_enter(M) sqlite3_mutex_enter(M)
#  define fsl__sq3_mutex_leave(M) sqlite3_mutex_leave(M)
#endif

#if defined(__cplusplus)
extern "C" {
#endif

typedef struct fsl__bccache fsl__bccache;
typedef struct fsl__bccache_line fsl__bccache_line;
typedef struct fsl__pq fsl__pq;
typedef struct fsl__pq_entry fsl__pq_entry;

/** @internal

    Queue entry type for the fsl__pq class.

    Potential TODO: we don't currently use the (data) member. We can
    probably remove it.
*/
struct fsl__pq_entry {
  /** RID of the entry. */
  fsl_id_t id;
  /** Raw data associated with this entry. */
  void * data;
  /** Priority of this element. */
  double priority;
};
/** @internal
    Empty-initialized fsl__pq_entry structure.
*/
#define fsl__pq_entry_empty_m {0,NULL,0.0}

/** @internal

    A simple priority queue class. Instances _must_ be initialized
    by copying fsl__pq_empty or fsl__pq_empty_m (depending on where
    the instance lives).
*/
struct fsl__pq {
  /** Number of items allocated in this->list. */
  fsl_size_t capacity;
  /** Number of items used in this->list. */
  fsl_size_t used;
  /** The queue. It is kept sorted by entry->priority. */
  fsl__pq_entry * list;
};

/** @internal
    Empty-initialized fsl__pq struct, intended for const-copy initialization.
*/
#define fsl__pq_empty_m {0,0,NULL}

/** @internal
    Empty-initialized fsl__pq struct, intended for copy initialization.
*/
extern  const fsl__pq fsl__pq_empty;

/** @internal

    Clears the contents of p, freeing any memory it owns, but not
    freeing p. Results are undefined if !p.
*/
void fsl__pq_clear(fsl__pq * p);

/** @internal

    Insert element e into the queue. Returns 0 on success, FSL_RC_OOM
    on error. Results are undefined if !p. pData may be NULL.
*/
int fsl__pq_insert(fsl__pq *p, fsl_id_t e,
                  double v, void *pData);

/** @internal

    Extracts (removes) the first element from the queue (the element
    with the smallest value) and return its ID.  Return 0 if the queue
    is empty. If pp is not NULL then *pp is (on success) assigned to
    opaquedata pointer mapped to the entry.
*/
fsl_id_t fsl__pq_extract(fsl__pq *p, void **pp);

/** @internal

    Holds one "line" of a fsl__bccache cache.
*/
struct fsl__bccache_line {
  /**
     RID of the cached record.
  */
  fsl_id_t rid;
  /**
     Age. Newer is larger.
  */
  fsl_uint_t age;
  /**
     Content of the artifact.
  */
  fsl_b content;
};
/** @internal

    Empty-initialized fsl__bccache_line structure.
*/
#define fsl__bccache_line_empty_m { 0,0,fsl_b_empty_m }


/** @internal

    A cache for tracking the existence of blobs while the internal
    goings-on of fsl_content_get() and friends are going on.

    "bc" ==> blob cache.

    Historically fossil caches artifacts as their blob content, but
    libfossil will likely (at some point) to instead cache fsl_deck
    instances, which contain all of the same data in pre-parsed form.
    It cost more memory, though. That approach also precludes caching
    non-structural artifacts (i.e. opaque client blobs).

    Potential TODO: the limits of the cache size are currently
    hard-coded and changing them "by hand" won't have much effect.
    We should possibly have an API to tweak these limits.
*/
struct fsl__bccache {
  /**
     Total amount of buffer memory (in bytes) used by cached content.
     This does not account for memory held by this->list.
  */
  unsigned szTotal;
  /**
     Limit on the (approx.) amount of memory (in bytes) which can be
     taken up by the cached buffers at one time. Fossil's historical
     value is 50M.
  */
  unsigned szLimit;
  /**
     Number of entries "used" in this->list.
  */
  uint16_t used;
  /**
     Approximate upper limit on the number of entries in this->list.
     This limit may be violated slightly.

     This list gets searched linearly so this number should ideally be
     relatively small: 3 digits or less. Fossil's historical value is
     500.
  */
  uint16_t usedLimit;
  /**
     Number of allocated slots in this->list.
  */
  uint16_t capacity;
  /**
     Next cache counter age. Higher is newer.
  */
  fsl_uint_t nextAge;

  /**
     Gets incremented on each insert for purposes of invalidating
     this cache. See the notes for fsl__ptl::changeMarker. It's okay
     if this overflows.
  */
  unsigned changeMarker;

  /**
     List of cached content, ordered by age.
  */
  fsl__bccache_line * list;
  /**
     RIDs of all artifacts currently in the this->list
     cache.
  */
  fsl_id_bag inCache;

  /**
     Metrics solely for internal use in looking for
     optimizations. These are only updated by fsl_content_get().
  */
  struct {
    unsigned hits;
    unsigned misses;
  } metrics;
};
/** @internal

    Empty-initialized fsl__bccache structure, intended
    for const-copy initialization.
*/
#define fsl__bccache_empty_m {     \
  .szTotal = 0U,                   \
  .szLimit = 100000000U/*was 20M; sync/dephantomize needs a deeper working set*/, \
  .used = 0U, .usedLimit = 5000U/*was 400; delta chains can be long*/,\
  .capacity = 0,                   \
  .nextAge = 0,                    \
  .changeMarker = 0,               \
  .list = NULL,                    \
  .inCache = fsl_id_bag_empty_m,   \
  .metrics = {.hits = 0U, .misses = 0U}  \
}

/** @internal

   The "PRAGMA cache_size" value which a fsl_cx applies to each
   database it opens or attaches. As for the pragma, a negative value
   is in KiB and a positive value is in pages.
*/
#ifndef FSL__DB_CACHE_SIZE
#  define FSL__DB_CACHE_SIZE -32000
#endif

/**
   Milliseconds a connection libfossil opens waits for another
   connection's write lock before reporting SQLITE_BUSY. fossil(1)
   uses the same value in its db_open().
*/
#ifndef FSL__DB_BUSY_TIMEOUT_MS
#  define FSL__DB_BUSY_TIMEOUT_MS 15000
#endif
#if FSL__DB_CACHE_SIZE < -2000000 || FSL__DB_CACHE_SIZE > 500000
#  error "FSL__DB_CACHE_SIZE is outside -2000000 (about 2 GB) to 500000 pages"
#endif

/** @internal

   Very internal.

   "Manifest cache" for fsl_deck entries encountered during
   crosslinking. This type is intended only to be embedded in fsl_cx.

   The routines for managing this cache are static in deck.c:
   fsl__cx_mcache_insert() and fsl__cx_mcache_search().

   The array members in this struct MUST have the same length
   or results are undefined.
*/
struct fsl__mcache {
  /** Next age value. No clue how the cache will react once this
      overflows. */
  fsl_uint_t nextAge;
  /** Counts the number of cache hits. */
  unsigned hits;
  /** Counts the number of cache misses. */
  unsigned misses;
  /** The virtual age of each deck in the cache. They get evicted
      oldest first. */
  fsl_uint_t aAge[4];
  /**
     Stores bitwise copies of decks. Storing a fsl_deck_malloc() deck
     into the cache requires bitwise-copying is contents, wiping out
     its contents via assignment from fsl_deck_empty, then
     fsl_free()'ing it (as opposed to fsl_deck_finalize(), which would
     attempt to clean up memory which now belongs to the cache's
     copy).

     Array sizes of 6 and 10 do not appreciably change the hit rate
     compared to 4, at least not for current (2021-11-18) uses.
  */
  fsl_deck decks[4];
};

/** @internal
  Convenience typedef. */
typedef struct fsl__mcache fsl__mcache;

/** @internal
    Initialized-with-defaults fsl__mcache structure, intended for
    const-copy initialization. */
#define fsl__mcache_empty_m {                    \
    .nextAge=0, .hits=0, .misses=0,              \
    .aAge = {0,0,0,0},                           \
    .decks = {fsl_deck_empty_m,fsl_deck_empty_m, \
              fsl_deck_empty_m, fsl_deck_empty_m}\
}

/**@internal
  Initialized-with-defaults fsl__mcache structure, intended for
  non-const copy initialization. */
extern const fsl__mcache fsl__mcache_empty;

/**
   This will fail to compile if the arrays fsl__mcache::aAge and
   fsl__mcache::decks have different sizes. They must have the same
   size.
*/
typedef int fsl__mcache_StaticAssertArraySizes[
 ((sizeof(fsl__mcache_empty.aAge)
  /sizeof(fsl__mcache_empty.aAge[0]))
 == (sizeof(fsl__mcache_empty.decks)
     /sizeof(fsl__mcache_empty.decks[0])))
 ? 1 : -1
];

/**
   Expands to a list of the names of all fsl_id_bag members of the
   fsl__ptl_line struct by invoking macro E(NAME) once for each name.
*/
#define fsl__ptl_line_map(E)                        \
  E(toVerify/*RIDs of blobs added at this level*/)  \
  E(leafCheck/*Used during the processing of manifests to keep track
               of "leaf checks" which need to be done downstream.*/) \
  E(available/*RIDs of known-available content*/)   \
  E(missing/*RIDs of known-missing content*/) \
  E(dephantomize/*An experiment in queueing up dephantomization work*/)

/**
   A cache of fsl_cx state which applies per transaction level.  We
   need one of these per level in the transaction stack.
*/
struct fsl__ptl_line {
#define E(X) fsl_id_bag X;
  fsl__ptl_line_map(E)
#undef E
  /**
     A poor-man's approach to recognizing when to clear
     fsl_cx::cache::blobContent when a fsl__ptl stack level is popped.
     The problem is that fsl__bccache is global to a given fsl_cx
     instance but may hold RIDs which are invalidated when a
     transaction level pops. fsl__bccache is not structured such that
     removing individual entries by RID is easy or cheap, so we
     invalidate the whole cache if a given transaction level added
     anything to fsl_cx::cache::blobContent. When pushing a PTL level,
     we record fsl__bccache::changeMarker here and compare it when the
     transaction pops. If they differ, the blob content cache is
     cleared. An improvement to this would be to extend fsl__bccache
     to be able to remove entries by RID, but that's not on today's
     proverbial menu.
  */
  unsigned changeMarker;
};

typedef struct fsl__ptl_line fsl__ptl_line;

/**
   Enum entries corresponding to fsl__ptl_line members.
*/
enum fsl__ptl_e {
  /** Sentinel value needed in slot 0. */
  fsl__ptl_e_dummy = 0,
#define E(X) fsl__ptl_e_ ## X,
  fsl__ptl_line_map(E)
#undef E
};
typedef enum fsl__ptl_e fsl__ptl_e;

/**
   This object manages a stack of fsl__ptl_line objects for a
   fsl_cx.

   ptl = per transaction level
*/
struct fsl__ptl {
  /** Persistent error code. */
  int rc;
  /** Number of levels currently allocated. */
  uint16_t allocated;
  /** 0-based level. 0 is for work done without an explicit
      transaction on the stack. */
  uint16_t level;
  /**
     The transaction level in which the first RIDs (in this
     transaction stack) were added. This is used for determining when
     to run certain checks. A negative value means no RIDs have been
     added.
   */
  int validateRidLevel;
  /** Memory living in this->mem. */
  fsl__ptl_line * stack;
  /** Current line in this->stack. */
  fsl__ptl_line * line;
  /** Memory for this->stack. */
  fsl_b mem;
};

typedef struct fsl__ptl fsl__ptl;

/** Empty-initialized fsl__ptl struct. */
#define fsl__ptl_empty_m {               \
    .rc = 0, .allocated = 0, .level = 0, \
    .validateRidLevel = -1,              \
    .stack = NULL, .line = NULL,         \
    .mem = fsl_b_empty_m            \
  }


/**
   Generic array-of-T list memory-reservation routine.

   *list is the input array-of-T. nDesired is the number of entries to
   reserve (list entry count, not byte length). *nAlloc is the number
   of entries allocated in the list. sizeOfEntry is the sizeof(T) for
   each entry in *list. T may be either a value type or a pointer
   type and sizeofEntry must match, i.e. it must be sizeof(T*) for a
   list-of-pointers and sizeof(T) for a list-of-objects.

   If e is not NULL then this function updates e's error state on
   error, else it simply returns FSL_RC_OOM on error. If e is not
   NULL then this function is a no-op if called when e's error state
   is set, returning that code without other side-effects.

   If nDesired > *nAlloc then *list is reallocated to contain at least
   nDesired entries, else this function returns without side effects.
   If it allocates, it is free to allocate for more than nDesired
   entries.

   On success *list is re-assigned to the reallocated list memory, all
   newly-(re)allocated memory is zeroed out, and *nAlloc is updated to
   the new allocation size of *list (the number of list entries, not
   the number of bytes).

   On failure neither *list nor *nAlloc are modified.

   Returns 0 on success or FSL_RC_OOM on error.  Errors generated by
   this routine are, at least in principle, recoverable, not that the
   app can necessarily otherwise recover from an OOM.

   License note: this code and the fsl__b_list pieces it was
   added for were ported into libfossil by the same person who wrote
   the original it was ported from.
*/
int fsl__array_reserve(fsl_error *e, void **list, fsl_size_t nDesired,
                       fsl_size_t * nAlloc, unsigned sizeOfEntry);

#define fsl__cx_array_reserve(CX,LI,MIN) fsl__array_reserve(&(CX)->error, (LI), (MIN))

/**
   fsl__b_list sorting policies. NULL entries must
   always sort last.
*/
enum fsl__b_list_e {
  fsl__b_list_e_UNSORTED,
  /* Smallest buffers first. */
  fsl__b_list_e_ASC,
  /* Largest buffers first. */
  fsl__b_list_e_DESC
};

/**
   Declares struct T as a container for a list-of-MT.  MT may be
   pointer-qualified. fsl__ListType_impl() with the same arguments
   implements T_reserve() for basic list allocation. Cleanup, alas, is
   MT-dependent.
*/
#define fsl__ListType_decl(T,MT) \
  struct T {                     \
    MT * list;                   \
    fsl_size_t used;             \
    fsl_size_t capacity;         \
  };                             \
  typedef struct T T;            \
  int T ## _reserve(fsl_error *e, T *li, fsl_size_t min)

#define fsl__ListType_impl(T,MT)                                 \
  int T ## _reserve(fsl_error *e,struct T *li, fsl_size_t min) { \
    void * p = li->list;                                         \
    int const rc = fsl__array_reserve(e, &p, min,                \
                                      &li->capacity, sizeof(MT));\
    li->list = p;                                                \
    return rc;                                                   \
  }

#define fsl__ListType__reserve1_size(li,nInitial) \
  (li->used ? (li->used==li->capacity ? li->capacity * 2 : li->used+1) : nInitial)

#define fsl__LIST_T_empty_m {.list=0,.used=0,.capacity=0}

fsl__ListType_decl(fsl__b_list,fsl_b*);
#define fsl__b_list_empty_m fsl__LIST_T_empty_m
extern const fsl__b_list fsl__b_list_empty;
void fsl__b_list_cleanup(fsl__b_list *li);
//void fsl__b_list_reuse(fsl__b_list *li);

/**
   A collection of buffers for use with fsl_cx_b_borrow().
*/
struct fsl__b_library {
  fsl__b_list list;
  /**
     How/whether this->list is sorted.  This is a bit of a historical
     hanger-on from a time in this code's history when it made sense
     to sort buffers. We currently dole out buffers in FIFO order so
     do not really need this but return it in case we want to extend
     borrowing to provide a hint as to whether the caller wants a
     "small" buffer or a "large" one, in which case we would sort by
     size pull from the start resp. end of the list.
  */
  enum fsl__b_list_e sort;
  /**
     Max number of buffers to cache. 0 disables borrowing, always
     allocating. When this limit is reached, fsl_cx_b_borrow()
     will still hand out buffers but fsl_cx_b_return() will
     start freeing them immediately so long as it's over the
     limit.
  */
  uint32_t limitCount;
  /**
     Largest capacity of single buffer to keep.  If exceeded, we keep
     the fsl_b instance but toss its buffered memory. A value of
     0 disables this limit.
  */
  uint32_t limitSingleCapacity;
  /**
     Max total of fsl_b::capacity in the buffers.  0 means no
     limit.  Limit enforcement is as per this->limitSingleCapacity.
  */
  uint64_t limitCapacity;
  /**
     Current fsl_b::capacity in the buffers.
  */
  uint64_t currentCapacity;
  /** Running total of buffers borrowed. Incremented on each borrow. */
  uint64_t nBorrowed;
  /** Running total of buffers returned. Incremented on each borrow. */
  uint64_t nReturned;
  /** Running total of bytes borrowed. Incremented by b->capacity on
      each borrow. */
  int64_t nBytesBorrowed;
  /** Running total of bytes returned. Incremented by b->capacity on
      each return. */
  uint64_t nBytesReturned;
  /** Max number of buffers concurrently borrowed.
      Incremented on each borrow. */
  uint64_t peakBorrowed;
  /** Max concurrent capacity. Incremented on each return. */
  uint64_t peakCapacity;
};
typedef struct fsl__b_library fsl__b_library;
#define fsl__b_library_empty_m {     \
    .list=fsl__b_list_empty_m,       \
    .sort=fsl__b_list_e_UNSORTED,    \
    .limitCount=30,                       \
    .limitSingleCapacity=1024 * 1024 * 12,\
    .limitCapacity=1024 * 1024 * 32,      \
    .currentCapacity=0,                   \
    .nBorrowed=0, .nReturned=0,           \
    .nBytesBorrowed=0, .nBytesReturned=0, \
    .peakBorrowed=0, .peakCapacity=0      \
}

//fsl_b * fsl__b_borrow(fsl__b_list *li);
//void fsl__b_return(fsl__b_list *li, fsl_b *b);

/*
  The fsl_cx class is documented in the main public header. ALL of its
  members are to be considered private/internal.

  Reminder to self:

  i'd like to rename this to fsl__cx and have a public (typedef struct
  fsl__cx fsl_cx) like we do for fsl_xfer, but doing so breaks fnc,
  which uses (struct fsl_cx) in a few places and triggers an "is not a
  struct" error.
*/
struct fsl_cx {
  /**
     A pointer to the "main" db handle. Exactly which db IS the main
     db is, because we have three DBs, not generally knowable.

     The internal management of fsl_cx's db handles has changed
     a couple of times. As of 2022-01-01 the following applies:

     dbMain starts out NULL. When a repo or checkout is opened, dbMain
     is pointed at the first of those which is opened.  When its
     partner is opened, it is ATTACHed to dbMain.  dbMain->role holds
     a bitmask of fsl_dbrole_e values reflecting which roles are
     opened/attached to it.

     The db-specific separate handles (this->{repo,ckout}.db) are used
     to store the name and file path to each db. ONE of those will
     have a db->dbh value of non-NULL, and that one is the instance
     which dbMain points to.

     Whichever db is opened first gets its "main" schema aliased to
     the corresponding fsl_db_role_name() for is role so that SQL code
     need not care which db is "main" and which is "repo" or
     "ckout". (Sidebar: when this library was started, the ability to
     alias a db with another name did not exist, and thus we required
     a middle-man "main" db to which we ATTACHed the repo and checkout
     dbs. That led to locking problems.)

     As of 20211230, f->config.db is its own handle, not ATTACHed with
     the others. Its db gets aliased to
     fsl_db_role_name(FSL_DBROLE_CONFIG).

     Internal code should rely as little as possible on the actual
     arrangement of internal DB handles, and should use
     fsl_cx_db_repo(), fsl_cx_db_ckout(), and fsl_cx_db_config() to
     get a handle to the specific db they want. Whether or not they
     return the same handle or 3 different ones may change at some
     point, so the public API treats them as separate entities. That
     is especially important for the global config db, as that one
     is (for locking reason) almost certain to remain in its own
     db handle, independent of the repo/checkout dbs.

     In any case, the internals very much rely on the repo and
     checkout dbs being accessible via a single db handle because the
     checkout-related SQL requires both dbs for most queries. The
     internals are less picky about the genuine layout of those
     handles (e.g. which one, if either, is the MAIN db).
  */
  fsl_db * dbMain;

  /**
     Marker which tells us whether fsl_cx_finalize() needs
     to fsl_free() this instance or not.
  */
  void const * allocStamp;

  /**
     A bitwise copy of the config object passed to fsl_cx_init() (or
     some default).
  */
  fsl_cx_config cxConfig;

  struct {
    /**
       Holds info directly related to a checkout database.
    */
    struct {
      /** The db. */
      fsl_db db;
      /**
         The directory part of an opened checkout db. This is currently
         only set by fsl_ckout_open_dir(). It contains a trailing slash,
         largely because that simplifies porting fossil(1) code and
         appending filenames to this directory name to create absolute
         paths (a frequently-needed option).

         Useful for doing absolute-to-relative path conversions for
         checking file lists.
      */
      char * dir;
      /**
         Optimization: fsl_strlen() of dir. Guaranteed to be set to
         dir's length if dir is not NULL, else it will be 0.
      */
      fsl_size_t dirLen;
      /**
         The rid of the current checkout. May be 0 for an empty
         repo/checkout. Must be negative if not yet known.
      */
      fsl_id_t rid;
      /**
         The UUID of the current checkout. Only set if this->rid is
         positive. Owned by the containing fsl_cx object.
      */
      fsl_uuid_str uuid;
      /**
         Julian mtime of the checkout version, as reported by the
         [event] table.
      */
      double mtime;
    } ckout;

    /**
       Holds info directly related to a repo database.
    */
    struct {
      /** The db. */
      fsl_db db;
      /**
         The default user name, for operations which need one.
         See fsl_cx_user_set().
      */
      char * user;

      /** The 'main-branch' repo config setting, defaulting to trunk. */
      char * mainBranch;
    } repo;

    /**
       Holds info directly related to a global config database.
    */
    struct {
      /**
         The global config db. This handle is managed separately from
         the repo/ckout handles because this db is shared by all
         fossil instances are we have to ensure that we don't lock it
         for longer than necessary, thus this db may get opened and
         closed multiple times within even within a short-lived
         application.
      */
      fsl_db db;
    } gconfig;

    /**
       State for a context bound to a host's db handle with
       fsl_cx_host_db().
    */
    struct {
      /** The host's handle, or NULL. Owned by the host. */
      fsl_db_t * dbh;
      /**
         True once fsl_cx_host_db_closing() has been called. The handle
         may then no longer run SQL.
      */
      bool closing;
      /**
         If true, attaching skips fsl__cx_host_shadow_check(). For
         f-sanity's decoy tests only, which attach a repository ahead
         of the context's on purpose, to show that libfossil's SQL
         never reaches it.
      */
      bool noShadowCheck;
      /**
         The value libfossil last wrote to f's row of TEMP.fsl_host_gen
         (one row per context on the connection, keyed by its id). If
         the row holds anything else, the host rolled back work that
         f's caches remember. See fsl__cx_host_rollback_check().
      */
      int64_t gen;
    } host;

    int peakTxnLevel;
    fsl_size_t nBegin;
    fsl_size_t nCommit;
    fsl_size_t nRollback;
  } db;

  /**
     State for incrementally preparing a checkin operation.
  */
  struct {
    /**
       Holds a list of "selected files" in the form
       of vfile.id values.
    */
    fsl_id_bag selectedIds;

    /**
       The deck used for incrementally building certain parts of a
       checkin.
    */
    fsl_deck mf;
  } ckin;

  /**
     Confirmation callback. Used by routines which may have to
     interactively ask a user to confirm things.
  */
  fsl_confirmer confirmer;

  /**
     Artifact signing callback. See fsl_cx_signer() and
     fsl_deck_save().
  */
  fsl_signer signer;

  /**
     Storage for the checkout's files. iVersion==0 means
     fsl_ckout_fs_os, the filesystem. See fsl_cx_ckout_fs() and the
     fsl__cfs_xxx() functions, through which the checkout code reaches
     it.
  */
  fsl_ckout_fs ckoutFs;

  /**
     Output channel used by fsl_output() and friends.

     This was added primarily so that fossil client apps can share a
     single output channel which the user can swap out, e.g. to direct
     all output to a UI widget or a file.

     Though the library has adamantly avoided adding a "warning"
     output channel, features like:

     https://fossil-scm.org/home/info/52a389d3dbd4b6cc

     arguably call for one.
  */
  fsl_outputer output;

  /**
     Can be used to tie client-specific data to the context. Its
     finalizer is called when fsl_cx_finalize() cleans up. The library
     does not use this state. It is intended primarily for tying,
     e.g., scripting-engine information to the context, e.g. mapping a
     scripting engine context to this one for later use in fossil-side
     callbacks.
  */
  fsl_state clientState;

  /**
     Holds error state. As a general rule, this information is updated
     only by routines which need to return more info than a simple
     integer error code. e.g. this is often used to hold
     db-driver-provided error state. It is not used by "simple"
     routines for which an integer code always suffices. APIs which
     set this should denote it with a comment like "updates the
     context's error state on error."
  */
  fsl_error error;

  /**
     Reuseable scratchpads for low-level file canonicalization
     buffering and whatnot. Not intended for huge content: use
     this->cache.fileContent and friends for that. This list should
     stay relatively short, as should the buffers (a few kb each, at
     most).

     This struct predates fsl_cx_b_borrow(), and that API
     should generally be preferred for this purpose.

     @see fsl__cx_scratchpad()
     @see fsl__cx_scratchpad_yield()
  */
  struct {
    /**
       Strictly-internal temporary buffers we intend to reuse many
       times, mostly for filename canonicalization, holding hash
       values, and small encoding/decoding tasks. These must never be
       used for values which will be long-lived, nor are they intended
       to be used for large content, e.g. reading files, with the
       possible exception of holding versioned config settings, as
       those are typically rather small. They must also not be held
       while recursion back into a function holding one of these is
       possible.

       If needed, the lengths of this->buf[] and this->used[] may be
       extended, but anything beyond 8, maybe 10, seems a bit extreme.
       They should only be increased if we find code paths which
       require it. As of this writing (2021-03-17), the peak
       concurrently used was 5. In any case fsl__cx_scratchpad() fails
       fatally if it needs more than it has, so we won't/can't fail to
       overlook such a case.
    */
    fsl_b buf[8];
    /**
       Flags telling us which of this->buf is currenly in use.
    */
    bool used[8];
    /**
       A cursor _hint_ to try to speed up fsl__cx_scratchpad() by about
       half a nanosecond, making it O(1) instead of O(small N) for the
       common case.
    */
    short next;
    /**
       A scratchpad specific to fsl__cx_emit() and friends.
    */
    fsl_b emit;
    /**
       A scratchpad specific to fsl_cx_format() and friends. This one
       has to account for potential recursion.
    */
    fsl_b format;
  } scratchpads;

  /**
     Flags, some (or one) of which is runtime-configurable by the
     client (see fsl_cx_flags_e). We can get rid of this and add the
     flags to the cache member along with the rest of them.
  */
  fsl_flag32_t flags;

  /**
     Error flag which is intended to be set via signal handlers or a
     UI thread to tell this context to cancel any currently
     long-running operation. Not all operations honor this check, but
     the ones which are prone to "exceedingly long" operation (at
     least a few seconds) do.
  */
  volatile int interrupted;

  /**
     List of callbacks for deck crosslinking purposes.
  */
  fsl_xlinker_list xlinkers;

  /**
     A place for caching generic things.
  */
  struct {
    /**
       If true, skip "dephantomization" of phantom blobs.  This is a
       detail from fossil(1) with as-yet-undetermined utility. It's
       apparently only used during the remote-sync process, which this
       API does not (as of 2021-10) yet have.
    */
    bool ignoreDephantomizations;

    /**
       Whether or not a running commit process should be marked as
       private. This member is used for communicating this flag
       through multiple levels of API.
    */
    bool markPrivate;

    /**
       True if fsl__crosslink_begin() has been called but
       fsl__crosslink_end() is still pending.
    */
    bool isCrosslinking;

    /**
       Flag indicating that only cluster control artifacts should be
       processed by manifest crosslinking. This will only be relevant
       if/when the sync protocol is implemented.
    */
    bool xlinkClustersOnly;

    /**
       Is used to tell the content-save internals that a "final
       verification" (a.k.a. verify-before-commit) is underway.
    */
    bool inFinalVerify;

    /**
       True when a sync is active, to prevent recursive attempts to
       sync.
    */
    bool isSyncing;

    /**
       Specifies whether SOME repository-level file-name
       comparisons/searches will work case-insensitively. <0 means
       not-yet-determined, 0 = no, >0 = yes.
    */
    short caseInsensitive;

    /**
       Cached copy of the allow-symlinks config option, because it is
       (hypothetically) needed on many stat() call. Negative
       value=="not yet determined", 0==no, positive==yes. The negative
       value means we need to check the repo config resp. the global
       config to see if this is on.

       As of late 2020, fossil(1) is much more restrictive with
       symlinks due to vulnerabilities which were discovered by a
       security researcher, and we definitely must not default any
       symlink-related features to enabled/on. As of Feb. 2021, my
       personal preference, and very likely plan of attack, is to only
       treat SCM'd symlinks as if symlinks support is disabled. It's
       very unlikely that i will implement "real" symlink support but
       would, *solely* for compatibility with fossil(1), be convinced
       to permit such changes if someone else wants to implement them.
       Patches are joyfully considered!
    */
    short allowSymlinks;

    /**
       Indicates whether or not this repo has ever seen a delta
       manifest. If none has ever been seen then the repository will
       prefer to use baseline (non-delta) manifests. Once a delta is
       seen in the repository, the checkin algorithm is free to choose
       deltas later on unless it's otherwise prohibited, e.g. by the
       `forbid-delta-manifests` config db setting.

       This article provides an overview to the topic delta manifests
       and essentially debunks their ostensible benefits:

       https://fossil-scm.org/home/doc/tip/www/delta-manifests.md

       Values: negative==undetermined, 0==no, positive==yes. This is
       updated when a repository is first opened and when new content
       is written to it.
    */
    short seenDeltaManifest;

    /**
       Records whether this repository has an FTS search
       index. <0=undetermined, 0=no, >0=yes.
    */
    short searchIndexExists;

    /**
       Cache for the `manifest` config setting, as used by
       fsl_ckout_manifest_setting(), with the caveat that
       if the setting changes after it is cached, we won't necessarily
       see that here!
    */
    short manifestSetting;

    /**
       Record ID of rcvfrom entry during commits. This is likely to
       remain unused in libf until/unless the sync protocol is
       implemented.

       2025-07-21: this will probably need to be manipulated by
       fsl_xfer. rcvId is used in fsl__content_put_ex() but it's
       historically (in this library, not fossil(1)) always been 0.
       Setting the rcvId requires high-level info that fossil(1) uses,
       and it's only really relevant for the sync layer.
    */
    fsl_id_t rcvId;

    /**
       A place for temporarily holding file content. We use this in
       places where we have to loop over files and read their entire
       contents, so that we can reuse this buffer's memory if
       possible.  The loop and the reading might be happening in
       different functions, though, and some care must be taken to
       avoid use in two functions concurrently.

       All access to this must be acquired by fsl__cx_content_buffer()
       and released by fsl__cx_content_buffer_yield().
    */
    fsl_b fileContent;

    /**
       Reusable buffer for creating and fetching deltas via
       fsl_content_get() and fsl__content_deltify(). The number of
       allocations this actually saves is pretty small.
    */
    fsl_b deltaContent;

    /**
       fsl_content_get() cache.
    */
    fsl__bccache blobContent;

    /**
       Per-transaction-level cache.
    */
    fsl__ptl ptl;

    /**
       An internal cache for fsl__content_mark_availble().  This is
       only used in that routine but it's called frequently during
       checkins and sync.
    */
    fsl_id_bag markAvailableCache;

    /**
       Infrastructure for fsl_mtime_of_manifest_file(). It
       remembers the previous RID so that it knows when it has to
       invalidate/rebuild its ancestry cache.
    */
    fsl_id_t mtimeManifest;
    /**
       The "project-code" config option. This is primarily for use
       with the sync protocol. It is managed by
       fsl_repo_project_code().
    */
    char * projectCode;

    /**
       Internal optimization to avoid duplicate fsl_stat() calls
       across two functions in some cases.
    */
    fsl_fstat fstat;

    /**
       Parsed-deck cache.
    */
    fsl__mcache mcache;

    /**
       Holds various glob lists. That said... these features are
       actually app-level stuff which the library itself does not
       resp. should not enforce. We can keep track of these for users
       but the library internals _generally_ have no business using
       them.

       _THAT_ said... these have enough generic utility that we can
       justify storing them and _optionally_ applying them. See
       fsl_checkin_opt for an example of where we do this.
    */
    struct {
      /**
         Holds the "ignore-glob" globs.
      */
      fsl_list ignore;
      /**
         Holds the "binary-glob" globs.
      */
      fsl_list binary;
      /**
         Holds the "crnl-glob" globs.
      */
      fsl_list crnl;
    } globs;

    /**
       Very-frequently-used SQL statements.
    */
    struct {
/**
  This macro greatly simplifies maintenance of the caches fsl_stmt
  objects elsewhere, believe it or not. The 1st argument to E is the
  name of the fsl_cx::cache::stmt member. The 2nd argument is the SQL
  of that statement.

  Potential TODO: add a fsl_dbrole_e value to each so that we
  centrally know which db to check for (for error-reporting purposes)
  before preparation.
*/
#define fsl__cx_cache_stmt_map(E)                 \
      E(afterDephantomizeOrphans, \
        "SELECT rid FROM {{dbname.repo}}.orphan WHERE baseline=?1") \
      E(afterDephantomizeDeltas, \
        "SELECT rid FROM {{dbname.repo}}.delta AS delta WHERE srcid=?1 " \
        "AND NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.mlink WHERE mid=delta.rid)") \
      E(deltaR2S,"SELECT srcid FROM {{dbname.repo}}.delta WHERE rid=?1")  \
      E(deltaS2R,"SELECT rid FROM {{dbname.repo}}.delta WHERE srcid=?1")  \
      E(uuidToRid,\
        "SELECT rid FROM {{dbname.repo}}.blob WHERE uuid=?1")     \
      E(ridToUuid,\
        "SELECT uuid FROM {{dbname.repo}}.blob WHERE rid=?1") \
      E(ridIsLeaf,\
        "SELECT 1 FROM {{dbname.repo}}.plink AS plink "                             \
        "WHERE pid=?1 "                                    \
        "AND coalesce("                                    \
        "(SELECT value FROM {{dbname.repo}}.tagxref "                      \
        "WHERE tagid=8/*FSL_TAGID_BRANCH*/ AND rid=?1"     \
        " AND tagtype>0), "                                \
        "?2 /*main branch name*/)"                         \
        "=coalesce((SELECT value FROM {{dbname.repo}}.tagxref "            \
        "WHERE tagid=8/*FSL_TAGID_BRANCH*/ "               \
        "AND rid=plink.cid AND tagtype>0), "               \
        "?2 /*main branch name*/)")                        \
      E(ridIsPrivate,"SELECT 1 FROM {{dbname.repo}}.private WHERE rid=?1") \
      E(contentSize,"SELECT size FROM {{dbname.repo}}.blob WHERE rid=?1")  \
      E(contentBlob,"SELECT content, size FROM {{dbname.repo}}.blob WHERE rid=?1") \
      E(uuidIsShunned,"SELECT 1 FROM {{dbname.repo}}.shun WHERE uuid=?1")  \
      E(contentNew,\
        "INSERT INTO {{dbname.repo}}.blob(rcvid,size,uuid,content) " \
        "VALUES(0,-1,?1,NULL) "                      \
        "RETURNING rid")                             \
      E(insertPhantomRid,"INSERT OR IGNORE INTO {{dbname.repo}}.phantom VALUES(?1)") \
      E(insertPrivateRid,"INSERT OR IGNORE INTO {{dbname.repo}}.private VALUES(?1)") \
      E(insertUnclusteredRid,"INSERT OR IGNORE INTO {{dbname.repo}}.unclustered VALUES(?1)") \
      E(insertUnsentRid,"INSERT OR IGNORE INTO {{dbname.repo}}.unsent VALUES(?1)") \
      E(ridDelDelta,"DELETE FROM {{dbname.repo}}.delta WHERE rid=?1")              \
      E(ridDelPrivate,"DELETE FROM {{dbname.repo}}.private WHERE rid=?1")       \
      E(ridDelPhantom,"DELETE FROM {{dbname.repo}}.phantom WHERE rid=?1")       \
      E(replaceDelta,                                           \
        "REPLACE INTO {{dbname.repo}}.delta(rid,srcid) VALUES(?1,?2)")          \
      E(contentUndeltify,                                       \
        "UPDATE {{dbname.repo}}.blob SET content=?1, size=?2 WHERE rid=?3")     \
      E(blobRidSize,"SELECT rid, size FROM {{dbname.repo}}.blob WHERE uuid=?1") \
      E(blobUpdateContent,                                      \
        "UPDATE {{dbname.repo}}.blob SET content=?1 WHERE rid=?2")      \
      E(phantomPopulate,                                \
        "UPDATE {{dbname.repo}}.blob SET rcvid=?1, size=?2, "           \
        "content=?3 WHERE rid=?4")                      \
      E(blobInsertFull,                                 \
        "INSERT INTO {{dbname.repo}}.blob (rcvid,size,uuid,content) "   \
        "VALUES(?1,?2,?3,?4) RETURNING rid")            \
      E(leafInsert,                                     \
        "INSERT OR IGNORE INTO {{dbname.repo}}.leaf VALUES (?1)")       \
      E(leafDelete,                                     \
        "DELETE FROM {{dbname.repo}}.leaf WHERE rid=?1")                \
      E(leavesInsert,                                   \
        "INSERT OR IGNORE INTO {{temp.leaves}} VALUES (?1)")     \
      E(parentsOf,                                      \
        "SELECT pid FROM {{dbname.repo}}.plink WHERE cid=?1 AND pid>0") \
      E(branchOfRid,                                    \
        "SELECT value FROM {{dbname.repo}}.tagxref WHERE rid=?1 "       \
        "AND tagid=8/*==FSL_TAGID_BRANCH*/ "            \
        "AND tagtype>0")                                \
      E(ridIsCheckin,                                   \
        "SELECT 1 FROM {{dbname.repo}}.event WHERE objid=?1 "           \
        "AND type='ci'"                                 \
      )                                                 \
      E(ridHasTagId,                                    \
        "SELECT tag.tagid FROM {{dbname.repo}}.tagxref AS tagxref, {{dbname.repo}}.tag AS tag"            \
        " WHERE tagxref.rid=?1 AND tagtype>0 "          \
        " AND tag.tagid=?2"                             \
        " AND tagxref.tagid=tag.tagid")                 \
      /*
         TODO. Something akin to:

         WITH RECURSIVE
         dchain(rid,srcid,level) AS (
           SELECT ?1 rid, NULL srcid, 0 level
           UNION ALL
           SELECT delta.rid, delta.srcid, dchain.level+1
           FROM delta JOIN dchain ON delta.srcid=dchain.rid
           ORDER BY 2
         )
         SELECT rid, srcid FROM dchain WHERE level>0

       i.e.: for RID ?1, get a list of all deltas which
       depend on this. (Is it really all?).

       Remember that we can have multiple paths to a parent,
       as in this simulated delta table:

       drop table if exists dmap;
       create temp table dmap(rid INTEGER NOT NULL, srcid INTEGER NOT NULL);
       insert into dmap values(2,4),(4,6),(6,8),(8,10);
       insert into dmap values(1,11),(11,10);
       insert into dmap values(20,30),(30,0);

       For a ?1 of 10 that will emit:

       rid|srcid
       8|10
       6|8
       4|6
       2|4
       11|10 -- note that we re-visit the root here
       1|11
      */ \
      E(deltaChainForRid,"")

#define STMT(MEMBER,IGNORED) fsl_stmt MEMBER;
      fsl__cx_cache_stmt_map(STMT)
#undef STMT

    } stmt;

    /**
       Holds a list of temp-dir names. Must be allocated using
       fsl_temp_dirs_get() and freed using fsl_temp_dirs_free().
    */
    char **tempDirs;

    /**
       Buffers managed by fsl_cx_b_borrow() and
       fsl_cx_b_return(). This fundamentally does the same thing
       as the fsl__cx_scratchpad family but this list is dynamic and
       has no hard upper limit like those do.
    */
    fsl__b_library buf;
  } cache;

  /**
     Ticket-related information.
  */
  struct {
    /**
       Holds a list of (fsl_card_J*) records representing custom
       ticket table fields available in the db.

       Each entry's flags member denotes (using fsl_card_J_flags)
       whether that field is used by the ticket or ticketchng
       tables.

       TODO, eventually: add a separate type for these entries.  We
       use fsl_card_J because the infrastructure is there and they
       provide what we need, but fsl_card_J::flags only exists for
       this list. A custom type would be smaller than fsl_card_J
       (only two members) but adding it requires adding some
       infrastructure which isn't worth the effort at the moment.
    */
    fsl_list customFields;

    /**
       Gets set to true (at some point) if the client has the
       ticket db table.
    */
    bool hasTicket;

    /**
       Gets set to true (at some point) if the client has the
       ticket.tkt_ctime db field.
    */
    bool hasCTime;

    /**
       Gets set to true (at some point) if the client has the
       ticketchng db table.
    */
    bool hasChng;

    /**
       Gets set to true (at some point) if the client has the
       ticketchng.rid db field.
    */
    bool hasChngRid;

    /**
       The name of the ticket-table field which refers to a ticket's
       title. Default = "title". The bytes are owned by this object.
    */
    char * titleColumn;

    /**
       The name of the ticket-table field which refers to a ticket's
       status. Default = "status". The bytes are owned by this object.
    */
    char * statusColumn;
  } ticket;

  /**
     Various metrics.
  */
  struct {
    /** Content-specific metrics. */
    struct {
      /**
         Number of times the internal content cache was used.
      */
      fsl_size_t nCached;
      /**
         Total of the number of "used" bytes of the content cache
         each time it was relinquished.
      */
      fsl_size_t nTotalUsed;

      /**
         The maximum buffer capacity the content buffer had at
         relenquish-time.
      */
      fsl_size_t nPeakBufSize;

      /**
         The number of times the content cache buffer was trimmed
         below the built-in maximum size.
      */
      fsl_size_t nCappedMaxSize;
    } content;
  } metrics;
};

/** @internal
    Initialized-with-defaults fsl_cx instance.
*/
extern const fsl_cx fsl__cx_empty;

#if !defined(NDEBUG)
/**
   Ensure that fsl_cx::scratchpads::buf/used have the same array size.
*/
typedef int fsl__cx_StaticAssertScratchpadSizes[
 ((sizeof(fsl__cx_empty.scratchpads.buf)
  /sizeof(fsl__cx_empty.scratchpads.buf[0]))
 == (sizeof(fsl__cx_empty.scratchpads.used)
     /sizeof(fsl__cx_empty.scratchpads.used[0])))
 ? 1 : -1
];
#endif

/*
  TODO:

  int fsl_b_append_getenv( fsl_b * b, char const * env )

  Fetches the given env var and appends it to b. Returns FSL_RC_NOT_FOUND
  if the env var is not set. The primary use for this would be to simplify
  the Windows implementation of fsl_find_home_dir().
*/


/** @internal

    Expires the single oldest entry in c. Returns true if it removes
    an item, else false.
*/
bool fsl__bccache_expire_oldest(fsl__bccache * c);

/** @internal

    Removes the cache entry for the given rid, if any, freeing its
    content and updating the cache's size accounting. Returns true if
    an entry was removed, else false.
*/
bool fsl__bccache_remove(fsl__bccache * c, fsl_id_t rid);

/** @internal

    Add an entry to the content cache.

    This routines transfers the contents of pBlob over to c,
    regardless of success or failure.  The cache will deallocate the
    memory when it has finished with it.

    If the cache cannot add the entry due to cache-internal
    constraints, as opposed to allocation errors, it clears the buffer
    (for consistency's sake) and returns 0.

    Returns 0 on success, FSL_RC_OOM on allocation error. Has undefined
    behaviour if !c, rid is not semantically valid, !pBlob. An empty
    blob is normally semantically illegal but is not strictly illegal
    for this cache's purposes.
*/
int fsl__bccache_insert(fsl__bccache * c, fsl_id_t rid,
                       fsl_b * pBlob);

/** @internal

    Frees all memory held by c, and clears out c's state, but does
    not free c. Results are undefined if !c.
*/
void fsl__bccache_clear(fsl__bccache * c);

/** @internal

    Resets all bags associated with the given cache and frees all
    cached buffer memory, but keeps any fsl_id_bag memory intact for
    re-use. This does not reset the hit/miss metrics.
*/
void fsl__bccache_reuse(fsl__bccache * c);


/** @internal

    Checks f->cache.blobContent to see if rid is available in the
    repository opened by f.

    Returns 0 if the content for the given rid is available in the
    repo or the cache. Returns FSL_RC_NOT_FOUND if it is not in the
    repo nor the cache. Returns some other non-0 code for "real
    errors," e.g. FSL_RC_OOM if a cache allocation fails. This
    operation may update the cache's contents.

    If this function detects a loop in artifact lineage, it fails an
    assert() in debug builds and returns FSL_RC_CONSISTENCY in
    non-debug builds. That doesn't happen in real life, though.

    Reminder to self: it should arguably return FSL_RC_PHANTOM if it's
    a phantom but the next call for that same rid would pull from
    f->cache.blobContent.missing and lose the distinction between
    "wasn't found" and "is a phantom", so would have to return
    FSL_RC_NOT_FOUND. If we ever need another fsl_id_bag for tracking
    phantoms, we can adjust this to return FSL_RC_PHANTOM by checking
    that bag for the RID.
*/
int fsl__bccache_check_available(fsl_cx * f, fsl_id_t rid);

/** @internal

    This is THE ONLY ROUTINE IN THE LIBRARY which is permitted to add
    content to the blob table.  Only one other routine
    (fsl__phantom_new()) adds new blob entries, but that one does not
    add blobs with content.

    This writes the given buffer content into the repository
    database's blob tabe. It Returns the record ID via outRid (if it
    is not NULL).  If the content is already in the database (as
    determined by a lookup of its hash against blob.uuid), this
    routine fetches the RID (via *outRid) but has no side effects in
    the repo.

    If srcId is >0 then pBlob must contain delta content from
    the srcId record. srcId might be a phantom.

    pBlob is normally uncompressed text, but if uncompSize>0 then the
    pBlob value is assumed to be compressed (via fsl_b_compress()
    or equivalent) and uncompSize is its uncompressed size. If
    uncompSize>0 then zUuid must be valid and refer to the hash of the
    _uncompressed_ data (which is why this routine does not calculate
    it for the client).

    Sidebar 2025-08-04: it is legal for the uncompressed size to be 0
    when the content is compressed (and larger). That case can't be
    represented with the above semantics. Do we actually handle the
    empty-file case properly? 2026-09-29: the 0-size case was added
    recently to handle synced-in files.

    Sidebar: we "could" use fsl_b_is_compressed() and friends to
    determine if pBlob is compressed and get its decompressed size,
    then remove the uncompSize parameter, but that would require that
    this function decompress the content to calculate the hash. Since
    the caller likely just compressed it, that seems like a huge
    waste. Sniffing the bytes is also unreliable: ordinary content
    can look compressed, so this function never does that. A cfile
    for the empty artifact (usize 0) is passed in as empty raw
    content instead.

    zUuid is the UUID of the artifact, if it is not NULL.  When
    srcId is specified then zUuid must always be specified.  If
    srcId is zero, and zUuid is zero then the correct zUuid is
    computed from pBlob.  If zUuid is not NULL then this function
    asserts (in debug builds) that fsl_is_uuid() returns true for
    zUuid.

    If isPrivate is true or if f->cache.markPrivate is true, the blob
    is created as a private record.

    If the record already exists but is a phantom, the pBlob content
    is inserted and the phatom becomes a real record.

    The original content of pBlob is not disturbed.  The caller continues
    to be responsible for pBlob.  This routine does *not* take over
    responsibility for freeing pBlob.

    If outRid is not NULL then on success *outRid is assigned to the
    RID of the underlying blob record.

    Returns 0 on success and there are too many potential error cases
    to name - this function is a massive beast.

    On success, the new blob's RID is queued up for pre-commit content
    validation. If this is the first call to this function in the
    current transaction stack, the RID is queued in the COMMIT handler
    for the _parent_ transaction. Subsequent calls will cause the RID
    to be queued in that same transaction level. We cannot validate in
    _this_ function because the validation would trigger at the end of
    the transaction level which _this_ function installs. Content
    validation has to be delayed until we believe we have all content
    which will be injected in the current transaction stack.

    @see fsl__content_put()
*/
int fsl__content_put_ex( fsl_cx * f,
                        fsl_b const * pBlob,
                        fsl_uuid_cstr zUuid, fsl_id_t srcId,
                        fsl_size_t uncompSize, bool isPrivate,
                        fsl_id_t * outRid);
/** @internal

    Equivalent to fsl__content_put_ex(f,pBlob,NULL,0,0,false,newRid).

    This must only be used for saving raw (non-delta) content.

    @see fsl__content_put_ex()
*/
int fsl__content_put( fsl_cx * f,
                     fsl_b const * pBlob,
                     fsl_id_t * newRid);


/** @internal

    If the given blob ID refers to deltified repo content, this routine
    undeltifies it and replaces its content with its expanded
    form.

    Returns 0 on success, FSL_RC_NOT_A_REPO if f has no opened
    repository, FSL_RC_RANGE if rid is not positive, and any number of
    other potential errors during the db and content operations. This
    function treats already unexpanded content as success.

    @see fsl__content_deltify()
*/
int fsl__content_undeltify(fsl_cx * f, fsl_id_t rid);


/** @internal

    The converse of fsl__content_undeltify(), this replaces the storage
    of the given blob record so that it is a delta of srcid.

    If rid is already a delta from some other place then no conversion
    occurs and this is a no-op unless force is true, which case the
    content is undeltified and re-delta'd against srcid.

    If rid's contents are not available because the the rid is a
    phantom or depends to one, no delta is generated and 0 is
    returned.

    It never generates a delta that carries a private artifact into
    a public artifact. Otherwise, when we go to send the public
    artifact on a sync operation, the other end of the sync will
    never be able to receive the source of the delta.  It is OK to
    delta private->private, public->private, and public->public.
    Just no private->public delta. For such cases this function
    returns 0, as opposed to FSL_RC_ACCESS or some similar code, and
    leaves the content untouched.

    If srcid is a delta that depends on rid, then srcid is
    converted to undelta'd text.

    If either rid or srcid contain less than some "small,
    unspecified number" of bytes (currently 50), or if the resulting
    delta does not achieve a compression of at least 25%, the rid is
    left untouched.

    Returns 0 if a delta is successfully made or none needs to be
    made, non-0 on error.

    Requires that fsl_cx_txn_level() be greater than 0.

    @see fsl__content_undeltify()
*/
int fsl__content_deltify(fsl_cx * f, fsl_id_t rid,
                        fsl_id_t srcid, bool force);


/** @internal

    Creates a new phantom blob with the given UUID and return its
    artifact ID via *newId. Returns 0 on success, any of many codes on
    error.  If isPrivate is true _or_ f has been flagged as being in
    "private mode" then the new content is flagged as private. newId
    may be NULL, but if it is then the caller will have to find the
    record id himself by using the UUID (see fsl_uuid_to_rid()).
*/
int fsl__phantom_new( fsl_cx * f, fsl_uuid_cstr uuid,
                      bool isPrivate, fsl_id_t * newId );

/** @internal

    Schedules a leaf check for "rid" and its parents. Returns 0 on
    success.
*/
int fsl__leaf_eventually_check( fsl_cx * f, fsl_id_t rid);

/** @internal

    Perform all pending leaf checks. Returns 0 on success or if it
    has nothing to do.
*/
int fsl__leaf_do_pending_checks(fsl_cx * f);

/** @internal

    Inserts a tag into f's repo db. It does not create the related
    control artifact - use fsl_tag_an_rid() for that.

    rid is the artifact to which the tag is being applied.

    srcId is the artifact that contains the tag. It is often, but
    not always, the same as rid. This is often the RID of the
    manifest containing tags added as part of the commit, in which
    case rid==srcId. A Control Artifact which tags a different
    artifact will have rid!=srcId.

    mtime is the Julian timestamp for the tag. Defaults to the
    current time if mtime <= 0.0.

    If outRid is not NULL then on success *outRid is assigned the
    record ID of the generated tag (the tag.tagid db field).

    If a more recent (compared to mtime) entry already exists for
    this tag/rid combination then its tag.tagid is returned via
    *outRid (if outRid is not NULL) and no new entry is created.

    Returns 0 on success, and has a huge number of potential error
    codes.
*/
int fsl__tag_insert( fsl_cx * f,
                     fsl_tagtype_e tagtype,
                     char const * zTag,
                     char const * zValue,
                     fsl_id_t srcId,
                     double mtime,
                     fsl_id_t rid,
                     fsl_id_t *outRid );
/** @internal

    Propagate all propagatable tags in artifact pid to the children of
    pid. Returns 0 on... non-error. Returns FSL_RC_RANGE if pid<=0.
*/
int fsl__tag_propagate_all(fsl_cx * f, fsl_id_t pid);

/** @internal

    Propagates a tag through the various internal pipelines.

    pid is the artifact id to whose children the tag should be
    propagated.

    tagid is the id of the tag to propagate (the tag.tagid db value).

    tagType is the type of tag to propagate. Must be either
    FSL_TAGTYPE_CANCEL or FSL_TAGTYPE_PROPAGATING. Note that
    FSL_TAGTYPE_ADD is not permitted.  The tag-handling internals
    (other than this function) translate ADD to CANCEL for propagation
    purposes. A CANCEL tag is used to stop propagation. (That's a
    historical behaviour inherited from fossil(1).) A potential TODO
    is for this function to simply treat ADD as CANCEL, without
    requiring that the caller be sure to never pass an ADD tag.

    origId is the artifact id of the origin tag if tagType ==
    FSL_TAGTYPE_PROPAGATING, otherwise it is ignored.

    zValue is the optional value for the tag. May be NULL.

    mtime is the Julian timestamp for the tag. Must be a valid time
    (no defaults here).

    This function is unforgiving of invalid values/ranges, and may assert
    in debug mode if passed invalid ids (values<=0), a NULL f, or if f has
    no opened repo.
*/
int fsl__tag_propagate(fsl_cx * f,
                      fsl_tagtype_e tagType,
                      fsl_id_t pid,
                      fsl_id_t tagid,
                      fsl_id_t origId,
                      const char *zValue,
                      double mtime );

/**
   Marks libfossil as running inside a host process which owns
   SQLite, e.g. as a SQLite extension. It must be called before any
   other libfossil API. Afterwards, library-level init does not
   install an atexit() handler.
*/
void fsl__lib_hosted(void);

/**
   Makes db use a host's open sqlite3 handle. fsl_db_close() will not
   close it. db must not already be opened.
*/
void fsl__db_borrow(fsl_db * const db, sqlite3 * const dbh);

/**
   Returns true if db's sqlite3 handle came from fsl__db_borrow().
*/
bool fsl__db_is_borrowed(fsl_db const * const db);

/**
   Drops TEMP table zTable if it exists. If SQLite refuses because
   another statement is running, e.g. a host's statement which called
   us through a SQL function, it empties the table instead, so callers
   which create it again must use CREATE TEMP TABLE IF NOT EXISTS.
   Returns 0 or a db error code.
*/
int fsl__db_temp_drop(fsl_db * const db, char const * zTable);

/**
   Returns true if db's connection is inside a transaction or has a
   statement running, e.g. a host's statement which called us through
   a SQL function. A read-only operation which would open a
   transaction only so that its several statements see one consistent
   snapshot must skip that when this is true: the running statement
   or the open transaction already holds the connection's read (or
   write) lock, so no other connection can commit in between, and
   SQLite refuses to open a savepoint while a writing statement is in
   progress. Never use this to skip a transaction which protects
   writes, including writes to caches and TEMP tables.
*/
bool fsl__db_in_statement_or_txn(fsl_db * const db);

/** @internal

    Generates an fsl_appendf()-formatted message to stderr and
    fatally aborts the application by calling exit(). This is only
    (ONLY!) intended for us as a placeholder for certain test cases
    and is neither thread-safe nor reantrant.

    fmt may be empty or NULL, in which case only the code and its
    fsl_rc_cstr() representation are output.

    This function does not return.

    Possible todo: expose this in the public API as fcli_fatal().
*/
void fsl__fatal(int code, char const * fmt, ...)
#ifdef __GNUC__
  __attribute__ ((noreturn))
#endif
  ;

/** @internal

    Translate a normalized, repo-relative filename into a
    filename-id (fnid). Create a new fnid if none previously exists
    and createNew is true. On success returns 0 and sets *rv to the
    filename.fnid record value. If createNew is false and no match
    is found, 0 is returned but *rv will be set to 0. Returns non-0
    on error.  Results are undefined if any parameter is NULL.


    In debug builds, this function asserts that no pointer arguments
    are NULL and that f has an opened repository.
*/
int fsl__repo_filename_fnid2( fsl_cx * f, char const * filename,
                             fsl_id_t * rv, bool createNew );


/** @internal

    Clears and frees all (char*) members of db but leaves the rest
    intact. If alsoBuffers is true then the error state and prep
    buffer are also freed, else they are kept as well.
*/
void fsl__db_clear_strings(fsl_db * db, bool alsoBuffers );

/** @internal

    Returns 0 if db appears to have a current repository schema, 1
    if it appears to have an out of date schema, and -1 if it
    appears to not be a repository. Results are undefined if db is
    NULL or not opened.
*/
int fsl__db_repo_verify_schema(fsl_db * db);


/** @internal

    Flags for APIs which add phantom blobs to the repository.  The
    values in this enum derive from fossil(1) code and should not be
    changed without careful forethought and (afterwards) testing.  A
    phantom blob is a blob about whose existence we know but for which
    we have no content. This normally happens during sync or rebuild
    operations, but can also happen when artifacts are stored directly
    as files in a repo (like this project's repository does, storing
    artifacts from *other* projects for testing purposes).
*/
enum fsl__phantom_e {
/**
   Indicates to fsl__uuid_to_rid2() that no phantom artifact
   should be created.
*/
FSL_PHANTOM_NONE = 0,
/**
   Indicates to fsl__uuid_to_rid2() that a public phantom
   artifact should be created if no artifact is found.
*/
FSL_PHANTOM_PUBLIC = 1,
/**
   Indicates to fsl__uuid_to_rid2() that a private phantom
   artifact should be created if no artifact is found.
*/
FSL_PHANTOM_PRIVATE = 2
};
typedef enum fsl__phantom_e fsl__phantom_e;

/** @internal

    Works like fsl_uuid_to_rid(), with these differences:

    - uuid is required to be a complete UUID, not a prefix.

    - If it finds no entry and the mode argument specifies so then it
      will add either a public or private phantom entry and return its
      new rid. If mode is FSL_PHANTOM_NONE then this this behaves just
      like fsl_uuid_to_rid().

    Returns a positive value on success, 0 if it finds no entry and
    mode==FSL_PHANTOM_NONE, and1 a negative value on error (e.g. if
    fsl_is_uuid(uuid) returns false). Errors which happen after
    argument validation will "most likely" update f's error state
    with details.
*/
fsl_id_t fsl__uuid_to_rid2( fsl_cx * f, fsl_uuid_cstr uuid,
                           fsl__phantom_e mode );

/** @internal

    Schedules the given rid to be verified before it is commited, but
    whether the validation will be done at the commit of the current
    transaction level or a higher-up one is as-yet unspecified . This
    is used by routines which add artifact records to the blob table.

    The only error case, assuming the arguments are valid, is an
    allocation error while appending rid to the internal to-verify
    queue.

    @see fsl__repo_verify_at_commit()
    @see fsl_repo_verify_cancel()
*/
int fsl__repo_verify_before_commit( fsl_cx * f, fsl_id_t rid );

/** @internal

    Clears the current transaction level's verify-at-commit list of
    RIDs.

    @see fsl__repo_verify_at_commit()
    @see fsl__repo_verify_before_commit()
*/
void fsl__repo_verify_cancel( fsl_cx * f );

/** @internal

    Processes all pending verify-at-commit entries for the current
    transaction level and clears the to-verify list. Returns 0 on
    success. On error f's error state will likely be updated.

    ONLY call this from fsl_db_txn_end() or its delegate (if
    refactored).

    Verification calls fsl_content_get() to "unpack" content added in
    the current transaction. If fetching the content (which applies
    any deltas it may need to) fails or its hash does not match its
    blob.uuid value then this routine fails and returns non-0.

    @see fsl_repo_verify_cancel()
    @see fsl__repo_verify_before_commit()
*/
int fsl__repo_verify_at_commit( fsl_cx * f );

/** @internal

    Verifies one blob record: if its content can be reconstructed,
    its hash must match its blob.uuid value. Returns 0 on success, and
    also for a phantom or for a delta whose source is not yet
    available, which cannot be verified yet. On a hash mismatch it
    returns FSL_RC_CONSISTENCY. If the content cannot be reconstructed
    (e.g. a delta which does not apply) it returns that error code.
    On error it updates f's error state.

    This is the per-RID check done by fsl__repo_verify_at_commit(),
    for callers which need to verify content as it arrives.
*/
int fsl__repo_verify_rid( fsl_cx * f, fsl_id_t rid );

/** @internal

    Removes all entries from the repo's blob table which are listed
    in the shun table. Returns 0 on success. This operation is
    wrapped in a transaction. Delta content which depend on
    to-be-shunned content are replaced with their undeltad forms.

    Returns 0 on success. On error, its transaction is aborted or a
    pseudo-nested transaction is set into a rollback state.
*/
int fsl__repo_shun_artifacts(fsl_cx * f);

/** @internal.

    Return a pointer to a string that contains the RHS of an SQL IN
    operator which will select config.name values that are part of
    the configuration that matches iMatch (a bitmask of
    fsl_configset_e values). Ownership of the returned string is
    passed to the caller, who must eventually pass it to
    fsl_free(). Returns NULL on allocation error.

    Reminder to self: this is part of the infrastructure for copying
    config state from an existing repo when creating new repo.
*/
char *fsl__config_inop_rhs(int iMask);

/** @internal

    Applies a single "config" card received over the sync protocol.

    zName is the card's wire name ("/shun", "/user", ...). pContent is
    the card's payload, which is tokenized IN PLACE and thus modified;
    callers must treat it as scratch space afterwards. groupMask is a
    bitmask of FSL_CONFIGSET_* values limiting which configuration
    groups may be applied.

    The payload is a sequence of token pairs: first the mtime and the
    target row's primary key, then zero or more (column, value) pairs.
    A row is inserted if absent and overwritten only if the incoming
    mtime is strictly newer than the stored one.

    Returns 0 on success AND on every protocol-legal skip: an unknown
    or unsupported card name, a name outside groupMask, an unknown
    column, or a malformed payload. This mirrors fossil, which never
    fails a sync over a bad config card. A non-0 result means a real
    db or allocation error and should abort the transfer.
*/
int fsl__config_receive(fsl_cx * const f, char const * zName,
                        fsl_b * const pContent, int groupMask);

/** @internal

    Returns the FSL_CONFIGSET_* mask this build considers zName
    exportable/receivable under via a /config sync card (per its
    entry in the internal fslConfigXfer[] allow-list), or 0 if zName
    is unknown to that table or is on the hard-coded sensitive-setting
    deny list. A 0 result means fsl__config_receive() will always
    skip a /config card for this name, regardless of groupMask.

    This is exposed beyond src/config.c specifically so callers that
    seed local config rows outside of sync (e.g. fsl_repo_create())
    can assert that a seeded name is NOT wire-syncable: any name which
    is both locally pre-seeded with a "now" mtime AND wire-syncable
    will permanently block a real, older incoming value, since
    fsl__config_receive()'s overwrite guard is `mtime<incoming`. See
    the DBSET_INT block in fsl_repo_create() for the concrete case
    this closed (2026-07-22, "timeline-plaintext").
*/
int fsl__config_name_mask(char const * zName);

/** @internal

    Return a pointer to a string that contains the RHS of an IN
    operator that will select config.name values that are in the
    list of control settings. Ownership of the returned string is
    passed to the caller, who must eventually pass it to
    fsl_free(). Returns NULL on allocation error.

    Reminder to self: this is part of the infrastructure for copying
    config state from an existing repo when creating new repo.
*/
char *fsl__db_setting_inop_rhs(void);

/** @internal

    Creates the ticket and ticketchng tables in f's repository db,
    DROPPING them if they already exist. The schema comes from
    fsl_schema_ticket().

    TODO? Add a flag specifying whether to drop or keep existing
    copies.

    Returns 0 on success.
*/
int fsl__cx_ticket_create_table(fsl_cx * f);

/** @internal

    Frees all J-card entries in the given list.

    li is assumed to be empty or contain (fsl_card_J*)
    instances. If alsoListMem is true then any memory owned
    by li is also freed. li itself is not freed.

    Results are undefined if li is NULL.
*/
void fsl__card_J_list_free( fsl_list * li, bool alsoListMem );

/** @internal

    Values for fsl_card_J::flags.
*/
enum fsl_card_J_flags {
/**
   Sentinel value.
*/
FSL_CARD_J_INVALID = 0,
/**
   Indicates that the field is used by the ticket table.
*/
FSL_CARD_J_TICKET = 0x01,
/**
   Indicates that the field is used by the ticketchng table.
*/
FSL_CARD_J_CHNG = 0x02,
/**
   Indicates that the field is used by both the ticket and
   ticketchng tables.
*/
FSL_CARD_J_BOTH = FSL_CARD_J_TICKET | FSL_CARD_J_CHNG
};

/** @internal

    Loads all custom/customizable ticket fields from f's repo's
    ticket table info f. If f has already loaded the list and
    forceReload is false, this is a no-op.

    Returns 0 on success.

    @see fsl_cx::ticket::customFields
*/
int fsl__cx_ticket_load_fields(fsl_cx * f, bool forceReload);

/** @internal

    A comparison routine for qsort(3) which compares fsl_card_J
    instances in a lexical manner based on their names. The order is
    important for card ordering in generated manifests.

    This routine expects to get passed (fsl_card_J**) (namely from
    fsl_list entries), and will not work on an array of J-cards.
*/
int fsl__qsort_cmp_J_cards( void const * lhs, void const * rhs );

/** @internal

    This function updates the repo and/or global config databases
    with links between the dbs intended for various fossil-level
    bookkeeping and housecleaning. These links are not essential to
    fossil's functionality but assist in certain "global"
    operations.

    If no checkout is opened but a repo is, the global config (if
    opened) is updated to know about the opened repo db.

    If a checkout is opened, global config (if opened) and the
    repo are updated to point to the checked-out db.
*/
int fsl__repo_record_filename(fsl_cx * f);

/** @internal

    Updates f->ckout.uuid and f->ckout.rid to reflect the current
    checkout state. If no checkout is opened, the uuid is freed/NULLed
    and the rid is set to 0. Returns 0 on success. If it returns an
    error (OOM or db-related), the f->ckout state is left in a
    potentially inconsistent state, and it should not be relied upon
    until/unless the error is resolved.

    This is done when a checkout db is opened, when performing a
    checkin, and otherwise as needed, and so calling it from other
    code is normally not necessary.

    @see fsl__ckout_version_write()
*/
int fsl__ckout_version_fetch( fsl_cx * f );

/** @internal

    Updates f->ckout's state to reflect the given version info and
    writes the 'checkout' and 'checkout-hash' properties to the
    currently-opened checkout db. Returns 0 on success,
    FSL_RC_NOT_A_CKOUT if no checkout is opened (may assert() in that
    case!), or some other code if writing to the db fails.

    If vid is 0 then the version info is null'd out. Else if uuid is
    NULL then fsl_rid_to_uuid() is used to fetch the UUID for vid.

    If the RID differs from f->ckout.rid then f->ckout's version state
    is updated to the new values.

    This routine also updates or removes the checkout's manifest
    files, as per fsl_ckout_manifest_write(). If vid is 0 then it
    removes any such files which themselves are not part of the
    current checkout.

    @see fsl__ckout_version_fetch()
    @see fsl_cx_ckout_version_set()
*/
int fsl__ckout_version_write( fsl_cx * f, fsl_id_t vid,
                             fsl_uuid_cstr uuid );

/**
   @internal

   Exports the file with the given [vfile].[id] to the checkout,
   overwriting (if possible) anything which gets in its way. If
   the file is determined to have not been modified, it is
   unchanged.

   If the final argument is not NULL then it is set to 0 if the file
   was not modified, 1 if only its permissions were modified, and 2 if
   its contents were updated (which also requires resetting its
   permissions to match their repo-side state).

   Returns 0 on success, any number of potential non-0 codes on
   error, including, but not limited to:

   - FSL_RC_NOT_A_CKOUT - no opened checkout.
   - FSL_RC_NOT_FOUND - no matching vfile entry.
   - FSL_RC_OOM - we cannot escape this eventuality.

   Trivia:

   - fossil(1)'s vfile_to_disk() is how it exports a whole vfile, or a
   single vfile entry, to disk. e.g. it performs a checkout that way,
   whereas we currently perform a checkout using the "repo extraction"
   API. The checkout mechanism was probably the first major core
   fossil feature which was structured radically differently in
   libfossil, compared to the feature's fossil counterpart, when it
   was ported over.

   - This routine always writes to the vfile.pathname entry, as
   opposed to vfile.origname.

   Maintenance reminders: internally this code supports handling
   multiple files at once, but (A) that's not part of the interface
   and may change and (B) the 3rd parameter makes little sense in that
   case unless maybe we change it to a callback, which seems like
   overkill for our use cases.

   BUGS:

   - When doing a fsl_ckout_revert(), this function does not recognize
     a file which has been modified (only) via a merge as modified, so
     does not set `*wasWritten`. Whether that bug is in _this_
     function or fsl__is_locally_modified() is not yet clear.
     fsl_ckout_revert() works around that so that the client can be
     notified of reverted files, but that's only hiding the underlying
     discrepancy.
*/
int fsl__vfile_to_ckout(fsl_cx * f, fsl_id_t vfileId,
                       int * wasWritten);

/** @internal

    On Windows platforms (only), if fsl_isalpha(*zFile)
    and ':' == zFile[1] then this returns zFile+2,
    otherwise it returns zFile.
*/
char * fsl__file_without_drive_letter(char * zFile);

/** @internal

    This is identical to the public-API member fsl_deck_F_search(),
    except that it returns a non-const F-card.

    Locate a file named zName in d->F.list.  Return a pointer to the
    appropriate fsl_card_F object. Return NULL if not found. Names
    match byte for byte, whatever the context's case-sensitivity
    setting, as fossil(1)'s manifest_file_seek() does;
    fsl_deck_F_search() also matches case-insensitively when that
    setting is off.

    If d->f is set (as it is when loading decks via
    fsl_deck_load_rid() and friends), this routine works even if p is
    a delta-manifest. The pointer returned might be to the baseline
    and d->B.baseline is loaded on demand if needed.

    If the returned card's uuid member is NULL, it means that the file
    was removed in the checkin represented by d.

    If !d, zName is NULL or empty, or FSL_SATYPE_CHECKIN!=d->type, it
    asserts in debug builds and returns NULL in non-debug builds.

    We assume that filenames are in sorted order and use a binary
    search. As an optimization, to support the most common use case,
    searches through a deck update d->F.cursor to the last position a
    search was found. Because searches are normally done in lexical
    order (because of architectural reasons), this is normally an O(1)
    operation. It degrades to O(N) if out-of-lexical-order searches
    are performed.
*/
fsl_card_F * fsl__deck_F_seek(fsl_deck * d, const char *zName);

/** @internal

    Works like fsl__deck_F_seek() but tells a missing file from a
    search which could not be done: sets *rv to the entry or NULL and
    returns 0, or returns an error code, with d->f's error state set,
    if the search cannot be done (a delta manifest's baseline cannot
    be loaded). *rv is NULL whenever the result is not 0.
*/
int fsl__deck_F_seek2(fsl_deck * d, const char *zName, fsl_card_F ** rv);

/**
   Works like fsl_deck_F_add(), but if strictNames is false, name and
   oldName get only the structural check of fsl_is_simple_pathname(),
   not its check for new filenames. Use false where the names come from
   existing artifacts or the checkout, which may hold names that older
   versions of fossil(1) or an import wrote and that the strict check
   refuses. fsl_deck_F_add() passes true.
*/
int fsl__deck_F_add2( fsl_deck * mf, char const * name,
                      char const * uuid, fsl_fileperm_e perms,
                      char const * oldName, bool strictNames );

/** @internal

    Ensures that f's single file content buffer is available for use
    and returns it to the caller. If it appears to already be in use,
    this function fails fatally via fsl__fatal(), indicating a serious
    misuse of the internal API.

    Calling this obligates the caller to call
    fsl__cx_content_buffer_yield() as soon as they are done with the
    buffer.
*/
fsl_b * fsl__cx_content_buffer(fsl_cx * f);

/** @internal

    Part of the fsl_cx::cache::fileContent optimization. Passes
    f->cache.fileContent to fsl_b_reuse() and if its capacity is
    over a certain (unspecified, unconfigurable) size then it is
    trimmed to that size. It also updates some of f's metrics.
*/
void fsl__cx_content_buffer_yield(fsl_cx * f);

/**
   Inserts the given rid into the repo.private table.
*/
int fsl__private_rid_add(fsl_cx * f, fsl_id_t rid);

/**
   Deletes the given rid from the repo.private table.
*/
int fsl__private_rid_delete(fsl_cx * f, fsl_id_t rid);

/**
   Inserts the given rid into the repo.unclustered table.
*/
int fsl__unclustered_rid_add(fsl_cx * f, fsl_id_t rid);
/**
   Inserts the given rid into the repo.phantom table.
*/
int fsl__phantom_rid_add(fsl_cx * f, fsl_id_t rid);
/**
   Inserts the given rid into the repo.unsent table.
*/
int fsl__unsent_rid_add(fsl_cx * f, fsl_id_t rid);
/**
   Replaces the repo.delta entry with the given rid. This does not
   manipulate the related blobs in any way.
*/
int fsl__delta_replace(fsl_cx * f, fsl_id_t rid, fsl_id_t srcid);
/**
   Replaces the repo.delta entry with the given rid. This does not
   manipulate the related blobs in any way.
*/
int fsl__delta_delete(fsl_cx * f, fsl_id_t rid);

/**
   Expects zTable to name a table with an rid field. That record
   is deleted.
*/
int fsl__rid_delete(fsl_cx * f, fsl_dbrole_e dbRole,
                    char const *zTable, fsl_id_t rid);

/** @internal

   Currently disabled (always returns 0) pending resolution of a
   "wha???" result from one of the underlying queries.

   Queues up the given artifact for a search index update. This is
   only intended to be called from crosslinking steps and similar
   content updates. Returns 0 on success.

   The final argument is intended only for wiki titles (the L-card of
   a wiki post).

   If the repository database has no search index or the given content
   is marked as private, this function returns 0 and makes no changes
   to the db.
*/
int fsl__search_doc_touch(fsl_cx * f, fsl_satype_e saType,
                         fsl_id_t rid, const char * docName);

/** @internal

   Returns true if the given file name is a reserved filename
   (case-insensitive) on Windows platforms, else returns false.

   zPath must be a canonical path with forward-slash directory
   separators. nameLen is the length of zPath. If negative, fsl_strlen()
   is used to determine its length.
*/
bool fsl__is_reserved_fn_windows(const char *zPath, fsl_int_t nameLen);

/** @internal

   Modes for fsl__ckout_clear_merge_state(), describing the caller's
   intent so that the checkout-level merge markers (vmerge.id<=0:
   merge, cherry-pick, backout, integrate) are only discarded when the
   user has plausibly abandoned them.
*/
enum fsl__ckout_merge_clear_e {
/**
   Partial wipe for state-refresh scans (fsl_vfile_changes_scan()):
   clears per-file merge state (vmerge.id>0) for unchanged files but
   never removes the checkout-level markers. A scan performed on
   behalf of some other operation must not unilaterally decide that a
   pending merge has been abandoned. fossil(1)'s scan never touches
   vmerge.
*/
FSL__MERGE_CLEAR_SCAN = 0,
/**
   Unconditionally wipes all vmerge state. For use once a commit has
   consumed the merge state or a checkout/update has invalidated it.
*/
FSL__MERGE_CLEAR_ALL = 1,
/**
   Like FSL__MERGE_CLEAR_SCAN except that cherry-pick/backout markers
   may also be swept once no vfile entry shows active merge
   involvement (chnged>1) and no per-file merge state remains. For
   use by explicit-abandonment operations (fsl_ckout_revert()), where
   the user reverting the merged file's changes is the signal that
   the pending cherry-pick/backout is being abandoned.
*/
FSL__MERGE_CLEAR_REVERT = 2
};

/** @internal

   Clears pending merge state from the f's checkout db's vmerge
   table, as described for the given fsl__ckout_merge_clear_e mode.
   Returns 0 on success, non-0 on db error.
*/
int fsl__ckout_clear_merge_state( fsl_cx * f,
                                  enum fsl__ckout_merge_clear_e mode );

/** @internal

   Installs or reinstalls the checkout database schema into f's open
   checkout db. Returns 0 on success, FSL_RC_NOT_A_CKOUT if f has
   no opened checkout, or an code if a lower-level operation fails.

   If dropIfExists is true then all affected tables are dropped
   beforehand if they exist. "It's the only way to be sure."

   If dropIfExists is false and the schema appears to already exists
   (without actually validating its validity), 0 is returned.
*/
int fsl__ckout_install_schema(fsl_cx * f, bool dropIfExists);

/** @internal

   Attempts to remove empty directories from under a checkout,
   starting with tgtDir and working upwards until it either cannot
   remove one or it reaches the top of the checkout dir.

   The second argument must be the canonicalized absolute path to some
   directory under the checkout root. The contents of the buffer may,
   for efficiency's sake, be modified by this routine as it traverses
   the directory tree. It will never grow the buffer but may mutate
   its memory's contents.

   Returns the number of directories it is able to remove.

   Results are undefined if tgtDir is not an absolute path rooted in
   f's current checkout.

   There are any number of valid reasons removal of a directory might
   fail, and this routine stops at the first one which does.
*/
unsigned int fsl__ckout_rm_empty_dirs(fsl_cx * f,
                                      fsl_b const * tgtDir);

/** @internal

   This is intended to be passed the name of a file which was just
   deleted and "might" have left behind an empty directory. The name
   _must_ an absolute path based in f's current checkout. This routine
   uses fsl_file_dirpart() to strip path components from the string
   and remove directories until either removing one fails or the top
   of the checkout is reached. Since removal of a directory can fail for
   any given reason, this routine ignores such errors. It returns 0 on
   success, FSL_RC_OOM if allocation of the working buffer for the
   filename hackery fails, and FSL_RC_MISUSE if zFilename is not
   rooted in the checkout (in which case it may assert(), so don't do
   that).

   @see fsl_is_rooted_in_ckout()
   @see fsl_rm_empty_dirs()
*/
int fsl__ckout_rm_empty_dirs_for_file(fsl_cx * f, char const *zAbsPath);

/** @internal

    If f->cache.seenDeltaManifest<=0 then this routine sets it to 1
    and sets the 'seen-delta-manifest' repository config setting to 1,
    else this has no side effects. Returns 0 on success, non-0 if
    there is an error while writing to the repository config.
*/
int fsl__cx_update_seen_delta_deck(fsl_cx * f);

/** @internal

   Very, VERY internal.

   Returns the next available buffer from f->scratchpads. Fatally
   aborts if there are no free buffers because "that should not
   happen."  Calling this obligates the caller to eventually pass
   its result to fsl__cx_scratchpad_yield().

   This function guarantees the returned buffer's 'used' member will be
   set to 0.

   Maintenance note: the number of buffers is hard-coded in the
   fsl_cx::scratchpads anonymous struct.
*/
fsl_b * fsl__cx_scratchpad(fsl_cx * f);

/** @internal

   Very, VERY internal.

   "Yields" a buffer which was returned from fsl__cx_scratchpad(),
   making it available for re-use. The caller must treat the buffer as
   if this routine frees it: using the buffer after having passed it
   to this function will internally be flagged as explicit misuse and
   will lead to a fatal crash the next time that buffer is fetched via
   fsl__cx_scratchpad(). So don't do that.
*/
void fsl__cx_scratchpad_yield(fsl_cx * f, fsl_b * b);

/** @internal

   Run automatically by fsl_deck_save(), so it needn't normally be run
   aside from that, at least not from average client code.

   Runs postprocessing on the Structural Artifact represented by
   d. d->f must be set, d->rid must be set and valid and d's contents
   must accurately represent the stored manifest for the given
   rid. This is normally run just after the insertion of a new
   manifest, but is sometimes also run after reading a deck from the
   database (in order to rebuild all db relations and add/update the
   timeline entry).

   Returns 0 on succes, FSL_RC_MISUSE !d->f, FSL_RC_RANGE if
   d->rid<=0, FSL_RC_MISUSE (with more error info in f) if d does not
   contain all required cards for its d->type value. It may return
   various other codes from the many routines it delegates work to.

   Crosslinking of ticket artifacts is currently (2021-11 resp.
   2026-09) only partially implemented.

   Design note: d "really should" be const here but some internals
   (d->F.cursor and delayed baseline loading) prohibit it.

   @see fsl__deck_crosslink_one()
*/
int fsl__deck_crosslink( fsl_deck /* const */ * d );

/** @internal

   Run automatically by fsl_deck_save(), so it needn't normally be run
   aside from that, at least not from average client code.

   This is a convience form of crosslinking which must only be used
   when a single deck (and only a single deck) is to be crosslinked.
   This function wraps the crosslinking in fsl_crosslink_begin()
   and fsl__crosslink_end(), but otherwise behaves the same as
   fsl__deck_crosslink(). If crosslinking fails, any in-progress
   transaction will be flagged as failed.

   Returns 0 on success.
*/
int fsl__deck_crosslink_one( fsl_deck * d );

/** @internal

   Checks whether the given filename is "safe" for writing to within
   f's current checkout.

   zFilename must be in canonical form: only '/' directory separators.
   If zFilename is not absolute, it is assumed to be relative to the top
   of the current checkout, else it must point to a file under the current
   checkout.

   Checks made on the filename include:

   - It must refer to a file under the current checkout.

   - Ensure that each directory listed in the file's path is actually
   a directory, and fail if any part other than the final one is a
   non-directory.

   If the name refers to something not (yet) in the filesystem, that
   is not considered an error.

   Returns 0 on success. On error f's error state is updated with
   information about the problem.
*/
int fsl__ckout_safe_file_check(fsl_cx * f, char const * zFilename);

/**
   Starts recording undo state for an operation (see undo.c and
   undo.h) labeled zLabel, or, if zLabel is NULL, suppresses
   recording for the duration of an operation. If another operation
   is already recording (or suppressing) on f's connection, this does
   nothing. *owner is set to true if this call started it, and the
   caller must then pass the operation's result and owner to
   fsl__undo_end(). Returns 0 on success.
*/
int fsl__undo_begin(fsl_cx * const f, char const * zLabel,
                    bool * const owner);

/**
   Finishes what fsl__undo_begin() started: if rc is 0 and the
   operation recorded, its record becomes the one fsl_undo() uses;
   otherwise the record in progress is dropped. Returns rc if it is
   non-0, else the result of finishing.
*/
int fsl__undo_end(fsl_cx * const f, int rc, bool owner);

/**
   If an operation is recording undo state, saves a copy of stash
   stashId (or all stashes if it is negative), which the operation is
   about to remove, so that undo can put it back. Returns 0 on
   success.
*/
int fsl__undo_keep_stash(fsl_cx * const f, fsl_id_t stashId);

/** @internal
   Creates zLinkFile as a symlink to zTgtFile, as fossil(1)'s
   symlink_create() does: a real symlink if f's 'allow-symlinks'
   setting is on and the platform and f's checkout filesystem support
   them, else a regular file holding the single line zTgtFile (which
   is how fossil manages symlinks on Windows and, since late 2020,
   by default). Whatever was at zLinkFile is removed first, so this
   never writes through an existing symlink.

   zLinkFile may be an absolute path rooted at f's current checkout or
   may be a checkout-relative path.

   Returns 0 on success, non-0 on error:

   - FSL_RC_NOT_A_CKOUT if f has no opened checkout.

   - FSL_RC_RANGE if zLinkFile is an absolute path outside of the
   current checkout.

   - FSL_RC_OOM on allocation error.

   - The result of fsl__cfs_symlink_create() if creating zLinkFile
   fails, in which case f's error state names the file.
*/
int fsl__ckout_symlink_create(fsl_cx * f, char const *zTgtFile,
                              char const * zLinkFile);


/** @internal
   Compute all file name changes that occur going from check-in iFrom
   to check-in iTo. Requires an opened repository.

   If revOK is true, the algorithm is free to move backwards in the
   chain. This is the opposite of the oneWayOnly parameter for
   fsl_vpath_shortest().

   On success, the number of name changes is written into *pnChng.
   For each name change, two integers are allocated for *piChng. The
   first is the filename.fnid for the original name as seen in
   check-in iFrom and the second is for new name as it is used in
   check-in iTo. If *pnChng is 0 then *aiChng will be NULL.

   On error returns non-0, pnChng and aiChng are not modified, and
   f's error state might (depending on the error) contain a description
   of the problem.

   Space to hold *aiChng is obtained from fsl_malloc() and must
   be released by the caller.
*/
int fsl__find_filename_changes(fsl_cx * f,
                               fsl_id_t iFrom,
                               fsl_id_t iTo,
                               bool revOK,
                               uint32_t *pnChng,
                               fsl_id_t **aiChng);

/**  @internal
   Bitmask of file change types for use with
   fsl__is_locally_modified().
*/
enum fsl__localmod_e {
/** Sentinel value. */
FSL__LOCALMOD_NONE = 0,
/**
   Permissions changed.
*/
FSL__LOCALMOD_PERM = 0x01,
/**
   File size or hash (i.e. content) differ.
*/
FSL__LOCALMOD_CONTENT = 0x02,
/**
   The file type was switched between symlink and normal file.  In
   this case, no check for content change, beyond the file size
   change, is performed.
*/
FSL__LOCALMOD_LINK = 0x04,
/**
   File was not found in the local checkout.
 */
FSL__LOCALMOD_NOTFOUND = 0x10
};
typedef enum fsl__localmod_e fsl__localmod_e;
/** @internal

   Checks whether the given file has been locally modified compared to
   a known size, hash value, and permissions. Requires that f has an
   opened checkout.

   If zFilename is not an absolute path, it is assumed to be relative
   to the checkout root (as opposed to the current directory) and is
   canonicalized into an absolute path for purposes of this function.

   fileSize is the "original" version's file size.  zOrigHash is the
   initial hash of the file to use as a basis for comparison.
   zOrigHashLen is the length of zOrigHash, or a negative value if
   this function should use fsl_is_uuid() to determine the length. If
   the hash length is not that of one of the supported hash types,
   FSL_RC_RANGE is returned and f's error state is updated. This
   length is used to determine which hash to use for the comparison.

   If the file's current size differs from the given size, it is
   quickly considered modified, otherwise the file's contents get
   hashed and compared to zOrigHash.

   Because this is used for comparing local files to their state from
   the fossil database, where files have no timestamps, the local
   file's timestamp is never considered for purposes of modification
   checking.

   If isModified is not NULL then on success it is set to a bitmask of
   values from the fsl__localmod_e enum specifying the type(s) of
   change(s) detected:

   - FSL__LOCALMOD_PERM = permissions changed.

   - FSL__LOCALMOD_CONTENT = file size or hash (i.e. content) differ.

   - FSL__LOCALMOD_LINK = the file type was switched between symlink
     and normal file. In this case, no check for content change,
     beyond the file size change, is performed.

   - FSL__LOCALMOD_NOFOUND = file was not found in the local checkout.

   Noting that:

   - Combined values of (FSL__LOCALMOD_PERM | FSL__LOCALMOD_CONTENT) are
   possible, but FSL__LOCALMOD_NOTFOUND will never be combined with one
   of the other values.

   If stat() fails for any reason other than file-not-found
   (e.g. permissions), an error is triggered.

   Returns 0 on success. On error, returns non-0 and f's error state
   will be updated and isModified...  isNotModified. Errors include,
   but are not limited to:

   - Invalid hash length: FSL_RC_RANGE
   - f has no opened checkout: FSL_RC_NOT_A_CKOUT
   - Cannot find the file: FSL_RC_NOT_FOUND
   - Error accessing the file: FSL_RC_ACCESS
   - Allocation error: FSL_RC_OOM
   - I/O error during hashing: FSL_RC_IO

   And potentially other errors, roughly translated from errno values,
   for corner cases such as passing a directory name instead of a
   file.

   Results are undefined if any pointer argument is NULL or invalid.

   This function currently does NOT follow symlinks for purposes of
   resolving zFilename, but that behavior may change in the future or
   may become dependent on the repository's 'allow-symlinks' setting.

   Internal detail, not relevant for clients: this updates f's
   cache stat entry.
*/
int fsl__is_locally_modified(fsl_cx * f,
                            const char * zFilename,
                            fsl_size_t fileSize,
                            const char * zOrigHash,
                            fsl_int_t zOrigHashLen,
                            fsl_fileperm_e origPerm,
                            int * isModified);

/** @internal

   This routine cleans up the state of selected cards in the given
   deck. The 2nd argument is an list of upper-case letters
   representing the cards which should be cleaned up, e.g. "ADG". If
   it is NULL, all cards are cleaned up but d has non-card state
   which is not cleaned up by this routine. Unknown letters are simply
   ignored.
*/
void fsl__deck_clean_cards(fsl_deck * d, char const * letters);

/** @internal

    This starts a transaction (possibly nested) on the repository db
    and initializes some temporary db state needed for the
    crosslinking certain artifact types. It "should" (see below) be
    called at the start of the crosslinking process. Crosslinking
    *can* work without this but certain steps for certain (subject to
    change) artifact types will be skipped, possibly leading to
    unexpected timeline data or similar funkiness. No permanent
    SCM-relevant state will be missing, but the timeline might not be
    updated and tickets might not be fully processed. This should be
    used before crosslinking any artifact types, but will only have
    significant side effects for certain (subject to change) types.

    Returns 0 on success.

    If it returns 0 then the caller is OBLIGATED to either 1) call
    fsl__crosslink_end() or 2) call fsl_db_txn_rollback() and
    set f->cache.isCrosslinking to false. This process may install
    temporary tables and/or triggers, so failing to call one or the
    other of those will result in misbehavior.

    @see fsl__deck_crosslink()
*/
int fsl__crosslink_begin(fsl_cx * f);

/** @internal

    Must not be called unless fsl__crosslink_begin() has
    succeeded. This performs crosslink post-processing on certain
    artifact types and cleans up any temporary db state initialized by
    fsl__crosslink_begin().

    If the 2nd argument is not 0 then this routine triggers a rollback
    of the transaction started by fsl__crosslink_begin() and
    propagates any pending error code from f or (if f has no error
    code) from f's db handle.

    The second argument is intended to be the value of any pending
    result code (0 or otherwise) from any work done _after_
    fsl__crosslink_begin() succeeded. If passed 0, it assumes that
    there is no propagating error state and will attempt to complete
    the crosslinking process. If passed non-0, it triggers a rollback
    and unsets the f->cache.isCrosslinking flag, but does no
    additional work, then returns resultCode.

    Returns 0 on success. On error it initiates (or propagates) a
    rollback for the current transaction. If called when a rollback is
    pending, it unsets the crosslink-is-running flag and returns the
    propagating result code.
*/
int fsl__crosslink_end(fsl_cx * f, int resultCode);

/** @internal

   Installs the core timeline crosslink listeners. Defined in deck.c.
*/
int fsl__cx_install_timeline_crosslinkers(fsl_cx * const f);

/** @internal

   Searches the current repository database for a fingerprint and
   returns it as a string in *zOut.

   If rcvid<=0 then the fingerprint matches the last entry in the
   [rcvfrom] table, where "last" means highest-numbered rcvid (as
   opposed to most recent mtime, for whatever reason). If rcvid>0 then
   it searches for an exact match.

   Returns 0 on non-error. Finding no matching rcvid results in
   FSL_RC_NOT_FOUND. If 0 is returned then *zOut will be non-NULL and
   ownership of that value is transferred to the caller, who must
   eventually pass it to fsl_free(). On error, *zOut is not modified.

   Returns FSL_RC_NOT_A_REPO if f has no opened repository, FSL_RC_OOM
   on allocation error, or any number of potential db-related codes if
   something goes wrong at the db level.

   This API internally first checks for "version 1" fossil
   fingerprints and falls back to "version 0" fingerprint if a v1
   fingerprint is not found. Version 0 was very short-lived and is not
   expected to be in many repositories which are accessed via this
   library. Practice has, however, revealed some.

   @see fsl_ckout_fingerprint_check()
*/
int fsl__repo_fingerprint_search(fsl_cx * f, fsl_id_t rcvid,
                                 char ** zOut);
/**
   When a record is converted from a phantom to a real record, if that
   record has other records that are derived by delta, then call
   fsl__deck_crosslink() on those other records.

   If the formerly phantom record or any of the other records derived
   by delta from the former phantom are a baseline manifest, then also
   invoke fsl__deck_crosslink() on the delta-manifests associated with
   that baseline.

   Returns 0 on success, any number of non-0 results on error.

   The 3rd argument must always be 0 except in recursive
   calls to this function.
*/
int fsl__after_dephantomize(fsl_cx * f, fsl_id_t rid, bool tryCrosslink);

/** @internal

   Returns true if rid's content can be reconstructed: it is not a
   phantom and no delta in its chain is based on a phantom. The
   counterpart of fossil(1)'s content_is_available().
*/
bool fsl__content_is_available(fsl_cx * f, fsl_id_t rid);

/** @internal

   State for running a raw diff.

   @see fsl__diff_all()
*/
struct fsl__diff_cx {
  /**
     aEdit describes the raw diff. Each triple of integers in aEdit[]
     means:

     (1) COPY:   Number of lines aFrom and aTo have in common
     (2) DELETE: Number of lines found only in aFrom
     (3) INSERT: Number of lines found only in aTo

     The triples repeat until all lines of both aFrom and aTo are
     accounted for. The array is terminated with a triple of (0,0,0).
  */
  int *aEdit /*TODO unsigned*/;
  /** Number of integers (3x num of triples) in aEdit[]. */
  int nEdit /*TODO unsigned*/;
  /** Number of elements allocated for aEdit[]. */
  int nEditAlloc /*TODO unsigned*/;
  /** File content for the left side of the diff. */
  fsl_dline *aFrom;
  /** Number of lines in aFrom[]. */
  int nFrom /*TODO unsigned*/;
  /** File content for the right side of the diff. */
  fsl_dline *aTo;
  /** Number of lines in aTo[]. */
  int nTo /*TODO unsigned*/;
  /** Predicate for comparing LHS/RHS lines for equivalence. */
  int (*cmpLine)(const fsl_dline * const, const fsl_dline *const);
};
/** @internal
   Convenience typeef.
*/
typedef struct fsl__diff_cx fsl__diff_cx;
/** @internal
    Initialized-with-defaults fsl__diff_cx structure, intended for
    const-copy initialization. */
#define fsl__diff_cx_empty_m {\
  NULL,0,0,NULL,0,NULL,0,fsl_dline_cmp \
}
/** @internal
   Initialized-with-defaults fsl__diff_cx structure, intended for
   non-const copy initialization. */
extern const fsl__diff_cx fsl__diff_cx_empty;

/** @internal

    Compute the differences between two files already loaded into
    the fsl__diff_cx structure.

    A divide and conquer technique is used.  We look for a large
    block of common text that is in the middle of both files.  Then
    compute the difference on those parts of the file before and
    after the common block.  This technique is fast, but it does
    not necessarily generate the minimum difference set.  On the
    other hand, we do not need a minimum difference set, only one
    that makes sense to human readers, which this algorithm does.

    Any common text at the beginning and end of the two files is
    removed before starting the divide-and-conquer algorithm.

    Returns 0 on succes, FSL_RC_OOM on an allocation error.
*/
int fsl__diff_all(fsl__diff_cx * p);

/** @internal */
void fsl__diff_cx_clean(fsl__diff_cx * cx);



/** @internal

    Undocumented. For internal debugging only. The 2nd argument is
    intended to be __FILE__ and the 3rd is intended to be __LINE__.
*/
void fsl__dump_triples(fsl__diff_cx const * p,
                       char const * zFile, int ln );

/** @internal

    Removes from the BLOB table all artifacts that are in the SHUN
    table. Returns 0 on success. Requires (asserts) that a repo is
    opened. Note that this is not a simple DELETE operation, as it
    requires ensuring that all removed blobs have been undeltified
    first so that no stale delta records are left behind.
*/
int fsl__shunned_remove(fsl_cx * f);

/** @internal

   This function is, as of this writing, only exposed via a header file
   for the sake of fnc, which still relies on it after we moved the
   "v1" diff code out of this library and into fnc.

   Attempt to shift insertion or deletion blocks so that they begin and
   end on lines that are pure whitespace.  In other words, try to transform
   this:

   ```
        int func1(int x){
           return x*10;
       +}
       +
       +int func2(int x){
       +   return x*20;
        }

        int func3(int x){
           return x/5;
        }
   ```

   Into one of these:

   ```
        int func1(int x){              int func1(int x){
           return x*10;                   return x*10;
        }                              }
       +
       +int func2(int x){             +int func2(int x){
       +   return x*20;               +   return x*20;
       +}                             +}
                                      +
        int func3(int x){              int func3(int x){
           return x/5;                    return x/5;
        }                              }
   ```
*/
void fsl__diff_optimize(fsl__diff_cx * p);

/** @internal

   This is a fossil-specific internal detail not needed by the more
   generic parts of the fsl_db API. It loops through all "cached"
   prepared statements for which stmt->role has been assigned a value
   which bitmasks as true against the given role and finalizes
   them. If such a statement is currently held by a call to/via
   fsl_db_prepare_cachedv() then this will NOT finalize that
   statement, will update db's error state, and return
   FSL_RC_MISUSE.

   Returns 0 on success.

   As a special case, if role==0 then ALL cached statements are
   closed, with the caveat that the process will still fail if any
   statement is currently flagged as active.
*/
int fsl__db_cached_clear_role(fsl_db * db, fsl_flag32_t role);

/** @internal

    Part of the crosslinking bits: rebuilds the entry for the ticket
    with the given K-card value.
*/
int fsl__ticket_rebuild(fsl_cx * f, char const * zTktId);

/** @internal

    Values for the srctype column of the repo.backlink table, which
    say what kind of artifact a link was found in. Their numeric values
    are shared with fossil(1) and must not change.
*/
enum fsl__bklnk_e {
/** A check-in comment. srcid is the check-in's rid. */
FSL_BKLNK_COMMENT = 0,
/** A ticket change. srcid is the rid of the ticket artifact. */
FSL_BKLNK_TICKET = 1,
/** A wiki page. srcid is the id of its "wiki-NAME" tag. */
FSL_BKLNK_WIKI = 2,
/** A technote. fossil(1) defines this but does not use it. */
FSL_BKLNK_EVENT = 3,
/** A forum post. srcid is the post's rid. */
FSL_BKLNK_FORUM = 4
};

/** @internal

    Markup languages which links can be extracted from, as parsed by
    fsl__backlink_mimetype().
*/
enum fsl__bklnk_mt_e {
/** No mimetype was specified. Treated like FSL_BKLNK_MT_WIKI. */
FSL_BKLNK_MT_NONE = 0,
/** Fossil wiki. */
FSL_BKLNK_MT_WIKI = 1,
/** Markdown. */
FSL_BKLNK_MT_MARKDOWN = 2,
/** Anything else. Nothing is extracted from it. */
FSL_BKLNK_MT_UNKNOWN = 3
};

/** @internal

    Transforms a mimetype string into one of the FSL_BKLNK_MT_xxx
    values. A NULL mimetype is FSL_BKLNK_MT_NONE. Port of fossil(1)'s
    parse_mimetype().
*/
int fsl__backlink_mimetype(char const * zMimetype);

/** @internal

    Callback type for fsl__backlink_scan(). It is called once for each
    hyperlink which targets an artifact, in the order the links appear
    in the text, with the link's target in canonical form: 4 to 64
    lower-case hex digits. If it returns non-0 then scanning stops and
    that code is returned from fsl__backlink_scan().
*/
typedef int (*fsl__backlink_f)(void * state, char const * zTarget);

/** @internal

    Scans zSrc, which must be NUL-terminated, for hyperlinks which look
    like references to artifacts and passes each to cb. The text is
    interpreted per the given FSL_BKLNK_MT_xxx value. If wikiHtml is
    true then, for the wiki mimetype, the text is taken to be HTML
    in which only [target] and [target|label] are interpreted, as for
    fossil(1)'s wiki-use-html setting. This does not touch the
    database. zSrc is not modified.

    Returns 0 on success, FSL_RC_OOM if allocation fails, or the first
    non-0 result of cb.

    Port of the scanning done by fossil(1)'s backlink_extract().
*/
int fsl__backlink_scan(char const * zSrc, int mimetype, bool wikiHtml,
                       fsl__backlink_f cb, void * cbState);

/** @internal

    Scans zSrc as per fsl__backlink_scan() and records each link in
    f's repository's backlink table as coming from the artifact of type
    srcType (one of FSL_BKLNK_xxx) with id srcId, with the time mtime
    (a Julian day). If replace is true then any links already recorded
    for that artifact are removed first, even if zSrc is NULL. Does
    nothing if the repository has no backlink table.

    Returns 0 on success, else a FSL_RC_xxx code with f's error state
    updated.

    Port of fossil(1)'s backlink_extract().
*/
int fsl__backlink_extract(fsl_cx * f, char const * zSrc, int mimetype,
                          fsl_id_t srcId, int srcType, double mtime,
                          bool replace);

/** @internal

    Replaces the links recorded for the wiki page named zWikiTitle with
    those in its latest version. Does nothing if there is no such page.

    Returns 0 on success, else a FSL_RC_xxx code with f's error state
    updated.

    Port of fossil(1)'s backlink_wiki_refresh().
*/
int fsl__backlink_wiki_refresh(fsl_cx * f, char const * zWikiTitle);

/** @internal

    Removes the links recorded for all of the artifacts of the ticket
    whose "tkt-UUID" tag has the id tagId, as the first step of
    recording them anew when the ticket is rebuilt. Does nothing if the
    repository has no backlink table.

    Returns 0 on success, else a FSL_RC_xxx code with f's error state
    updated.
*/
int fsl__backlink_ticket_reset(fsl_cx * f, fsl_id_t tagId);

/** @internal

   Calls all registered crosslink link listeners, passing each the
   given deck. Returns 0 if there are no listeners or if all return 0,
   else it propagates an error from a failed listener.

   This must only be called while crosslinking is underway.

   @see fsl_xlink_listener()
*/
int fsl__call_xlink_listeners(fsl_deck * d);

/** @internal

   Copies symlink zFrom to a new symlink or pseudo-symlink named
   zTo.

   If realLink is true and this is a non-Windows platform,
   symlink zFrom is copied to zTo.

   If realLink is false or this is a Windows platform them...

   - On Windows this has currently undesired, or at least, highly
     arguable, behavior (historical, inherited from fossil(1)), in
     that an empty file named zTo will be created. In fossil(1) this
     function's counterpart is (apparently) never called on Windows,
     so that behavior seems to be moot. It is, however, important that
     this library never call it on Windows.

   - On non-Windows, a pseudo-symlink will be created: the string
     zFrom will be written to a regular file named zTo. That is, the
     file zTo will hold, as its contents, what it would point to if
     it were a symlink.
*/
int fsl__symlink_copy(char const *zFrom, char const *zTo, bool realLink);

/** @internal

   Translates sqliteCode (or, if it's 0, sqlite3_errcode()) to an
   approximate FSL_RC_xxx match but treats SQLITE_ROW and SQLITE_DONE
   as non-errors (result code 0). If non-0 is returned db's error
   state is updated with the current sqlite3_errmsg() string.
*/
int fsl__db_errcode(fsl_db * db, int sqliteCode);

/** @internal

   Plug in fsl_cx-specific db functionality into the given db handle.
   This must only be passed the MAIN db handle for the context,
   immediately after opening that handle, before f->dbMain is
   assigned.

   This function has very limited applicability and various
   preconditions which are assert()ed.
*/
int fsl__cx_init_db(fsl_cx * f, fsl_db * db);

/**
   Undoes what fsl__cx_init_db() did to a borrowed db handle: removes
   f's SQL functions and modules and its "fsl_cx" client data.
*/
void fsl__cx_uninit_db(fsl_cx * const f, fsl_db * const db);

/**
   For a context bound to a host db handle: if the host has rolled
   back a transaction holding libfossil's writes since f last looked,
   clears f's caches, which may hold artifacts and RIDs which no
   longer exist. A host transaction can end without libfossil seeing
   it, and libfossil cannot use the connection's one rollback hook
   without displacing the host's, so libfossil keeps a marker row in
   TEMP.fsl_host_gen instead: TEMP tables roll back with the host's
   transaction. This is a no-op for other contexts. Returns 0 or a db
   error code.
*/
int fsl__cx_host_rollback_check(fsl_cx * const f);

/** @internal

    Attaches the given db file to f with the given role. This function "should"
    be static but we need it in repo.c when creating a new repository.

    This function has tightly-controlled preconditions which will assert
    if not met. r must be one of FSL_DBROLE_CKOUT or FSL_DBROLE_REPO.

    If createIfNotExists is true and zDbName does not exist in the
    filesystem, it is created before/as part of the OPEN or ATTACH. This is
    almost never desired, but is required for operations which create a
    repo (e.g. the aptly-named fsl_repo_create()) or a checkout db
    (e.g. fsl_repo_open_ckout()).
*/
int fsl__cx_attach_role(fsl_cx * f, const char *zDbName,
                        fsl_dbrole_e r, bool createIfNotExists);

/** @internal

    Returns one of f->{repo,ckout}.db or NULL.

    ACHTUNG and REMINDER TO SELF: the current (2021-03) design means
    that none of these handles except for FSL_DBROLE_MAIN actually has
    an sqlite3 db handle assigned to it. This returns a handle to the
    "level of abstraction" we need to keep track of each db's name and
    db-specific other state.

    e.g. passing a role of FSL_DBROLE_CKOUT this does NOT return
    the same thing as fsl_cx_db_ckout().
*/
fsl_db * fsl__cx_db_for_role(fsl_cx * f, fsl_dbrole_e r);

/** @internal

    Frees/clears the non-db state of f->ckout.
*/
void fsl__cx_ckout_clear(fsl_cx * f);


/** @internal
   Register the "files of checkin" (fsl_foci) SQLite3 virtual table.
*/
int fsl__foci_register(fsl_cx * f, fsl_db * db);

/** @internal

    Maximum length of a line in a text file, in bytes. (2**15 = 32k)
*/
#define FSL__LINE_LENGTH_MASK_SZ  15

/** @internal

    Bitmask which, when AND-ed with a number, will result in the
    bottom FSL__LINE_LENGTH_MASK_SZ bits of that number.
*/
#define FSL__LINE_LENGTH_MASK     ((1<<FSL__LINE_LENGTH_MASK_SZ)-1)

/** @internal

    Internal impl of fsl_b_err(), implemented as a macro for
    efficiency's sake.
*/
#define fsl__buffer_err(B) (B)->errCode

//#if FSL_ENABLE_MUTEX
/** @internal

    If the lib is built with FSL_ENABLE_MUTEX, locks the library's
    global non-recursive mutex, which only guards a small amount of
    state. If the lib is not built with FSL_ENABLE_MUTEX, this is a
    no-op.
*/
void fsl__mutex_enter(void);

/** @internal

    If the lib is built with FSL_ENABLE_MUTEX, unlocks the library's
    global non-recursive mutex, else it's a no-op.

    May assert() that fsl__mutex_enter() has been called.
*/
void fsl__mutex_leave(void);

/** @internal

    Returns true if fsl__mutex_enter() is active, else false. Always
    returns true(!) in-single-threaded builds because that's how
    SQLite does it. This is only intended for use in assert() and the
    like - it must not be used for flow control.

    May assert() that fsl__mutex_enter() has been called.
*/
bool fsl__mutex_held(void);
//#else /* !FSL_ENABLE_MUTEX */
//#define fsl__mutex_held(X) ((void)(X),1)
//#define fsl__mutex_enter() (void)0
//#define fsl__mutex_leave() (void)0
//#endif
/** @internal

    Internal helper for parsing manifests and sync protocol lines.
    Holds the (mutable) content of a source file or input line and
    gets parsed and updated by fsl__tokenizer_next().
*/
struct fsl__tokenizer {
  /**
      First char of the next token.
  */
  unsigned char * z;
  /**
      One-past-the-end of the input.
  */
  unsigned char * zEnd;
  /**
      True if z points to the start of a new line.
  */
  bool atEol;
};
typedef struct fsl__tokenizer fsl__tokenizer;
#define fsl__tokenizer_empty_m {NULL,NULL,false}
extern const fsl__tokenizer fsl__tokenizer_empty;

/** @internal

   Returns a pointer to the next space-separated token in pIn. The
   token is zero-terminated.  Return NULL if there are no more tokens
   on the current line, but the call after that will return non-NULL
   unless we have reached the end of the input. If this function
   returns non-NULL then *pLen (which must not be NULL) is set to the
   byte length of the new token. Once the end of the input is reached,
   this function always returns NULL.

   A token is defined as a sequence of a non-whitespace (0x20),
   non-newline (0x0A) bytes. The input is modified, replacing
   spaces and newlines with a NUL.
*/
unsigned char *fsl__tokenizer_next(fsl__tokenizer * pIn,
                                   fsl_size_t * pLen);

enum {
  /**
     Max number of expected tokens in fsl_xfer::line.  This number is
     inherited from fossil(1).
  */
  fsl__xfer_max_tokens = 6
};

/** @internal

   Internal state for an ongoing fsl_sync(). Modelled largely after
   fossil(1)'s xfer.c:Xfer class.
*/
struct fsl_xfer {
  /**
     This object's fossil context. Errors encountered by the channel
     should be sent here using fsl_xfer_error() and friends. A channel's
     impl may use the context for other purposes, e.g. fetching or
     storing channel-specific configuration info like credentials or
     using a db-side cache.

     f must outlive this object.
  */
  fsl_cx * f;

  /**
     The underlying communication channel.
  */
  fsl_sc * ch;

  /**
     The configuration object for a given xfer trip. Its initial state
     represents the initial request parameters and it may get updated
     as the sync progresses.
  */
  fsl_xfer_config * config;

  /**
     Almost all APIs which deal with this class (A) become no-ops if
     this is non-0, returning this value instead, and (B) set their
     result code in this member. This simplifies some internals by
     allowing us to forego explicit error checks when making multiple
     xfer-related calls in a row.
  */
  int rc;

  /** One line of sync protocol input, which we tokenize via
      fsl__xfer_readln() for ease of processing. */
  struct {
    /**
       Holds the current input line. Populated and tokenized by
       fsl__xfer_readln().
    */
    fsl_b b;
    /**
       A raw, untokenized copy of b.
    */
    fsl_b bRaw;
    /** Holds pointers to the individual tokens of b.
        The memory lives in this->b. These are non-const
        only so that we can use fsl_bytes_defossilize()
        on them. */
    unsigned char * aToken[fsl__xfer_max_tokens];
    /**
       Holds the strlen() of each token in aTokens.
    */
    fsl_size_t aTokLen[fsl__xfer_max_tokens];
    /** The number of tokens in use in aToken. */
    uint8_t nToken;
  } line;
  /** Memory buffers */
  struct {
    /**
       When using compressed responses, this is where it will store
       the uncompressed response. We decompress it on behalf of the
       fsl_sc so that those impls don't have to all do this on their
       own.
    */
    fsl_b uresp;
    /** Hashing and UUID-fetching buffer */
    fsl_b hash;
    /** Generic scratchpad buffer */
    fsl_b scratch;
    /** Card payloads */
    fsl_b cardPayload;
  } buf;
  /** Prepared statements */
  struct {
    fsl_stmt igotInsert;
    fsl_stmt igotHasRid;
    fsl_stmt gimmeInsert;
    //fsl_stmt gimmeDelete;
    fsl_stmt remoteUnkUuid;
  } q;
  /** Various flags. */
  /* TODO: move some of this into fsl_xfer_config. */
  struct {
    unsigned configRcvMask;
    unsigned configSendMask;
    /** True once a reqconfig card has been queued, so that we ask
        exactly once and know not to end a clone before asking. */
    bool configReqSent;
    char const *zAltPCode;
    /** True to enable syncing private content */
    bool syncPrivate;
    /** If true, next "file" received is a private artifact. */
    bool nextIsPrivate;
    /** True if the current error came from the contents of a reply
        (an error card, a card that could not be handled, or a body
        that did not match its headers) rather than from local storage
        or memory. fsl__xfer_client_run() records the first such error
        in replyErr and goes on (or, in the first clone reply, ignores
        it), and this is set again if the session ends with a reply
        error. fsl_sync_client() then keeps what was received. */
    bool peerError;
    /** True if the current error must end the session and keep
        nothing received, e.g. a received file or cfile which did not
        match its hash (sync draft section 10.1). Never a peerError. */
    bool fatalError;
    /** True if fsl_sync_client() opened the outermost transaction,
        i.e. its caller had none open. Only then can a round give
        the write lock back during the exchange. */
    bool ownsTxn;
  } flag;
  /** RIDs gimme'd in the pending request, so that
      fsl__xfer_request_phantoms() does not ask twice. */
  fsl_id_bag gimmePending;
  /** RIDs of private artifacts the peer asked for, without private
      sync in effect, to be answered with "igot HASH 1" in the next
      request (sync draft section 8.6). */
  fsl_id_bag privateIgot;
  /** RIDs from the unsent table which the pending request pushes.
      Their unsent rows are deleted in the transaction which
      processes the reply, so that a failed exchange leaves them
      queued. */
  fsl_id_bag unsentPending;
  /** RIDs crosslinked so far by fsl__xfer_crosslink_rcvd(). */
  fsl_id_bag xlinked;
  /** The first reply error (see flag.peerError) of a sync session,
      which becomes the session's result unless a fatal or local
      error ends the session first. */
  fsl_error replyErr;
  /** Info about the remote. */
  struct {
    int releaseVersion;
    int manifestDate;
    int manifestTime;
    /** Seconds of offset from localhost. */
    int clockSkewSeen;
    /* Reminder to self: calculating the clock skew currently requires
       parsing a comment line from the sync protocol. TODO is add a
       pragma to simplify that on the remote end. */
  } remote;
  struct {
    int number;
    int date;
    int time;
    /**
       Tells us whether the remote project-code matches this one.
       If not, some operations won't work (like logging in - that
       only works when project codes match because the project code
       is part of the password hash).

       Values: <0=unknown, 0=mismatch, >0=match.
    */
    short projCodeMatch;
  } clientVersion;
  struct {
    int protocolVersion;
    fsl_size_t seqNo;
    /** True if the most recent reply held a well-formed push card.
        A modern (protocol 2+) clone asks for more only if it did
        (sync draft section 8.2). */
    bool pushSeen;
  } clone;
  /**
     Info about the user which is relevant for sync.
  */
  struct {
    /**
       User name memory owned by fsl_xfer::url.
    */
    char const * name;
    /**
       Password memory owned by fsl_xfer::url.
    */
    char const * password;
    /**
       Password memory owned by this object. Gets extracted from the
       repo.user table if no password is otherwise provided.
    */
    char * passwordToFree;

    /**
       Permissions calculated for the current user from sync login
       info.
    */
    fsl_uperm perm;
  } user;
  /**
     When using compressed responses, we need a layer of buffer to do
     the decompression. This object, if populated, is a _partial_
     fsl_sc implementation which buffers the whole uncompressed
     response and only supports reading.
  */
  fsl_sc chz;
  /** Various counters. */
  fsl_xfer_metrics n;

  struct {
    /**
       Hash of all request payload content, for generating the sync
       login card.
    */
    fsl_sha1_cx sha1;
    fsl_b loginCard;
    /**
       Number of bytes submitted for the request body, before any
       compression.
    */
    fsl_size_t nBytes;
    /**
       For a compressed request (FSL_SC_F_COMPRESSED): the body being
       built. It is compressed and handed to the channel only when the
       request is complete, because the compressed container leads with
       the uncompressed length and Content-Length must give the
       compressed one (draft-fossil-sync-protocol-00 section 4.1).
    */
    fsl_b body;
  } request;

  struct {
    int httpVersion;
    int httpCode;
  } response;
#if 0
  /* From fossil(1) xfer.c:Xfer struct: */
  fsl_size_t mxSend;         /* Stop sending "file" when pOut reaches this size */
  int resync;         /* Send igot cards for all holdings */
  uint32_t remoteVersion;  /* Version of fossil running on the other side */
  uint32_t remoteDate;     /* Date for specific client software edition */
  uint32_t remoteTime;     /* Time of date correspoding on remoteDate */
  fsl_time_t maxTime;     /* Time when this transfer should be finished */
#endif
};
/** Empty-initialized fsl_xfer instance, intended for copy
    initialization. */
extern const fsl_xfer fsl_xfer_empty;

/** @internal

   Initializes xf's core-most state. Defined, and documented, in
   xfer.c.
*/
int fsl__xfer_setup(fsl_cx * const f, fsl_xfer * const xf,
                    fsl_xfer_config * xc, fsl_sc * const channel);

/** @internal

   Create a child process running command "zCmd". *pfdIn gets
   assigned to the stdout from the child process. If zStdinFile is
   not NULL the child reads its stdin from that file and *ppOut is
   set to NULL; otherwise *ppOut is a FILE which becomes the child's
   stdin. On Unix zCmd runs through /bin/sh; on Windows it runs
   directly as a command line, without a shell. *pChildPid gets the
   child's id for fsl__pclose2().

   On success the values returned via *pfdIn, *ppOut, and *pChildPid
   must be passed to fsl__pclose2() to properly clean up.

   Return 0 on success, non-0 on error.

   @internal
*/
int fsl__popen2(const char *zCmd, const char *zStdinFile,
                int *pfdIn, FILE **ppOut, int *pChildPid);

/** @internal

   Close the connection to a child process previously created using
   fsl__popen2(). All 3 arguments are assumed to values returned via
   fsl__popen2()'s output parameters: the input file descriptor,
   output FILE handle, and child process PID.

   Blocks until the child exits. Returns the child's exit status, or
   (on Unix) the negated number of the signal which ended it, or 0 if
   its status cannot be determined.
*/
int fsl__pclose2(int fdIn, FILE *pOut, int childPid);


/** @internal

   Hash value for fsl_xfcard card name hashing.

   This algo historically uses 32-bit hashes because the values
   (generated at build-time) were used in switch/case contexts, where
   64-bit values are not portable.

   @internal
*/
typedef uint32_t fsl_xfcard_hash_t;

/** @internal

   Objects for mapping known sync cards to their fsl_xfcard_e and
   hash of their name.
*/
struct fsl_xfcard {
  /** Card type ID. */
  const fsl_xfcard_e type;
  /** The protocol-level name of this card, e.g. "file" or "cfile". */
  char const * const name;
  /** A hash unique (in the context of fsl_xfcard) to this->name.
      Not const: fsl__xfcard_search() computes it on first use. */
  fsl_xfcard_hash_t hash;
};
typedef struct fsl_xfcard fsl_xfcard;

/** @internal

   Searches for a sync card with the given name. Returns a
   static/const instance of one on success, else NULL. This is a
   binary search ordered on the card names' hashes, so is fairly fast:
   hash z, binary search on that hash, and one fsl_strcmp() on a
   match.  The hash algo bails early if z is not shaped like a card
   name.

   Design note: this takes an unsigned string because its argument is
   invariably from fsl_xfer::line::aToken.
*/
fsl_xfcard const *fsl__xfcard_search(unsigned char const *z);
/** Non-unsigned-qualified C-string convenience form of fsl__xfcard_search(). */
#define fsl__xfcard_searchNU(WORD) fsl__xfcard_search((unsigned const char *)(WORD))

/** @internal

   An fgets() workalike which uses an unbuffered file descriptor for
   reading.

   Scans the input 1 byte at a time for a '\n', appending each read
   character to pOut, including the '\n' and a trailing NUL, up to a
   maximum of nOut-1 (to account for the NUL). If it hits EOF before
   finding a \n, that is not treated as an error, and downstream code
   may need to special-case that.

   On success it returns 0, sets *ppOut to pOut, and *pnOut to the
   number of bytes filled out in pOut. On error, returns FSL_RC_IO on
   read error or FSL_RC_RANGE if no newline is found before nOut bytes
   are read.

   If called when fdIn is at EOF, it will return 0 but set *pnOut to
   0.

   On error it will return either FSL_RC_RANGE (if it finds now
   newline before nOut bytes) or propagate an error from the read()
   call, in the form of another non-0 fsl_rc_e value.
*/
int fsl__fdgets(int fdIn, unsigned char * pOut, fsl_size_t nOut,
                char **ppOut, fsl_size_t * pnOut);

/** @internal

   fsl_file_tempname() proxy which uses fsl_temp_dirs_get() to get the
   target dir. zBaseName may be NULL but library routines are strongly
   enouraged to use a of "libfossil-PURPOSE", where PURPOSE is a
   descrtive identifier, e.g. "PopenRequest" or "popen-request".
*/
int fsl__tmpfile( fsl_b * tgt, char const * zBaseName );

/**
   If FSL_PLATFORM_IS_UNIX then this returns the result of chmod(2)
   for the given file name, converted from errno using
   fsl_errno_to_rc(). It uses permissions 0600.

   On other platforms this is a no-op and returns 0.
*/
int fsl__tmpchmod( char const * z );

// Potential TODO
//int fsl__tmpfile_open( char const * zBaseName, FILE **fOut );

/** @internal

   Searches the OS path zPath for a binary named zBinName. If found,
   it puts a library-allocated copy of the resolved name to *zOut
   (which the caller must eventually pass to fsl_free()) then returns
   0.

   If zPath is NULL, getenv("PATH") is used.

   On error, *zOut is not modified and non-0 is returned:

   - FSL_RC_NOT_FOUND if no match is found. This will also be returned
     if both zPath and $PATH are NULL.

   - FSL_RC_OOM on allocation error.

   On Windows platforms it will extend the search to include a ".exe"
   extension.
*/
int fsl__find_bin( char const *zPath, char const *zBinName, char **zOut );

/**
   If d->P.used then this makes d->P.list[0] a delta from d->rid, else
   this is a no-op. Returns non-0 if fetching the parent RID or
   deltification fail. Returns 0 if there's nothing to do or if what
   needs doing gets done.
*/
int fsl__deck_deltify_parent(fsl_deck * d);

/**
   Imports content to f's opened repository's BLOB table using a
   client-provided input source. f must have an opened repository
   db. inFunc is the source of the data and inState is the first
   argument passed to inFunc(). If inFunc() succeeds in fetching all
   data (i.e. if it always returns 0 when called by this function)
   then that data is inserted into the blob table _if_ no existing
   record with the same hash is already in the table. If such a record
   exists, it is assumed that the content is identical and this
   function has no side-effects vis-a-vis the db in that case.

   If rid is not NULL then the BLOB.RID record value (possibly of an
   older record!) is stored in *rid.  If uuid is not NULL then the
   BLOB.UUID record value is stored in *uuid and the caller takes
   ownership of those bytes, which must eventually be passed to
   fsl_free() to release them.

   rid and uuid are only modified on success and only if they are
   not NULL.

   Returns 0 on success, non-0 on error. For errors other than basic
   argument validation and OOM conditions, f's error state is
   updated with a description of the problem. Returns FSL_RC_MISUSE
   if either f or inFunc are NULL. Whether or not inState may be
   NULL depends on inFunc's concrete implementation.

   Be aware that BLOB.RID values can (but do not necessarily) change
   in the life of a repod db (via a reconstruct, a full re-clone, or
   similar, or simply when referring to different clones of the same
   repo). Thus clients should always store the full UUID, as opposed
   to the RID, for later reference. RIDs should, in general, be
   treated as session-transient values. That said, for purposes of
   linking tables in the db, the RID is used exclusively (clients are
   free to link their own extension tables using UUIDs, but doing so
   has a performance penalty comared to RIDs). For long-term storage
   of external links, and to guaranty that the data be usable with
   other copies of the same repo, the UUID is required.

   Note that Fossil may deltify, compress, or otherwise modify
   content on its way into the blob table, and it may even modify
   content long after its insertion (e.g. to make it a delta against
   a newer version). Thus clients should normally never try
   to read back the blob directly from the database, but should
   instead read it using fsl_content_get().

   That said: this routine has no way of associating and older version
   (if any) of the same content with this newly-imported version, and
   therefore cannot delta-compress the older version.

   Maintenance reminder: this is basically just a glorified form of
   the internal fsl__content_put(). Interestingly, fsl__content_put()
   always sets content to public (by default - the f object may
   override that later). It is not yet clear whether this routine
   needs to have a flag to set the blob private or not. Generally
   speaking, privacy is applied to fossil artifacts, as opposed to
   content blobs.

   @see fsl__repo_import_buffer()
*/
int fsl__repo_import_blob( fsl_cx * f, fsl_input_f inFunc,
                          void * inState, fsl_id_t * rid,
                          fsl_uuid_str * uuid );

/**
   A convenience form of fsl__repo_import_blob(), equivalent to:

   ```
   fsl__repo_import_blob(f, fsl_input_f_buffer, bIn, rid, uuid )
   ```

   except that (A) bIn is const in this call and non-const in the
   other form (due to cursor traversal requirements) and (B) it
   returns FSL_RC_MISUSE if bIn is NULL.
*/
int fsl__repo_import_buffer( fsl_cx * f, fsl_b const * bIn,
                            fsl_id_t * rid, fsl_uuid_str * uuid );

enum fsl__cx_stmt_e {
#define E(NAME,IGNORED) fsl__cx_stmt_e_ ## NAME,
  fsl__cx_cache_stmt_map(E)
#undef E
};

/**
   Returns the given cached statement object, preparing it if needed.
   If preparation fails then NULL is returned and f->error will
   hold the details.

   This function MUST NOT be used in routines may, perhaps indirectly,
   recurse. That is, the returned statement WILL misbehave if served
   twice by this function without an intervening fsl__cx_stmt_yield()
   between them.

   If this returns non-NULL then the caller is obligated to pass the
   same q object to fsl__cx_stmt_yield().
*/
fsl_stmt * fsl__cx_stmt(fsl_cx * f, enum fsl__cx_stmt_e which);

/**
   Must be passed all statement pointers obtained via fsl__cx_stmt().
   It MUST NOT be passed any statement from elsewhere except that
   q==NULL is permitted to simplify its usage. This resets the
   statement and clears any bindings.

   Callers must treat q as if this function finalizes it, i.e. they
   must not derefence any members or pass it to another API after
   this. It can only be legally used again after fetching it from
   fsl__cx_stmt().
*/
void fsl__cx_stmt_yield(fsl_cx * f, fsl_stmt * q);

/**
   Steps q for a row-iteration loop. If *rc is non-zero, returns false
   without stepping. On a row, returns true. On completion, returns
   false. On a step error, uplifts q's database error to f, stores the
   result in *rc, and returns false.
*/
static inline bool fsl__cx_stmt_step_each(fsl_cx * f, fsl_stmt * q,
                                          int *rc){
  int stepRc;
  if( *rc ) return false;
  stepRc = fsl_stmt_step(q);
  if( FSL_RC_STEP_ROW==stepRc ) return true;
  if( FSL_RC_STEP_DONE!=stepRc ){
    *rc = fsl_cx_uplift_db_error2(f, q->db, stepRc);
  }
  return false;
}

/**
    Clears various internal caches and resets various
    internally-cached values related to repository and checkout
    dbs. Its argument must be true if we're clearing caches as a
    result of a transaction commit, else false (i.e. a rollback is in
    process).
*/
void fsl__cx_caches_reset(fsl_cx * f, bool isTxnCommit);

/**
   May clear or reset cached data. This is intended to be called as
   part of a transaction commit/rollback hook and be passed true for a
   commit and false for a rollback.
*/
void fsl__cx_reset_for_txn(fsl_cx * f, bool isCommit);

/**
   Clears only caches which are relevant to content lookup.
*/
void fsl__cx_content_caches_clear(fsl_cx * f);

/**
   Clears the contents of f->cache.mcache.
*/
void fsl__cx_mcache_clear(fsl_cx * f);

/**
   An experiment.

   Runs BODY ( a {...} block) in the context of a fsl_cx savepoint.
   The body is expected to assign int-type RcVar to 0 on success and
   false on error. If RcVar is 0 when this is invoked, BODY is not
   run.  If BODY succeeds, the savepoint is saved if KeepSPOnSuccess
   is true, else it is silently discarded. If RollbackTopOnError is
   true then any outer savepoint is put into a persistent rollback
   state, else any outer savepoint is unaffected. If BODY succeeds but
   the commit/rollback fails, RcVar is set to that failure code.
*/
#define fsl__cx_txn(FslCx, RcVar, RollbackTopOnError, KeepSPOnSuccess, BODY) { \
    RcVar = fsl_cx_txn_begin(FslCx);                                \
    if( 0==RcVar ){                                                 \
      BODY                                                          \
    }                                                               \
    int const RcVar ## __ =                                         \
      fsl_cx_txn_end_v2((FslCx), (0==RcVar) && (KeepSPOnSuccess),   \
                        ((RollbackTopOnError) && (0!=RcVar)));      \
    if( !RcVar ) RcVar = RcVar ## __;                               \
  }

/**
   fsl__cx_txn() proxy for use with local savepoints which should not
   trigger a global savepoint rollback on error.
*/
#define fsl__cx_txn_local(FslCx, RcVar, KeepSPOnSuccess, BODY) \
    fsl__cx_txn(FslCx, RcVar, 0, KeepSPOnSuccess, BODY)

/**
   fsl__cx_txn() proxy for use with local savepoints which should
   trigger a global savepoint rollback on error.
*/
#define fsl__cx_txn_global(FslCx, RcVar, KeepSPOnSuccess, BODY) \
    fsl__cx_txn(FslCx, RcVar, 1, KeepSPOnSuccess, BODY)

void fsl__id_bag_dump(fsl_id_bag const * src, FILE *to/*NULL==stdout*/,
                      char const *zHeader);

/* fsl__ptl details are in cache.c */
int fsl__ptl_init(fsl__ptl * c, uint16_t prealloc);
void fsl__ptl_clear(fsl__ptl * c);
bool fsl__ptl_has(fsl__ptl const * c, fsl__ptl_e where, fsl_id_t rid);
int fsl__ptl_insert(fsl__ptl * c, fsl__ptl_e where, fsl_id_t rid);
bool fsl__ptl_remove(fsl__ptl const * c, fsl__ptl_e where, fsl_id_t rid);

/**
   Can fail with OOM if isCommit and f->cache.ptl.level>0.
*/
int fsl__cx_ptl_pop(fsl_cx * f, bool isCommit);
int fsl__cx_ptl_push(fsl_cx * f);
/**
   Returns the given bag for the current transaction level.  Never
   returns NULL unless "which" is invalid, in which case it prefers to
   fail fatally.
*/
fsl_id_bag * fsl__cx_ptl_bag(fsl_cx *f, fsl__ptl_e which);
/**
   Removes rid from the given PTL list.
*/
bool fsl__cx_ptl_remove(fsl_cx * f, fsl__ptl_e where, fsl_id_t rid);
#define fsl__cx_ptl_has(F,W,R) fsl__ptl_has(&(F)->cache.ptl, W, R)
#define fsl__cx_ptl_insert(F,W,R) fsl__ptl_insert(&(F)->cache.ptl, W, R)

/**
   Works like the public fsl_cx_b_borrow() but if honorErrorState
   is false then it will attempt to retrieve or allocate a buffer even
   if f->error is flagged as having an allocation error.
*/
fsl_b * fsl__cx_buffer_borrow(fsl_cx *f, bool honorErrorState);

/**
   Sets *rid to f->db.ckout.rid, fetching the latter if
   needed. Returns non-0 if fetching fails.
*/
int fsl__ckout_rid(fsl_cx * f, fsl_id_t *rid);

/**
   Passed dest to fsl_xfer_config_cleanup() then bitwise copies src to
   dest and rewires some memory to avoid duplicate frees and the like:

   dest->url points to src->url's memory, but as an "external"
   buffer. src must outlive dest.

   dest->debug.b is zeroed out.

   This is intended for making call-local copies.
*/
void fsl__xfer_config_almost_copy(fsl_xfer_config const *src,
                                  fsl_xfer_config *dest);


/**
   Functionally identical to fsl_deck_B_set() except that it sets
   the R-card. Returns 0 on succes, FSL_RC_SYNTAX if md5 is neither
   NULL nor exactly FSL_STRLEN_MD5 hexadecimal digits (not including
   trailing NUL). If md5==NULL the current R value is cleared.

   It would be highly unusual to have to set the R-card manually,
   as its calculation is quite intricate/intensive. See
   fsl_deck_R_calc() and fsl_deck_unshuffle() for details
*/
int fsl__deck_R_set( fsl_deck * mf, char const *md5);

#if !defined(NDEBUG)
/**
   A place to put a breakpoint to help trace down errors. Pass it the
   rc of a just-failed operation and set a breakpoint in the if(rc)
   block of this function in fsl.c. Returns its argument.
*/
int fsl__bprc(int rc);
#else
#define fsl__bprc(X) (X)
#endif

/** @internal

   The fsl__cfs_xxx() functions are the checkout code's file
   operations. Each does the same as the public function it is named
   after, through f's checkout file storage (fsl_cx_ckout_fs()), which
   is fsl_ckout_fs_os, the filesystem, unless another is installed.

   - fsl__cfs_stat(): fsl_stat()
   - fsl__cfs_size(): fsl_file_size()
   - fsl__cfs_mtime(): fsl_file_mtime()
   - fsl__cfs_is_file(): fsl_is_file()
   - fsl__cfs_is_file_or_link(): fsl_is_file_or_link()
   - fsl__cfs_is_symlink(): fsl_is_symlink(); always false for a
     storage with no symlinks
   - fsl__cfs_isexec(): fsl_file_isexec()
   - fsl__cfs_dir_check(): fsl_dir_check()
   - fsl__cfs_dir_is_empty(): fsl_dir_is_empty()
   - fsl__cfs_read(): fsl_b_fill_from_filename()
   - fsl__cfs_write(): fsl_b_to_filename()
   - fsl__cfs_unlink(): fsl_file_unlink()
   - fsl__cfs_rename(): fsl_file_rename()
   - fsl__cfs_rmdir(): fsl_rmdir()
   - fsl__cfs_mkdir_for_file(): fsl_mkdir_for_file()
   - fsl__cfs_exec_set(): fsl_file_exec_set()
   - fsl__cfs_mtime_set(): fsl_file_mtime_set()
   - fsl__cfs_copy(): fsl_file_copy()
   - fsl__cfs_sha1sum(): fsl_sha1sum_filename()
   - fsl__cfs_sha3sum(): fsl_sha3sum_filename()
   - fsl__cfs_dircrawl(): fsl_dircrawl()
   - fsl__cfs_symlink_read(): fsl_symlink_read(); for a storage with
     no symlinks, reads the file holding the link's target
   - fsl__cfs_symlink_create(): fsl_symlink_create(); for a storage
     with no symlinks, realLink is ignored and the target is written
     as a file
   - fsl__cfs_symlink_copy(): fsl_symlink_copy(), likewise

   And one with no fs.c counterpart:

   - fsl__cfs_write_blob(): writes blob rid's content to file zName
     through the storage's xWriteBlob() if it has one, else does what
     the checkout code did before it existed: fsl_content_get() into
     *content (skipped if loaded is true: content already holds the
     blob), then fsl__cfs_write(). content is the caller's scratch
     buffer, which holds the blob afterwards only in the second case
     (content->used is 0 otherwise, if it was on entry). If
     pWriteFailed is not NULL, it is set to whether a failure came
     from the write (xWriteBlob() or xWrite()) rather than from
     fsl_content_get(), whose error state is set by it: the caller
     adds context to a write failure, as it did around
     fsl__cfs_write(). Creating the directory, the executable bit and
     mtime stay the caller's, as around fsl__cfs_write().
*/

/** @internal

   The libfossil contexts (fsl_cx) using one db connection: a host's
   connection (fsl_cx_host_db()) can carry several, and a connection
   of the library's own has exactly one. It is the connection's
   "fsl_cxreg" client data, which owns it. The SQL functions which need
   a context get it from here (fsl__cx_for_dbh()), as no function can
   be told about more than one.
*/
typedef struct fsl__cxreg fsl__cxreg;
struct fsl__cxreg {
  /**
     The context whose statement is being stepped, set around each
     sqlite3_step() by the fsl_db functions on a shared connection,
     or NULL outside of them.
  */
  fsl_cx * cur;
  /**
     The context the host's own SQL gets (fsl__cx_for_dbh()) when no
     library statement is stepping, if set (fsl__cxreg_default_set()),
     else the first to join.
  */
  fsl_cx * dflt;
  /** The contexts, in the order they joined. */
  fsl_cx ** a;
  unsigned n;
  unsigned cap;
  /** The id given to the last context to join. Ids start at 1. */
  unsigned lastId;
  /**
     The main dbs of the contexts which own the connection's open
     savepoints, innermost last. RELEASE and ROLLBACK TO also end the
     savepoints opened after the one they name, so a context may only
     end a transaction level of its own when no other context's
     savepoint is inside it (see fsl_db_txn_end_v2()).
  */
  fsl_db ** sp;
  unsigned nSp;
  unsigned capSp;
};

/** @internal

   Adds f to the registry of db's connection, creating it if needed,
   and records the registry, f and f's new id in db->impl.share. Sets
   *pFirst to true if f is the connection's only context. Returns 0
   or FSL_RC_OOM.
*/
int fsl__cxreg_join(fsl_cx * const f, fsl_db * const db, bool * pFirst);

/** @internal

   False if another context sharing db's (host's) connection owns a
   savepoint inside db's innermost one, which ending db's would end
   too (see fsl__cxreg::sp), else true.
*/
bool fsl__db_txn_is_innermost(fsl_db const * const db);

/** @internal

   Forgets db's open transaction levels without ending them, for a
   context closing while fsl__db_txn_is_innermost() is false. Its
   savepoints stay open in the host's transaction, which the host
   ends.
*/
void fsl__db_txn_abandon(fsl_db * const db);

/** @internal

   Removes db's context from its connection's registry and clears
   db->impl.share's registry fields. Returns the number of contexts
   left. If none are, the registry is freed and the connection's
   client data cleared.
*/
unsigned fsl__cxreg_leave(fsl_db * const db);

/** @internal

   Returns the context for a SQL function running on connection dbh:
   the one whose statement is stepping, else the default
   (fsl__cxreg_default_set()), else the first to join, else NULL if
   none has.
*/
fsl_cx * fsl__cx_for_dbh(sqlite3 * dbh);

/** @internal

   Makes f, which must be one of dbh's contexts, the one the host's own
   SQL on dbh gets from the SQL functions, e.g. for the SQL extension's
   fsl_use(). NULL, or a context not on dbh, restores the first to
   join. A no-op if dbh has no registry.
*/
void fsl__cxreg_default_set(sqlite3 * dbh, fsl_cx * f);

/** @internal

   Returns the name of role r's schema on db's connection, e.g. "repo"
   in "SELECT ... FROM repo.blob". This is where a role's schema name
   comes from, for SQL text (via the {{dbname.repo}} and
   {{dbname.ckout}} placeholders, which the fsl_db SQL functions and
   fsl_cx_format() expand) and for sqlite3 calls taking a schema name.
   That is fsl_db_role_name(r) unless db's context shares a connection
   with another one, which gets names of its own (e.g. "repo_2"), or
   "main" while the role's tables are prefixed tables of the host's
   main db (fsl__db_ckout_prefix(), fsl__db_repo_prefix()), whose names
   then need that prefix too (fsl__db_table_name()).
*/
char const * fsl__db_schema(fsl_db const * const db, fsl_dbrole_e r);

/** @internal

   Appends the expansion of placeholder token zTok (n bytes, the X of
   {{X}}) for db to b: "dbname.repo" and "dbname.ckout" become the
   schema names (fsl__db_schema()), and "temp.NAME" becomes the TEMP
   table NAME of db's context, "temp.NAME" for a connection's first
   context and "temp.fslN_NAME" for its Nth, and "bare.temp.NAME" that
   name without its schema, for e.g. CREATE INDEX's ON clause.
   "bare.ckout.NAME" becomes the checkout table NAME without its
   schema, for the same uses: NAME, or "PNAME" (quoted) while db's
   checkout tables are prefixed with P (fsl__db_ckout_prefix()).
   "bare.repo.NAME" does the same for a repository table
   (fsl__db_repo_prefix()).

   zTail, if not NULL, is the NUL-terminated text after the token's
   closing braces, and *pnConsumed (which must then not be NULL
   either) gets the number of bytes of it which this call expanded
   along with the token, 0 unless noted. While db's checkout tables are
   prefixed, "dbname.ckout" must be followed by ".IDENT", where IDENT
   is a table (or index or trigger) name of [A-Za-z0-9_] characters:
   the whole of "{{dbname.ckout}}.IDENT" becomes main."PIDENT" and
   *pnConsumed is the length of ".IDENT". Without such a tail, or with
   a NULL zTail, the token is then refused with FSL_RC_MISUSE, so that
   no SQL names a checkout table which the prefix would miss. The same
   holds for "dbname.repo" while db's repository tables are prefixed.
   Without a prefix, the token's expansion is the schema name alone,
   as for the other tokens.

   db may be NULL, for the defaults. Returns FSL_RC_NOT_FOUND for any
   other token.
*/
int fsl__db_schema_token(fsl_db const * const db, char const * zTok,
                         fsl_size_t n, char const * zTail,
                         fsl_size_t * pnConsumed, fsl_b * const b);

/** @internal

   For fsl_repo_open_ckout() with a
   fsl_repo_open_ckout_opt::hostTablePrefix: makes the tables of f's
   host's main db whose names start with zPrefix f's checkout db,
   instead of ATTACHing one. f must have a repository opened on a host
   db handle, whose main db must be a file, and zPrefix must match
   [A-Za-z_][A-Za-z0-9_]* and not be another context's on that handle.
   The checkout fsl_db then has the name "main" and the main db's file
   name. Creates no tables. Returns 0 or an error code, with f's error
   state set.
*/
int fsl__cx_attach_ckout_prefixed(fsl_cx * const f, char const * zPrefix);

/** @internal

   The checks of fsl__cx_attach_ckout_prefixed() on f and zPrefix,
   without attaching anything: f has a repository on a host db handle
   whose main db is a file, and zPrefix is a valid prefix which does
   not overlap (one being the start of the other, ignoring case)
   another context's on that handle. Returns 0 or an error code, with
   f's error state set.
*/
int fsl__cx_ckout_prefix_check(fsl_cx * const f, char const * zPrefix);

/** @internal

   For fsl_repo_open_host() and fsl_repo_create() resp.
   fsl_repo_import() with a table prefix: makes the tables of the main
   db of f's host db handle whose names start with zPrefix f's
   repository db, instead of ATTACHing a file. f must be bound to a
   host db handle (fsl_cx_host_db()), whose main db must be a file, and
   have no repository opened; if it has a checkout opened (as for
   fsl_ckout_open_dir() of a checkout of such a repository), that
   becomes the repository's counterpart, else the repository becomes
   f's main db. zPrefix must match [A-Za-z_][A-Za-z0-9_]*, not start
   with "sqlite_", and overlap (one being the start of the other,
   ignoring case) neither another prefix of a context on that handle
   nor the SQLite extension's working copies' "fslfiles_", "fslclock_"
   and "fslwc_". The repository fsl_db then has the name "main" and
   the main db's file name. Checks no tables and creates none (see
   fsl__host_prefix_recorded_check()). Returns 0 or an error code,
   with f's error state set.
*/
int fsl__cx_attach_repo_prefixed(fsl_cx * const f, char const * zPrefix);

/** @internal

   The checks of fsl__cx_attach_repo_prefixed() on zPrefix, on dbM,
   f's main db or a fsl_db on the host's handle it is to use: zPrefix
   is a valid prefix which overlaps no other of a context on that
   handle, nor the names of the SQLite extension's working copies,
   which are tables fslfiles_NAME and fslclock_NAME beside checkout
   tables prefixed with fslwc_NAME_, and which
   fsl__host_prefix_recorded_check() does not see. Returns 0 or an
   error code, with f's error state set.
*/
int fsl__cx_repo_prefix_check(fsl_cx * const f, fsl_db * const dbM,
                              char const * zPrefix);

/** @internal

   Refuses zPre as a table prefix for role r (FSL_DBROLE_REPO or
   FSL_DBROLE_CKOUT) in the main db of db's connection if it and the
   prefix P of a repository or working copy recorded there, other than
   one of role r with prefix zPre itself, are leading parts of one
   another, ignoring case (FSL_RC_ALREADY_EXISTS). A recorded working
   copy is a P for which main has tables Pvvar, with a 'ckout-root'
   row, and Pvfile; a recorded repository one for which it has tables
   Pblob and Pconfig, with a 'content-schema' row. Some tables of each
   are created as they are first used (the stash's and undo's, the
   forum's), so a recorded prefix stands for its whole namespace.
   Returns 0 or an error code, with f's error state set.
*/
int fsl__host_prefix_recorded_check(fsl_cx * const f, fsl_db * const db,
                                    fsl_dbrole_e r, char const * zPre);

/** @internal

   True if f's newly opened repository has the tables which fossil(1)'s
   db_looks_like_a_repository() requires, with their prefix if they
   are tables of a host's main db (fsl__db_repo_prefix()). Clears any
   db-level error state the check leaves behind.
*/
bool fsl__repo_looks_valid(fsl_cx * const f);

/** @internal

   What a checkout of a repository which is tables of a host's main db
   (fsl_repo_open_host()) records as its repository (its vvar
   "repository" entry), followed by their prefix. It is not an absolute
   file name, so it is never one which libfossil or fossil(1) records
   for a repository db file, which they record canonically.
*/
#define FSL__REPO_HOST_REF "fsl-host-prefix:"

/** @internal

   The name a checkout records for f's opened repository (its vvar
   "repository" entry): its db's file name, or FSL__REPO_HOST_REF and
   its table prefix if it is tables of a host's main db. Returns a
   string for the caller to fsl_free(), or NULL on OOM, with f's error
   state set.
*/
char * fsl__cx_repo_ref(fsl_cx * const f);

/** @internal

   Updates f's cached state after a repository, or a checkout and its
   repository, was opened: the checkout's version, the glob lists, the
   user name. Returns 0 or an error code.
*/
int fsl__cx_after_open(fsl_cx * const f);

/** @internal

   Detaches (or, for prefixed checkout tables, just forgets) f's
   checkout, which must be opened alongside its repository, leaving the
   repository opened.
*/
int fsl__cx_detach_ckout(fsl_cx * const f);

/** @internal

   Sets PRAGMA synchronous=FULL on f's repository db, for a check-in's
   atomic commit of the repository and checkout dbs. SQLite refuses
   that inside a transaction. Returns 0 or an error code, with f's
   error state set.
*/
int fsl__cx_repo_sync_full(fsl_cx * const f);

/** @internal

   Takes the write lock of db's main db for the transaction which must
   be open on it (e.g. by fsl_db_txn_begin()), as BEGIN IMMEDIATE
   would, without locking the other attached dbs, and without changing
   anything. Returns 0 or the db error code (e.g. FSL_RC_LOCKED if
   another connection holds it).
*/
int fsl__db_main_write_lock(fsl_db * const db);

/** @internal

   Replaces the absolute file name in b with the same file's name with
   symbolic links resolved, as realpath() does: the whole name's if the
   file exists, else its directory part's, so that a file which does
   not exist yet, e.g. a db's -wal file, compares equal however its
   directory is spelled. Leaves b as it is if neither can be resolved
   (and on Windows, where it does nothing). Returns 0 or FSL_RC_OOM.
*/
int fsl__file_realpath(fsl_b * const b);

/** @internal

   The prefix of the names of db's checkout tables while they are
   tables of the host's main db (fsl_repo_open_ckout_opt::hostTablePrefix),
   else NULL.
*/
char const * fsl__db_ckout_prefix(fsl_db const * const db);

/** @internal

   The prefix of the names of db's repository tables while they are
   tables of the host's main db (fsl_repo_open_host()), else NULL.
*/
char const * fsl__db_repo_prefix(fsl_db const * const db);

/** @internal

   Appends the name of table zTable of role r (FSL_DBROLE_REPO or
   FSL_DBROLE_CKOUT) of db's connection to b. If qualified is true it
   is SQL which names the table: schema.zTable, as
   {{dbname.repo}}.zTable resp. {{dbname.ckout}}.zTable expand,
   including main."PzTable" for prefixed repository or checkout tables
   (fsl__db_repo_prefix(), fsl__db_ckout_prefix()). Else it is the
   table's bare name, unquoted, for APIs which take a table's name as
   a value, e.g. sqlite3_table_column_metadata() or PRAGMA
   table_info(%Q): zTable, or PzTable for prefixed tables. zTable may also name an
   index or trigger of that schema. Returns 0 or b->errCode.
*/
int fsl__db_table_name(fsl_db const * const db, fsl_dbrole_e r,
                       char const * zTable, bool qualified,
                       fsl_b * const b);

/** @internal

   fsl_db_table_has_column() for table zTable in role r's schema of
   db's connection (fsl__db_schema()), rather than whichever schema an
   unqualified name finds first.
*/
bool fsl__db_table_has_column(fsl_db * const db, fsl_dbrole_e r,
                              char const *zTable, char const *zCol);

/** @internal

   fsl_b_appendf(b, zFmt, ...) after replacing the schema placeholders
   ({{dbname.repo}}, {{dbname.ckout}}, {{temp.NAME}},
   {{bare.temp.NAME}}, see fsl__db_schema_token()) in zFmt, never in
   the values formatted into it, for db. For SQL built up in a buffer
   and then prepared as a "%b" argument, which the fsl_db SQL
   functions do not expand.
*/
int fsl__db_appendf(fsl_db * const db, fsl_b * const b,
                    char const * zFmt, ... );

/** @internal

   Appends zIn, SQL which creates the ticket tables (from
   fsl_cx_schema_ticket(): libfossil's default schema or a repository's
   own "ticket-table" setting, which fossil(1) writes without schema
   names), to out, with the object name of each CREATE TABLE and
   CREATE [UNIQUE] INDEX given db's repository schema name
   (fsl__db_schema()): a name's own qualifier, if any, is replaced.
   Strings, quoted identifiers and comments are copied as they are.
   The schema is data, so the placeholders of fsl__db_schema_token()
   are not used for it. Returns 0 or FSL_RC_OOM.
*/
int fsl__ticket_schema_qualify(fsl_db * const db, char const * zIn,
                               fsl_b * const out);

/** @internal

   Creates the ticket tables of f's repository from zSql (see
   fsl__ticket_schema_qualify()). If the repository is tables of a
   host's main db (fsl__db_repo_prefix()), every object which zSql
   makes gets the prefix, and every reference to its tables follows,
   by way of a scratch db and SQLite's ALTER TABLE RENAME, and a schema
   which names any other table, or makes anything but tables, indexes,
   views and triggers, is refused with FSL_RC_CONSISTENCY, so that
   nothing of it binds to the host's tables. Returns 0 or an error
   code, with f's error state set.
*/
int fsl__ticket_schema_install(fsl_cx * const f, char const * zSql);

/** @internal

   Checks that a repository with table prefix zPre can be made in the
   main db of db's connection: that the prefix overlaps no recorded
   one and that main has no object whose name starts with it, ignoring
   case. Returns 0 or an error code, with f's error state set.
*/
int fsl__repo_host_free_check(fsl_cx * f, fsl_db * db, char const * zPre);

/** @internal

   Appends zSql, the CREATE statement of a table, index, view or
   trigger as SQLite records it in sqlite_schema ("CREATE [UNIQUE]
   TABLE|INDEX|VIEW|TRIGGER name..."), to b with its name replaced
   by zSchema."zName". Returns 0, FSL_RC_RANGE if zSql has no such
   form, or FSL_RC_OOM.
*/
int fsl__repo_copy_sql(fsl_b * const b, char const * zSql,
                       char const * zSchema, char const * zName);

/** @internal

   Callback type for fsl__brace_expand(): appends the replacement for
   the n-byte token zTok (the X of {{X}}) to b, doubling each '%' in
   it if escPct is true. zTail is the NUL-terminated rest of the format
   string after the token's closing braces. A callback which expands
   some of that along with the token sets *pnConsumed (0 on entry) to
   the number of bytes of zTail it expanded, which the parser then
   skips. Returns 0 on success, FSL_RC_NOT_FOUND if zTok is not one it
   knows, in which case nothing may have been appended, or another
   code (normally b->errCode) on error.
*/
typedef int (*fsl__brace_f)(void * state, char const * zTok, fsl_size_t n,
                            char const * zTail, fsl_size_t * pnConsumed,
                            fsl_b * const b, bool escPct);

/** @internal

   Appends zFmt to b with each {{X}} placeholder replaced by xToken():
   the parser behind fsl_cx_formatv() and behind the {{dbname.repo}}
   and {{dbname.ckout}} schema placeholders in the fsl_db SQL
   functions. Unknown
   and empty placeholders are passed through as-is, as is everything
   after a "{{" which is never closed. Text after a placeholder which
   xToken() reports having expanded along with it (see fsl__brace_f)
   is skipped. Stops at and returns the first error code from xToken()
   other than FSL_RC_NOT_FOUND, else returns b->errCode.
*/
int fsl__brace_expand(fsl_b * const b, char const * const zFmt,
                      bool escPct, fsl__brace_f xToken, void * state);

/** @internal

   Calls cb() for each entry of directory zDir, by name (as
   fsl_dircrawl() presents names: UTF-8, precomposed on macOS), except
   "." and "..", stopping at and returning the first non-0 result.
   Returns non-0 if the directory cannot be read. This is
   fsl_ckout_fs_os's xDirList().
*/
int fsl__dir_list(char const * zDir,
                  int (*cb)(void * cbState, char const * zEntry),
                  void * cbState);

int fsl__cfs_stat(fsl_cx * const f, char const *zName, fsl_fstat * fst,
                  bool derefLinks);
fsl_int_t fsl__cfs_size(fsl_cx * const f, char const *zName);
fsl_time_t fsl__cfs_mtime(fsl_cx * const f, char const *zName);
bool fsl__cfs_is_file(fsl_cx * const f, char const *zName);
bool fsl__cfs_is_file_or_link(fsl_cx * const f, char const *zName);
bool fsl__cfs_is_symlink(fsl_cx * const f, char const *zName);
bool fsl__cfs_isexec(fsl_cx * const f, char const *zName);
int fsl__cfs_dir_check(fsl_cx * const f, char const *zName);
int fsl__cfs_dir_is_empty(fsl_cx * const f, char const *zName);
int fsl__cfs_read(fsl_cx * const f, fsl_b * const dest, char const *zName);
int fsl__cfs_write(fsl_cx * const f, fsl_b const * const b,
                   char const *zName);
int fsl__cfs_write_blob(fsl_cx * const f, char const *zName,
                        fsl_id_t rid, fsl_b * const content,
                        bool loaded, bool * const pWriteFailed);
int fsl__cfs_unlink(fsl_cx * const f, char const *zName);
int fsl__cfs_rename(fsl_cx * const f, char const *zFrom, char const *zTo);
int fsl__cfs_rmdir(fsl_cx * const f, char const *zName);
int fsl__cfs_mkdir_for_file(fsl_cx * const f, char const *zName,
                            bool forceFlag);
int fsl__cfs_exec_set(fsl_cx * const f, char const *zName, bool isExec);
int fsl__cfs_mtime_set(fsl_cx * const f, char const *zName,
                       fsl_time_t mtime);
int fsl__cfs_copy(fsl_cx * const f, char const *zFrom, char const *zTo);
int fsl__cfs_sha1sum(fsl_cx * const f, char const *zName, fsl_b * const tgt);
int fsl__cfs_sha3sum(fsl_cx * const f, char const *zName, fsl_b * const tgt);
int fsl__cfs_dircrawl(fsl_cx * const f, char const *zDir,
                      fsl_dircrawl_f callback, void * cbState);
int fsl__cfs_symlink_read(fsl_cx * const f, fsl_b * const tgt,
                          char const *zName);
int fsl__cfs_symlink_create(fsl_cx * const f, char const *zTarget,
                            char const *zLink, bool realLink);
int fsl__cfs_symlink_copy(fsl_cx * const f, char const *zFrom,
                          char const *zTo, bool realLink);

/** @internal

   Reads checkout file zName into tgt as fossil(1)'s
   blob_read_from_file(...,RepoFILE) does: with the allow-symlinks
   setting on, a symlink's content is its target name, else the
   symlink is followed. If isLink is not NULL, *isLink is set to
   whether zName was read as a symlink.

   Returns 0 on success or the non-0 result of fsl__cfs_read() or
   fsl__cfs_symlink_read(), e.g. FSL_RC_NOT_FOUND. It does not set
   f's error state.
*/
int fsl__cfs_read_repofile(fsl_cx * const f, fsl_b * const tgt,
                           char const *zName, bool * isLink);

/** @internal

   Returns the permission of a checkout file as fossil(1)'s
   file_perm(...,RepoFILE) does, given its fsl_fstat. fst must come
   from a successful fsl__cfs_stat() which dereferenced symlinks
   unless allowSymlinks, which must be the allow-symlinks setting
   (fsl_cx_allows_symlinks()). A symlink is FSL_FILE_PERM_LINK, and
   never also executable.
*/
fsl_fileperm_e fsl__fstat_perm(fsl_fstat const * fst, bool allowSymlinks);


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_INTERNAL_H_INCLUDED */
#endif /*defined(FSL_EXPOSE_INTERNAL_APIS)*/
#endif /*ORG_FOSSIL_SCM_LIBFOSSIL_AMAL_H_INCLUDED*/
/* end of libfossil.h */
#undef FSL_EXPOSE_INTERNAL_APIS
/* start of file src/xdirent.h */
/**
  Origin: https://gist.github.com/isakbosman/758eb668938806aabb04830736f4ac41

  Modified only very slightly for use in the libfossil project: a
  couple of #if's were added to allow us to include this file without
  having to check which platform we're building on. In non-Windows builds
  it uses the corresponding POSIX APIs.
*/
/*
 * dirent.h - dirent API for Microsoft Visual Studio
 *
 * Copyright (C) 2006-2012 Toni Ronkko
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * ``Software''), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * $Id: dirent.h,v 1.20 2014/03/19 17:52:23 tronkko Exp $
 */
#ifndef DIRENT_H
#define DIRENT_H

#if FSL_PLATFORM_IS_WINDOWS
/*
 * Define architecture flags so we don't need to include windows.h.
 * Avoiding windows.h makes it simpler to use windows sockets in conjunction
 * with dirent.h.
 */
#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_IX86)
#   define _X86_
#endif
#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_AMD64)
#define _AMD64_
#endif

#include <stdio.h>
#include <stdarg.h>
#include <windef.h>
#include <winbase.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

/* Indicates that d_type field is available in dirent structure */
#define _DIRENT_HAVE_D_TYPE

/* Indicates that d_namlen field is available in dirent structure */
#define _DIRENT_HAVE_D_NAMLEN

/* Entries missing from MSVC 6.0 */
#if !defined(FILE_ATTRIBUTE_DEVICE)
#   define FILE_ATTRIBUTE_DEVICE 0x40
#endif

/* File type and permission flags for stat() */
#if !defined(S_IFMT)
#   define S_IFMT   _S_IFMT                     /* File type mask */
#endif
#if !defined(S_IFDIR)
#   define S_IFDIR  _S_IFDIR                    /* Directory */
#endif
#if !defined(S_IFCHR)
#   define S_IFCHR  _S_IFCHR                    /* Character device */
#endif
#if !defined(S_IFFIFO)
#   define S_IFFIFO _S_IFFIFO                   /* Pipe */
#endif
#if !defined(S_IFREG)
#   define S_IFREG  _S_IFREG                    /* Regular file */
#endif
#if !defined(S_IREAD)
#   define S_IREAD  _S_IREAD                    /* Read permission */
#endif
#if !defined(S_IWRITE)
#   define S_IWRITE _S_IWRITE                   /* Write permission */
#endif
#if !defined(S_IEXEC)
#   define S_IEXEC  _S_IEXEC                    /* Execute permission */
#endif
#if !defined(S_IFIFO)
#   define S_IFIFO _S_IFIFO                     /* Pipe */
#endif
#if !defined(S_IFBLK)
#   define S_IFBLK   0                          /* Block device */
#endif
#if !defined(S_IFLNK)
#   define S_IFLNK   0                          /* Link */
#endif
#if !defined(S_IFSOCK)
#   define S_IFSOCK  0                          /* Socket */
#endif

#if defined(_MSC_VER)
#   define S_IRUSR  S_IREAD                     /* Read user */
#   define S_IWUSR  S_IWRITE                    /* Write user */
#   define S_IXUSR  0                           /* Execute user */
#   define S_IRGRP  0                           /* Read group */
#   define S_IWGRP  0                           /* Write group */
#   define S_IXGRP  0                           /* Execute group */
#   define S_IROTH  0                           /* Read others */
#   define S_IWOTH  0                           /* Write others */
#   define S_IXOTH  0                           /* Execute others */
#endif

/* Maximum length of file name */
#if !defined(PATH_MAX)
#   define PATH_MAX MAX_PATH
#endif
#if !defined(FILENAME_MAX)
#   define FILENAME_MAX MAX_PATH
#endif
#if !defined(NAME_MAX)
#   define NAME_MAX FILENAME_MAX
#endif

/* File type flags for d_type */
#define DT_UNKNOWN  0
#define DT_REG      S_IFREG
#define DT_DIR      S_IFDIR
#define DT_FIFO     S_IFIFO
#define DT_SOCK     S_IFSOCK
#define DT_CHR      S_IFCHR
#define DT_BLK      S_IFBLK
#define DT_LNK      S_IFLNK

/* Macros for converting between st_mode and d_type */
#define IFTODT(mode) ((mode) & S_IFMT)
#define DTTOIF(type) (type)

/*
 * File type macros.  Note that block devices, sockets and links cannot be
 * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are
 * only defined for compatibility.  These macros should always return false
 * on Windows.
 */
#define	S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
#define	S_ISDIR(mode)  (((mode) & S_IFMT) == S_IFDIR)
#define	S_ISREG(mode)  (((mode) & S_IFMT) == S_IFREG)
#define	S_ISLNK(mode)  (((mode) & S_IFMT) == S_IFLNK)
#define	S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
#define	S_ISCHR(mode)  (((mode) & S_IFMT) == S_IFCHR)
#define	S_ISBLK(mode)  (((mode) & S_IFMT) == S_IFBLK)

/* Return the exact length of d_namlen without zero terminator */
#define _D_EXACT_NAMLEN(p) ((p)->d_namlen)

/* Return number of bytes needed to store d_namlen */
#define _D_ALLOC_NAMLEN(p) (PATH_MAX)


#ifdef __cplusplus
extern "C" {
#endif


/* Wide-character version */
struct _wdirent {
    long d_ino;                                 /* Always zero */
    unsigned short d_reclen;                    /* Structure size */
    size_t d_namlen;                            /* Length of name without \0 */
    int d_type;                                 /* File type */
    wchar_t d_name[PATH_MAX];                   /* File name */
};
typedef struct _wdirent _wdirent;

struct _WDIR {
    struct _wdirent ent;                        /* Current directory entry */
    WIN32_FIND_DATAW data;                      /* Private file data */
    int cached;                                 /* True if data is valid */
    HANDLE handle;                              /* Win32 search handle */
    wchar_t *patt;                              /* Initial directory name */
};
typedef struct _WDIR _WDIR;

static _WDIR *_wopendir (const wchar_t *dirname);
static struct _wdirent *_wreaddir (_WDIR *dirp);
static int _wclosedir (_WDIR *dirp);
static void _wrewinddir (_WDIR* dirp);


/* For compatibility with Symbian */
#define wdirent _wdirent
#define WDIR _WDIR
#define wopendir _wopendir
#define wreaddir _wreaddir
#define wclosedir _wclosedir
#define wrewinddir _wrewinddir


/* Multi-byte character versions */
struct dirent {
    long d_ino;                                 /* Always zero */
    unsigned short d_reclen;                    /* Structure size */
    size_t d_namlen;                            /* Length of name without \0 */
    int d_type;                                 /* File type */
    char d_name[PATH_MAX];                      /* File name */
};
typedef struct dirent dirent;

struct DIR {
    struct dirent ent;
    struct _WDIR *wdirp;
};
typedef struct DIR DIR;

static DIR *opendir (const char *dirname);
static struct dirent *readdir (DIR *dirp);
static int closedir (DIR *dirp);
static void rewinddir (DIR* dirp);


/* Internal utility functions */
static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp);
static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp);

static int dirent_mbstowcs_s(
    size_t *pReturnValue,
    wchar_t *wcstr,
    size_t sizeInWords,
    const char *mbstr,
    size_t count);

static int dirent_wcstombs_s(
    size_t *pReturnValue,
    char *mbstr,
    size_t sizeInBytes,
    const wchar_t *wcstr,
    size_t count);

static void dirent_set_errno (int error);

/*
 * Open directory stream DIRNAME for read and return a pointer to the
 * internal working area that is used to retrieve individual directory
 * entries.
 */
static _WDIR*
_wopendir(
    const wchar_t *dirname)
{
    _WDIR *dirp = NULL;
    int error;

    /* Must have directory name */
    if (dirname == NULL  ||  dirname[0] == '\0') {
        dirent_set_errno (ENOENT);
        return NULL;
    }

    /* Allocate new _WDIR structure */
    dirp = (_WDIR*) malloc (sizeof (struct _WDIR));
    if (dirp != NULL) {
        DWORD n;

        /* Reset _WDIR structure */
        dirp->handle = INVALID_HANDLE_VALUE;
        dirp->patt = NULL;
        dirp->cached = 0;

        /* Compute the length of full path plus zero terminator */
        n = GetFullPathNameW (dirname, 0, NULL, NULL);

        /* Allocate room for absolute directory name and search pattern */
        dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16);
        if (dirp->patt) {

            /*
             * Convert relative directory name to an absolute one.  This
             * allows rewinddir() to function correctly even when current
             * working directory is changed between opendir() and rewinddir().
             */
            n = GetFullPathNameW (dirname, n, dirp->patt, NULL);
            if (n > 0) {
                wchar_t *p;

                /* Append search pattern \* to the directory name */
                p = dirp->patt + n;
                if (dirp->patt < p) {
                    switch (p[-1]) {
                    case '\\':
                    case '/':
                    case ':':
                        /* Directory ends in path separator, e.g. c:\temp\ */
                        /*NOP*/;
                        break;

                    default:
                        /* Directory name doesn't end in path separator */
                        *p++ = '\\';
                    }
                }
                *p++ = '*';
                *p = '\0';

                /* Open directory stream and retrieve the first entry */
                if (dirent_first (dirp)) {
                    /* Directory stream opened successfully */
                    error = 0;
                } else {
                    /* Cannot retrieve first entry */
                    error = 1;
                    dirent_set_errno (ENOENT);
                }

            } else {
                /* Cannot retrieve full path name */
                dirent_set_errno (ENOENT);
                error = 1;
            }

        } else {
            /* Cannot allocate memory for search pattern */
            error = 1;
        }

    } else {
        /* Cannot allocate _WDIR structure */
        error = 1;
    }

    /* Clean up in case of error */
    if (error  &&  dirp) {
        _wclosedir (dirp);
        dirp = NULL;
    }

    return dirp;
}

/*
 * Read next directory entry.  The directory entry is returned in dirent
 * structure in the d_name field.  Individual directory entries returned by
 * this function include regular files, sub-directories, pseudo-directories
 * "." and ".." as well as volume labels, hidden files and system files.
 */
static struct _wdirent*
_wreaddir(
    _WDIR *dirp)
{
    WIN32_FIND_DATAW *datap;
    struct _wdirent *entp;

    /* Read next directory entry */
    datap = dirent_next (dirp);
    if (datap) {
        size_t n;
        DWORD attr;
        
        /* Pointer to directory entry to return */
        entp = &dirp->ent;

        /* 
         * Copy file name as wide-character string.  If the file name is too
         * long to fit in to the destination buffer, then truncate file name
         * to PATH_MAX characters and zero-terminate the buffer.
         */
        n = 0;
        while (n + 1 < PATH_MAX  &&  datap->cFileName[n] != 0) {
            entp->d_name[n] = datap->cFileName[n];
            n++;
        }
        dirp->ent.d_name[n] = 0;

        /* Length of file name excluding zero terminator */
        entp->d_namlen = n;

        /* File type */
        attr = datap->dwFileAttributes;
        if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
            entp->d_type = DT_CHR;
        } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
            entp->d_type = DT_DIR;
        } else {
            entp->d_type = DT_REG;
        }

        /* Reset dummy fields */
        entp->d_ino = 0;
        entp->d_reclen = sizeof (struct _wdirent);

    } else {

        /* Last directory entry read */
        entp = NULL;

    }

    return entp;
}

/*
 * Close directory stream opened by opendir() function.  This invalidates the
 * DIR structure as well as any directory entry read previously by
 * _wreaddir().
 */
static int
_wclosedir(
    _WDIR *dirp)
{
    int ok;
    if (dirp) {

        /* Release search handle */
        if (dirp->handle != INVALID_HANDLE_VALUE) {
            FindClose (dirp->handle);
            dirp->handle = INVALID_HANDLE_VALUE;
        }

        /* Release search pattern */
        if (dirp->patt) {
            free (dirp->patt);
            dirp->patt = NULL;
        }

        /* Release directory structure */
        free (dirp);
        ok = /*success*/0;

    } else {
        /* Invalid directory stream */
        dirent_set_errno (EBADF);
        ok = /*failure*/-1;
    }
    return ok;
}

/*
 * Rewind directory stream such that _wreaddir() returns the very first
 * file name again.
 */
static void
_wrewinddir(
    _WDIR* dirp)
{
    if (dirp) {
        /* Release existing search handle */
        if (dirp->handle != INVALID_HANDLE_VALUE) {
            FindClose (dirp->handle);
        }

        /* Open new search handle */
        dirent_first (dirp);
    }
}

/* Get first directory entry (internal) */
static WIN32_FIND_DATAW*
dirent_first(
    _WDIR *dirp)
{
    WIN32_FIND_DATAW *datap;

    /* Open directory and retrieve the first entry */
    dirp->handle = FindFirstFileW (dirp->patt, &dirp->data);
    if (dirp->handle != INVALID_HANDLE_VALUE) {

        /* a directory entry is now waiting in memory */
        datap = &dirp->data;
        dirp->cached = 1;

    } else {

        /* Failed to re-open directory: no directory entry in memory */
        dirp->cached = 0;
        datap = NULL;

    }
    return datap;
}

/* Get next directory entry (internal) */
static WIN32_FIND_DATAW*
dirent_next(
    _WDIR *dirp)
{
    WIN32_FIND_DATAW *p;

    /* Get next directory entry */
    if (dirp->cached != 0) {

        /* A valid directory entry already in memory */
        p = &dirp->data;
        dirp->cached = 0;

    } else if (dirp->handle != INVALID_HANDLE_VALUE) {

        /* Get the next directory entry from stream */
        if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) {
            /* Got a file */
            p = &dirp->data;
        } else {
            /* The very last entry has been processed or an error occured */
            FindClose (dirp->handle);
            dirp->handle = INVALID_HANDLE_VALUE;
            p = NULL;
        }

    } else {

        /* End of directory stream reached */
        p = NULL;

    }

    return p;
}

/* 
 * Open directory stream using plain old C-string.
 */
static DIR*
opendir(
    const char *dirname) 
{
    struct DIR *dirp;
    int error;

    /* Must have directory name */
    if (dirname == NULL  ||  dirname[0] == '\0') {
        dirent_set_errno (ENOENT);
        return NULL;
    }

    /* Allocate memory for DIR structure */
    dirp = (DIR*) malloc (sizeof (struct DIR));
    if (dirp) {
        wchar_t wname[PATH_MAX];
        size_t n;

        /* Convert directory name to wide-character string */
        error = dirent_mbstowcs_s (&n, wname, PATH_MAX, dirname, PATH_MAX);
        if (!error) {

            /* Open directory stream using wide-character name */
            dirp->wdirp = _wopendir (wname);
            if (dirp->wdirp) {
                /* Directory stream opened */
                error = 0;
            } else {
                /* Failed to open directory stream */
                error = 1;
            }

        } else {
            /* 
             * Cannot convert file name to wide-character string.  This
             * occurs if the string contains invalid multi-byte sequences or
             * the output buffer is too small to contain the resulting
             * string.
             */
            error = 1;
        }

    } else {
        /* Cannot allocate DIR structure */
        error = 1;
    }

    /* Clean up in case of error */
    if (error  &&  dirp) {
        free (dirp);
        dirp = NULL;
    }

    return dirp;
}

/*
 * Read next directory entry.
 *
 * When working with text consoles, please note that file names returned by
 * readdir() are represented in the default ANSI code page while any output to
 * console is typically formatted on another code page.  Thus, non-ASCII
 * characters in file names will not usually display correctly on console.  The
 * problem can be fixed in two ways: (1) change the character set of console
 * to 1252 using chcp utility and use Lucida Console font, or (2) use
 * _cprintf function when writing to console.  The _cprinf() will re-encode
 * ANSI strings to the console code page so many non-ASCII characters will
 * display correcly.
 */
static struct dirent*
readdir(
    DIR *dirp) 
{
    WIN32_FIND_DATAW *datap;
    struct dirent *entp;

    /* Read next directory entry */
    datap = dirent_next (dirp->wdirp);
    if (datap) {
        size_t n;
        int error;

        /* Attempt to convert file name to multi-byte string */
        error = dirent_wcstombs_s(
            &n, dirp->ent.d_name, PATH_MAX, datap->cFileName, PATH_MAX);

        /* 
         * If the file name cannot be represented by a multi-byte string,
         * then attempt to use old 8+3 file name.  This allows traditional
         * Unix-code to access some file names despite of unicode
         * characters, although file names may seem unfamiliar to the user.
         *
         * Be ware that the code below cannot come up with a short file
         * name unless the file system provides one.  At least
         * VirtualBox shared folders fail to do this.
         */
        if (error  &&  datap->cAlternateFileName[0] != '\0') {
            error = dirent_wcstombs_s(
                &n, dirp->ent.d_name, PATH_MAX, 
                datap->cAlternateFileName, PATH_MAX);
        }

        if (!error) {
            DWORD attr;

            /* Initialize directory entry for return */
            entp = &dirp->ent;

            /* Length of file name excluding zero terminator */
            entp->d_namlen = n - 1;

            /* File attributes */
            attr = datap->dwFileAttributes;
            if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
                entp->d_type = DT_CHR;
            } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
                entp->d_type = DT_DIR;
            } else {
                entp->d_type = DT_REG;
            }

            /* Reset dummy fields */
            entp->d_ino = 0;
            entp->d_reclen = sizeof (struct dirent);

        } else {
            /* 
             * Cannot convert file name to multi-byte string so construct
             * an errornous directory entry and return that.  Note that
             * we cannot return NULL as that would stop the processing
             * of directory entries completely.
             */
            entp = &dirp->ent;
            entp->d_name[0] = '?';
            entp->d_name[1] = '\0';
            entp->d_namlen = 1;
            entp->d_type = DT_UNKNOWN;
            entp->d_ino = 0;
            entp->d_reclen = 0;
        }

    } else {
        /* No more directory entries */
        entp = NULL;
    }

    return entp;
}

/*
 * Close directory stream.
 */
static int
closedir(
    DIR *dirp) 
{
    int ok;
    if (dirp) {

        /* Close wide-character directory stream */
        ok = _wclosedir (dirp->wdirp);
        dirp->wdirp = NULL;

        /* Release multi-byte character version */
        free (dirp);

    } else {

        /* Invalid directory stream */
        dirent_set_errno (EBADF);
        ok = /*failure*/-1;

    }
    return ok;
}

/*
 * Rewind directory stream to beginning.
 */
static void
rewinddir(
    DIR* dirp) 
{
    /* Rewind wide-character string directory stream */
    _wrewinddir (dirp->wdirp);
}

/* Convert multi-byte string to wide character string */
static int
dirent_mbstowcs_s(
    size_t *pReturnValue,
    wchar_t *wcstr,
    size_t sizeInWords,
    const char *mbstr,
    size_t count)
{
    int error;

#if defined(_MSC_VER)  &&  _MSC_VER >= 1400

    /* Microsoft Visual Studio 2005 or later */
    error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count);

#else

    /* Older Visual Studio or non-Microsoft compiler */
    size_t n;

    /* Convert to wide-character string (or count characters) */
    n = mbstowcs (wcstr, mbstr, sizeInWords);
    if (!wcstr  ||  n < count) {

        /* Zero-terminate output buffer */
        if (wcstr  &&  sizeInWords) {
            if (n >= sizeInWords) {
                n = sizeInWords - 1;
            }
            wcstr[n] = 0;
        }

        /* Length of resuting multi-byte string WITH zero terminator */
        if (pReturnValue) {
            *pReturnValue = n + 1;
        }

        /* Success */
        error = 0;

    } else {

        /* Could not convert string */
        error = 1;

    }

#endif

    return error;
}

/* Convert wide-character string to multi-byte string */
static int
dirent_wcstombs_s(
    size_t *pReturnValue,
    char *mbstr,
    size_t sizeInBytes, /* max size of mbstr */
    const wchar_t *wcstr,
    size_t count)
{
    int error;

#if defined(_MSC_VER)  &&  _MSC_VER >= 1400

    /* Microsoft Visual Studio 2005 or later */
    error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count);

#else

    /* Older Visual Studio or non-Microsoft compiler */
    size_t n;

    /* Convert to multi-byte string (or count the number of bytes needed) */
    n = wcstombs (mbstr, wcstr, sizeInBytes);
    if (!mbstr  ||  n < count) {

        /* Zero-terminate output buffer */
        if (mbstr  &&  sizeInBytes) {
            if (n >= sizeInBytes) {
                n = sizeInBytes - 1;
            }
            mbstr[n] = '\0';
        }

        /* Lenght of resulting multi-bytes string WITH zero-terminator */
        if (pReturnValue) {
            *pReturnValue = n + 1;
        }

        /* Success */
        error = 0;

    } else {

        /* Cannot convert string */
        error = 1;

    }

#endif

    return error;
}

/* Set errno variable */
static void
dirent_set_errno(
    int error)
{
#if defined(_MSC_VER)  &&  _MSC_VER >= 1400

    /* Microsoft Visual Studio 2005 and later */
    _set_errno (error);

#else

    /* Non-Microsoft compiler or older Microsoft compiler */
    errno = error;

#endif
}


#ifdef __cplusplus
}
#endif

#else /* !FSL_PLATFORM_IS_WINDOWS */
#include <sys/types.h>
#include <dirent.h>
#endif /* !FSL_PLATFORM_IS_WINDOWS */

#endif /*DIRENT_H*/
/* end of file src/xdirent.h */
/* start of file src/fsl.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*****************************************************************************
  This file houses some context-independent API routines as well as
  some of the generic helper functions and types.
*/

#include <assert.h>
#include <stdlib.h> /* malloc() and friends, qsort() */
#include <memory.h> /* memset() */
#include <time.h> /* strftime() and gmtime() */
#if FSL_PLATFORM_IS_UNIX
#  include <sys/stat.h>
#endif
#if defined(_WIN32) || defined(WIN32)
# include <io.h>
#define isatty(h) _isatty(h)
#else
# include <unistd.h> /* isatty() */
#endif

#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

/*
  Please keep all (or most) fsl_XXX_empty initializers in one place
  (here) and lexically sorted (ignoring _ chars for that purpose).
*/
const fsl_branch_opt fsl_branch_opt_empty = fsl_branch_opt_empty_m;
const fsl_b fsl_b_empty = fsl_b_empty_m;
const fsl_card_F fsl_card_F_empty = fsl_card_F_empty_m;
const fsl_card_F_list fsl_card_F_list_empty = fsl_card_F_list_empty_m;
const fsl_card_J fsl_card_J_empty = fsl_card_J_empty_m;
const fsl_card_Q fsl_card_Q_empty = fsl_card_Q_empty_m;
const fsl_card_T fsl_card_T_empty = fsl_card_T_empty_m;
const fsl_checkin_opt fsl_checkin_opt_empty = fsl_checkin_opt_empty_m;
const fsl_checkin_queue_opt fsl_checkin_queue_opt_empty =
  fsl_checkin_queue_opt_empty_m;
const fsl_cidiff_opt fsl_cidiff_opt_empty = fsl_cidiff_opt_empty_m;
const fsl_cidiff_state fsl_cidiff_state_empty = fsl_cidiff_state_empty_m;
const fsl_ckout_manage_opt fsl_ckout_manage_opt_empty =
  fsl_ckout_manage_opt_empty_m;
const fsl_ckout_rename_opt fsl_ckout_rename_opt_empty =
  fsl_ckout_rename_opt_empty_m;
const fsl_ckout_unmanage_opt fsl_ckout_unmanage_opt_empty =
  fsl_ckout_unmanage_opt_empty_m;
const fsl_ckup_opt fsl_ckup_opt_empty = fsl_ckup_opt_m;
const fsl_confirmer fsl_confirmer_empty = fsl_confirmer_empty_m;
const fsl_signer fsl_signer_empty = fsl_signer_empty_m;
const fsl_confirm_detail fsl_confirm_detail_empty =
  fsl_confirm_detail_empty_m;
const fsl_confirm_response fsl_confirm_response_empty =
  fsl_confirm_response_empty_m;
const fsl_cx_config fsl_cx_config_empty = fsl_cx_config_empty_m;
const fsl_db fsl_db_empty = fsl_db_empty_m;
const fsl_deck fsl_deck_empty = fsl_deck_empty_m;
const fsl_error fsl_error_empty = fsl_error_empty_m;
const fsl_fstat fsl_fstat_empty = fsl_fstat_empty_m;
const fsl_list fsl_list_empty = fsl_list_empty_m;
const fsl__mcache fsl__mcache_empty = fsl__mcache_empty_m;
const fsl_merge_opt fsl_merge_opt_empty = fsl_merge_opt_empty_m;
const fsl_outputer fsl_outputer_FILE = fsl_outputer_FILE_m;
const fsl_outputer fsl_outputer_empty = fsl_outputer_empty_m;
const fsl_pathfinder fsl_pathfinder_empty = fsl_pathfinder_empty_m;
const fsl__pq fsl__pq_empty = fsl__pq_empty_m;
const fsl_msg_rebuild fsl_msg_rebuild_empty = fsl_msg_rebuild_empty_m;
const fsl_rebuild_opt fsl_rebuild_opt_empty = fsl_rebuild_opt_empty_m;
const fsl_repo_create_opt fsl_repo_create_opt_empty =
  fsl_repo_create_opt_empty_m;
const fsl_repo_extract_opt fsl_repo_extract_opt_empty =
  fsl_repo_extract_opt_empty_m;
const fsl_repo_extract_state fsl_repo_extract_state_empty =
  fsl_repo_extract_state_empty_m;
const fsl_repo_open_ckout_opt fsl_repo_open_ckout_opt_empty =
  fsl_repo_open_ckout_opt_m;
const fsl_ckout_revert_opt fsl_ckout_revert_opt_empty =
  fsl_ckout_revert_opt_empty_m;
const fsl_sha1_cx fsl_sha1_cx_empty = fsl_sha1_cx_empty_m;
const fsl_state fsl_state_empty = fsl_state_empty_m;
const fsl_stmt fsl_stmt_empty = fsl_stmt_empty_m;
const fsl_timer fsl_timer_empty = fsl_timer_empty_m;
const fsl_uperm fsl_uperm_empty = fsl_uperm_empty_m;
const fsl_uperm fsl_uperm_all = {
#define X(NAME,CH) .NAME = true,
  fsl_uperm_map_base(X)
#undef X
  .xReader = false, .xDeveloper = false
};
const fsl_xlinker fsl_xlinker_empty = fsl_xlinker_empty_m;
const fsl_xlinker_list fsl_xlinker_list_empty = fsl_xlinker_list_empty_m;
const fsl_zip_writer fsl_zip_writer_empty = fsl_zip_writer_empty_m;
const fsl__tokenizer fsl__tokenizer_empty = fsl__tokenizer_empty_m;

const fsl_allocator fsl_allocator_stdalloc = {
fsl_realloc_f_stdalloc,
NULL
};

fsl_lib_configurable_t fsl_lib_configurable = {
  {/*allocator*/ fsl_realloc_f_stdalloc, NULL}
};

void * fsl_malloc( fsl_size_t n ){
  return n
    ? fsl_realloc(NULL, n)
    : NULL;
}

void fsl_free( void * mem ){
  if(mem) fsl_realloc(mem, 0);
}

void * fsl_realloc( void * mem, fsl_size_t n ){
#define FLCA fsl_lib_configurable.allocator
#if SIZE_MAX < UINT64_MAX
  if( n > (fsl_size_t)SIZE_MAX ){
    /* No object of n bytes can exist here, and passing n on to an
       allocator taking size_t would truncate it. */
    return NULL;
  }
#endif
  if(!mem){
    /* malloc() */
    return n
      ? FLCA.f(FLCA.state, NULL, n)
      : NULL;
  }else if(!n){
    /* free() */
    FLCA.f(FLCA.state, mem, 0);
    return NULL;
  }else{
    /* realloc() */
    return FLCA.f(FLCA.state, mem, n);
  }
#undef FLCA
}

void * fsl_realloc_f_stdalloc( void * state fsl__unused,
                               void * mem, fsl_size_t n ){
  (void)state;
#if SIZE_MAX < UINT64_MAX
  if( n > (fsl_size_t)SIZE_MAX ) return NULL;
#endif
  if(!mem){
    return malloc((size_t)n);
  }else if(!n){
    free(mem);
    return NULL;
  }else{
    return realloc(mem, (size_t)n);
  }
}

int fsl_is_uuid(char const * str){
  fsl_size_t const len = fsl_strlen(str);
  if(FSL_STRLEN_SHA1==len){
    return fsl_validate16(str, FSL_STRLEN_SHA1) ? FSL_STRLEN_SHA1 : 0;
  }else if(FSL_STRLEN_K256==len){
    return fsl_validate16(str, FSL_STRLEN_K256) ? FSL_STRLEN_K256 : 0;
  }else{
    return 0;
  }
}
int fsl_is_uuid_len(int x){
  switch(x){
    case FSL_STRLEN_SHA1:
    case FSL_STRLEN_K256:
      return x;
    default:
      return 0;
  }
}
void fsl_error_clear( fsl_error * const err ){
  if( err ){
    fsl_b_clear(&err->msg);
    *err = fsl_error_empty;
  }
}

void fsl_error_reset( fsl_error * const err ){
  if( err ){
    err->code = 0;
    fsl_b_reuse(&err->msg);
  }
}

int fsl_error_copy( fsl_error const * const src, fsl_error * const dest ){
  if(src==dest) return FSL_RC_MISUSE;
  else {
    int rc = 0;
    fsl_b_reuse(&dest->msg);
    dest->code = src->code;
    if(FSL_RC_OOM!=src->code){
      rc = fsl_b_append( &dest->msg, src->msg.mem, src->msg.used );
    }
    return rc;
  }
}

void fsl_error_propagate( fsl_error * const lower, fsl_error * const higher ){
  if( lower != higher ){
    fsl_error const err = *lower;
    *lower = *higher;
    lower->code = 0;
    lower->msg.used = lower->msg.cursor = 0;
    *higher = err;
  }
}

int fsl_error_setv( fsl_error * const err, int code, char const * fmt,
                    va_list args ){
  int rc = code;
  if( err ){
    fsl_b_reuse(&err->msg);
    if((err->code = code) && FSL_RC_OOM!=code){
      int rc2;
      if(fmt) rc2 = fsl_b_appendfv(&err->msg, fmt, args);
      else rc2 = fsl_b_appendf(&err->msg, "fsl_rc_e #%d: %s",
                               code, fsl_rc_cstr(code));
      if(rc2) err->code = rc2;
    }
  }
  return rc;
}

int fsl_error_set( fsl_error * const err, int code, char const * fmt,
                   ... ){
  int rc = code;
  if( err ){
    va_list args;
    va_start(args,fmt);
    rc = fsl_error_setv(err, code, fmt, args);
    va_end(args);
  }
  return rc;
}


int fsl_error_get( fsl_error const * const err, char const ** str,
                   fsl_size_t * const len ){
  if(str) *str = err->msg.used
            ? (char const *)err->msg.mem
            : NULL;
  if(len) *len = err->msg.used;
  return err->code;
}


char const * fsl_rc_cstr(int rc){
  switch((fsl_rc_e)rc){
    /* we cast ^^^^ so that gcc will warn if the switch() below is
       missing any fsl_rc_e entries. */
#define E(N,V,H) case N: return # N;
    fsl_rc_e_map(E)
#undef E
  }
  return NULL;
}

char const * fsl_library_version(void){
  return FSL_LIBRARY_VERSION;
}

FSL_EXPORT char const * fsl_library_version_scm(void){
  return FSL_LIB_VERSION_HASH " " FSL_LIB_VERSION_TIMESTAMP;
}


bool fsl_library_version_matches(char const * yourLibVersion){
  return 0 == fsl_strcmp(FSL_LIBRARY_VERSION, yourLibVersion);
}

double fsl_unix_to_julian( fsl_time_t unix_ ){
  return (unix_ * 1.0 / 86400.0 ) + 2440587.5;
}

double fsl_julian_now(void){
  return fsl_unix_to_julian( time(0) );
}


int fsl_strcmp(const char *zA, const char *zB){
  if( zA==0 ) return zB ? -1 : 0;
  else if( zB==0 ) return 1;
  else{
    int a, b;
    do{
      a = *zA++;
      b = *zB++;
    }while( a==b && a!=0 );
    return ((unsigned char)a) - (unsigned char)b;
  }
}


int fsl_strcmp_cmp( void const * lhs, void const * rhs ){
  return fsl_strcmp((char const *)lhs, (char const *)rhs);
}

int fsl_strncmp(const char *zA, const char *zB, fsl_size_t nByte){
  if( !zA ) return zB ? -1 : 0;
  else if( !zB ) return +1;
  else if(!nByte) return 0;
  else{
    int a, b;
    do{
      a = *zA++;
      b = *zB++;
    }while( a==b && a!=0 && (--nByte)>0 );
    return (nByte>0) ? (((unsigned char)a) - (unsigned char)b) : 0;
  }
}

int fsl_uuidcmp( fsl_uuid_cstr lhs, fsl_uuid_cstr rhs ){
  if(!lhs) return rhs ? -1 : 0;
  else if(!rhs) return 1;
  else if(lhs[FSL_STRLEN_SHA1] && rhs[FSL_STRLEN_SHA1]){
    return fsl_strncmp( lhs, rhs, FSL_STRLEN_K256);
  }else if(!lhs[FSL_STRLEN_SHA1] && !rhs[FSL_STRLEN_SHA1]){
    return fsl_strncmp( lhs, rhs, FSL_STRLEN_SHA1 );
  }else{
    return fsl_strcmp(lhs, rhs);
  }
}

int fsl_strnicmp(const char *zA, const char *zB, fsl_int_t nByte){
  if( zA==0 ){
    if( zB==0 ) return 0;
    return -1;
  }else if( zB==0 ){
    return +1;
  }
  if( nByte<0 ) nByte = (fsl_int_t)fsl_strlen(zB);
  return sqlite3_strnicmp(zA, zB, nByte);
}

int fsl_stricmp(const char *zA, const char *zB){
  if( zA==0 ) return zB ? -1 : 0;
  else if( zB==0 ) return 1;
  else{
    fsl_int_t nByte;
    int rc;
    nByte = (fsl_int_t)fsl_strlen(zB);
    rc = sqlite3_strnicmp(zA, zB, nByte);
    return ( rc==0 && zA[nByte] ) ? 1 : rc;
  }
}

int fsl_stricmp_cmp( void const * lhs, void const * rhs ){
  return fsl_stricmp((char const *)lhs, (char const *)rhs);
}

fsl_size_t fsl_strlen( char const * src ){
  if( !src ) return 0;
#if 1
  return (fsl_size_t)strlen(src);
#else
  char const * const b = src;
  while( *src ) ++src;
  return (fsl_size_t)(src - b);
#endif
}

char * fsl_strndup( char const * src, fsl_int_t len ){
  if(!src) return NULL;
  else{
    fsl_b b = fsl_b_empty;
    fsl_b_append( &b, src, len );
    return (char*)b.mem;
  }
}

char * fsl_strdup( char const * src ){
  return fsl_strndup(src, -1);
}

fsl_size_t fsl_strlcpy(char * dst, const char * src, fsl_size_t dstsz){
  fsl_size_t offset = 0;

  if(dstsz){
    while((*(dst+offset) = *(src+offset))!='\0'){
      if(++offset == dstsz){
        --offset;
        break;
      }
    }
    *(dst+offset) = '\0';
  }
  while(*(src+offset)!='\0'){
    ++offset; /* Return src length. */
  }
  return offset;
}

fsl_size_t fsl_strlcat(char *dst, const char *src, fsl_size_t dstsz){
  fsl_size_t offset;
  fsl_size_t dstlen, srclen, idx = 0;

  offset = dstlen = fsl_strlen(dst);
  srclen = fsl_strlen(src);
  if( !dstsz || offset>=dstsz-1 )
    return dstlen+srclen;

  while((*(dst+offset++) = *(src+idx++))!='\0'){
    if(offset==dstsz-1){
      break;
    }
  }
  *(dst+offset)='\0';
  return dstlen+srclen;
}

/*
   Return TRUE if the string begins with something that looks roughly
   like an ISO date/time string.  The SQLite date/time functions will
   have the final say-so about whether or not the date/time string is
   well-formed.
*/
bool fsl_str_is_date(const char *z){
  if(!z || !*z) return 0;
  else if( !fsl_isdigit(z[0]) ) return 0;
  else if( !fsl_isdigit(z[1]) ) return 0;
  else if( !fsl_isdigit(z[2]) ) return 0;
  else if( !fsl_isdigit(z[3]) ) return 0;
  else if( z[4]!='-') return 0;
  else if( !fsl_isdigit(z[5]) ) return 0;
  else if( !fsl_isdigit(z[6]) ) return 0;
  else if( z[7]!='-') return 0;
  else if( !fsl_isdigit(z[8]) ) return 0;
  else if( !fsl_isdigit(z[9]) ) return 0;
  else return 1;
}

int fsl_str_is_date2(const char *z){
  int rc = -1;
  int pos = 0;
  if(!z || !*z) return 0;
  else if( !fsl_isdigit(z[pos++]) ) return 0;
  else if( !fsl_isdigit(z[pos++]) ) return 0;
  else if( !fsl_isdigit(z[pos++]) ) return 0;
  else if( !fsl_isdigit(z[pos++]) ) return 0;
  else if( z[pos]=='-') ++pos;
  else{
    if(fsl_isdigit(z[pos++]) && '-'==z[pos++]){
      rc = 1;
    }else{
      return 0;
    }
  }
  if( !fsl_isdigit(z[pos++]) ) return 0;
  else if( !fsl_isdigit(z[pos++]) ) return 0;
  else if( z[pos++]!='-') return 0;
  else if( !fsl_isdigit(z[pos++]) ) return 0;
  else if( !fsl_isdigit(z[pos++]) ) return 0;
  assert(10==pos || 11==pos);
  return rc;
}

bool fsl_str_bool( char const * s ){
  switch(s ? *s : 0){
    case 0: case '0':
    case 'f': case 'F': // "false"
    case 'n': case 'N': // "no"
      return false;
    case '1':
    case 't': case 'T': // "true"
    case 'y': case 'Y': // "yes"
      return true;
    default: {
      char buf[5] = {0,0,0,0,0};
      int i;
      for( i = 0; (i<5) && *s; ++i, ++s ){
        buf[i] = fsl_tolower(*s);
      }
      if(0==fsl_strncmp(buf, "off", 3)) return false;
      return true;
    }
  }
}

char * fsl_user_name_guess(void){
  char const ** e;
  static char const * list[] = {
  "FOSSIL_USER",
#if defined(_WIN32)
  "USERNAME",
#else
  "USER",
  "LOGNAME",
#endif
  NULL /* sentinel */
  };
  char * rv = NULL;
  for( e = list; *e; ++e ){
    rv = fsl_getenv(*e);
    if(rv){
      /*
        Because fsl_getenv() has the odd requirement of needing
        fsl_os_str_free(), and we want strings returned from this
        function to be safe for passing to fsl_free(), we have to dupe
        the string. We "could" block this off to happen only on the
        platforms for which fsl_getenv() requires an extra encoding
        step, but that would likely eventually lead to a bug.
      */
      char * kludge = fsl_strdup(rv);
      fsl_os_str_free(rv);
      rv = kludge;
      break;
    }
  }
  return rv;
}

void fsl__fatal( int code, char const * fmt, ... ){
  static bool inFatal = false;
  if(inFatal){
    /* This can only happen if the fsl_appendv() bits
       call this AND trigger it via fsl_fprintf() below,
       neither of which is currently the case.
    */
    assert(!"fsl__fatal() called recursively.");
    abort();
  }else{
    va_list args;
    inFatal = true;
    fsl_fprintf(stderr, "FATAL ERROR: code=%d (%R)\n",
                code, code);
    if(fmt){
      va_start(args,fmt);
      fsl_fprintfv(stderr, fmt, args);
      va_end(args);
      fwrite("\n", 1, 1, stderr);
    }
    assert(!"fsl__fatal()");
    exit(EXIT_FAILURE);
  }
}

#if 0
char * fsl_unix_to_iso8601( fsl_time_t u ){
  enum { BufSize = 20 };
  char buf[BufSize]= {0,};
  time_t const tt = (time_t)u;
  fsl_strftime( buf, BufSize, "%Y-%m-%dT%H:%M:%S", gmtime(&tt) );
  return fsl_strdup(buf);
}
#endif


bool fsl_iso8601_to_julian( char const * zDate, double * out ){
  /* Adapted from this article:

     https://quasar.as.utexas.edu/BillInfo/JulianDatesG.html
  */
  char const * p = zDate;
  int y = 0, m = 0, d = 0;
  int h = 0, mi = 0, s = 0, f = 0;
  double j = 0;
  if(!zDate || !*zDate){
    return 0;
  }
#define DIG(NUM) if(!fsl_isdigit(*p)) return 0; \
  NUM=(NUM*10)+(*(p++)-'0')

  DIG(y);DIG(y);DIG(y);DIG(y);
  if('-'!=*p++) return 0;
  DIG(m);DIG(m);
  if('-'!=*p++) return 0;
  DIG(d);DIG(d);
  if('T' != *p++) return 0;
  DIG(h);DIG(h);
  if(':'!=*p++) return 0;
  DIG(mi);DIG(mi);
  if(':'!=*p++) return 0;
  DIG(s);DIG(s);
  if('.'==*p++){
    DIG(f);DIG(f);DIG(f);
  }
  if( m<1 || m>12 || d<1 || d>31 || h>24 || mi>59 || s>59 ){
    /* The ranges SQLite's julianday(), and thus fossil(1), accept. */
    return 0;
  }
  if(out){
    typedef int64_t TI;
    TI A, B, C, E, F;
    if(m<3){
      --y;
      m += 12;
    }
    A = y/100;
    B = A/4;
    C = 2-A+B;
    E = (TI)(365.25*(y+4716));
    F = (TI)(30.6001*(m+1));
    j = C + d + E + F - 1524.5;
    j += ((1.0*h)/24) + ((1.0*mi)/1440) + ((1.0*s)/86400);
    if(0 != f){
      j += (1.0*f)/86400000;
    }
    *out = j;
  }
  return 1;
#undef DIG
}

fsl_time_t fsl_julian_to_unix( double JD ){
  return (fsl_time_t) ((JD - 2440587.5) * 86400);
}

bool fsl_julian_to_iso8601( double J, char * out, bool addMs ){
  /* Adapted from this article:

     https://quasar.as.utexas.edu/BillInfo/JulianDatesG.html
  */
  typedef int64_t TI;
  int Y, M, D, H, MI, S, F;
  TI ms;
  char * z = out;
  if(!out || (J<=0)) return 0;
  else{
    double Z;
    TI W, X;
    TI A, B;
    TI C, DD, E, F;

    Z = J + 0.5;
    W = (TI)((Z-1867216.25)/36524.25);
    X = W/4;
    A = (TI)(Z+1+W-X);
    B = A+1524;
    C = (TI)((B-122.1)/365.25);
    DD = (TI)(365.25 * C);
    E = (TI)((B-DD)/30.6001);
    F = (TI)(30.6001 * E);
    D = (int)(B - DD - F);
    M = (E<=13) ? (E-1) : (E-13);
    Y = (M<3) ? (C-4715) : (C-4716);
  }

  if(Y<0 || Y>9999) return 0;
  else if(M<1 || M>12) return 0;
  else if(D<1 || D>31) return 0;

  ms = (TI)((J-(TI)J) * 86400001.0)
    /* number of milliseconds in the fraction part of the JDay. The
       non-0 at the end works around a problem where SS.000 converts
       to (SS-1).999. This will only hide the bug for the cases i've
       seen it, and might introduce other inaccuracies
       elsewhere. Testing it against the current libfossil event table
       produces good results - at most a 1ms round-trip fidelity loss
       for the (currently ~1157) records being checked. The suffix of
       1.0 was found to be a decent value via much testing with the
       libfossil and fossil(1) source repos.
    */;

  if( (H = ms / 3600000) ){
    ms -= H * 3600000;
    H = (H + 12) % 24;
  }else{
    H = 12 /* astronomers start their day at noon. */;
  }
  if( (MI = ms / 60000) ) ms -= MI * 60000;
  if( (S = ms / 1000) ) ms -= S * 1000;
  assert(ms<1000);
  F = (int)(ms);

  assert(H>=0 && H<24);
  assert(MI>=0 && MI<60);
  assert(S>=0 && S<60);
  assert(F>=0 && F<1000);

  if(H<0 || H>23) return 0;
  else if(MI<0 || MI>59) return 0;
  else if(S<0 || S>59) return 0;
  else if(F<0 || F>999) return 0;
#define UGLY_999_KLUDGE 1
  /* The fossil(1) repo has 27 of 10041 records which exhibit the
     SS.999 behaviour commented on above. With this kludge, that
     number drops to 0. But it's still an ugly, ugly kludge.
     OTOH, the chance of the .999 being correct is 1 in 1000,
     whereas we see "correct" behaviour more often (2.7 in 1000)
     with this workaround.
   */
#if UGLY_999_KLUDGE
  if(999==F){
    char oflow = 0;
    int s2 = S, mi2 = MI, h2 = H;
    if(++s2 == 60){ /* Overflow minute */
      s2 = 0;
      if(++mi2 == 60){ /* Overflow hour */
        mi2 = 0;
        if(++h2 == 24){ /* Overflow day */
          /* leave this corner-corner case in place */
          oflow = 1;
        }
      }
    }
    /* MARKER(("UGLY 999 KLUDGE (A): H=%d MI=%d S=%d F=%d\n", H, MI, S, F)); */
    if(!oflow){
      F = 0;
      S = s2;
      MI = mi2;
      H = h2;
      /* MARKER(("UGLY 999 KLUDGE (B): H=%d MI=%d S=%d F=%d\n", H, MI, S, F)); */
    }
  }
#endif
#undef UGLY_999_KLUDGE
  *(z++) = '0'+(Y/1000);
  *(z++) = '0'+(Y%1000/100);
  *(z++) = '0'+(Y%100/10);
  *(z++) = '0'+(Y%10);
  *(z++) = '-';
  *(z++) = '0'+(M/10);
  *(z++) = '0'+(M%10);
  *(z++) = '-';
  *(z++) = '0'+(D/10);
  *(z++) = '0'+(D%10);
  *(z++) = 'T';
  *(z++) = '0'+(H/10);
  *(z++) = '0'+(H%10);
  *(z++) = ':';
  *(z++) = '0'+(MI/10);
  *(z++) = '0'+(MI%10);
  *(z++) = ':';
  *(z++) = '0'+(S/10);
  *(z++) = '0'+(S%10);
  if(addMs){
    *(z++) = '.';
    *(z++) = '0'+(F%1000/100);
    *(z++) = '0'+(F%100/10);
    *(z++) = '0'+(F%10);
  }
  *z = 0;
  return 1;
}

#if FSL_CONFIG_ENABLE_TIMER
/**
   For the fsl_timer_xxx() family of functions...
*/
#ifdef _WIN32
# include <windows.h>
#else
# include <sys/time.h>
# include <sys/resource.h>
# include <unistd.h>
# include <fcntl.h>
# include <errno.h>
#endif

#if !defined(HAVE_CLOCK_GETTIME)
#define HAVE_CLOCK_GETTIME 0
#endif

#endif /* FSL_CONFIG_ENABLE_TIMER */

/**
   Get user and kernel times in microseconds.
*/
static void fsl__cpu_times(uint64_t *piUser, uint64_t *piKernel,
                           uint64_t *pWall){
#if !FSL_CONFIG_ENABLE_TIMER
  if(piUser) *piUser = 0U;
  if(piKernel) *piKernel = 0U;
  if(pWall) *pWall = 0U;
#else
  if( pWall ){
#if HAVE_CLOCK_GETTIME
    struct timespec sNow;
    clock_gettime(CLOCK_REALTIME, &sNow);
    *pWall = (uint64_t)sNow.tv_sec*1000000 + sNow.tv_nsec/1000;
#elif defined(_WIN32)
    FILETIME ft; /* 100ns units since 1601 */
    GetSystemTimeAsFileTime(&ft);
    *pWall = ((((uint64_t)ft.dwHighDateTime)<<32)
              + (uint64_t)ft.dwLowDateTime) / 10;
#else
    *pWall = 0;
#endif
  }
#ifdef _WIN32
  FILETIME not_used;
  FILETIME kernel_time;
  FILETIME user_time;
  GetProcessTimes(GetCurrentProcess(), &not_used, &not_used,
                  &kernel_time, &user_time);
  if( piUser ){
     *piUser = ((((uint64_t)user_time.dwHighDateTime)<<32) +
                         (uint64_t)user_time.dwLowDateTime + 5)/10;
  }
  if( piKernel ){
     *piKernel = ((((uint64_t)kernel_time.dwHighDateTime)<<32) +
                         (uint64_t)kernel_time.dwLowDateTime + 5)/10;
  }
#else
  struct rusage s;
  getrusage(RUSAGE_SELF, &s);
  if( piUser ){
    *piUser = ((uint64_t)s.ru_utime.tv_sec)*1000000 + s.ru_utime.tv_usec;
  }
  if( piKernel ){
    *piKernel =
              ((uint64_t)s.ru_stime.tv_sec)*1000000 + s.ru_stime.tv_usec;
  }
#endif
#endif/* FSL_CONFIG_ENABLE_TIMER */
}

void fsl_timer_start(fsl_timer * const ft){
  fsl__cpu_times(&ft->user, &ft->system, &ft->wall);
}

void fsl_timer_fetch(fsl_timer const * const t,
                     uint64_t * pUser, uint64_t * pSys,
                     uint64_t *pWall){
  uint64_t eu, es, ew;
  fsl__cpu_times(&eu, &es, &ew);
  if( pUser ) *pUser = eu - t->user;
  if( pSys )  *pSys  = es - t->system;
  if( pWall ) *pWall = ew - t->wall;
}

uint64_t fsl_timer_cpu(fsl_timer const * const t){
  uint64_t eu = 0, es = 0;
  fsl__cpu_times( &eu, &es, NULL );
  return (eu - t->user) + (es - t->system);
}


void fsl_timer_add(fsl_timer const * const tStart,
                   fsl_timer * const tgt){
  uint64_t eu, es, ew;
  fsl__cpu_times(&eu, &es, &ew);
  tgt->system += es - tStart->system;
  tgt->user += eu - tStart->user;
  tgt->wall += ew - tStart->wall;
}

uint64_t fsl_timer_stop(fsl_timer * const t){
  fsl_timer tt = fsl_timer_empty;
  fsl_timer_add(t, &tt);
  *t = tt;
  return t->system + t->user;
}

unsigned int fsl_rgb_encode( int r, int g, int b ){
  return (unsigned int)(((r&0xFF)<<16) + ((g&0xFF)<<8) + (b&0xFF));
}

void fsl_rgb_decode( unsigned int src, int *r, int *g, int *b ){
  if(r) *r = (src&0xFF0000)>>16;
  if(g) *g = (src&0xFF00)>>8;
  if(b) *b = src&0xFF;
}

unsigned fsl_gradient_color(unsigned c1, unsigned c2, unsigned int n, unsigned int i){
  unsigned c;   /* Result color */
  unsigned x1, x2;
  if( i==0 || n==0 ) return c1;
  else if(i>=n) return c2;
  x1 = (c1>>16)&0xff;
  x2 = (c2>>16)&0xff;
  c = (x1*(n-i) + x2*i)/n<<16 & 0xff0000;
  x1 = (c1>>8)&0xff;
  x2 = (c2>>8)&0xff;
  c |= (x1*(n-i) + x2*i)/n<<8 & 0xff00;
  x1 = c1&0xff;
  x2 = c2&0xff;
  c |= (x1*(n-i) + x2*i)/n & 0xff;
  return c;
}


fsl_size_t fsl_simplify_sql( char * sql, fsl_strlen_t len ){
  char * wat = sql /* write pos */;
  char * rat = sql /* read pos */;
  char const * end /* one-past-the-end */;
  char inStr = 0 /* in an SQL string? */;
  char prev = 0 /* previous character. Sometimes. */;
  if(!sql || !*sql) return 0;
  len = fsl_nstrlen(sql, len);
  if(!len) return 0;
  end = sql + len;
  while( *rat && (rat < end) ){
    switch(*rat){
      case 0: break;
      case '\r':
      case '\n':
        /* Bug: we don't handle \r\n pairs. Because nobody
           should never have to :/. */
        if(inStr || (prev!=*rat)){
          /* Keep them as-is */
          prev = *wat++ = *rat++;
        }else{
          /* Collapse multiples into one. */
          ++rat;
        }
        continue;
      case ' ':
      case '\t':
      case '\v':
      case '\f':
        if(inStr){
          /* Keep them as-is */
          prev = *wat++ = *rat++;
        }else{
          /* Reduce to a single space. */
          /* f_out("prev=[%c] rat=[%c]\n", prev, *rat); */
          if(prev != *rat){
            *wat++ = ' ';
            prev = *rat;
          }
          ++rat;
        }
        continue;
      case '\'': /* SQL strings */
        prev = *wat++ = *rat++;
        if(!inStr){
          inStr = 1;
        }else if('\'' == *rat){
          /* Escaped quote */
          *wat++ = *rat++;
        }else{
          /* End of '...' string. */
          inStr = 0;
        }
        continue;
      default:
        prev = *wat++ = *rat++;
        continue;
    }
  }
  *wat = 0;
  return (fsl_size_t)(wat - sql);
}

fsl_size_t fsl_simplify_sql_buffer( fsl_b * const b ){
  return b->used = fsl_simplify_sql( (char *)b->mem, (fsl_int_t)b->used );
}

char const *fsl_preferred_ckout_db_name(void){
#if FSL_PLATFORM_IS_WINDOWS
  return "_FOSSIL_";
#else
  return ".fslckout";
#endif
}

bool fsl_isatty(int fd){
  return isatty(fd) ? true : false;
}
#if defined(_WIN32) || defined(WIN32)
#undef isatty
#endif

bool fsl__is_reserved_fn_windows(const char *zPath, fsl_int_t nameLen){
  static const char *const azRes[] = {
    "CON", "PRN", "AUX", "NUL", "COM", "LPT"
  };
  unsigned int i;
  char const * zEnd;
  if(nameLen<0) nameLen = (fsl_int_t)fsl_strlen(zPath);
  zEnd = zPath + nameLen;
  while( zPath < zEnd ){
    for(i=0; i<sizeof(azRes)/sizeof(azRes[0]); ++i){
      if( fsl_strnicmp(zPath, azRes[i], 3)==0
       && ((i>=4 && fsl_isdigit(zPath[3])
                 && (zPath[4]=='/' || zPath[4]=='.' || zPath[4]==0))
          || (i<4 && (zPath[3]=='/' || zPath[3]=='.' || zPath[3]==0)))
      ){
        return true;
      }
    }
    while( zPath<zEnd && zPath[0]!='/' ) ++zPath;
    while( zPath<zEnd && zPath[0]=='/' ) ++zPath;
  }
  return false;
}

bool fsl_is_reserved_fn(const char *zFilename, fsl_int_t nameLen){
  fsl_size_t nFilename = nameLen>=0
    ? (fsl_size_t)nameLen : fsl_strlen(zFilename);
  char const * zEnd;
  int gotSuffix = 0;
  assert( zFilename && "API misuse" );
#if FSL_PLATFORM_IS_WINDOWS // || 1
  if(nFilename>2 && fsl__is_reserved_fn_windows(zFilename, nameLen)){
    return true;
  }
#endif
  if( nFilename<8 ) return false; /* strlen("_FOSSIL_") */
  zEnd = zFilename + nFilename;
  if( nFilename>=12 ){ /* strlen("_FOSSIL_-(shm|wal)") */
    /* Check for (-wal, -shm, -journal) suffixes, with an eye towards
    ** runtime speed. */
    if( zEnd[-4]=='-' ){
      if( fsl_strnicmp("wal", &zEnd[-3], 3)
       && fsl_strnicmp("shm", &zEnd[-3], 3) ){
        return false;
      }
      gotSuffix = 4;
    }else if( nFilename>=16 && zEnd[-8]=='-' ){ /*strlen(_FOSSIL_-journal) */
      if( fsl_strnicmp("journal", &zEnd[-7], 7) ) return false;
      gotSuffix = 8;
    }
    if( gotSuffix ){
      assert( 4==gotSuffix || 8==gotSuffix );
      zEnd -= gotSuffix;
      nFilename -= gotSuffix;
      gotSuffix = 1;
    }
    assert( nFilename>=8 && "strlen(_FOSSIL_)" );
    assert( gotSuffix==0 || gotSuffix==1 );
  }
  switch( zEnd[-1] ){
    case '_':{
      if( fsl_strnicmp("_FOSSIL_", &zEnd[-8], 8) ) return false;
      if( 8==nFilename ) return true;
      return zEnd[-9]=='/' ? true : !!gotSuffix;
    }
    case 'T':
    case 't':{
      if( nFilename<9 || zEnd[-9]!='.'
       || fsl_strnicmp(".fslckout", &zEnd[-9], 9) ){
        return false;
      }
      if( 9==nFilename ) return true;
      return zEnd[-10]=='/' ? true : !!gotSuffix;
    }
    default:{
      return false;
    }
  }
}

void fsl_randomness(unsigned int n, void *tgt){
  sqlite3_randomness((int)n, tgt);
}

int fsl_system(const char *zOrigCmd){
  int rc;
  /* The following was ported over from fossil(1). As of this writing,
     the Windows version is completely untested even for
     compilability. */
#if defined(_WIN32)
  /* On windows, we have to put double-quotes around the entire command.
  ** Who knows why - this is just the way windows works.
  */
  char *zNewCmd = fsl_mprintf("\"%s\"", zOrigCmd);
  if(!zNewCmd){fsl_report_oom; return FSL_RC_OOM;}
  wchar_t *zUnicode = (wchar_t *)fsl_utf8_to_unicode(zNewCmd);
  if(zUnicode){
    //fossil_assert_safe_command_string(zOrigCmd);
    rc = _wsystem(zUnicode) ? FSL_RC_ERROR : 0;
    fsl_unicode_free(zUnicode);
  }else{
    fsl_report_oom;
    rc = FSL_RC_OOM;
  }
  fsl_free(zNewCmd);
  return rc;
#else
  /* On unix, evaluate the command directly.
  */
  //fossil_assert_safe_command_string(zOrigCmd);
  /* The regular system() call works to get a shell on unix */
  rc = system(zOrigCmd);
  if(-1==rc){
    rc = fsl_errno_to_rc(errno, FSL_RC_ERROR);
  }else if(rc){
    rc = FSL_RC_ERROR;
  }
  return rc;
#endif
}

#if 0
/* This was written as part of the fsl_sc_CurlBin experiment
   but, at least in that context, introduces mis-reads in
   later requests. fgets() also does (this routine was written
   to rule that out). So fsl__fdgets() was born.
*/
//static
int fsl__fgets(FILE *in, unsigned char * pOut, fsl_size_t nOut,
               char **ppOut, fsl_size_t * pnOut){
  fsl_size_t i = 0;
  int rc = 0;
  bool atEof = false;
  *ppOut = 0;
  *pnOut = 0;
  for( ; 0==rc && i<nOut-1; ++i){
    pOut[i] = 0;
    if( 1!=fread(&pOut[i], 1, 1, in) ){
      if( (atEof = !!feof(in)) ) break;
      else return FSL_RC_IO;
    }
    if( pOut[i]=='\n' ){
      ++i;
      break;
    }
  }
  if( !atEof && (!i || '\n'!=pOut[i-1]) ){
    return FSL_RC_RANGE;
  }

  pOut[i] = 0;
  *pnOut = i;
  *ppOut = (char *)pOut;
  return 0;
}
#endif

int fsl__fdgets(int fdIn, unsigned char * pOut, fsl_size_t nOut,
                char **ppOut, fsl_size_t * pnOut){
  fsl_size_t i = 0;
  int rc = 0;
  bool atEof = false;
  *ppOut = 0;
  *pnOut = 0;
  for( ; 0==rc && i<nOut-1; ++i){
    pOut[i] = 0;
    fsl_int_t const rn = read(fdIn, &pOut[i], 1);
    if( -1==rn ){
      //MARKER(("read falure: %s\n", fsl_rc_cstr(fsl_errno_to_rc(errno, FSL_RC_IO))));
      return fsl_errno_to_rc(errno, FSL_RC_IO);
    }else if( 0==rn ){
      /* Assume EOF */
      atEof = true;
      break;
    }else if( pOut[i]=='\n' ){
      ++i;
      break;
    }
  }
  if( !atEof && (!i || '\n'!=pOut[i-1]) ){
    return FSL_RC_RANGE;
  }
  if( 0 ){
    MARKER(("read %u bytes atEof=%d\n", (unsigned)i, atEof));
  }
  pOut[i] = 0;
  *pnOut = i;
  *ppOut = (char *)pOut;
  return 0;
}

/**
   Global state specific to this file.
*/
static struct {
  /* SQLite's main lib-level mutex, which we use only to guard
     lib-level initialization. */
  sqlite3_mutex *sq3StaticMaster;
#if FSL_ENABLE_MUTEX
  sqlite3_mutex *mutex;
#endif
  char **azTempDirs;
  /* True if libfossil runs inside a host process which owns SQLite,
     e.g. as a SQLite extension. See fsl__lib_hosted(). */
  bool hosted;
} Fsl = {
  .sq3StaticMaster = 0,
#if FSL_ENABLE_MUTEX
  .mutex = 0,
#endif
  .azTempDirs = NULL,
  .hosted = false
};

void fsl__lib_hosted(void){
  Fsl.hosted = true;
}

static void fsl__atexit(void){
  Fsl.sq3StaticMaster = 0;
#if FSL_ENABLE_MUTEX
  if( Fsl.mutex ){
    sqlite3_mutex_free( Fsl.mutex );
    Fsl.mutex = 0;
  }
#endif
  if( Fsl.azTempDirs ){
    fsl_temp_dirs_free(Fsl.azTempDirs);
    Fsl.azTempDirs = 0;
  }
  sqlite3_reset_auto_extension()
    /* Clean up pseudo-leak valgrind complains about:
       https://www.sqlite.org/c3ref/auto_extension.html */;
}

/**
   Global state type categories for for fsl__libinit().
*/
enum fsl__libinit_e {
  FSL__LIBINIT_MUTEX,
  FSL__LIBINIT_TMPDIRS
};

/**
   Sets up some global state which only needed by a few APIs, e.g.
   mutexes and fsl__tmpfile(). The first time this is run, it adds an
   atexit() handler
*/
//void fsl__libinit(enum fsl__libinit_e what);
static void fsl__libinit(enum fsl__libinit_e what){
  if( !Fsl.sq3StaticMaster ){
#if !defined(FSL_SQLEXT_LOADABLE)
    /* A loadable extension cannot call this (it is not in
       sqlite3_api_routines), and its host has already initialized
       SQLite by opening a connection. */
    sqlite3_initialize()
      /*the SQLITE_MUTEX_STATIC_MAIN will not cause autoinit
        of sqlite*/;
#endif
    sqlite3_mutex * const m = fsl__sq3_mutex_alloc(SQLITE_MUTEX_STATIC_MAIN);
    if( !m ){
      fsl_report_oom;
      fsl__fatal(FSL_RC_OOM, "Cannot allocate SQLITE_MUTEX_STATIC_MAIN")/*does not return*/;
    }
    fsl__sq3_mutex_enter(m);
    if( !Fsl.sq3StaticMaster ){
      Fsl.sq3StaticMaster = m;
      if( !Fsl.hosted ){
        /* A host may unload us before exit(), and the handler resets
           the host's auto-extensions, so only the library's own
           processes get it. */
        atexit( fsl__atexit );
      }
    }
    fsl__sq3_mutex_leave(m);
  }
  switch( what ){
    case FSL__LIBINIT_MUTEX:
#if FSL_ENABLE_MUTEX
      if( !Fsl.mutex ){
        sqlite3_mutex_enter(Fsl.sq3StaticMaster);
        if( !Fsl.mutex ){
          Fsl.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
          if( !Fsl.mutex ){
            sqlite3_mutex_leave(Fsl.sq3StaticMaster);
            fsl_report_oom;
            fsl__fatal(FSL_RC_OOM, "Cannot allocate libfossil mutex")/*does not return*/;
          }
        }
        sqlite3_mutex_leave(Fsl.sq3StaticMaster);
      }
#endif
      break;
    case FSL__LIBINIT_TMPDIRS:
      if( !Fsl.azTempDirs ){
        fsl__sq3_mutex_enter(Fsl.sq3StaticMaster);
        if( !Fsl.azTempDirs ){
          Fsl.azTempDirs = fsl_temp_dirs_get();
          if( ! Fsl.azTempDirs ){
            fsl__sq3_mutex_leave(Fsl.sq3StaticMaster);
            fsl_report_oom;
            fsl__fatal(FSL_RC_OOM,"Cannot allocate temp dir list");
          }
        }
        fsl__sq3_mutex_leave(Fsl.sq3StaticMaster);
      }
      break;
  }
}

int fsl__tmpfile( fsl_b * tgt, char const * zBaseName ){
  fsl__libinit(FSL__LIBINIT_TMPDIRS);
  return fsl_file_tempname(tgt, zBaseName, Fsl.azTempDirs);
}

int fsl__tmpchmod( char const * z ){
#if FSL_PLATFORM_IS_UNIX
  if( chmod(z, 0600 )<0 ){
    return fsl_errno_to_rc(errno, FSL_RC_IO);
  }
  return 0;
#else
  (void)z;
  return 0;
#endif
}

void fsl__mutex_enter(void){
#if FSL_ENABLE_MUTEX
  fsl__libinit(FSL__LIBINIT_MUTEX);
  assert( Fsl.mutex );
  sqlite3_mutex_enter(Fsl.mutex);
#endif
}

bool fsl__mutex_held(void){
#if FSL_ENABLE_MUTEX && defined(SQLITE_DEBUG)
  /* SQLite defines sqlite3_mutex_held() only in SQLITE_DEBUG builds. */
  assert( Fsl.mutex );
  return Fsl.mutex && 0!=sqlite3_mutex_held( Fsl.mutex );
#else
  return true/*this is how sqlite3 does it*/;
#endif
}

void fsl__mutex_leave(void){
#if FSL_ENABLE_MUTEX
  assert( fsl__mutex_held() );
  sqlite3_mutex_leave( Fsl.mutex );
#endif
}

char const * fsl_buildinfo(enum fsl_buildinfo_e what){
  switch(what){
    case FSL_BUILDINFO_VERSION: return FSL_LIBRARY_VERSION;
    case FSL_BUILDINFO_VERSION_HASH: return FSL_LIB_VERSION_HASH;
    case FSL_BUILDINFO_VERSION_TIMESTAMP: return FSL_LIB_VERSION_TIMESTAMP;
    case FSL_BUILDINFO_CONFIG_TIMESTAMP: return FSL_LIB_CONFIG_TIMESTAMP;
    default: return 0;
  }
}

void fsl_to_hex(unsigned char const * digest, fsl_size_t nDigest,
                char *zBuf){
  static char const zEncode[] = "0123456789abcdef";
  fsl_size_t i, j;
  for(j=i=0; i<nDigest; i++){
    zBuf[j++] = zEncode[(*digest>>4)&0xf];
    zBuf[j++] = zEncode[*digest++ & 0xf];
  }
  zBuf[j] = 0;
}

#if !defined(NDEBUG)
int fsl__bprc(int rc){
  if( rc ){
    //assert(!"here");
    fprintf(stderr, "%s:%d: %s(%d %s)\n", __FILE__,
            __LINE__, __func__, rc, fsl_rc_cstr(rc));
  }
  return rc;
}
#endif

int fsl_enum_search(char const *word, fsl_strlen_t nWord,
                    char const * const *aList, fsl_int_t nList){
  if( !word || !nWord ) return -1;
  fsl_size_t const nw = fsl_nstrlen(word, nWord);
  if( !nw ) return -1;
  /* Don't bother with bsearch(). An LLM assures me that an O(N) is,
     for this case, faster for "N approx. 16-32" on all modern systems
     and "competitive with bsearch when N approx. 64" for 64-bit
     platforms. */
  for( fsl_strlen_t i = 0; nList<0 ? !!aList[i] : i<nList; ++i ){
    if( 0==fsl_strncmp(aList[i], word, nw)
        && !aList[i][nw] ) return i;
  }
  return -1;
}


#undef MARKER
/* end of file src/fsl.c */
/* start of file src/annotate.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/************************************************************************
  This file implements the annoate/blame/praise-related APIs.
*/
#include <assert.h>
#include <string.h>/*memset()*/

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

const fsl_annotate_opt fsl_annotate_opt_empty = fsl_annotate_opt_empty_m;

/*
** The status of an annotation operation is recorded by an instance
** of the following structure.
*/
typedef struct Annotator Annotator;
struct Annotator {
  fsl__diff_cx c;       /* The diff-engine context */
  fsl_b headVersion;/*starting version of the content*/
  struct AnnLine {  /* Lines of the original files... */
    const char *z;       /* The text of the line. Points into
                            this->headVersion. */
    short int n;         /* Number of bytes (omitting trailing \n) */
    short int iVers;     /* Level at which tag was set */
  } *aOrig;
  unsigned int nOrig;/* Number of elements in aOrig[] */
  unsigned int nVers;/* Number of versions analyzed */
  bool bMoreToDo;    /* True if the limit was reached */
  fsl_id_t origId;       /* RID for the zOrigin version */
  fsl_id_t showId;       /* RID for the version being analyzed */
  struct AnnVers {
    char *zFUuid;   /* File being analyzed */
    char *zMUuid;   /* Check-in containing the file */
    char *zUser;    /* Name of user who did the check-in */
    double mtime;   /* [event].[mtime] db entry */
  } *aVers;         /* For each check-in analyzed */
  unsigned int naVers; /* # of entries allocated in this->aVers */
  fsl_timer timer;
};

static const Annotator Annotator_empty = {
fsl__diff_cx_empty_m,
fsl_b_empty_m/*headVersion*/,
NULL/*aOrig*/,
0U/*nOrig*/, 0U/*nVers*/,
false/*bMoreToDo*/,
0/*origId*/,
0/*showId*/,
NULL/*aVers*/,
0U/*naVerse*/,
fsl_timer_empty_m
};

static void fsl__annotator_clean(Annotator * const a){
  unsigned i;
  fsl__diff_cx_clean(&a->c);
  for(i = 0; i < a->nVers; ++i){
    fsl_free(a->aVers[i].zFUuid);
    fsl_free(a->aVers[i].zMUuid);
    fsl_free(a->aVers[i].zUser);
  }
  fsl_free(a->aVers);
  fsl_free(a->aOrig);
  fsl_b_clear(&a->headVersion);
}

static uint64_t fsl__annotate_opt_difflags(fsl_annotate_opt const * const opt){
  uint64_t diffFlags = FSL_DIFF2_STRIP_EOLCR;
  if(opt->spacePolicy>0) diffFlags |= FSL_DIFF2_IGNORE_ALLWS;
  else if(opt->spacePolicy<0) diffFlags |= FSL_DIFF2_IGNORE_EOLWS;
  return diffFlags;
}

/**
   Initializes the annocation process by populating `a` from
   a->toAnnote, which must have been previously populated.  `a` must
   have already been cleanly initialized via copying from
   Annotator_empty and a->headVersion populated.  Returns 0 on success,
   else:

   - FSL_RC_RANGE if a->headVersion is empty.
   - FSL_RC_DIFF_BINARY if a->headVersion appears to be binary.
   - FSL_RC_OOM on OOM.

   It does not set an error message: the caller does that.

   Regardless of success or failure, `a` must eventually be passed
   to fsl__annotator_clean() to free up any resources.
*/
static int fsl__annotation_start(Annotator * const a,
                                 fsl_annotate_opt const * const opt){
  int rc;
  uint64_t const diffFlags = fsl__annotate_opt_difflags(opt);
  if(opt->spacePolicy>0){
    a->c.cmpLine = fsl_dline_cmp_ignore_ws;
  }else{
    assert(fsl_dline_cmp == a->c.cmpLine);
  }
  rc = fsl_break_into_dlines(fsl_b_cstr(&a->headVersion),
                             (fsl_int_t)a->headVersion.used,
                             (uint32_t*)&a->c.nTo, &a->c.aTo, diffFlags);
  if(rc) goto end;
  if(!a->c.nTo){
    rc = FSL_RC_RANGE;
    goto end;
  }
  a->aOrig = fsl_malloc( (fsl_size_t)(sizeof(a->aOrig[0]) * a->c.nTo) );
  if(!a->aOrig){
    rc = FSL_RC_OOM;
    goto end;
  }
  for(int i = 0; i < a->c.nTo; ++i){
    a->aOrig[i].z = a->c.aTo[i].z;
    a->aOrig[i].n = a->c.aTo[i].n;
    a->aOrig[i].iVers = -1;
  }
  a->nOrig = (unsigned)a->c.nTo;
  end:
  return rc;
}

/**
   The input pParent is the next most recent ancestor of the file
   being annotated.  Do another step of the annotation. On success
   return 0. On error returns FSL_RC_DIFF_BINARY if pParent appears to
   be binary or FSL_RC_OOM on OOM, without setting an error message.
*/
static int fsl__annotation_step(
  Annotator * const a,
  fsl_b const *pParent,
  int iVers,
  fsl_annotate_opt const * const opt
){
  int i, j, rc;
  int lnTo;
  uint64_t const diffFlags = fsl__annotate_opt_difflags(opt);

  /* Prepare the parent file to be diffed */
  rc = fsl_break_into_dlines(fsl_b_cstr(pParent),
                             (fsl_int_t)pParent->used,
                             (uint32_t*)&a->c.nFrom, &a->c.aFrom,
                             diffFlags);
  if(rc) goto end;
  else if( a->c.aFrom==0 ){
    return 0;
  }
  //MARKER(("Line #1: %.*s\n", (int)a->c.aFrom[0].n, a->c.aFrom[0].z));
  /* Compute the differences going from pParent to the file being
  ** annotated. */
  rc = fsl__diff_all(&a->c);
  if(rc) goto end;

  /* Where new lines are inserted on this difference, record the
  ** iVers as the source of the new line.
  */
  for(i=lnTo=0; i<a->c.nEdit; i+=3){
    int const nCopy = a->c.aEdit[i];
    int const nIns = a->c.aEdit[i+2];
    lnTo += nCopy;
    for(j=0; j<nIns; ++j, ++lnTo){
      if( a->aOrig[lnTo].iVers<0 ){
        a->aOrig[lnTo].iVers = iVers;
      }
    }
  }

  /* Clear out the diff results except for c.aTo, as that's pointed to
     by a->aOrig.*/
  fsl_free(a->c.aEdit);
  a->c.aEdit = 0;
  a->c.nEdit = 0;
  a->c.nEditAlloc = 0;

  /* Clear out the from file */
  fsl_free(a->c.aFrom);
  a->c.aFrom = 0;
  a->c.nFrom = 0;
  end:
  return rc;
}


/**
   Sets f's error state for failure code rc while annotating
   opt->filename at the version in q's current row, unless rc is
   FSL_RC_OOM or f's error state is already set. fromContent is true
   if rc came from fetching that version's content. Returns rc.
*/
static int fsl__annotate_err(fsl_cx * const f, int rc,
                             fsl_stmt * const q,
                             fsl_annotate_opt const * const opt,
                             bool fromContent){
  if(FSL_RC_OOM==rc || f->error.code) return rc;
  char const * const zFile = fsl_stmt_g_text(q, 0, NULL);
  char const * const zCi = fsl_stmt_g_text(q, 1, NULL);
  if(fromContent){
    return fsl_cx_err_set(f, rc, "unable to retrieve content of "
                          "artifact %S (file %s in check-in %S): %R",
                          zFile, opt->filename, zCi, rc);
  }
  switch(rc){
    case FSL_RC_DIFF_BINARY:
      return fsl_cx_err_set(f, rc, "cannot annotate binary file %s "
                            "(artifact %S in check-in %S)",
                            opt->filename, zFile, zCi);
    case FSL_RC_RANGE:
      return fsl_cx_err_set(f, rc, "cannot annotate empty file %s "
                            "(artifact %S in check-in %S)",
                            opt->filename, zFile, zCi);
    default:
      return fsl_cx_err_set(f, rc, "error %R annotating file %s "
                            "(artifact %S in check-in %S)",
                            rc, opt->filename, zFile, zCi);
  }
}

static int fsl__annotate_file(fsl_cx * const f,
                              Annotator * const a,
                              fsl_annotate_opt const * const opt){
  int rc = FSL_RC_NYI;
  fsl_b step = fsl_b_empty /*previous revision*/;
  fsl_id_t cid = 0, fnid = 0; // , rid = 0;
  fsl_stmt q = fsl_stmt_empty;
  bool openedTransaction = false;
  fsl_db * const db = fsl_needs_repo(f);
  if(!db) return FSL_RC_NOT_A_REPO;
  if( !fsl__db_in_statement_or_txn(db) ){
    /* Read consistency only: see fsl__db_in_statement_or_txn(). The
       TEMP ancestor table filled below is scratch, emptied by every
       fsl__init_ancestor(), so its writes need no transaction. */
    rc = fsl_cx_txn_begin(f);
    if(rc) return rc;
    openedTransaction = true;
  }

  rc = fsl_db_get_id(db, &fnid,
                     "SELECT fnid FROM {{dbname.repo}}.filename WHERE name=%Q %s",
                     opt->filename, fsl_cx_filename_collation(f));
  if(rc) goto dberr;
  if(0==fnid){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "File not found in repository: %s",
                        opt->filename);
    goto end;
  }
  if(opt->versionRid>0){
    cid = opt->versionRid;
  }else{
    fsl_ckout_version_info(f, &cid, NULL);
    if(cid<=0){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_A_CKOUT,
                          "Cannot determine version RID to "
                          "annotate from.");
      goto end;
    }
  }
  if(opt->originRid>0){
    rc = fsl_vpath_shortest_store_in_ancestor(f, cid, opt->originRid, NULL);
  }else{
    rc = fsl_compute_direct_ancestors(f, cid);
  }
  if(rc) goto end;

  rc = fsl_db_prepare(db, &q,
    "SELECT DISTINCT"
    "   (SELECT uuid FROM {{dbname.repo}}.blob WHERE rid=mlink.fid),"
    "   (SELECT uuid FROM {{dbname.repo}}.blob WHERE rid=mlink.mid),"
    "   coalesce(event.euser,event.user),"
    "   mlink.fid, event.mtime"
    "  FROM {{dbname.repo}}.mlink AS mlink, {{dbname.repo}}.event AS event, {{temp.ancestor}} AS ancestor"
    " WHERE mlink.fnid=%" FSL_ID_T_PFMT
    "   AND ancestor.rid=mlink.mid"
    "   AND event.objid=mlink.mid"
    "   AND mlink.mid!=mlink.pid"
    " ORDER BY ancestor.generation;",
    fnid
  );
  if(rc) goto dberr;

  while(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q))){
    rc = 0;
    if(a->nVers>=3){
      /* Process at least 3 rows before imposing any limit. That is
         historical behaviour inherited from fossil(1). */
      if(opt->limitMs>0 &&
         fsl_timer_cpu(&a->timer)/1000 >= opt->limitMs){
        a->bMoreToDo = true;
        break;
      }else if(opt->limitVersions>0 && a->nVers>=opt->limitVersions){
        a->bMoreToDo = true;
        break;
      }
    }
    char * zTmp = 0;
    char const * zCol = 0;
    fsl_size_t nCol = 0;
    fsl_id_t const rid = fsl_stmt_g_id(&q, 3);
    double const mtime = fsl_stmt_g_double(&q, 4);
    if(0==a->nVers){
      rc = fsl_content_get(f, rid, &a->headVersion);
      if(rc){
        rc = fsl__annotate_err(f, rc, &q, opt, true);
        goto end;
      }
      rc = fsl_b_to_utf8_no_bom(&a->headVersion);
      if(!rc) rc = fsl__annotation_start(a, opt);
      if(rc){
        rc = fsl__annotate_err(f, rc, &q, opt, false);
        goto end;
      }
      a->bMoreToDo = opt->originRid>0;
      a->origId = opt->originRid;
      a->showId = cid;
      assert(0==a->nVers);
      assert(NULL==a->aVers);
    }
    if(a->naVers==a->nVers){
      unsigned int const n = a->naVers ? a->naVers*3/2 : 10;
      void * const x = fsl_realloc(a->aVers, n*sizeof(a->aVers[0]));
      if(NULL==x){
        rc = FSL_RC_OOM;
        goto end;
      }
      a->aVers = x;
      a->naVers = n;
    }
#define AnnStr(COL,FLD) zCol = NULL; \
    rc = fsl_stmt_get_text(&q, COL, &zCol, &nCol);  \
    if(rc) goto end;                                \
    else if(!zCol){ goto end;                                           \
      /*zCol=""; nCol=0; //causes downstream 'RID 0 is invalid' error*/}  \
    zTmp = fsl_strndup(zCol, (fsl_int_t)nCol);  \
    if(!zTmp){ rc = FSL_RC_OOM; goto end; } \
    a->aVers[a->nVers].FLD = zTmp
    AnnStr(0,zFUuid);
    AnnStr(1,zMUuid);
    AnnStr(2,zUser);
#undef AnnStr
    a->aVers[a->nVers].mtime = mtime;
    if( a->nVers>0 ){
      rc = fsl_content_get(f, rid, &step);
      if(rc){
        rc = fsl__annotate_err(f, rc, &q, opt, true);
        goto end;
      }
      rc = fsl_b_to_utf8_no_bom(&step);
      if(!rc) rc = fsl__annotation_step(a, &step, a->nVers-1, opt);
      fsl_b_reuse(&step);
      if(rc){
        rc = fsl__annotate_err(f, rc, &q, opt, false);
        goto end;
      }
    }
    ++a->nVers;
  }
  if(FSL_RC_STEP_DONE==rc) rc = 0;
  else if(rc) goto dberr;

  assert(0==rc);
  if(0==a->nVers){
    if(opt->versionRid>0){
      char * const zCi = fsl_rid_to_uuid(f, opt->versionRid);
      if(zCi){
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "file %s does not exist in check-in %S",
                            opt->filename, zCi);
        fsl_free(zCi);
      }else{
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "file %s does not exist "
                            "in check-in RID %" FSL_ID_T_PFMT,
                            opt->filename, opt->versionRid);
      }
    }else{
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "No history found for file: %s",
                          opt->filename);
    }
  }
  
  end:
  fsl_b_clear(&step);
  fsl_stmt_finalize(&q);
  if(openedTransaction) fsl_cx_txn_end(f, rc!=0);
  return rc;
  dberr:
  assert(rc!=0);
  fsl_stmt_finalize(&q);
  fsl_b_clear(&step);
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  if(openedTransaction) fsl_cx_txn_end(f, rc!=0);
  return rc;
}

int fsl_annotate_step_f_fossilesque(void * state,
                                    fsl_annotate_opt const * const opt,
                                    fsl_annotate_step const * const step){
  static const int szHash = 10;
  fsl_outputer const * fout = (fsl_outputer*)state;
  int rc = 0;
  char ymd[24];
  if(step->mtime>0){
    fsl_julian_to_iso8601(step->mtime, &ymd[0], false);
    ymd[10] = 0;
  }
  switch(step->stepType){
    case FSL_ANNOTATE_STEP_VERSION:
      rc = fsl_appendf(fout->out, fout->state,
                       "version %3d: %s %.*s file %.*s\n",
                       step->stepNumber+1, ymd, szHash,
                       step->versionHash, szHash, step->fileHash);
      break;
    case FSL_ANNOTATE_STEP_FULL:
      if(opt->praise){
        rc = fsl_appendf(fout->out, fout->state,
                         "%.*s %s %13.13s: %.*s\n",
                         szHash,
                         opt->fileVersions ? step->fileHash : step->versionHash,
                         ymd, step->username,
                         (int)step->lineLength, step->line);
      }else{
        rc = fsl_appendf(fout->out, fout->state,
                         "%.*s %s %5d: %.*s\n",
                         szHash, opt->fileVersions ? step->fileHash : step->versionHash,
                         ymd, step->lineNumber,
                         (int)step->lineLength, step->line);
      }
      break;
    case FSL_ANNOTATE_STEP_LIMITED:
      if(opt->praise){
        rc = fsl_appendf(fout->out, fout->state,
                         "%*s %.*s\n", szHash+26, "",
                         (int)step->lineLength, step->line);
      }else{
        rc = fsl_appendf(fout->out, fout->state,
                         "%*s %5" PRIu32 ": %.*s\n",
                         szHash+11, "", step->lineNumber,
                         (int)step->lineLength, step->line);
      }
      break;
  }
  return rc;
}


int fsl_annotate( fsl_cx * const f, fsl_annotate_opt const * const opt ){
  int rc;
  Annotator ann = Annotator_empty;
  unsigned int i;
  fsl_b * const scratch = fsl_cx_b_borrow(f);
  fsl_annotate_step aStep;

  if( !scratch ) return f->error.code;
  if(!opt->out){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "fsl_annotate_opt is missing its output function.");
  }
  if(opt->limitMs>0) fsl_timer_start(&ann.timer);
  rc = fsl__annotate_file(f, &ann, opt);
  if(rc) goto end;
  memset(&aStep,0,sizeof(fsl_annotate_step));

  if(opt->dumpVersions){
    struct AnnVers *av;
    for(av = ann.aVers, i = 0;
        0==rc && i < ann.nVers; ++i, ++av){
      aStep.fileHash = av->zFUuid;
      aStep.versionHash = av->zMUuid;
      aStep.mtime = av->mtime;
      aStep.stepNumber = i;
      aStep.stepType = FSL_ANNOTATE_STEP_VERSION;
      rc = opt->out(opt->outState, opt, &aStep);
    }
    if(rc) goto end;
  }

  for(i = 0; 0==rc && i<ann.nOrig; ++i){
    short iVers = ann.aOrig[i].iVers;
    char const * z = ann.aOrig[i].z;
    int const n = ann.aOrig[i].n;
    if(iVers<0 && !ann.bMoreToDo){
      iVers = ann.nVers-1;
    }
    fsl_b_reuse(scratch);
    rc = fsl_b_append(scratch, z, n);
    if(rc) break;
    aStep.stepNumber = iVers;
    ++aStep.lineNumber;
    aStep.line = fsl_b_cstr(scratch);
    aStep.lineLength = (uint32_t)scratch->used;

    if(iVers>=0){
      struct AnnVers * const av = &ann.aVers[iVers];
      aStep.fileHash = av->zFUuid;
      aStep.versionHash = av->zMUuid;
      aStep.mtime = av->mtime;
      aStep.username = av->zUser;
      aStep.stepType = FSL_ANNOTATE_STEP_FULL;
    }else{
      aStep.fileHash = aStep.versionHash =
        aStep.username = NULL;
      aStep.stepType = FSL_ANNOTATE_STEP_LIMITED;
      aStep.mtime = 0.0;
    }
    rc = opt->out(opt->outState, opt, &aStep);
  }

  end:
  fsl_cx_b_return(f, scratch);
  fsl__annotator_clean(&ann);
  return rc;
}

#undef MARKER
/* end of file src/annotate.c */
/* start of file src/appendf.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/************************************************************************
The printf-like implementation in this file is based on the one found
in the sqlite3 distribution is in the Public Domain.

This copy was forked for use with the clob API in Feb 2008 by Stephan
Beal (https://wanderinghorse.net/home/stephan/) and modified to send
its output to arbitrary targets via a callback mechanism. Also
refactored the %X specifier handlers a bit to make adding/removing
specific handlers easier.

All code in this file is released into the Public Domain.

The printf implementation (fsl_appendfv()) is pretty easy to extend
(e.g. adding or removing %-specifiers for fsl_appendfv()) if you're
willing to poke around a bit and see how the specifiers are declared
and dispatched. For an example, grep for 'etSTRING' and follow it
through the process of declaration to implementation.

LICENSE for the version in the libfossil source tree:

  This program is free software; you can redistribute it and/or
  modify it under the terms of the Simplified BSD License (also
  known as the "2-Clause License" or "FreeBSD License".)

  This program is distributed in the hope that it will be useful,
  but without any warranty; without even the implied warranty of
  merchantability or fitness for a particular purpose.
**********************************************************************/

#include <string.h> /* strlen(), strcspn() */
#include <limits.h> /* INT_MAX */
#include <ctype.h>
#include <assert.h>

#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

/**
   SQLite eliminated all "long double" support in version 3.47, and
   all of this code originally (back in the 200x's) came from there,
   so we'll stop using "long double" here too.
*/
typedef double LONGDOUBLE_TYPE;

/*
  Most C compilers handle variable-sized arrays, so we enable
  that by default. Some (e.g. tcc) do not, so we provide a way
  to disable it: set FSLPRINTF_HAVE_VARARRAY to 0.

  One approach would be to look at:

  defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)

  but some compilers support variable-sized arrays even when not
  explicitly running in c99 mode.
*/
/*
  2022-05-17: apparently VLAs were made OPTIONAL in C11 and MSVC
  decided not to support them. So we'll go ahead and remove the VLA
  usage altogether.
*/
#define FSLPRINTF_HAVE_VARARRAY 0
#if 0
#if !defined(FSLPRINTF_HAVE_VARARRAY)
#  if defined(__TINYC__)
#    define FSLPRINTF_HAVE_VARARRAY 0
#  else
#    if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
#        define FSLPRINTF_HAVE_VARARRAY 1 /*use 1 in C99 mode */
#    else
#        define FSLPRINTF_HAVE_VARARRAY 0
#    endif
#  endif
#endif
#endif

/*
  Conversion types fall into various categories as defined by the
  following enumeration.
*/
enum PrintfCategory {
  etRADIX = 1, /* Integer types.  %d, %x, %o, and so forth */
  etFLOAT = 2, /* Floating point.  %f */
  etEXP = 3, /* Exponentional notation. %e and %E */
  etGENERIC = 4, /* Floating or exponential, depending on exponent. %g */
  /* 5 can be reused. Formerly etSIZE (%n) */
  etSTRING = 6, /* Strings. %s */
  etDYNSTRING = 7, /* Dynamically allocated strings. %z */
  etPERCENT = 8, /* Percent symbol. %% */
  etCHARX = 9, /* Characters. %c */
  /* The rest are extensions, not normally found in printf() */
  etCHARLIT = 10, /* Literal characters.  %' */
  etSQLESCAPE = 11, /* Strings with '\'' doubled.  %q */
  etSQLESCAPE2 = 12, /* Strings with '\'' doubled and enclosed in '',
                        NULL pointers replaced by SQL NULL.  %Q */
  etSQLESCAPE3 = 13, /* %!Q -> SQL identifiers wrapped in \" with
                        inner '\"' doubled */
  etBLOBSQL = 14, /* %B -> Works like %Q,
                     but requires a (fsl_b*) argument. */
  etPOINTER = 15, /* The %p conversion */
  etORDINAL = 17, /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
  etHTML = 18, /* %h -> basic HTML escaping. */
  etURLENCODE = 19, /* %t -> URL encoding. */
  etURLDECODE = 20, /* %T -> URL decoding. */
  etPATH = 21, /* %/ -> replace '\\' with '/' in path-like strings. */
  etBLOB = 22, /* Works like %s, but requires a (fsl_b*) argument. */
  etFOSSILIZE = 23, /* %F => like %s, but fossilizes it. */
  etSTRINGID = 24, /* String with length limit for a UUID prefix: %S */
  etJSONSTR = 25,  /* %j => JSON-escaped string. %!j adds outer
                       double-quotes to it. */
  etFSLRC = 26, /* %R => render as fsl_rc_cstr(int ARG) */
#if 0
  etSHELLESC = 27,
  /* %$ => shell-escapes a token, e.g. command name. That can only
     work if the output is all going to a single fsl_b, but this
     implementation is one layer of abstraction too far away to know
     that. */
#endif
  etPLACEHOLDER = 100
};

/**
   fsl_appendf_spec_handler is an almost-generic interface for farming
   work out of fsl_appendfv()'s code into external functions.  It doesn't
   actually save much (if any) overall code, but it makes the fsl_appendfv()
   code more manageable.


   REQUIREMENTS of implementations:

   - Expects an implementation-specific vargp pointer.
   fsl_appendfv() passes a pointer to the converted value of
   an entry from the format va_list. If it passes a type
   other than the expected one, undefined results.

   - If it calls pf it must do: pf( pfArg, D, N ), where D is
   the data to export and N is the number of bytes to export.
   It may call pf() an arbitrary number of times

   - If pf() successfully is called, the return value must be the
   accumulated totals of its return value(s), plus (possibly, but
   unlikely) an implementation-specific amount.

   - If it does not call pf() then it must return 0 (success)
   or a negative number (an error) or do all of the export
   processing itself and return the number of bytes exported.

   SIGNIFICANT LIMITATIONS:

   - Has no way of iterating over the format string, so handling
   precisions and such here can't work too well. (Nevermind:
   precision/justification is handled in fsl_appendfv().)
*/
typedef int (*fsl_appendf_spec_handler)( fsl_output_f pf,
                                         void * pfArg,
                                         unsigned int pfLen,
                                         void * vargp );

static int spech_string_to_html( fsl_output_f pf, void * pfArg,
                                 unsigned int pfLen, void * varg );
static int spech_urlencode( fsl_output_f pf, void * pfArg,
                            unsigned int pfLen, void * varg );
static int spech_urldecode( fsl_output_f pf, void * pfArg,
                            unsigned int pfLen, void * varg );
/*
  An "etByte" is an 8-bit unsigned value.
*/
typedef unsigned char etByte;

/*
  Each builtin conversion character (ex: the 'd' in "%d") is described
  by an instance of this struct.
*/
typedef struct et_info {   /* Information about each format field */
  char fmttype;            /* The format field code letter */
  etByte base;             /* The base for radix conversion */
  etByte flags;            /* One or more of FLAG_ constants below */
  etByte type;             /* Conversion paradigm */
  etByte charset;          /* Offset into aDigits[] of the digits string */
  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
  fsl_appendf_spec_handler callback;
} et_info;

/*
  Allowed values for et_info.flags
*/
enum et_info_flags {
  FLAG_SIGNED = 1,    /* True if the value to convert is signed */
  FLAG_EXTENDED = 2,  /* True if for internal/extended use only. */
  FLAG_STRING = 4     /* Allow infinity precision */
};

/*
  Historically, the following table was searched linearly, so the most
  common conversions were kept at the front.

  Change 2008 Oct 31 by Stephan Beal: we reserve an array of ordered
  entries for all chars in the range [32..126]. Format character
  checks can now be done in constant time by addressing that array
  directly.  This takes more static memory, but reduces the time and
  per-call overhead costs of fsl_appendfv().
*/
static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
static const char aPrefix[] = "-x0\000X0";
static const et_info fmtinfo[] = {
/*
  These entries MUST stay in ASCII order, sorted on their fmttype
  member! They MUST start with fmttype==32 and end at fmttype==126.
*/
{' '/*32*/, 0, 0, 0, 0, 0, 0 },
{'!'/*33*/, 0, 0, 0, 0, 0, 0 },
{'"'/*34*/, 0, 0, 0, 0, 0, 0 },
{'#'/*35*/, 0, 0, 0, 0, 0, 0 },
{'$'/*36*/, 0, 0, 0, 0, 0, 0 },
{'%'/*37*/, 0, 0, etPERCENT, 0, 0, 0 },
{'&'/*38*/, 0, 0, 0, 0, 0, 0 },
{'\''/*39*/, 0, 0, 0, 0, 0, 0 },
{'('/*40*/, 0, 0, 0, 0, 0, 0 },
{')'/*41*/, 0, 0, 0, 0, 0, 0 },
{'*'/*42*/, 0, 0, 0, 0, 0, 0 },
{'+'/*43*/, 0, 0, 0, 0, 0, 0 },
{','/*44*/, 0, 0, 0, 0, 0, 0 },
{'-'/*45*/, 0, 0, 0, 0, 0, 0 },
{'.'/*46*/, 0, 0, 0, 0, 0, 0 },
{'/'/*47*/, 0, 0, etPATH, 0, 0, 0 },
{'0'/*48*/, 0, 0, 0, 0, 0, 0 },
{'1'/*49*/, 0, 0, 0, 0, 0, 0 },
{'2'/*50*/, 0, 0, 0, 0, 0, 0 },
{'3'/*51*/, 0, 0, 0, 0, 0, 0 },
{'4'/*52*/, 0, 0, 0, 0, 0, 0 },
{'5'/*53*/, 0, 0, 0, 0, 0, 0 },
{'6'/*54*/, 0, 0, 0, 0, 0, 0 },
{'7'/*55*/, 0, 0, 0, 0, 0, 0 },
{'8'/*56*/, 0, 0, 0, 0, 0, 0 },
{'9'/*57*/, 0, 0, 0, 0, 0, 0 },
{':'/*58*/, 0, 0, 0, 0, 0, 0 },
{';'/*59*/, 0, 0, 0, 0, 0, 0 },
{'<'/*60*/, 0, 0, 0, 0, 0, 0 },
{'='/*61*/, 0, 0, 0, 0, 0, 0 },
{'>'/*62*/, 0, 0, 0, 0, 0, 0 },
{'?'/*63*/, 0, 0, 0, 0, 0, 0 },
{'@'/*64*/, 0, 0, 0, 0, 0, 0 },
{'A'/*65*/, 0, 0, 0, 0, 0, 0 },
{'B'/*66*/, 0, 2, etBLOBSQL, 0, 0, 0 },
{'C'/*67*/, 0, 0, 0, 0, 0, 0 },
{'D'/*68*/, 0, 0, 0, 0, 0, 0 },
{'E'/*69*/, 0, FLAG_SIGNED, etEXP, 14, 0, 0 },
{'F'/*70*/, 0, 4, etFOSSILIZE, 0, 0, 0 },
{'G'/*71*/, 0, FLAG_SIGNED, etGENERIC, 14, 0, 0 },
{'H'/*72*/, 0, 0, 0, 0, 0, 0 },
{'I'/*73*/, 0, 0, 0, 0, 0, 0 },
{'J'/*74*/, 0, 0, 0, 0, 0, 0 },
{'K'/*75*/, 0, 0, 0, 0, 0, 0 },
{'L'/*76*/, 0, 0, 0, 0, 0, 0 },
{'M'/*77*/, 0, 0, 0, 0, 0, 0 },
{'N'/*78*/, 0, 0, 0, 0, 0, 0 },
{'O'/*79*/, 0, 0, 0, 0, 0, 0 },
{'P'/*80*/, 0, 0, 0, 0, 0, 0 },
{'Q'/*81*/, 0, FLAG_STRING, etSQLESCAPE2, 0, 0, 0 },
{'R'/*82*/, 0, 0, etFSLRC, 0, 0, 0 },
{'S'/*83*/, 0, FLAG_STRING, etSTRINGID, 0, 0, 0 },
{'T'/*84*/, 0, FLAG_STRING, etURLDECODE, 0, 0, spech_urldecode },
{'U'/*85*/, 0, 0, 0, 0, 0, 0 },
{'V'/*86*/, 0, 0, 0, 0, 0, 0 },
{'W'/*87*/, 0, 0, 0, 0, 0, 0 },
{'X'/*88*/, 16, 0, etRADIX,      0,  4, 0 },
{'Y'/*89*/, 0, 0, 0, 0, 0, 0 },
{'Z'/*90*/, 0, 0, 0, 0, 0, 0 },
{'['/*91*/, 0, 0, 0, 0, 0, 0 },
{'\\'/*92*/, 0, 0, 0, 0, 0, 0 },
{']'/*93*/, 0, 0, 0, 0, 0, 0 },
{'^'/*94*/, 0, 0, 0, 0, 0, 0 },
{'_'/*95*/, 0, 0, 0, 0, 0, 0 },
{'`'/*96*/, 0, 0, 0, 0, 0, 0 },
{'a'/*97*/, 0, 0, 0, 0, 0, 0 },
{'b'/*98*/, 0, 2, etBLOB, 0, 0, 0 },
{'c'/*99*/, 0, 0, etCHARX,      0,  0, 0 },
{'d'/*100*/, 10, FLAG_SIGNED, etRADIX,      0,  0, 0 },
{'e'/*101*/, 0, FLAG_SIGNED, etEXP,        30, 0, 0 },
{'f'/*102*/, 0, FLAG_SIGNED, etFLOAT,      0,  0, 0},
{'g'/*103*/, 0, FLAG_SIGNED, etGENERIC,    30, 0, 0 },
{'h'/*104*/, 0, FLAG_STRING, etHTML, 0, 0, spech_string_to_html },
{'i'/*105*/, 10, FLAG_SIGNED, etRADIX,      0,  0, 0},
{'j'/*106*/, 0, 0, etJSONSTR, 0, 0, 0 },
{'k'/*107*/, 0, 0, 0, 0, 0, 0 },
{'l'/*108*/, 0, 0, 0, 0, 0, 0 },
{'m'/*109*/, 0, 0, 0, 0, 0, 0 },
{'n'/*110*/, 0, 0, 0, 0, 0, 0 },
{'o'/*111*/, 8, 0, etRADIX,      0,  2, 0 },
{'p'/*112*/, 16, 0, etPOINTER, 0, 1, 0 },
{'q'/*113*/, 0, FLAG_STRING, etSQLESCAPE,  0, 0, 0 },
{'r'/*114*/, 10, (FLAG_EXTENDED|FLAG_SIGNED), etORDINAL,    0,  0, 0},
{'s'/*115*/, 0, FLAG_STRING, etSTRING,     0,  0, 0 },
{'t'/*116*/,  0, FLAG_STRING, etURLENCODE, 0, 0, spech_urlencode },
{'u'/*117*/, 10, 0, etRADIX,      0,  0, 0 },
{'v'/*118*/, 0, 0, 0, 0, 0, 0 },
#if 1
{'w'/*119*/, 0, 0, 0, 0, 0, 0 },
#else
/* This role is filled by %!Q. %w is not currently used/documented. */
{'w'/*119*/, 0, FLAG_STRING, etSQLESCAPE3, 0, 0, 0 },
#endif
{'x'/*120*/, 16, 0, etRADIX,      16, 1, 0  },
{'y'/*121*/, 0, 0, 0, 0, 0, 0 },
{'z'/*122*/, 0, FLAG_STRING, etDYNSTRING,  0,  0, 0 },
{'{'/*123*/, 0, 0, 0, 0, 0, 0 },
{'|'/*124*/, 0, 0, 0, 0, 0, 0 },
{'}'/*125*/, 0, 0, 0, 0, 0, 0 },
{'~'/*126*/, 0, 0, 0, 0, 0, 0 }
};
#define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))

/*
  "*val" is a double such that 0.1 <= *val < 10.0
  Return the ascii code for the leading digit of *val, then
  multiply "*val" by 10.0 to renormalize.

  Example:
  input:     *val = 3.14159
  output:    *val = 1.4159    function return = '3'

  The counter *cnt is incremented each time.  After counter exceeds
  16 (the number of significant digits in a 64-bit float) '0' is
  always returned.
*/
static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  int digit;
  LONGDOUBLE_TYPE d;
  if( (*cnt)++ >= 16 ) return '0';
  digit = (int)*val;
  d = digit;
  digit += '0';
  *val = (*val - d)*10.0;
  return digit;
}

/*
  On machines with a small(?) stack size, you can redefine the
  FSLPRINTF_BUF_SIZE to be less than 350.  But beware - for smaller
  values some %f conversions may go into an infinite loop.
*/
#ifndef FSLPRINTF_BUF_SIZE
#  define FSLPRINTF_BUF_SIZE 350  /* Size of the output buffer for numeric conversions */
#endif

#if defined(FSL_INT_T_PFMT)
/* int64_t is already defined. */
#else
#  if ! defined(__STDC__) && !defined(__TINYC__)
#    ifdef FSLPRINTF_INT64_TYPE
typedef FSLPRINTF_INT64_TYPE int64_t;
typedef unsigned FSLPRINTF_INT64_TYPE uint64_t;
#    elif defined(_MSC_VER) || defined(__BORLANDC__)
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#    else
typedef long long int int64_t;
typedef unsigned long long int uint64_t;
#    endif
#  endif
#endif /* Set up of int64 type */

static int spech_string_to_html( fsl_output_f pf, void * pfArg,
                                 unsigned int pfLen, void * varg ){
  char const * ch = (char const *) varg;
  unsigned int i;
  int rc = 0;
  if( ! ch ) return 0;
  rc = 0;
  for( i = 0; 0==rc && (i<pfLen) && *ch; ++ch, ++i )
  {
    switch( *ch )
    {
      case '<': rc = pf( pfArg, "&lt;", 4 );
        break;
      case '&': rc = pf( pfArg, "&amp;", 5 );
        break;
      default:
        rc = pf( pfArg, ch, 1 );
        break;
    };
  }
  return rc;
}

static int httpurl_needs_escape( int c ){
  /*
    Definition of "safe" and "unsafe" chars
    was taken from:

    https://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4029/
  */
  return ( (c >= 32 && c <=47)
           || ( c>=58 && c<=64)
           || ( c>=91 && c<=96)
           || ( c>=123 && c<=126)
           || ( c<32 || c>=127)
           );
}

/**
   The handler for the etURLENCODE specifier.

   It expects varg to be a string value, which it will preceed to
   encode using an URL encoding algothrim (certain characters are
   converted to %XX, where XX is their hex value) and passes the
   encoded string to pf(). It returns the total length of the output
   string.
*/
static int spech_urlencode( fsl_output_f pf, void * pfArg,
                            unsigned int pfLen fsl__unused, void * varg ){
  char const * str = (char const *) varg;
  int rc = 0;
  char ch = 0;
  char const * hex = "0123456789ABCDEF";
#define xbufsz 10
  char xbuf[xbufsz];
  int slen = 0;
  (void)pfLen;
  if( ! str ) return 0;
  memset( xbuf, 0, xbufsz );
  ch = *str;
#define xbufsz 10
  slen = 0;
  for( ; 0==rc && ch; ch = *(++str) ){
    if( ! httpurl_needs_escape( ch ) ){
      rc = pf( pfArg, str, 1 );
      continue;
    }else{
      xbuf[0] = '%';
      xbuf[1] = hex[((ch>>4)&0xf)];
      xbuf[2] = hex[(ch&0xf)];
      xbuf[3] = 0;
      slen = 3;
      rc = pf( pfArg, xbuf, slen );
    }
  }
#undef xbufsz
  return rc;
}

/*
   hexchar_to_int():

   For 'a'-'f', 'A'-'F' and '0'-'9', returns the appropriate decimal
   number.  For any other character it returns -1.
*/
static int hexchar_to_int( int ch ){
  if( (ch>='0' && ch<='9') ) return ch-'0';
  else if( (ch>='a' && ch<='f') ) return ch-'a'+10;
  else if( (ch>='A' && ch<='F') ) return ch-'A'+10;
  else return -1;
}

/**
   The handler for the etURLDECODE specifier.

   It expects varg to be a ([const] char *), possibly encoded
   with URL encoding. It decodes the string using a URL decode
   algorithm and passes the decoded string to
   pf(). It returns the total length of the output string.
   If the input string contains malformed %XX codes then this
   function will return prematurely.
*/
static int spech_urldecode( fsl_output_f pf, void * pfArg,
                            unsigned int pfLen, void * varg ){
  char const * str = (char const *) varg;
  int rc = 0;
  char ch = 0;
  char ch2 = 0;
  char xbuf[4];
  int decoded;
  char const * end = str + pfLen;
  if( !str || !pfLen ) return 0;
  ch = *str;
  while(0==rc && ch && str<end){
    if( ch == '%' ){
      if(str+2>=end) goto outro/*invalid partial encoding - simply skip it*/;
      ch = *(++str);
      ch2 = *(++str);
      if( isxdigit((unsigned char)ch) &&
          isxdigit((unsigned char)ch2) )
      {
        decoded = (hexchar_to_int( ch ) * 16)
          + hexchar_to_int( ch2 );
        xbuf[0] = (char)decoded;
        xbuf[1] = 0;
        rc = pf( pfArg, xbuf, 1 );
        ch = *(++str);
        continue;
      }else{
        xbuf[0] = '%';
        xbuf[1] = ch;
        xbuf[2] = ch2;
        xbuf[3] = 0;
        rc = pf( pfArg, xbuf, 3 );
        ch = *(++str);
        continue;
      }
    }else if( ch == '+' ){
      xbuf[0] = ' ';
      xbuf[1] = 0;
      rc = pf( pfArg, xbuf, 1 );
      ch = *(++str);
      continue;
    }
    outro:
    xbuf[0] = ch;
    xbuf[1] = 0;
    rc = pf( pfArg, xbuf, 1 );
    ch = *(++str);
  }
  return rc;
}

/**
   Quotes the (char *) varg as an SQL string 'should' be quoted. The
   exact type of the conversion is specified by xtype, which must be
   one of etSQLESCAPE, etSQLESCAPE2, etSQLESCAPE3.

   Search this file for those constants to find the associated
   documentation.
*/
static int spech_sqlstring( int xtype, fsl_output_f pf,
                            void * pfArg, unsigned int pfLen,
                            void * varg ){
  enum { BufLen = 512 };
  char buf[BufLen];
  unsigned int i = 0, j = 0;
  int ch;
  char const q = xtype==etSQLESCAPE3 ?'"':'\''; /* Quote character */
  char const * escarg = (char const *) varg;
  bool const isnull = escarg==0;
  bool const needQuote =
    !isnull && (xtype==etSQLESCAPE2
                || xtype==etBLOBSQL
                || xtype==etSQLESCAPE3);
  if( isnull ){
    if(xtype==etSQLESCAPE2||xtype==etSQLESCAPE3){
      escarg = "NULL";
      pfLen = 4;
    }else{
      escarg = "(NULL)";;
      pfLen = 6;
    }
  }
  if( needQuote ) buf[j++] = q;
  for(i=0; (ch=escarg[i])!=0 && i<pfLen; ++i){
    buf[j++] = ch;
    if( ch==q ) buf[j++] = ch;
    if(j+2>=BufLen){
      int const rc = pf( pfArg, &buf[0], j );
      if(rc) return rc;
      j = 0;
    }
  }
  if( needQuote ) buf[j++] = q;
  buf[j] = 0;
  return j>0 ? pf( pfArg, &buf[0], j ) : 0;
}

/* TODO? Move these UTF8 bits into the public API? */
/*
** This lookup table is used to help decode the first byte of
** a multi-byte UTF8 character.
**
** Taken from sqlite3:
** https://www.sqlite.org/src/artifact?ln=48-61&name=810fbfebe12359f1
*/
static const unsigned char fsl_utfTrans1[] = {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00
};
static unsigned int fsl_utf8_read_char(
  const unsigned char *zIn,       /* First byte of UTF-8 character */
  const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
){
  /*
    Adapted from sqlite3:
    https://www.sqlite.org/src/artifact?ln=155-165&name=810fbfebe12359f1
  */
  unsigned c;
  if(zIn>=zTerm){
    *pzNext = zTerm;
    c = 0;
  }else{
    c = (unsigned int)*(zIn++);
    if( c>=0xc0 ){
      c = fsl_utfTrans1[c-0xc0];
      while( zIn!=zTerm && (*zIn & 0xc0)==0x80 )
        c = (c<<6) + (0x3f & *(zIn++));
      if( c<0x80 || (c&0xFFFFF800)==0xD800 ){
        /*https://sqlite.org/src/info/0f5ddd0041*/
        c = 0xFFFD;
      }
    }
    *pzNext = zIn;
  }
  return c;
}

static int fsl_utf8_char_to_cstr(unsigned int c, unsigned char *output, unsigned char length){
    /* Stolen from the internet, adapted from several variations which
      all _seem_ to have derived from librdf. */
    unsigned char size=0;

    /* check for illegal code positions:
     * U+D800 to U+DFFF (UTF-16 surrogates)
     * U+FFFE and U+FFFF
     */
    if((c > 0xD7FF && c < 0xE000)
       || c == 0xFFFE || c == 0xFFFF) return -1;

    /* Unicode 3.2 only defines U+0000 to U+10FFFF and UTF-8 encodings of it */
    if(c > 0x10ffff) return -1;

    if (c < 0x00000080) size = 1;
    else if (c < 0x00000800) size = 2;
    else if (c < 0x00010000) size = 3;
    else size = 4;
    if(!output) return (int)size;
    else if(size > length) return -1;
    else switch(size) {
      case 0:
          assert(!"can't happen anymore");
          output[0] = 0;
          return 0;
      case 4:
          output[3] = 0x80 | (c & 0x3F);
          c = c >> 6;
          c |= 0x10000;
          /* Fall through */
      case 3:
          output[2] = 0x80 | (c & 0x3F);
          c = c >> 6;
          c |= 0x800;
          /* Fall through */
      case 2:
          output[1] = 0x80 | (c & 0x3F);
          c = c >> 6;
          c |= 0xc0;
          /* Fall through */
      case 1:
        output[0] = (unsigned char)c;
          /* Fall through */
      default:
        return (int)size;
    }
}

struct SpechJson {
  char const * z;
  bool addQuotes;
  bool escapeSmallUtf8;
};

/**
   fsl_appendf_spec_handler for etJSONSTR. It assumes that varg is a
   SpechJson struct instance.
*/
static int spech_json( fsl_output_f pf, void * pfArg,
                       unsigned int pfLen, void * varg ){
  struct SpechJson const * state = (struct SpechJson *)varg;
  int pfRc = 0;
  const unsigned char *z = (const unsigned char *)state->z;
  const unsigned char *zEnd = z ? z + pfLen : NULL;
  const unsigned char * zNext = 0;
  unsigned int c;
  unsigned char c1;

#define out(X,N) pfRc=pf(pfArg, (char const *)(X), N); \
  if(0!=pfRc) return pfRc
#define outc c1 = (unsigned char)c; out(&c1,1)
  if(!z){
    out("null",4);
    return pfRc;
  }
  if(state->addQuotes){
    out("\"", 1);
  }
  for( ; 0==pfRc && (z < zEnd)
         && (c=fsl_utf8_read_char(z, zEnd, &zNext));
       z = zNext ){
    if( c=='\\' || c=='"' ){
      out("\\", 1);
      outc;
    }else if( c<' ' ){
      out("\\",1);
      switch(c){
        case '\b': out("b",1); break;
        case '\f': out("f",1); break;
        case '\n': out("n",1); break;
        case '\t': out("t",1); break;
        case '\r': out("r",1); break;
        default:{
          unsigned char ubuf[5] = {'u',0,0,0,0};
          int i;
          for(i = 4; i>0; --i){
            ubuf[i] = "0123456789abcdef"[c&0xf];
            c >>= 4;
          }
          out(ubuf,5);
          break;
        }
      }
    }else if(c<128){
      outc;
    }/* At this point we know that c is part of a multi-byte
        character. We're assuming legal UTF8 input, which means
        emitting a surrogate pair if the value is > 0xffff. */
    else if(c<0xFFFF){
      unsigned char ubuf[6];
      if(state->escapeSmallUtf8){
        /* Output char in \u#### form. */
        fsl_snprintf((char *)ubuf, 6, "\\u%04x", c);
        out(ubuf, 6);
      }else{
        /* Output character literal. */
        int const n = fsl_utf8_char_to_cstr(c, ubuf, 4);
        if(n<0){
          out("?",1);
        }else{
          assert(n>0);
          out(ubuf, n);
        }
      }
    }else{
      /* Surrogate pair. */
      unsigned char ubuf[12];
      c -= 0x10000;
      fsl_snprintf((char *)ubuf, 12, "\\u%04x\\u%04x",
                   (0xd800 | (c>>10)),
                   (0xdc00 | (c & 0x3ff)));
      out(ubuf, 12);
    }
  }
  if(state->addQuotes){
    out("\"",1);
  }
  return pfRc;
#undef out
#undef outc
}

/*
   Find the length of a string as long as that length does not
   exceed N bytes.  If no zero terminator is seen in the first
   N bytes then return N.  If N is negative, then this routine
   is an alias for strlen(). Returns -1 if the length would exceed
   INT_MAX.
*/
static int StrNLen32(const char *z, int N){
  int n = 0;
  while( (N-- != 0) && *(z++)!=0 ){
    if( INT_MAX==n ) return -1;
    n++;
  }
  return n;
}

#if 0
/**
   Given the first byte of an assumed-to-be well-formed UTF8
   character, returns the length of that character. Returns 0 if the
   character appears to be an invalid UTF8 character, else returns its
   length, in bytes (1-4). Note that a NUL byte is a valid length-1
   character.
*/
static int utf8__char_length( unsigned char const * const c ){
  switch(0xF0 & *c) {
    case 0xF0: return (c[1]&0x80 && c[2]&0x80 && c[3]&0x80) ? 4 : 0;
    case 0xE0: return (c[1]&0x80 && c[2]&0x80) ? 3 : 0;
    case 0xC0: return (c[1]&0x80) ? 2 : 0;
    case 0x80: return 0;
    default: return 1;
      /* See also: https://stackoverflow.com/questions/4884656/utf-8-encoding-size */
  }
}
#endif

/**
   Internal helper for %#W.Ps format.
*/
static void appendf__utf8_altform(char const * z, int * pLength,
                                  int * pPrecision, int * pWidth){
  /* Treat %#W.Ps as a width/precision limit of W resp. P UTF8
     characters instead of bytes. */
  int pC = 0/*precision, chars*/, pB = 0/*precision, bytes*/,
    wC = 0/*width, chars*/, wB = 0/*width, bytes*/;
  char const * const zEnd = z + *pLength;
  int lc;
  while( z < zEnd ){
    switch(0xF0 & *z) {
      case 0xF0: lc = (z[1]&0x80 && z[2]&0x80 && z[3]&0x80) ? 4 : 0; break;
      case 0xE0: lc = (z[1]&0x80 && z[2]&0x80) ? 3 : 0; break;
      case 0xC0: lc = (z[1]&0x80) ? 2 : 0; break;
      case 0x80: lc = 0; break;
      default: lc = 1; break;
    }
    if(!lc) break;
    else if(wC<*pWidth && (*pPrecision<=0 || pC<*pPrecision)){ ++wC; wB+=lc;}
    if(pC<*pPrecision){ ++pC; pB+=lc;}
    z+=lc;
  }
  if(*pPrecision>0) *pLength = pB;
  if(*pWidth>0) *pWidth = *pWidth - wC + wB;
}

/*
  The root printf program.  All variations call this core.  It
  implements most of the common printf behaviours plus some extended
  ones.

  INPUTS:

  pfAppend : The is a fsl_output_f function which is responsible for
  accumulating the output. If pfAppend returns non-0 then processing
  stops immediately.

  pfAppendArg : is ignored by this function but passed as the first
  argument to pfAppend. pfAppend will presumably use it as a data
  store for accumulating its string.

  fmt : This is the format string, as in the usual printf().

  ap : This is a pointer to a list of arguments.  Same as in
  vprintf() and friends.

  OUTPUTS:

  The return value is 0 on success, non-0 on error. Historically it
  returned the total number bytes reported appended by pfAppend, but
  those semantics (A) are only very, very rarely useful and (B) they
  make sensibly reporting errors via the generic callback interface
  next to impossible. e.g. the callback may encounter I/O or allocation
  errors.

  Much of this code dates back to the early 1980's, supposedly.

  Known change history (most historic info has been lost):

  10 Feb 2008 by Stephan Beal: refactored to remove the 'useExtended'
  flag (which is now always on). Added the fsl_output_f typedef to
  make this function generic enough to drop into other source trees
  without much work.

  31 Oct 2008 by Stephan Beal: refactored the et_info lookup to be
  constant-time instead of linear.
*/
int fsl_appendfv(fsl_output_f pfAppend, /* Accumulate results here */
                 void * pfAppendArg,     /* Passed as first arg to pfAppend. */
                 const char *fmt,        /* Format string */
                 va_list ap              /* arguments */
                 ){
  /**
     HISTORIC NOTE (author and year unknown):

     Note that the order in which automatic variables are declared below
     seems to make a big difference in determining how fast this beast
     will run.
  */
  int pfrc = 0;              /* result from calling pfAppend */
  int c;                     /* Next character in the format string */
  char *bufpt = 0;           /* Pointer to the conversion buffer */
  int precision = 0;         /* Precision of the current field */
  int length;                /* Length of the field */
  int idx;                   /* A general purpose loop counter */
  int width;                 /* Width of the current field */
  etByte flag_leftjustify;   /* True if "-" flag is present */
  etByte flag_plussign;      /* True if "+" flag is present */
  etByte flag_blanksign;     /* True if " " flag is present */
  etByte flag_althash;       /* True if "#" flag is present */
  etByte flag_altbang;       /* True if "!" flag is present */
  etByte flag_zeropad;       /* True if field width constant starts with zero */
  etByte flag_long;          /* True if "l" flag is present */
  etByte flag_longlong;      /* True if the "ll" flag is present */
  etByte done;               /* Loop termination flag */
  etByte cThousand           /* Thousands separator for %d and %u */
    /* ported in from https://fossil-scm.org/home/info/2cdbdbb1c9b7ad2b */;
  uint64_t longvalue;        /* Value for integer types */
  LONGDOUBLE_TYPE realvalue; /* Value for real types */
  const et_info *infop = 0;      /* Pointer to the appropriate info structure */
  char buf[FSLPRINTF_BUF_SIZE];       /* Conversion buffer */
  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
  etByte xtype = 0;          /* Conversion paradigm */
  char * zExtra = 0;         /* Extra memory used for conversions */
  int  exp, e2;              /* exponent of real numbers */
  double rounder;            /* Used for rounding floating point values */
  etByte flag_dp;            /* True if decimal point should be shown */
  etByte flag_rtz;           /* True if trailing zeros should be removed */
  etByte flag_exp;           /* True to force display of the exponent */
  int nsd;                   /* Number of significant digits returned */
  char bufSpaces[128] = {0}; /* Buffer for space-padded values */

/**
   FSLPRINTF_CHARARRAY is a helper to allocate variable-sized arrays.
   This exists mainly so this code can compile with the tcc compiler.
*/
#if FSLPRINTF_HAVE_VARARRAY
#  define FSLPRINTF_CHARARRAY(V,N) char V[N+1]; memset(V,0,N+1)
#  define FSLPRINTF_CHARARRAY_FREE(V)
#else
#  define FSLPRINTF_CHARARRAY(V,N)         \
  char * V;                                \
  if((int)(N)<((int)sizeof(bufSpaces))){   \
    V = &bufSpaces[0];                     \
  }else{                                   \
    V = (char *)fsl_malloc(N+1);           \
    if(!V) {FSLPRINTF_RETURN(FSL_RC_OOM);} \
  }
#  define FSLPRINTF_CHARARRAY_FREE(V) if(V!=&bufSpaces[0]) fsl_free(V)
#endif

  /* FSLPRINTF_RETURN, FSLPRINTF_CHECKERR, and FSLPRINTF_SPACES
     are internal helpers.
  */
#define FSLPRINTF_RETURN(RC) pfrc=RC; goto end
#define FSLPRINTF_CHECKERR if( 0!=pfrc ) goto end
/* Sets length to SZ, failing with FSL_RC_RANGE if SZ does not fit. */
#define FSLPRINTF_SETLEN(SZ)                                \
  { fsl_size_t const sz__ = (SZ);                          \
    if( sz__ > (fsl_size_t)INT_MAX ){                      \
      FSLPRINTF_RETURN(FSL_RC_RANGE);                      \
    }                                                      \
    length = (int)sz__; }
#define FSLPRINTF_SPACES(N)                     \
  {                                             \
    FSLPRINTF_CHARARRAY(zSpaces,N);             \
    memset( zSpaces,' ',N);                     \
    pfrc = pfAppend(pfAppendArg, zSpaces, N);   \
    FSLPRINTF_CHARARRAY_FREE(zSpaces);          \
    FSLPRINTF_CHECKERR;                         \
  } (void)0

  length = 0;
  bufpt = 0;
  for(; (c=(*fmt))!=0; ++fmt){
    assert(0==pfrc);
    if( c!='%' ){
      int amt;
      bufpt = (char *)fmt;
      amt = 1;
      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
      pfrc = pfAppend( pfAppendArg, bufpt, amt);
      FSLPRINTF_CHECKERR;
      if( c==0 ) break;
    }
    if( (c=(*++fmt))==0 ){
      pfrc = pfAppend( pfAppendArg, "%", 1);
      FSLPRINTF_CHECKERR;
      break;
    }
    /* Find out what flags are present */
    flag_leftjustify = flag_plussign = flag_blanksign = cThousand =
      flag_althash = flag_altbang = flag_zeropad = 0;
    done = 0;
    do{
      switch( c ){
        case '-':   flag_leftjustify = 1;  break;
        case '+':   flag_plussign = 1;     break;
        case ' ':   flag_blanksign = 1;    break;
        case '#':   flag_althash = 1;      break;
        case '!':   flag_altbang = 1;      break;
        case '0':   flag_zeropad = 1;      break;
        case ',':   cThousand = ',';       break;
        default:    done = 1;              break;
      }
    }while( !done && (c=(*++fmt))!=0 );
    /* Get the field width */
    width = 0;
    if( c=='*' ){
      width = va_arg(ap,int);
      if( width<0 ){
        flag_leftjustify = 1;
        width = width >= -2147483647 ? -width : 0;
      }
      c = *++fmt;
    }else{
      unsigned wx = 0;
      while( c>='0' && c<='9' ){
        wx = wx * 10 + c - '0';
        width = width*10 + c - '0';
        c = *++fmt;
      }
      width = wx & 0x7fffffff;
    }
    if( width > FSLPRINTF_BUF_SIZE-10 ){
      width = FSLPRINTF_BUF_SIZE-10;
    }
    /* Get the precision */
    if( c=='.' ){
      precision = 0;
      c = *++fmt;
      if( c=='*' ){
        precision = va_arg(ap,int);
        c = *++fmt;
        if( precision<0 ){
          precision = precision >= -2147483647 ? -precision : -1;
        }
      }else{
        unsigned px = 0;
        while( c>='0' && c<='9' ){
          px = px*10 + c - '0';
          c = *++fmt;
        }
        precision = px & 0x7fffffff;
      }
    }else{
      precision = -1;
    }
    /* Get the conversion type modifier */
    if( c=='l' ){
      flag_long = 1;
      c = *++fmt;
      if( c=='l' ){
        flag_longlong = 1;
        c = *++fmt;
      }else{
        flag_longlong = 0;
      }
    }else{
      flag_long = flag_longlong = 0;
    }
    /* Fetch the info entry for the field */
    infop = 0;
#define FMTNDX(N) (N - fmtinfo[0].fmttype)
#define FMTINFO(N) (fmtinfo[ FMTNDX(N) ])
    infop = ((c>=(fmtinfo[0].fmttype)) && (c<fmtinfo[etNINFO-1].fmttype))
      ? &FMTINFO(c)
      : 0;
    /*fprintf(stderr,"char '%c'/%d @ %d,  type=%c/%d\n",c,c,FMTNDX(c),infop->fmttype,infop->type);*/
    if( infop ) xtype = infop->type;
#undef FMTINFO
#undef FMTNDX
    if( (!infop) || (!infop->type) ){
      FSLPRINTF_RETURN(FSL_RC_RANGE);
    }
    assert( !zExtra );

    /* Limit the precision to prevent overflowing buf[] during conversion */
    if( precision>FSLPRINTF_BUF_SIZE-40 && (infop->flags & FLAG_STRING)==0 ){
      precision = FSLPRINTF_BUF_SIZE-40;
    }

    /*
      At this point, variables are initialized as follows:

      flag_althash                TRUE if a '#' is present.
      flag_altbang                TRUE if a '!' is present.
      flag_plussign               TRUE if a '+' is present.
      flag_leftjustify            TRUE if a '-' is present or if the
                                  field width was negative.
      flag_zeropad                TRUE if the width began with 0.
      flag_long                   TRUE if the letter 'l' (ell) prefixed
                                  the conversion character.
      flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
                                  the conversion character.
      flag_blanksign              TRUE if a ' ' is present.
      width                       The specified field width.  This is
                                  always non-negative.  Default is 0.
      precision                   The specified precision.  The default
                                  is -1.
      xtype                       The class of the conversion.
      infop                       Pointer to the appropriate info struct.
    */
    switch( xtype ){
      case etPOINTER:
        flag_longlong = sizeof(char*)==sizeof(int64_t);
        flag_long = sizeof(char*)==sizeof(long int);
        FSL_SWITCH_FALL_THROUGH;
      case etORDINAL:
      case etRADIX:
        if( infop->flags & FLAG_SIGNED ){
          int64_t v;
          if( flag_longlong )   v = va_arg(ap,int64_t);
          else if( flag_long )  v = va_arg(ap,long int);
          else                  v = va_arg(ap,int);
          if( v<0 ){
            longvalue = -(uint64_t)v;
            prefix = '-';
          }else{
            longvalue = v;
            if( flag_plussign )        prefix = '+';
            else if( flag_blanksign )  prefix = ' ';
            else                       prefix = 0;
          }
        }else{
          if( flag_longlong )   longvalue = va_arg(ap,uint64_t);
          else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
          else                  longvalue = va_arg(ap,unsigned int);
          prefix = 0;
        }
        if( longvalue==0 ) flag_althash = 0;
        if( flag_zeropad && precision<width-(prefix!=0) ){
          precision = width-(prefix!=0);
        }
        bufpt = &buf[FSLPRINTF_BUF_SIZE-1];
        if( xtype==etORDINAL ){
          static const char zOrd[] = "thstndrd";
          int x = longvalue % 10;
          if( x>=4 || (longvalue/10)%10==1 ){
            x = 0;
          }
          buf[FSLPRINTF_BUF_SIZE-3] = zOrd[x*2];
          buf[FSLPRINTF_BUF_SIZE-2] = zOrd[x*2+1];
          bufpt -= 2;
        }
        {
          int const base = infop->base;
          const char *cset = &aDigits[infop->charset];
          do{                                           /* Convert to ascii */
            *(--bufpt) = cset[longvalue%base];
            longvalue = longvalue/base;
          }while( longvalue>0 );
        }
        length = &buf[FSLPRINTF_BUF_SIZE-1]-bufpt;
        while( precision>length ){
          *(--bufpt) = '0';                             /* Zero pad */
          ++length;
        }
        if( cThousand ){
          int nn = (length - 1)/3;  /* Number of "," to insert */
          int ix = (length - 1)%3 + 1;
          bufpt -= nn;
          for(idx=0; nn>0; idx++){
            bufpt[idx] = bufpt[idx+nn];
            ix--;
            if( ix==0 ){
              bufpt[++idx] = cThousand;
              nn--;
              ix = 3;
            }
          }
        }
        if( prefix ) *(--bufpt) = prefix;         /* Add sign */
        if( flag_althash && infop->prefix ){      /* Add "0" or "0x" */
          const char *pre;
          char x;
          pre = &aPrefix[infop->prefix];
          if( *bufpt!=pre[0] ){
            for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
          }
        }
        length = &buf[FSLPRINTF_BUF_SIZE-1]-bufpt;
        break;
      case etFLOAT:
      case etEXP:
      case etGENERIC:
        realvalue = va_arg(ap,double);
        if( precision<0 ) precision = 6;         /* Set default precision */
        if( precision>FSLPRINTF_BUF_SIZE/2-10 ) precision = FSLPRINTF_BUF_SIZE/2-10;
        if( realvalue<0.0 ){
          realvalue = -realvalue;
          prefix = '-';
        }else{
          if( flag_plussign )          prefix = '+';
          else if( flag_blanksign )    prefix = ' ';
          else                         prefix = 0;
        }
        if( xtype==etGENERIC && precision>0 ) precision--;
#if 0
        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
        for(idx=precision & 0xfff, rounder=0.4999; idx>0; idx--, rounder*=0.1);
#else
        /* It makes more sense to use 0.5 */
        for(idx=precision & 0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
#endif
        if( xtype==etFLOAT ) realvalue += rounder;
        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
        exp = 0;
#if 1
        if( (realvalue)!=(realvalue) ){
          /* from sqlite3: #define sqlite3_isnan(X)  ((X)!=(X)) */
          /* This weird array thing is to avoid constness violations
             when assinging, e.g. "NaN" to bufpt.
          */
          static char NaN[4] = {'N','a','N','\0'};
          bufpt = NaN;
          length = 3;
          break;
        }
#endif
        if( realvalue>0.0 ){
          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
          while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
          while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
          if( exp>350 || exp<-350 ){
            if( prefix=='-' ){
              static char Inf[5] = {'-','I','n','f','\0'};
              bufpt = Inf;
              length = 4;
            }else if( prefix=='+' ){
              static char Inf[5] = {'+','I','n','f','\0'};
              bufpt = Inf;
              length = 4;
            }else{
              static char Inf[4] = {'I','n','f','\0'};
              bufpt = Inf;
              length = 3;
            }
            break;
          }
        }

        /* right around here somewhere we could port in
           https://sqlite.org/src/info/09e1d7c7b4615262dd03, which
           removes '-' signs from results containing only '0'
           digits. This impl has diverged far from that one since its
           original fork (in 2008-ish), so that change may not be
           straightforward here. */

        bufpt = buf;
        /*
          If the field type is etGENERIC, then convert to either etEXP
          or etFLOAT, as appropriate.
        */
        flag_exp = xtype==etEXP;
        if( xtype!=etFLOAT ){
          realvalue += rounder;
          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
        }
        if( xtype==etGENERIC ){
          flag_rtz = !flag_althash;
          if( exp<-4 || exp>precision ){
            xtype = etEXP;
          }else{
            precision = precision - exp;
            xtype = etFLOAT;
          }
        }else{
          flag_rtz = 0;
        }
        if( xtype==etEXP ){
          e2 = 0;
        }else{
          e2 = exp;
        }
        nsd = 0;
        flag_dp = (precision>0) | flag_althash | flag_altbang;
        /* The sign in front of the number */
        if( prefix ){
          *(bufpt++) = prefix;
        }
        /* Digits prior to the decimal point */
        if( e2<0 ){
          *(bufpt++) = '0';
        }else{
          for(; e2>=0; e2--){
            *(bufpt++) = et_getdigit(&realvalue,&nsd);
          }
        }
        /* The decimal point */
        if( flag_dp ){
          *(bufpt++) = '.';
        }
        /* "0" digits after the decimal point but before the first
           significant digit of the number */
        for(e2++; e2<0 && precision>0; precision--, e2++){
          *(bufpt++) = '0';
        }
        /* Significant digits after the decimal point */
        while( (precision--)>0 ){
          *(bufpt++) = et_getdigit(&realvalue,&nsd);
        }
        /* Remove trailing zeros and the "." if no digits follow the "." */
        if( flag_rtz && flag_dp ){
          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
          /* assert( bufpt>buf ); */
          if( bufpt[-1]=='.' ){
            if( flag_altbang ){
              *(bufpt++) = '0';
            }else{
              *(--bufpt) = 0;
            }
          }
        }
        /* Add the "eNNN" suffix */
        if( flag_exp || (xtype==etEXP && exp) ){
          *(bufpt++) = aDigits[infop->charset];
          if( exp<0 ){
            *(bufpt++) = '-'; exp = -exp;
          }else{
            *(bufpt++) = '+';
          }
          if( exp>=100 ){
            *(bufpt++) = (exp/100)+'0';                /* 100's digit */
            exp %= 100;
          }
          *(bufpt++) = exp/10+'0';                     /* 10's digit */
          *(bufpt++) = exp%10+'0';                     /* 1's digit */
        }
        *bufpt = 0;

        /* The converted number is in buf[] and zero terminated. Output it.
           Note that the number is in the usual order, not reversed as with
           integer conversions. */
        length = bufpt-buf;
        bufpt = buf;

        /* Special case:  Add leading zeros if the flag_zeropad flag is
           set and we are not left justified */
        if( flag_zeropad && !flag_leftjustify && length < width){
          int i;
          int nPad = width - length;
          for(i=width; i>=nPad; i--){
            bufpt[i] = bufpt[i-nPad];
          }
          i = prefix!=0;
          while( nPad-- ) bufpt[i++] = '0';
          length = width;
        }
        break;
      case etPERCENT:
        buf[0] = '%';
        bufpt = buf;
        length = 1;
        break;
      case etCHARLIT:
      case etCHARX:
        c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
        if( precision>=0 ){
          for(idx=1; idx<precision; idx++) buf[idx] = c;
          length = precision;
        }else{
          length =1;
        }
        bufpt = buf;
        break;
      case etPATH: {
        /* Sanitize path-like inputs, replacing \\ with /. */
        int i;
        int limit = flag_althash ? va_arg(ap,int) : -1;
        char const *e = va_arg(ap,char const*);
        if( e ){
          length = StrNLen32(e, limit);
          if( length<0 ){ FSLPRINTF_RETURN(FSL_RC_RANGE); }
          if( length >= FSLPRINTF_BUF_SIZE-1 ){
            zExtra = bufpt = fsl_malloc(length+1);
            if(!zExtra) return FSL_RC_OOM;
          }else{
            bufpt = buf;
          }
          for( i=0; i<length; i++ ){
            if( e[i]=='\\' ){
              bufpt[i]='/';
            }else{
              bufpt[i]=e[i];
            }
          }
          bufpt[length]='\0';
        }
        break;
      }
      case etSTRINGID: {
        precision = flag_altbang ? -1 : 16
          /* In fossil(1) this is configurable, but in this lib we
             don't have access to that state from here. Fossil also
             has the '!' flag_altbang, which indicates that it
             should be for a URL, and thus longer than the default.
             We are only roughly approximating that behaviour here. */;
        FSL_SWITCH_FALL_THROUGH;
      }
      case etDYNSTRING:
      case etSTRING: {
        bufpt = va_arg(ap,char*);
        length = bufpt
          ? StrNLen32(bufpt,
                      (precision>0 && flag_althash)
                      ? precision*4/*max bytes per char*/
                      : (precision>=0 ? precision : -1))
          : (int)0;
        if( length<0 ){ FSLPRINTF_RETURN(FSL_RC_RANGE); }
        if(flag_althash && length && (precision>0 || width>0)){
          appendf__utf8_altform(bufpt, &length, &precision, &width);
        }else if( length && precision>=0 && precision<length ){
          length = precision;
        }
        if( etDYNSTRING==xtype ){
          zExtra = bufpt /* will be freed below */;
        }
        break;
      }
      case etBLOB: {
        /* int const limit = flag_althash ? va_arg(ap, int) : -1; */
        fsl_b *pBlob = va_arg(ap, fsl_b*);
        bufpt = fsl_b_str(pBlob);
        FSLPRINTF_SETLEN(fsl_b_size(pBlob));
        if( precision>=0 && precision<length ) length = precision;
        /* if( limit>=0 && limit<length ) length = limit; */
        break;
      }
      case etFOSSILIZE:{
        int const limit = -1; /*flag_althash ? va_arg(ap,int) : -1;*/
        fsl_b fb = fsl_b_empty;
        int check;
        bufpt = va_arg(ap,char*);
        FSLPRINTF_SETLEN(bufpt ? fsl_strlen(bufpt) : 0);
        if((limit>=0) && (length>limit)) length = limit;
        check = fsl_bytes_fossilize((unsigned char const *)bufpt, length, &fb);
        if(check){
          fsl_b_reserve(&fb,0);
          FSLPRINTF_RETURN(check);
        }
        zExtra = bufpt = (char*)fb.mem /*transfer ownership*/;
        FSLPRINTF_SETLEN(fb.used);
        if( precision>=0 && precision<length ) length = precision;
        break;
      }
      case etJSONSTR: {
        struct SpechJson state;
        bufpt = va_arg(ap,char *);
        if( !bufpt ) length = 0;
        else if( precision>=0 ) length = precision;
        else FSLPRINTF_SETLEN(fsl_strlen(bufpt));
        state.z = bufpt;
        state.addQuotes = flag_altbang ? true : false;
        state.escapeSmallUtf8 = flag_althash ? true : false;
        pfrc = spech_json( pfAppend, pfAppendArg, (unsigned)length, &state );
        FSLPRINTF_CHECKERR;
        bufpt = NULL;
        length = 0;
        break;
      }
      case etHTML:
      case etURLENCODE:
      case etURLDECODE:{
        bufpt = va_arg(ap,char*);
        FSLPRINTF_SETLEN(bufpt ? fsl_strlen(bufpt) : 0);
        pfrc = infop->callback( pfAppend, pfAppendArg,
                                (precision>=0 && precision<length) ? precision : length,
                                bufpt );
        FSLPRINTF_CHECKERR;
        bufpt = NULL;
        length = 0;
        break;
      }
      case etBLOBSQL:
      case etSQLESCAPE:
      case etSQLESCAPE2:
      case etSQLESCAPE3: {
        if(flag_altbang && etSQLESCAPE2==xtype){
          xtype = etSQLESCAPE3;
        }
        if(etBLOBSQL==xtype){
          fsl_b * const b = va_arg(ap,fsl_b*);
          bufpt = b ? fsl_b_str(b) : NULL;
          FSLPRINTF_SETLEN(b ? fsl_b_size(b) : 0);
          if(flag_altbang) xtype = etSQLESCAPE3;
        }else{
          /* TODO?: add flag_althash support, i.e. %#q. See
             appendf__utf8_altform()). */
          bufpt = va_arg(ap,char*);
          FSLPRINTF_SETLEN(bufpt ? strlen(bufpt) : 0);
        }
        pfrc = spech_sqlstring( xtype, pfAppend, pfAppendArg,
                                (precision>=0 && precision<length) ? precision : length,
                                bufpt );
        FSLPRINTF_CHECKERR;
        length = 0;
        break;
      }
      case etFSLRC:{
        int const i = va_arg(ap,int);
        bufpt = (char*)fsl_rc_cstr(i);
        if( bufpt ){
          length = (int)fsl_strlen(bufpt);
        }else{
          length = snprintf( buf, sizeof(buf), "#%d", i);
          bufpt = buf;
        }
        break;
      }
    }/* End switch over the format type */
    /*
      The text of the conversion is pointed to by "bufpt" and is
      "length" characters long.  The field width is "width".  Do
      the output.
    */
    if( !flag_leftjustify ){
      int nspace;
      nspace = width-length;
      if( nspace>0 ){
        FSLPRINTF_SPACES(nspace);
      }
    }
    if( length>0 ){
      pfrc = pfAppend( pfAppendArg, bufpt, length);
      FSLPRINTF_CHECKERR;
    }
    if( flag_leftjustify ){
      int nspace;
      nspace = width-length;
      if( nspace>0 ){
        FSLPRINTF_SPACES(nspace);
      }
    }
    if( zExtra ) fsl_free(zExtra);
    zExtra = 0;
  }/* End for loop over the format string */
end:
  if( zExtra ) fsl_free(zExtra);
  return pfrc;
} /* End of function */


#undef FSLPRINTF_CHARARRAY
#undef FSLPRINTF_CHARARRAY_FREE
#undef FSLPRINTF_SPACES
#undef FSLPRINTF_CHECKERR
#undef FSLPRINTF_SETLEN
#undef FSLPRINTF_RETURN
#undef FSLPRINTF_BUF_SIZE

int fsl_appendf(fsl_output_f pfAppend, void * pfAppendArg,
                const char *fmt, ... ){
  int ret;
  va_list vargs;
  va_start( vargs, fmt );
  ret = fsl_appendfv( pfAppend, pfAppendArg, fmt, vargs );
  va_end(vargs);
  return ret;
}

int fsl_appendn(fsl_output_f pfAppend, void * pfAppendArg,
                const char *str, fsl_int_t n){
  return pfAppend(pfAppendArg, (void const *)str,
                  n<0 ? fsl_strlen(str) : (fsl_size_t)n);
}

int fsl_fprintfv( FILE * fp, char const * fmt, va_list args ){
  return (fp && fmt)
    ? fsl_appendfv( fsl_output_f_FILE, fp, fmt, args )
    :  FSL_RC_MISUSE;
}

int fsl_fprintf( FILE * fp, char const * fmt, ... ){
  int ret;
  va_list vargs;
  va_start( vargs, fmt );
  ret = fsl_fprintfv( fp, fmt, vargs );
  va_end(vargs);
  return ret;
}

char * fsl_mprintfv( char const * fmt, va_list vargs ){
  if( !fmt ) return 0;
  else if(!*fmt) return fsl_strndup("",0);
  else{
    fsl_b buf = fsl_b_empty;
    int const rc = fsl_b_appendfv( &buf, fmt, vargs );
    if(rc){
      fsl_b_reserve(&buf, 0);
      assert(0==buf.mem);
    }
    return (char*)buf.mem /*transfer ownership*/;
  }
}

char * fsl_mprintf( char const * fmt, ... ){
  char * ret;
  va_list vargs;
  va_start( vargs, fmt );
  ret = fsl_mprintfv( fmt, vargs );
  va_end( vargs );
  return ret;
}


/**
    Internal state for fsl_snprintfv().
 */
struct fsl_snp_state {
  /** Destination memory */
  char * dest;
  /** Current output position in this->dest. */
  fsl_size_t pos;
  /** Length of this->dest. */
  fsl_size_t len;
};
typedef struct fsl_snp_state fsl_snp_state;

static int fsl_output_f_snprintf( void * arg,
                                  void const * data_,
                                  fsl_size_t n ){
  char const * data = (char const *)data_;
  fsl_snp_state * st = (fsl_snp_state*) arg;
  if(n==0 || (st->pos >= st->len)) return 0;
  else if((n + st->pos) > st->len){
    n = st->len - st->pos;
  }
  memcpy(st->dest + st->pos, data, n);
  st->pos += n;
  assert(st->pos <= st->len);
  return 0;
}

int fsl_snprintfv( char * dest, fsl_size_t n,
                   char const * fmt, va_list args){
  fsl_snp_state st = {NULL,0,0};
  int rc = 0;
  if(!dest || !fmt) return FSL_RC_MISUSE;
  else if(!n || !*fmt){
    if(n) *dest = 0;
    return 0;
  }
  st.len = n;
  st.dest = dest;
  rc = fsl_appendfv( fsl_output_f_snprintf, &st, fmt, args );
  if(st.pos < st.len){
    dest[st.pos] = 0;
  }
  return rc;
}

int fsl_snprintf( char * dest, fsl_size_t n, char const * fmt, ... ){
  int rc = 0;
  va_list vargs;
  va_start( vargs, fmt );
  rc = fsl_snprintfv( dest, n, fmt, vargs );
  va_end( vargs );
  return rc;
}

/**
   Appends the first n bytes of z (all of it if n is negative) to b
   for fsl_cx_formatv(). If escPct is true, each '%' is doubled so
   that the result can be used as a fsl_appendfv() format string.
   Returns b->errCode.
*/
static int fsl__cx_format_subst(fsl_b * const b, char const * z,
                                fsl_int_t n, bool escPct){
  if( !z ) n = 0;
  else if( n<0 ) n = (fsl_int_t)fsl_strlen(z);
  if( !escPct ) return fsl_b_append(b, z, n);
  for( fsl_int_t i = 0; i<n && !b->errCode; ++i ){
    if( '%'==z[i] ) fsl_b_appendch(b, '%');
    fsl_b_appendch(b, z[i]);
  }
  return b->errCode;
}

int fsl__brace_expand(fsl_b * const b, char const * const zFmt,
                      bool escPct, fsl__brace_f xToken, void * state){
  char const * z = zFmt;
  char const * zLeft = z;
  char const * const zEnd =
    z ? (z + fsl_strlen(zFmt)) : NULL /* NULL+0 is UB */;
  while( z<zEnd && !b->errCode ){
    if( z<zEnd-5 /* 5 == length of {{x}} */
        && '{'==z[0] && '{'==z[1] ){
      /* Look for {{...}} */
      zLeft = z;
      z += 2;
      while( z<zEnd-1 && !('}'==z[0] && '}'==z[1]) ){
        ++z;
      }
      assert( z<=zEnd-1 );
      if( z==zEnd-1 ){
        /* Malformed. Pass it all through. */
        fsl_b_append(b, zLeft, (zEnd - zLeft));
        z = zEnd;
        continue;
      }
      assert( z[0]=='}' && z[1]=='}' );
      fsl_size_t const n = (fsl_size_t)(z - (zLeft + 2));
      fsl_size_t nTail = 0;
      int rc;
      z += 2;
      rc = n ? xToken(state, zLeft + 2, n, z, &nTail, b, escPct)
        : FSL_RC_NOT_FOUND;
      if( FSL_RC_NOT_FOUND==rc ){
        /* Unknown: pass the whole {{X}} through as-is. */
        fsl_b_append(b, zLeft, (z - zLeft));
      }else if( rc ){
        return rc;
      }else{
        assert( nTail <= (fsl_size_t)(zEnd - z) );
        z += nTail;
      }
    }else{
      fsl_b_appendch(b, *z);
      ++z;
    }
  }
  return b->errCode;
}

/** fsl__brace_f for fsl_cx_formatv(). */
static int fsl__cx_format_token(void * state, char const * zTok,
                                fsl_size_t n, char const * zTail,
                                fsl_size_t * pnConsumed, fsl_b * const b,
                                bool escPct){
  fsl_cx * const f = state;
  (void)zTail; (void)pnConsumed /* expands no tail */;
  switch( n ){
    case 7:
      if( 0==memcmp(zTok, "repo.db", n) ){
        return fsl__cx_format_subst(b, f->db.repo.db.filename, -1, escPct);
      }
      break;
    case 9:
      if( 0==memcmp(zTok, "user.name", n) ){
        return fsl__cx_format_subst(b, fsl_cx_user_guess(f), -1, escPct);
      }
      FSL_SWITCH_FALL_THROUGH;
    case 10:
      if( 0==memcmp(zTok, "ckout.dir", 9) ){
        fsl_size_t nd = fsl_strlen(f->db.ckout.dir);
        if( nd && 0!=memcmp(zTok, "ckout.dir/", 10) ){
          /* Remove trailing "/" */
          --nd;
        }
        return fsl__cx_format_subst(b, f->db.ckout.dir, (fsl_int_t)nd,
                                    escPct);
      }
      break;
    default:
      break;
  }
  /* {{dbname.repo}}, {{dbname.ckout}}, {{temp.NAME}} and
     {{bare.temp.NAME}}, as for the fsl_db SQL functions. Their names
     contain no '%'. */
  (void)escPct;
  int const rc = fsl__db_schema_token(f->dbMain, zTok, n, NULL, NULL, b);
  if( FSL_RC_MISUSE==rc ){
    bool const isRepo = 'r'==zTok[7] /* dbname.repo, not dbname.ckout */;
    return fsl_cx_err_set(f, rc, "{{%.*s}} cannot be expanded "
                          "while the %s's tables are prefixed "
                          "with \"%s\": it names no table.", (int)n, zTok,
                          isRepo ? "repository" : "checkout",
                          isRepo ? fsl__db_repo_prefix(f->dbMain)
                          : fsl__db_ckout_prefix(f->dbMain));
  }
  return rc;
}

int fsl_cx_formatv(fsl_cx * f, fsl_output_f out, void * outState,
                   char const * const zFmt, va_list args ){
  int rc = 0;
  fsl_b * const b = f->scratchpads.format.used
    ? fsl_cx_b_borrow(f)
    : &f->scratchpads.format
    /* This bit protects us against the eventuality of recursion via
       out() without requiring a call-local allocation for
       non-recursive calls. */;
  if( !b ) return f->error.code;
  assert( zFmt );
  bool const hasPct = 0!=strchr(zFmt,'%');
  //MARKER(("input=%s\n", zFmt));
  if( b==&f->scratchpads.format && !b->capacity ){
    fsl_b_reserve(b, 128);
  }
  rc = fsl__brace_expand(b, zFmt, hasPct, fsl__cx_format_token, f);
  if( 0==rc ){
    rc = hasPct
      ? fsl_appendfv(out, outState, (char const *)b->mem, args)
      : out(outState, b->mem, b->used);
  }
  if( b==&f->scratchpads.format ) fsl_b_reuse(b);
  else fsl_cx_b_return(f, b);
  return rc;
}

int fsl_cx_format(fsl_cx * f, fsl_output_f out, void * outState,
                  char const *zFmt, ... ){
  int rc;
  va_list args;
  va_start(args,zFmt);
  rc = fsl_cx_formatv(f, out, outState, zFmt, args);
  va_end(args);
  return rc;
}

int fsl_cx_format_buffer(fsl_cx * f, fsl_b * tgt,
                         char const *zFmt, ... ){
  int rc;
  va_list args;
  va_start(args,zFmt);
  rc = fsl_cx_formatv(f, fsl_output_f_b, tgt, zFmt, args);
  va_end(args);
  return rc;
}

int fsl_cx_format_FILE(fsl_cx * f, FILE * tgt,
                       char const *zFmt, ... ){
  int rc;
  va_list args;
  va_start(args,zFmt);
  rc = fsl_cx_formatv(f, fsl_output_f_FILE, tgt, zFmt, args);
  va_end(args);
  return rc;
}


#undef MARKER
/* end of file src/appendf.c */
/* start of file src/auth.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/***************************************************************************
  This file contains routines related to working with user authentication.
*/
#include <assert.h>

/* All for/around getpass(). Yes, it's deprecated. */
#if FSL_PLATFORM_IS_UNIX
#  include <unistd.h>
#endif
#include <stdlib.h> /* free() */
#include <errno.h>

char * fsl_sha1_shared_secret2( fsl_cx * f,
                                char const * zLoginName,
                                char const * zPw,
                                char const * zProjCode ){
  fsl_sha1_cx hash;
  unsigned char zResult[20];
  char zDigest[41];

  if( !zProjCode ){
    fsl_repo_project_code(f, &zProjCode);
    if( !zProjCode ){
      /*
        fossil(1) returns a copy of zPw here if !f->cache.projectCode,
        with the following comment:
      */
      /* On the first xfer request of a clone, the project-code is not yet
      ** known.  Use the cleartext password, since that is all we have.
      */
      /* libfossil, OTOH, will need to handle that case at a different
         level, as this routine doesn't have enough info to make that
         determination. */
      return 0 /* noting that f->error has FSL_RC_NOT_FOUND or
                  FSL_RC_OOM */;
    }
  }

  assert( f );
  assert( zLoginName );
  assert( zPw );
  assert( zProjCode );
  fsl_sha1_init(&hash);
  fsl_sha1_update(&hash, zProjCode, fsl_strlen(zProjCode));
  fsl_sha1_update(&hash, "/", 1);
  fsl_sha1_update(&hash, zLoginName, fsl_strlen(zLoginName));
  fsl_sha1_update(&hash, "/", 1);
  fsl_sha1_update(&hash, zPw, fsl_strlen(zPw));
  fsl_sha1_final(&hash, zResult);
  fsl_sha1_digest_to_base16(zResult, zDigest);
  return fsl_strndup( zDigest, FSL_STRLEN_SHA1 );
}

char * fsl_sha1_shared_secret( fsl_cx * f,
                               char const * zLoginName,
                               char const * zPw ){
  return fsl_sha1_shared_secret2(f, zLoginName, zPw, NULL);
}

char * fsl_repo_login_group_name(fsl_cx * const f){
  return f
    ? fsl_config_get_text(f, FSL_CONFDB_REPO,
                          "login-group-name", 0)
    : 0;
}

char * fsl_repo_login_cookie_name(fsl_cx * const f){
  fsl_db * db;
  if(!f || !(db = fsl_cx_db_repo(f))) return 0;
  else{
    char const * sql =
      "SELECT 'fossil-' || substr(value,1,16)"
      "  FROM {{dbname.repo}}.config"
      " WHERE name IN ('project-code','login-group-code')"
      " ORDER BY name /*sort*/";
    return fsl_db_g_text(db, 0, sql);
  }
}

int fsl_repo_login_search_uid(fsl_cx * const f, char const * zUsername,
                              char const * zPasswd,
                              fsl_id_t * userId){
  int rc;
  char * zSecret;
  fsl_db * db;
  if(!f || !userId
     || !zUsername || !*zUsername
     || !zPasswd /*??? || !*zPasswd*/){
    return FSL_RC_MISUSE;
  }
  else if(!(db = fsl_needs_repo(f))){
    return FSL_RC_NOT_A_REPO;
  }
  *userId = 0;
  zSecret = fsl_sha1_shared_secret(f, zUsername, zPasswd );
  if(!zSecret){
    /* f's error state holds FSL_RC_NOT_FOUND if the repo has no
       project-code. */
    return f->error.code ? f->error.code : FSL_RC_OOM;
  }
  rc = fsl_db_get_id(db, userId,
                     "SELECT uid FROM {{dbname.repo}}.user"
                     " WHERE login=%Q"
                     "   AND length(cap)>0 AND length(pw)>0"
                     "   AND login NOT IN ('anonymous','nobody','developer','reader')"
                     "   AND (pw=%Q OR (length(pw)<>40 AND pw=%Q))",
                     zUsername, zSecret, zPasswd);
  fsl_free(zSecret);
  if( rc ){
    if( FSL_RC_OOM!=rc ){
      /* db's own message holds the SQL, which holds the password, so
         it is not uplifted. */
      rc = fsl_cx_err_set(f, rc, "Error %R searching the user table "
                          "for login \"%s\": %s", rc, zUsername,
                          sqlite3_errmsg(db->dbh));
    }
    fsl_db_err_reset(db);
  }
  return rc;
}

int fsl_repo_login_clear( fsl_cx * const f, fsl_id_t userId ){
  fsl_db * db;
  if(!f) return FSL_RC_MISUSE;
  else if(!(db = fsl_needs_repo(f))) return FSL_RC_NOT_A_REPO;
  else{
    int const rc = fsl_db_exec(db,
                               "UPDATE {{dbname.repo}}.user SET cookie=NULL, ipaddr=NULL, "
                               " cexpire=0 WHERE "
                               " CASE WHEN %"FSL_ID_T_PFMT">=0 THEN uid=%"FSL_ID_T_PFMT""
                               " ELSE uid>0 END"
                               " AND login NOT IN('anonymous','nobody',"
                               " 'developer','reader')",
                               (fsl_id_t)userId, (fsl_id_t)userId);
    if(rc){
      fsl_cx_uplift_db_error(f, db);
    }
    return rc;
  }
}

#if 0
/* TODO: (A) lock behind a feature macro and (B) port of fossil(1)'s
   getpass() alternative. */
int fsl_pw_f_getpass(fsl_cx * f, char const * zUrl,
                     fsl_b *b, void * state){
  char * z = 0;

  assert( 0==b->used);
  fsl_b_appendf(b, "%.*c\nPassword for [%s]: ",
                     (int)fsl_strlen(zUrl) + 16,
                     '*', zUrl);
  if( 0==b->errCode ){
    z = getpass( fsl_b_cstr(b) );
    if( z ){
      fsl_b_reuse(b);
      if( *z ) fsl_b_append(b, z, -1);
      free(z);
    }else{
      b->errCode = fsl_errno_to_rc(errno, FSL_RC_OOM);
    }
  }
  return b->errCode;
}
#endif
/* end of file src/auth.c */
/* start of file src/backlink.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*************************************************************************
  This file implements the backlink table: the scanning of check-in
  comments, wiki pages, ticket changes and forum posts for hyperlinks
  to other artifacts, and the recording of those links in the repo's
  backlink table. It is a port of fossil(1)'s backlink.c plus the
  parts of its wikiformat.c and markdown.c which find hyperlinks.

  The scanners do not render anything, but they must parse the text
  exactly as fossil(1) does, because what is or is not a link depends
  on the full context. That is why the Markdown and wiki parsers below
  keep the structure of the originals (including their quirks) and
  differ from them only by dropping the HTML output.
*/
#include <assert.h>
#include <stdlib.h> /* qsort(), bsearch() */
#include <string.h> /* memchr(), memcmp(), strcspn() */

/**
   State shared by the wiki and Markdown scanners: the callback which
   receives each canonicalized link target, and the first error that
   callback (or an allocation) reported. Scanners stop as soon as rc
   is non-zero.
*/
typedef struct {
  fsl__backlink_f cb;
  void * cbState;
  int rc;
} bl_sink;

/**
   zTarget is a hyperlink target in some markup format. If it looks
   like a reference to another artifact, i.e. a 4 to 64 character hex
   string optionally prefixed by "/info/", pass the lower-cased hash
   to the sink. Port of fossil(1)'s backlink_create().
*/
static void bl_create(bl_sink * const p, const char *zTarget, int nTarget){
  char zLink[FSL_STRLEN_K256+4];
  int i;
  if( p->rc || zTarget==0 ) return;
  if( nTarget<4 ) return;
  if( nTarget>=10 && 0==memcmp(zTarget,"/info/",6) ){
    zTarget += 6;
    nTarget -= 6;
  }
  if( nTarget>FSL_STRLEN_K256 ) return;
  for(i=0; i<nTarget; i++){
    char const c = zTarget[i];
    if( !((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F')) ){
      return;
    }
    zLink[i] = (char)fsl_tolower(c);
  }
  zLink[nTarget] = 0;
  p->rc = p->cb(p->cbState, zLink);
}

/*
** Fossil wiki scanner. Port of the parts of fossil(1)'s wikiformat.c
** needed by wiki_extract_links().
**
** What follows is the allowed markup and attributes. These must stay in
** alphabetical order, in numerical sequence with their enums, because
** they are binary searched. Only the names matter here: which element
** is allowed where, and with which attributes, is a rendering concern.
*/
enum bl_attr_e {
  BLA_ALIGN = 1,
  BLA_ALT,
  BLA_BGCOLOR,
  BLA_BORDER,
  BLA_CELLPADDING,
  BLA_CELLSPACING,
  BLA_CITE,
  BLA_CLASS,
  BLA_CLEAR,
  BLA_COLOR,
  BLA_COLSPAN,
  BLA_COMPACT,
  BLA_DATETIME,
  BLA_FACE,
  BLA_FOR,
  BLA_HEIGHT,
  BLA_HIGH,
  BLA_HREF,
  BLA_HSPACE,
  BLA_ID,
  BLA_LINKS,
  BLA_LOW,
  BLA_MAX,
  BLA_MEDIA,
  BLA_MIN,
  BLA_NAME,
  BLA_OPEN,
  BLA_OPTIMUM,
  BLA_ROWSPAN,
  BLA_SIZE,
  BLA_SIZES,
  BLA_SRC,
  BLA_SRCSET,
  BLA_START,
  BLA_STYLE,
  BLA_TARGET,
  BLA_TITLE,
  BLA_TYPE,
  BLA_VALIGN,
  BLA_VALUE,
  BLA_VSPACE,
  BLA_WIDTH
};

static const char * const aAttribute[] = {
  0,
  "align",
  "alt",
  "bgcolor",
  "border",
  "cellpadding",
  "cellspacing",
  "cite",
  "class",
  "clear",
  "color",
  "colspan",
  "compact",
  "datetime",
  "face",
  "for",
  "height",
  "high",
  "href",
  "hspace",
  "id",
  "links",
  "low",
  "max",
  "media",
  "min",
  "name",
  "open",
  "optimum",
  "rowspan",
  "size",
  "sizes",
  "src",
  "srcset",
  "start",
  "style",
  "target",
  "title",
  "type",
  "valign",
  "value",
  "vspace",
  "width"
};

enum bl_markup_e {
  BLM_INVALID = 0,
  BLM_A,
  BLM_ABBR,
  BLM_ADDRESS,
  BLM_HTML5_ARTICLE,
  BLM_HTML5_ASIDE,
  BLM_B,
  BLM_BIG,
  BLM_BLOCKQUOTE,
  BLM_BR,
  BLM_CAPTION,
  BLM_CENTER,
  BLM_CITE,
  BLM_CODE,
  BLM_COL,
  BLM_COLGROUP,
  BLM_DD,
  BLM_DEL,
  BLM_DETAILS,
  BLM_DFN,
  BLM_DIV,
  BLM_DL,
  BLM_DT,
  BLM_EM,
  BLM_FIGCAPTION,
  BLM_FIGURE,
  BLM_FONT,
  BLM_HTML5_FOOTER,
  BLM_H1,
  BLM_H2,
  BLM_H3,
  BLM_H4,
  BLM_H5,
  BLM_H6,
  BLM_HTML5_HEADER,
  BLM_HR,
  BLM_I,
  BLM_IMG,
  BLM_INS,
  BLM_KBD,
  BLM_LABEL,
  BLM_LI,
  BLM_MARK,
  BLM_METER,
  BLM_HTML5_NAV,
  BLM_NOBR,
  BLM_NOWIKI,
  BLM_OL,
  BLM_P,
  BLM_PICTURE,
  BLM_PRE,
  BLM_PROGRESS,
  BLM_Q,
  BLM_S,
  BLM_SAMP,
  BLM_HTML5_SECTION,
  BLM_SMALL,
  BLM_SOURCE,
  BLM_SPAN,
  BLM_STRIKE,
  BLM_STRONG,
  BLM_SUB,
  BLM_SUMMARY,
  BLM_SUP,
  BLM_TABLE,
  BLM_TBODY,
  BLM_TD,
  BLM_TFOOT,
  BLM_TH,
  BLM_THEAD,
  BLM_TIME,
  BLM_TITLE,
  BLM_TR,
  BLM_TT,
  BLM_U,
  BLM_UL,
  BLM_VAR,
  BLM_VERBATIM,
  BLM_WBR
};

static const char * const aMarkup[] = {
  0,
  "a",
  "abbr",
  "address",
  "article",
  "aside",
  "b",
  "big",
  "blockquote",
  "br",
  "caption",
  "center",
  "cite",
  "code",
  "col",
  "colgroup",
  "dd",
  "del",
  "details",
  "dfn",
  "div",
  "dl",
  "dt",
  "em",
  "figcaption",
  "figure",
  "font",
  "footer",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "header",
  "hr",
  "i",
  "img",
  "ins",
  "kbd",
  "label",
  "li",
  "mark",
  "meter",
  "nav",
  "nobr",
  "nowiki",
  "ol",
  "p",
  "picture",
  "pre",
  "progress",
  "q",
  "s",
  "samp",
  "section",
  "small",
  "source",
  "span",
  "strike",
  "strong",
  "sub",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "time",
  "title",
  "tr",
  "tt",
  "u",
  "ul",
  "var",
  "verbatim",
  "wbr"
};

/*
** Use binary search to locate a tag in the aAttribute[] table.
*/
static int bl_find_attr(const char *z){
  int i, c, first, last;
  first = 1;
  last = (int)(sizeof(aAttribute)/sizeof(aAttribute[0])) - 1;
  while( first<=last ){
    i = (first+last)/2;
    c = fsl_strcmp(aAttribute[i], z);
    if( c==0 ){
      return i;
    }else if( c<0 ){
      first = i+1;
    }else{
      last = i-1;
    }
  }
  return 0;
}

/*
** Use binary search to locate a tag in the aMarkup[] table.
*/
static int bl_find_tag(const char *z){
  int i, c, first, last;
  first = 1;
  last = (int)(sizeof(aMarkup)/sizeof(aMarkup[0])) - 1;
  while( first<=last ){
    i = (first+last)/2;
    c = fsl_strcmp(aMarkup[i], z);
    if( c==0 ){
      return i;
    }else if( c<0 ){
      first = i+1;
    }else{
      last = i-1;
    }
  }
  return BLM_INVALID;
}

/*
** Token types
*/
#define BLT_MARKUP        1  /* <...> */
#define BLT_CHARACTER     2  /* "&" or "<" not part of markup */
#define BLT_LINK          3  /* [...] */
#define BLT_PARAGRAPH     4  /* blank lines */
#define BLT_NEWLINE       5  /* A single "\n" */
#define BLT_BUL_LI        6  /*  "  *  " */
#define BLT_NUM_LI        7  /*  "  #  " */
#define BLT_ENUM          8  /*  "  \(?\d+[.)]?  " */
#define BLT_INDENT        9  /*  "   " */
#define BLT_RAW           10 /* Output exactly (used when wiki-use-html==1) */
#define BLT_TEXT          11 /* None of the above */

/*
** State flags.
*/
#define BLS_AT_NEWLINE    0x0010000  /* At start of a line */
#define BLS_AT_PARAGRAPH  0x0020000  /* At start of a paragraph */
#define BLS_ALLOW_WIKI    0x0040000  /* Allow wiki markup */

/*
** Current state of the scanner. This is fossil(1)'s Renderer, minus
** everything which only exists to produce output.
*/
typedef struct bl_wiki bl_wiki;
struct bl_wiki {
  int state;                  /* Flags that govern scanning */
  int inVerbatim;             /* True in <verbatim> mode */
  int preVerbState;           /* Value of state prior to verbatim */
  const char *zVerbatimId;    /* The id= attribute of <verbatim> */
  int nStack;                 /* Number of elements on the stack */
  int nAlloc;                 /* Space allocated for aStack */
  struct bl_stack {
    short iCode;                 /* Markup code */
    short allowWiki;             /* BLS_ALLOW_WIKI if wiki allowed before tag */
    const char *zId;             /* ID attribute or NULL */
  } *aStack;
};

/*
** z points to a "<" character.  Check to see if this is the start of
** a valid markup.  If it is, return the total number of characters in
** the markup including the initial "<" and the terminating ">".  If
** it is not well-formed markup, return 0.
*/
static int bl_html_tag_length(const char *z){
  int n = 1;
  int inparen = 0;
  int c;
  if( z[n]=='/' ){ n++; }
  if( !fsl_isalpha(z[n]) ) return 0;
  while( fsl_isalnum(z[n]) || z[n]=='-' ){ n++; }
  c = z[n];
  if( c=='/' && z[n+1]=='>' ){ return n+2; }
  if( c!='>' && !fsl_isspace(c) ) return 0;
  while( (c = z[n])!=0 && (c!='>' || inparen) ){
    if( c==inparen ){
      inparen = 0;
    }else if( inparen==0 && (c=='"' || c=='\'') ){
      inparen = c;
    }
    n++;
  }
  if( z[n]!='>' ) return 0;
  return n+1;
}

/*
** z points to a "\n" character.  Check to see if this newline is
** followed by one or more blank lines.  If it is, return the number
** of characters through the closing "\n".  If not, return 0.
*/
static int bl_paragraph_break_length(const char *z){
  int i, n;
  int nNewline = 1;
  for(i=1, n=0; fsl_isspace(z[i]); i++){
    if( z[i]=='\n' ){
      nNewline++;
      n = i;
    }
  }
  if( nNewline>=2 ){
    return n+1;
  }else{
    return 0;
  }
}

/*
** Return the number of characters until the next "interesting"
** characters.
**
** Interesting characters are:
**
**      <
**      &
**      \n
**      [
**
** The "[" is only considered if flags contain BLS_ALLOW_WIKI. The "\n"
** is only considered interesting if the flags contains BLS_ALLOW_WIKI.
*/
static int bl_text_length(const char *z, int flags){
  const char *zReject;
  if( flags & BLS_ALLOW_WIKI ){
    zReject = "<&[\n";
  }else{
    zReject = "<&";
  }
  return (int)strcspn(z, zReject);
}

/*
** Return true if z[] begins with an HTML character element.
*/
static int bl_is_element(const char *z){
  int i;
  assert( z[0]=='&' );
  if( z[1]=='#' ){
    for(i=2; fsl_isdigit(z[i]); i++){}
    return i>2 && z[i]==';';
  }else{
    for(i=1; fsl_isalpha(z[i]); i++){}
    return i>1 && z[i]==';';
  }
}

/*
** Check to see if the z[] string is the beginning of a wiki list item.
** If it is, return the length of the bullet text.  Otherwise return 0.
*/
static int bl_list_item_length(const char *z, const char listChar){
  int i, n;
  n = 0;
  i = 0;
  while( z[n]==' ' || z[n]=='\t' ){
    if( z[n]=='\t' ) i++;
    i++;
    n++;
  }
  if( i<2 || z[n]!=listChar ) return 0;
  n++;
  i = 0;
  while( z[n]==' ' || z[n]=='\t' ){
    if( z[n]=='\t' ) i++;
    i++;
    n++;
  }
  if( i<2 || fsl_isspace(z[n]) ) return 0;
  return n;
}

/*
** Check to see if the z[] string is the beginning of an enumeration value.
** If it is, return the length of the bullet text.  Otherwise return 0.
**
** Syntax:
**    *  a tab or two or more spaces
**    *  one or more digits
**    *  optional "."
**    *  another tab or two ore more spaces.
*/
static int bl_enum_length(const char *z){
  int i, n;
  n = 0;
  i = 0;
  while( z[n]==' ' || z[n]=='\t' ){
    if( z[n]=='\t' ) i++;
    i++;
    n++;
  }
  if( i<2 ) return 0;
  for(i=0; fsl_isdigit(z[n]); i++, n++){}
  if( i==0 ) return 0;
  if( z[n]=='.' ){
    n++;
  }
  i = 0;
  while( z[n]==' ' || z[n]=='\t' ){
    if( z[n]=='\t' ) i++;
    i++;
    n++;
  }
  if( i<2 || fsl_isspace(z[n]) ) return 0;
  return n;
}

/*
** Check to see if the z[] string is the beginning of an indented
** paragraph.  If it is, return the length of the indent.  Otherwise
** return 0.
*/
static int bl_indent_length(const char *z){
  int i, n;
  n = 0;
  i = 0;
  while( z[n]==' ' || z[n]=='\t' ){
    if( z[n]=='\t' ) i++;
    i++;
    n++;
  }
  if( i<2 || fsl_isspace(z[n]) ) return 0;
  return n;
}

/*
** Check to see if the z[] string is a wiki hyperlink.  If it is,
** return the length of the hyperlink.  Otherwise return 0.
*/
static int bl_link_length(const char *z){
  int n;
  assert( z[0]=='[' );
  for(n=0; z[n] && z[n]!=']'; n++){}
  if( z[n]==']' ){
    return n+1;
  }else{
    return 0;
  }
}

/*
** Get the next wiki token.
**
** z points to the start of a token.  Return the number of
** characters in that token.  Write the token type into *pTokenType.
*/
static int bl_next_wiki_token(const char *z, bl_wiki *p, int *pTokenType){
  int n;
  if( z[0]=='<' ){
    n = bl_html_tag_length(z);
    if( n>0 ){
      *pTokenType = BLT_MARKUP;
      return n;
    }else{
      *pTokenType = BLT_CHARACTER;
      return 1;
    }
  }
  if( z[0]=='&' ){
    if( (p->inVerbatim || !bl_is_element(z)) ){
      *pTokenType = BLT_CHARACTER;
      return 1;
    }
  }
  if( (p->state & BLS_ALLOW_WIKI)!=0 ){
    if( z[0]=='\n' ){
      n = bl_paragraph_break_length(z);
      if( n>0 ){
        *pTokenType = BLT_PARAGRAPH;
        return n;
      }else{
        *pTokenType = BLT_NEWLINE;
        return 1;
      }
    }
    if( (p->state & BLS_AT_NEWLINE)!=0 && fsl_isspace(z[0]) ){
      n = bl_list_item_length(z, '*');
      if( n>0 ){
        *pTokenType = BLT_BUL_LI;
        return n;
      }
      n = bl_list_item_length(z, '#');
      if( n>0 ){
        *pTokenType = BLT_NUM_LI;
        return n;
      }
      n = bl_enum_length(z);
      if( n>0 ){
        *pTokenType = BLT_ENUM;
        return n;
      }
    }
    if( (p->state & BLS_AT_PARAGRAPH)!=0 && fsl_isspace(z[0]) ){
      n = bl_indent_length(z);
      if( n>0 ){
        *pTokenType = BLT_INDENT;
        return n;
      }
    }
    if( z[0]=='[' ){
      if( (n = bl_link_length(z))>0 ){
        *pTokenType = BLT_LINK;
        return n;
      }
    }
  }
  *pTokenType = BLT_TEXT;
  return 1 + bl_text_length(z+1, p->state);
}

/*
** Parse only Wiki links, return everything else as BLT_RAW. This is
** used when the wiki-use-html setting is on.
**
** z points to the start of a token.  Return the number of
** characters in that token. Write the token type into *pTokenType.
*/
static int bl_next_raw_token(const char *z, bl_wiki *p, int *pTokenType){
  int n;
  if( z[0]=='[' ){
    if( (n = bl_link_length(z))>0 ){
      *pTokenType = BLT_LINK;
      return n;
    }
  }
  *pTokenType = BLT_RAW;
  return 1 + bl_text_length(z+1, p->state);
}

/*
** A single markup is parsed into an instance of the following
** structure.
*/
typedef struct bl_markup bl_markup;
struct bl_markup {
  unsigned char endTag;   /* True if </...> instead of <...> */
  unsigned char iCode;    /* BLM_* */
  unsigned char nAttr;    /* Number of attributes */
  struct {
    unsigned char iACode;    /* BLA_* */
    char *zValue;            /* Argument to this attribute.  Might be NULL */
    char cTerm;              /* Original argument termination character */
  } aAttr[10];
};

/*
** Return true if attribute iACode has already been parsed into p.
*/
static int bl_markup_has_attr(const bl_markup *p, int iACode){
  int i;
  for(i=0; i<p->nAttr; i++){
    if( p->aAttr[i].iACode==iACode ) return 1;
  }
  return 0;
}

/*
** z[] is an HTML markup element - something that begins with '<'.
** Parse this element into the p structure.
**
** The content of z[] might be modified by converting characters
** to lowercase and by inserting some "\000" characters.
*/
static void bl_parse_markup(bl_markup *p, char *z){
  int i, j, c;
  int iACode;
  char *zValue;
  char zTag[100];

  if( z[1]=='/' ){
    p->endTag = 1;
    i = 2;
  }else{
    p->endTag = 0;
    i = 1;
  }
  j = 0;
  while( fsl_isalnum(z[i]) ){
    if( j<(int)sizeof(zTag)-1 ) zTag[j++] = (char)fsl_tolower(z[i]);
    i++;
  }
  zTag[j] = 0;
  p->iCode = (unsigned char)bl_find_tag(zTag);
  p->nAttr = 0;
  c = 0;
  if( z[i]=='-' ){
    p->aAttr[0].iACode = BLA_ID;
    i++;
    p->aAttr[0].zValue = &z[i];
    while( fsl_isalnum(z[i]) ){ i++; }
    p->aAttr[0].cTerm = c = z[i];
    z[i++] = 0;
    p->nAttr = 1;
    if( c=='>' ) return;
  }
  while( fsl_isspace(z[i]) ){ i++; }
  while( c!='>' && p->nAttr<8 && fsl_isalpha(z[i]) ){
    int attrOk;    /* True to preserve attribute.  False to ignore it */
    j = 0;
    while( fsl_isalnum(z[i]) ){
      if( j<(int)sizeof(zTag)-1 ) zTag[j++] = (char)fsl_tolower(z[i]);
      i++;
    }
    zTag[j] = 0;
    p->aAttr[p->nAttr].iACode = (unsigned char)(iACode = bl_find_attr(zTag));
    attrOk = iACode!=0 && !bl_markup_has_attr(p, iACode);
    while( fsl_isspace(z[i]) ){ z++; }
    if( z[i]!='=' ){
      p->aAttr[p->nAttr].zValue = 0;
      p->aAttr[p->nAttr].cTerm = 0;
      c = 0;
    }else{
      i++;
      while( fsl_isspace(z[i]) ){ z++; }
      if( z[i]=='"' ){
        i++;
        zValue = &z[i];
        while( z[i] && z[i]!='"' ){ i++; }
      }else if( z[i]=='\'' ){
        i++;
        zValue = &z[i];
        while( z[i] && z[i]!='\'' ){ i++; }
      }else{
        zValue = &z[i];
        while( !fsl_isspace(z[i]) && z[i]!='>' ){
          if( z[i]=='\'' || z[i]=='"' ) attrOk = 0;
          i++;
        }
      }
      if( attrOk ){
        p->aAttr[p->nAttr].zValue = zValue;
        p->aAttr[p->nAttr].cTerm = c = z[i];
        if( z[i]==0 ){
          i--;
        }else{
          z[i] = 0;
        }
      }
      i++;
    }
    if( attrOk ){
      p->nAttr++;
    }
    while( fsl_isspace(z[i]) ){ i++; }
    if( z[i]==0 || z[i]=='>' || (z[i]=='/' && z[i+1]=='>') ) break;
  }
}

/*
** When the markup was parsed, some "\000" may have been inserted.
** This routine restores to those "\000" values back to their
** original content.
*/
static void bl_unparse_markup(bl_markup *p){
  int i, n;
  for(i=0; i<p->nAttr; i++){
    char *z = p->aAttr[i].zValue;
    if( z==0 ) continue;
    if( p->aAttr[i].cTerm ){
      n = (int)fsl_strlen(z);
      z[n] = p->aAttr[i].cTerm;
    }
  }
}

/*
** Return the ID attribute for markup.  Return NULL if there is no
** ID attribute.
*/
static const char *bl_markup_id(bl_markup *p){
  int i;
  for(i=0; i<p->nAttr; i++){
    if( p->aAttr[i].iACode==BLA_ID ){
      return p->aAttr[i].zValue;
    }
  }
  return 0;
}

/*
** Pop a single element off of the stack.
*/
static void bl_pop_stack(bl_wiki *p){
  if( p->nStack ){
    p->nStack--;
  }
}

/*
** Push a new markup value onto the stack.  Enlarge the stack
** if necessary. Returns 0 on success or FSL_RC_OOM.
*/
static int bl_push_stack_with_id(bl_wiki *p, int elem, const char *zId, int w){
  if( p->nStack>=p->nAlloc ){
    int const nAlloc = p->nAlloc*2 + 100;
    struct bl_stack * const a =
      (struct bl_stack*)fsl_realloc(p->aStack, nAlloc*sizeof(p->aStack[0]));
    if( !a ) return FSL_RC_OOM;
    p->nAlloc = nAlloc;
    p->aStack = a;
  }
  p->aStack[p->nStack].iCode = (short)elem;
  p->aStack[p->nStack].zId = zId;
  p->aStack[p->nStack].allowWiki = (short)w;
  p->nStack++;
  return 0;
}

/*
** Pop the stack until the top-most iTag element is removed.
** If there is no iTag element on the stack, this routine
** is a no-op.
*/
static void bl_pop_stack_to_tag(bl_wiki *p, int iTag){
  int i;
  for(i=p->nStack-1; i>=0; i--){
    if( p->aStack[i].iCode!=iTag ) continue;
    if( p->aStack[i].zId ) continue;
    break;
  }
  if( i<0 ) return;
  while( p->nStack>i ){
    bl_pop_stack(p);
  }
}

/*
** Attempt to find a find a tag of type iTag with id zId.  Return -1
** if not found.  If found, return its stack level.
*/
static int bl_find_tag_with_id(bl_wiki *p, int iTag, const char *zId){
  int i;
  assert( zId!=0 );
  for(i=p->nStack-1; i>=0; i--){
    if( p->aStack[i].iCode!=iTag ) continue;
    if( p->aStack[i].zId==0 ) continue;
    if( fsl_strcmp(zId, p->aStack[i].zId)!=0 ) continue;
    break;
  }
  return i;
}

/*
** Check to see if the given parsed markup is the correct
** </verbatim> tag.
*/
static int bl_end_verbatim(bl_wiki *p, bl_markup *pMarkup){
  char *z;
  assert( p->inVerbatim );
  if( pMarkup->iCode!=BLM_VERBATIM ) return 0;
  if( !pMarkup->endTag ) return 0;
  if( p->zVerbatimId==0 ) return 1;
  if( pMarkup->nAttr!=1 ) return 0;
  z = pMarkup->aAttr[0].zValue;
  return fsl_strcmp(z, p->zVerbatimId)==0;
}

/*
** Parse text looking for wiki hyperlinks in one of the formats:
**
**       [target]
**       [target|...]
**
** Where "target" can be either an artifact ID prefix or a wiki page
** name. Each target is passed to bl_create(). The scanner may modify
** z while it runs, so it must be writable and NUL-terminated. If
** wikiHtmlOnly is true then the text is HTML in which only these
** hyperlinks are interpreted, as for fossil(1)'s wiki-use-html setting.
**
** Port of fossil(1)'s wiki_extract_links().
*/
static void bl_wiki_extract(bl_sink * const sink, char *z, int wikiHtmlOnly){
  bl_wiki renderer;
  int tokenType;
  bl_markup markup;
  int n;

  memset(&renderer, 0, sizeof(renderer));
  renderer.state = BLS_ALLOW_WIKI|BLS_AT_NEWLINE|BLS_AT_PARAGRAPH;

  while( z[0] && 0==sink->rc ){
    if( wikiHtmlOnly ){
      n = bl_next_raw_token(z, &renderer, &tokenType);
    }else{
      n = bl_next_wiki_token(z, &renderer, &tokenType);
    }
    switch( tokenType ){
      case BLT_LINK: {
        char *zTarget;
        int i;

        zTarget = &z[1];
        for(i=0; zTarget[i] && zTarget[i]!='|' && zTarget[i]!=']'; i++){}
        while(i>1 && zTarget[i-1]==' '){ i--; }
        bl_create(sink, zTarget, i);
        break;
      }
      case BLT_MARKUP: {
        const char *zId;
        int iDiv;
        bl_parse_markup(&markup, z);

        /* Markup of the form </div id=ID> where there is a matching
        ** ID somewhere on the stack.  Exit the verbatim if were are in
        ** it.  Pop the stack up to the matching <div>.  Discard the
        ** </div>
        */
        if( markup.iCode==BLM_DIV && markup.endTag &&
             (zId = bl_markup_id(&markup))!=0 &&
             (iDiv = bl_find_tag_with_id(&renderer, BLM_DIV, zId))>=0
        ){
          if( renderer.inVerbatim ){
            renderer.inVerbatim = 0;
            renderer.state = renderer.preVerbState;
          }
          while( renderer.nStack>iDiv+1 ) bl_pop_stack(&renderer);
          if( renderer.aStack[iDiv].allowWiki ){
            renderer.state |= BLS_ALLOW_WIKI;
          }else{
            renderer.state &= ~BLS_ALLOW_WIKI;
          }
          renderer.nStack--;
        }else

        /* If within <verbatim id=ID> ignore everything other than
        ** </verbatim id=ID> and the </dev id=ID2> above.
        */
        if( renderer.inVerbatim ){
          if( bl_end_verbatim(&renderer, &markup) ){
            renderer.inVerbatim = 0;
            renderer.state = renderer.preVerbState;
          }else{
            n = 1;
          }
        }else

        /* Render invalid markup literally.  The markup appears in the
        ** final output as plain text.
        */
        if( markup.iCode==BLM_INVALID ){
          n = 1;
        }else

        if( markup.iCode==BLM_NOWIKI ){
          if( markup.endTag ){
            renderer.state |= BLS_ALLOW_WIKI;
          }else{
            renderer.state &= ~BLS_ALLOW_WIKI;
          }
        }else

        /* Generate end-tags */
        if( markup.endTag ){
          bl_pop_stack_to_tag(&renderer, markup.iCode);
        }else

        /* Push <div> markup onto the stack together with the id=ID attribute.
        */
        if( markup.iCode==BLM_DIV ){
          sink->rc = bl_push_stack_with_id(&renderer, markup.iCode,
                                           bl_markup_id(&markup),
                                           (renderer.state
                                            & BLS_ALLOW_WIKI)!=0);
        }else

        /* Enter <verbatim> processing.  With verbatim enabled, all other
        ** markup other than the corresponding end-tag with the same ID is
        ** ignored.
        */
        if( markup.iCode==BLM_VERBATIM ){
          int vAttrIdx;
          renderer.zVerbatimId = 0;
          renderer.inVerbatim = 1;
          renderer.preVerbState = renderer.state;
          renderer.state &= ~BLS_ALLOW_WIKI;
          for (vAttrIdx = 0; vAttrIdx < markup.nAttr; vAttrIdx++){
            if( markup.aAttr[vAttrIdx].iACode == BLA_ID ){
              renderer.zVerbatimId = markup.aAttr[0].zValue;
            }
          }
        }

        /* Restore the input text to its original configuration
        */
        bl_unparse_markup(&markup);
        break;
      }
      default: {
        break;
      }
    }
    z += n;
  }
  fsl_free(renderer.aStack);
}

/*
** Markdown scanner. Port of fossil(1)'s markdown.c, driven by the
** renderer which backlink.c's markdown_extract_links() installs: one
** in which every callback succeeds, only the one for hyperlinks does
** anything, and no output is produced.
**
** Dropping the output means the callbacks and the output buffers are
** gone, along with the code which only computes table alignment, code
** span trimming and the like. What is kept is everything which decides
** how far each construct extends, what gets parsed recursively, and in
** what order, because that determines which hyperlinks are seen. In
** particular the iDepth bookkeeping stays where fossil(1) allocates and
** releases its work buffers, as it limits how deeply constructs nest
** and so decides whether the innermost ones are looked at at all.
*/

#define BL_LI_END 8  /* internal list flag */

/* list/listitem flags */
#define BL_LIST_ORDERED  1
#define BL_LI_BLOCK      2  /* <li> containing block data */

/*
** A link reference definition: "[id]: target".
*/
typedef struct bl_ref bl_ref;
struct bl_ref {
  fsl_b id;           /* must be the first field, see bl_cmp_ref() */
  fsl_b link;
};

/*
** A footnote's data. The id, text, and upc fields hold what fossil(1)'s
** struct footnote does, and are used the same way.
*/
typedef struct bl_note bl_note;
struct bl_note {
  fsl_b id;      /* must be the first field, see bl_cmp_ref() */
  fsl_b text;    /* footnote's content */
  fsl_b upc;     /* user-provided classes  .ASCII-alnum.or-hypen: */
  int bRndred;   /* true if `text` has been scanned for links */
  int defno;     /* serial number of definition, set during the first pass */
  int index;     /* index within the array of notes */
  int iMark;     /* user-visible numeric marker, assigned upon first use */
  int nUsed;     /* counts references to this note */
};

typedef struct bl_md bl_md;

/* Function pointer type for the active chars. Returns the number of
** chars taken care of. data is the pointer of the beginning of the
** span, offset is the number of valid chars before data. */
typedef size_t (*bl_trigger)(bl_md *md, char *data, size_t offset,
                             size_t size);

/*
** State of one scan, fossil(1)'s struct render.
*/
struct bl_md {
  bl_sink * sink;                 /* Where links go. sink->rc is the
                                  ** scan's error state. */
  bl_ref * aRef;                  /* Link reference definitions, sorted */
  int nRef;
  int nRefAlloc;
  bl_trigger active_char[256];
  int iDepth;                     /* Number of "work buffers" in use */
  struct {
    bl_note * a;                  /* Footnotes. The first nLbled are the
                                  ** labeled ones, sorted by id */
    int n;
    int nAlloc;
    int nLbled;                   /* number of labeled footnotes found
                                  ** during the first pass */
    int nMarks;                   /* counts distinct indices found during
                                  ** the second pass */
  } notes;
};

/* html_tag -- structure for quick HTML tag search */
struct bl_tag {
  const char *text;
  int size;
};

/*
** When these HTML tags are separated from other text by newlines
** then they are rendered verbatim.  Their content is not interpreted
** in any way.
*/
static const struct bl_tag bl_block_tags[] = {
  { "html",         4 },
  { "pre",          3 },
  { "script",       6 },
};

#define BL_OK(MD) (0==(MD)->sink->rc)

/* Records the first error of a scan. */
static void bl_err(bl_md * const md, int rc){
  if( rc && 0==md->sink->rc ) md->sink->rc = rc;
}

/* Appends n bytes of z to b, recording an allocation failure. */
static void bl_append(bl_md * const md, fsl_b * const b,
                      const char *z, size_t n){
  if( BL_OK(md) ) bl_err(md, fsl_b_append(b, z, (fsl_int_t)n));
}

/* Returns the contents of b as a string, which is empty if b is. */
static char *bl_bstr(fsl_b const * const b){
  return b->mem ? (char*)b->mem : (char*)"";
}

/*
** Compare two buffers, as fossil(1)'s blob_compare() does: first by
** content up to the shorter length, then by length.
*/
static int bl_blob_compare(fsl_b const * const pA, fsl_b const * const pB){
  int const szA = (int)pA->used;
  int const szB = (int)pB->used;
  int const sz = szA<szB ? szA : szB;
  int rc = sz ? memcmp(pA->mem, pB->mem, sz) : 0;
  if( rc==0 ) rc = szA - szB;
  return rc;
}

/*
** The "work buffer" accounting: fossil(1) keeps a count of the work
** buffers in use which doubles as the depth of recursion.
*/
static void bl_enter(bl_md * const md){ md->iDepth++; }
static void bl_leave(bl_md * const md){ md->iDepth--; }

/* return true if recursion has gone too deep */
static int bl_too_deep(bl_md const * const md){
  return md->iDepth>200;
}

/*
** collapse whitespace from input text to make it a ref id.
** Potential TODO: maybe also handle CR+LF line endings?
*/
static int bl_build_ref_id(bl_md * const md, fsl_b * const id,
                           const char *data, size_t size){
  size_t beg, i;
  char *id_data;

  /* skip leading whitespace */
  while( size>0 && (data[0]==' ' || data[0]=='\t' || data[0]=='\n') ){
    data++;
    size--;
  }

  /* skip trailing whitespace */
  while( size>0 && (data[size-1]==' '
   || data[size-1]=='\t'
   || data[size-1]=='\n')
  ){
    size--;
  }
  if( size==0 ) return -1;

  /* making the ref id */
  i = 0;
  fsl_b_reuse(id);
  while( i<size ){
    /* copy non-whitespace into the output buffer */
    beg = i;
    while( i<size && !(data[i]==' ' || data[i]=='\t' || data[i]=='\n') ){
      i++;
    }
    bl_append(md, id, data+beg, i-beg);

    /* add a single space and skip all consecutive whitespace */
    if( i<size ) bl_append(md, id, " ", 1);
    while( i<size && (data[i]==' ' || data[i]=='\t' || data[i]=='\n') ){ i++; }
  }

  /* turn upper-case ASCII into their lower-case counterparts */
  id_data = bl_bstr(id);
  for(i=0; i<id->used; i++){
    if( id_data[i]>='A' && id_data[i]<='Z' ) id_data[i] += 'a' - 'A';
  }
  return 0;
}

/* comparison function for bsearch() of bl_ref and bl_note arrays */
static int bl_cmp_ref(const void *key, const void *array_entry){
  bl_ref const * const lr = (bl_ref const *)array_entry;
  return bl_blob_compare((fsl_b const *)key, &lr->id);
}

/* comparison function for qsort() of bl_ref arrays */
static int bl_cmp_ref_sort(const void *a, const void *b){
  bl_ref const * const lra = (bl_ref const *)a;
  bl_ref const * const lrb = (bl_ref const *)b;
  return bl_blob_compare(&lra->id, &lrb->id);
}

/*
** comparison function for footnotes qsort.
** Empty IDs sort last (in undetermined order).
** Equal IDs are sorted in the order of definition in the source.
*/
static int bl_cmp_note_id(const void *fna, const void *fnb){
  const bl_note *a = (bl_note const *)fna, *b = (bl_note const *)fnb;
  const int szA = (int)a->id.used, szB = (int)b->id.used;
  if( szA ){
    if( szB ){
      int cmp = bl_blob_compare(&a->id, &b->id);
      if( cmp ) return cmp;
    }else return -1;
  }else return szB ? 1 : 0;
  /* IDs are equal and non-empty */
  if( a->defno < b->defno ) return -1;
  if( a->defno > b->defno ) return  1;
  assert(!"reachable");
  return 0; /* should never reach here */
}

/*
** comparison function for footnotes qsort.
** Unreferenced footnotes (when nUsed == 0) sort last and
** are sorted in the order of definition in the source.
*/
static int bl_cmp_note_sort(const void *fna, const void *fnb){
  const bl_note *a = (bl_note const *)fna, *b = (bl_note const *)fnb;
  int i, j;
  assert( a->nUsed >= 0 );
  assert( b->nUsed >= 0 );
  assert( a->defno >= 0 );
  assert( b->defno >= 0 );
  if( a->nUsed ){
    assert( a->iMark >  0 );
    if( !b->nUsed ) return -1;
    assert( b->iMark >  0 );
    i = a->iMark;
    j = b->iMark;
  }else{
    if( b->nUsed )  return  1;
    i = a->defno;
    j = b->defno;
  }
  if( i < j ) return -1;
  if( i > j ) return  1;
  return 0;
}

/* returns the current block tag, if any */
static const struct bl_tag *bl_find_block_tag(const char *data, size_t size){
  size_t i = 0;
  size_t k;

  /* looking for the word end */
  while( i<size
   && ((data[i]>='0' && data[i]<='9')
       || (data[i]>='A' && data[i]<='Z')
       || (data[i]>='a' && data[i]<='z'))
  ){
    i++;
  }
  if( i>=size ) return 0;

  /* The tag must be the whole word, regardless of case. */
  for(k=0; k<sizeof(bl_block_tags)/sizeof(bl_block_tags[0]); k++){
    struct bl_tag const * const t = &bl_block_tags[k];
    if( (int)i==t->size && 0==fsl_strnicmp(data, t->text, t->size) ){
      return t;
    }
  }
  return 0;
}


/****************************
 * INLINE PARSING FUNCTIONS *
 ****************************/

/* looks for the address part of a mail autolink and '>' */
/* this is less strict than the original markdown e-mail address matching */
static size_t bl_is_mail_autolink(char *data, size_t size){
  size_t i = 0, nb = 0;
  /* address is assumed to be: [-@._a-zA-Z0-9]+ with exactly one '@' */
  while( i<size && (data[i]=='-'
   || data[i]=='.'
   || data[i]=='_'
   || data[i]=='@'
   || (data[i]>='a' && data[i]<='z')
   || (data[i]>='A' && data[i]<='Z')
   || (data[i]>='0' && data[i]<='9'))
  ){
    if( data[i]=='@' ) nb++;
    i++;
  }
  if( i>=size || data[i]!='>' || nb!=1 ) return 0;
  return i+1;
}

/* autolink types, as fossil(1)'s mkd_autolink */
#define BL_NOT_AUTOLINK    0   /* used internally when it is not an autolink*/
#define BL_NORMAL          1   /* normal http/http/ftp link */
#define BL_EXPLICIT_EMAIL  2   /* e-mail link with explicit mailto: */
#define BL_IMPLICIT_EMAIL  3   /* e-mail link without mailto: */

/* returns the length of the given tag, or 0 if it's not valid */
static size_t bl_tag_length(char *data, size_t size, int *autolink){
  size_t i, j;

  /* a valid tag can't be shorter than 3 chars */
  if( size<3 ) return 0;

  /* begins with a '<' optionally followed by '/', followed by letter */
  if( data[0]!='<' ) return 0;
  i = (data[1]=='/') ? 2 : 1;
  if( (data[i]<'a' || data[i]>'z') &&  (data[i]<'A' || data[i]>'Z') ){
    if( data[1]=='!' && size>=7 && data[2]=='-' && data[3]=='-' ){
      for(i=6; i<size && (data[i]!='>'||data[i-1]!='-'|| data[i-2]!='-');i++){}
      if( i<size ) return i;
    }
    return 0;
  }

  /* scheme test */
  *autolink = BL_NOT_AUTOLINK;
  if( size>6
   && fsl_strnicmp(data+1, "http", 4)==0
   && (data[5]==':'
       || ((data[5]=='s' || data[5]=='S') && data[6]==':'))
  ){
    i = (data[5]==':') ? 6 : 7;
    *autolink = BL_NORMAL;
  }else if( size>5 && fsl_strnicmp(data+1, "ftp:", 4)==0 ){
    i = 5;
    *autolink = BL_NORMAL;
  }else if( size>7 && fsl_strnicmp(data+1, "mailto:", 7)==0 ){
    i = 8;
    /* not changing *autolink to go to the address test */
   }

  /* completing autolink test: no whitespace or ' or " */
  if( i>=size || i=='>' ){
    *autolink = BL_NOT_AUTOLINK;
  }else if( *autolink ){
    j = i;
    while( i<size
     && data[i]!='>'
     && data[i]!='\''
     && data[i]!='"'
     && data[i]!=' '
     && data[i]!='\t'
     && data[i]!='\n'
    ){
      i++;
    }
    if( i>=size ) return 0;
    if( i>j && data[i]=='>' ) return i+1;
    /* one of the forbidden chars has been found */
    *autolink = BL_NOT_AUTOLINK;
  }else if( (j = bl_is_mail_autolink(data+i, size-i))!=0 ){
    *autolink = (i==8) ? BL_EXPLICIT_EMAIL : BL_IMPLICIT_EMAIL;
    return i+j;
  }

  /* looking for something looking like a tag end */
  while( i<size && data[i]!='>' ){ i++; }
  if( i>=size ) return 0;
  return i+1;
}

/* parses inline markdown elements */
static void bl_parse_inline(bl_md *md, char *data, size_t size){
  size_t i = 0, end = 0;
  bl_trigger action = 0;

  if( bl_too_deep(md) ) return;
  while( i<size && BL_OK(md) ){
    /* skipping inactive chars */
    while( end<size
     && (action = md->active_char[(unsigned char)data[end]])==0
    ){
      end++;
    }
    if( end>=size ) break;
    i = end;

    /* calling the trigger */
    end = action(md, data+i, i, size-i);
    if( !end ){
      /* no action from the callback */
      end = i+1;
    }else{
      i += end;
      end = i;
    }
  }
}

/*
** data[*pI] should be a "`" character that introduces a code-span.
** The code-span boundary mark can be any number of one or more "`"
** characters.  We do not know the size of the boundary marker, only
** that there is at least one "`" at data[*pI].
**
** This routine increases *pI to move it past the code-span, including
** the closing boundary mark.  Or, if the code-span is unterminated,
** this routine moves *pI past the opening boundary mark only.
*/
static void bl_skip_codespan(const char *data, size_t size, size_t *pI){
  size_t i = *pI;
  size_t span_nb;   /* Number of "`" characters in the boundary mark */
  size_t bt;

  assert( i<size );
  assert( data[i]=='`' );
  data += i;
  size -= i;

  /* counting the number of opening backticks */
  i = 0;
  span_nb = 0;
  while( i<size && data[i]=='`' ){
    i++;
    span_nb++;
  }
  if( i>=size ){
    *pI += span_nb;
    return;
  }

  /* finding the matching closing sequence */
  bt = 0;
  while( i<size && bt<span_nb ){
    if( data[i]=='`' ) bt += 1; else bt = 0;
    i++;
  }
  *pI += (bt == span_nb) ? i : span_nb;
}

/* looks for the next emph char, skipping other constructs */
static size_t bl_find_emph_char(char *data, size_t size, char c){
  size_t i = data[0]!='`';

  while( i<size ){
    while( i<size && data[i]!=c && data[i]!='`' && data[i]!='[' ){ i++; }
    if( i>=size ) return 0;

    /* not counting escaped chars */
    if( i && data[i-1]=='\\' ){
      i++;
      continue;
    }

    if( data[i]==c ) return i;

    if( data[i]=='`' ){            /* skip a code span */
      bl_skip_codespan(data, size, &i);
    }else if( data[i]=='[' ){      /* skip a link */
      size_t tmp_i = 0;
      char cc;
      i++;
      while( i<size && data[i]!=']' ){
        if( !tmp_i && data[i]==c ) tmp_i = i;
        i++;
      }
      i++;
      while( i<size && (data[i]==' ' || data[i]=='\t' || data[i]=='\n') ){
        i++;
      }
      if( i>=size ) return tmp_i;
      if( data[i]!='[' && data[i]!='(' ){ /* not a link*/
        if( tmp_i ) return tmp_i; else continue;
      }
      cc = data[i];
      i++;
      while( i<size && data[i]!=cc ){
        if( !tmp_i && data[i]==c ) tmp_i = i;
        i++;
      }
      if( i>=size ) return tmp_i;
      i++;
    }
  }
  return 0;
}

/* CommonMark defines separate "right-flanking" and "left-flanking"
** deliminators for emphasis.  Whether a deliminator is left- or
** right-flanking, or both, or neither depends on the characters
** immediately before and after.
**
**   before   after   example    left-flanking   right-flanking
**   ------   -----   -------    -------------   --------------
**    space   space      *            no              no
**    space   punct      *)          yes              no
**    space   alnum      *x          yes              no
**    punct   space     (*            no             yes
**    punct   punct     (*)          yes             yes
**    punct   alnum     (*x          yes              no
**    alnum   space     a*            no             yes
**    alnum   punct     a*(           no             yes
**    alnum   alnum     a*x          yes             yes
**
** The following routines determine whether a delimiter is left
** or right flanking.
*/
static int bl_left_flanking(char before, char after){
  if( fsl_isspace(after) ) return 0;
  if( fsl_isalnum(after) ) return 1;
  if( fsl_isalnum(before) ) return 0;
  return 1;
}
static int bl_right_flanking(char before, char after){
  if( fsl_isspace(before) ) return 0;
  if( fsl_isalnum(before) ) return 1;
  if( fsl_isalnum(after) ) return 0;
  return 1;
}

/*
** parsing single emphasis.
** closed by a symbol not preceded by whitespace and not followed by symbol.
*/
static size_t bl_parse_emph1(bl_md *md, char *data, size_t size, char c){
  size_t i = 0, len;
  char after;

  /* skipping one symbol if coming from emph3 */
  if( size>1 && data[0]==c && data[1]==c ) i = 1;

  while( i<size ){
    len = bl_find_emph_char(data+i, size-i, c);
    if( !len ) return 0;
    i += len;
    if( i>=size ) return 0;

    if( i+1<size && data[i+1]==c ){
      i++;
      continue;
    }
    after = i+1<size ? data[i+1] : ' ';
    if( data[i]==c
     && bl_right_flanking(data[i-1],after)
     && (c!='_' || !fsl_isalnum(after))
     && !bl_too_deep(md)
    ){
      bl_enter(md);
      bl_parse_inline(md, data, i);
      bl_leave(md);
      return i+1;
    }
  }
  return 0;
}

/*
** parsing double emphasis.
*/
static size_t bl_parse_emph2(bl_md *md, char *data, size_t size, char c){
  size_t i = 0, len;
  char after;

  while( i<size ){
    len = bl_find_emph_char(data+i, size-i, c);
    if( !len ) return 0;
    i += len;
    after = i+2<size ? data[i+2] : ' ';
    if( i+1<size
     && data[i]==c
     && data[i+1]==c
     && bl_right_flanking(data[i-1],after)
     && (c!='_' || !fsl_isalnum(after))
     && !bl_too_deep(md)
    ){
      bl_enter(md);
      bl_parse_inline(md, data, i);
      bl_leave(md);
      return i+2;
    }
    i++;
  }
  return 0;
}

/*
** parsing triple emphasis.
** finds the first closing tag, and delegates to the other emph.
*/
static size_t bl_parse_emph3(bl_md *md, char *data, size_t size, char c){
  size_t i = 0, len;

  while( i<size ){
    len = bl_find_emph_char(data+i, size-i, c);
    if( !len ) return 0;
    i += len;

    /* skip whitespace preceded symbols */
    if( data[i]!=c || data[i-1]==' ' || data[i-1]=='\t' || data[i-1]=='\n' ){
      continue;
    }

    if( i+2<size
     && data[i+1]==c
     && data[i+2] == c
     && !bl_too_deep(md)
    ){
      /* triple symbol found */
      bl_enter(md);
      bl_parse_inline(md, data, i);
      bl_leave(md);
      return i+3;
    }else if( i+1<size && data[i+1]==c ){
      /* double symbol found, handing over to emph1 */
      len = bl_parse_emph1(md, data-2, size+2, c);
      return len ? len-2 : 0;
    }else{
      /* single symbol found, handing over to emph2 */
      len = bl_parse_emph2(md, data-1, size+1, c);
      return len ? len-1 : 0;
    }
  }
  return 0;
}

/*
** single and double emphasis parsing.
*/
static size_t bl_char_emphasis(bl_md *md, char *data, size_t offset,
                               size_t size){
  char c = data[0];
  char before = offset>0 ? data[-1] : ' ';
  size_t ret;

  if( size>2 && data[1]!=c ){
    if( !bl_left_flanking(before, data[1])
     || (c=='_' && fsl_isalnum(before))
     || (ret = bl_parse_emph1(md, data+1, size-1, c))==0
    ){
      return 0;
    }
    return ret+1;
  }

  if( size>3 && data[1]==c && data[2]!=c ){
    if( !bl_left_flanking(before, data[2])
     || (c=='_' && fsl_isalnum(before))
     || (ret = bl_parse_emph2(md, data+2, size-2, c))==0
    ){
      return 0;
    }
    return ret+2;
  }

  if( size>4 && data[1]==c && data[2]==c && data[3]!=c ){
    if( !bl_left_flanking(before, data[3])
     || (c=='_' && fsl_isalnum(before))
     || (ret = bl_parse_emph3(md, data+3, size-3, c))==0
    ){
      return 0;
    }
    return ret+3;
  }
  return 0;
}

/*
** '\n' preceded by two spaces.
*/
static size_t bl_char_linebreak(bl_md *md, char *data, size_t offset,
                                size_t size){
  (void)md;
  (void)size;
  if( offset<2 || data[-1]!=' ' || data[-2]!=' ' ) return 0;
  return 1;
}

/*
** '`' parsing a code span. Also used for fenced code blocks, in which
** case the "span" delimiter may be '~'.
*/
static size_t bl_char_codespan(bl_md *md, char *data, size_t offset,
                               size_t size){
  size_t end, nb = 0, i;
  char delim = data[0];
  (void)md;
  (void)offset;

  /* counting the number of backticks in the delimiter */
  while( nb<size && data[nb]==delim ){ nb++; }

  /* finding the next delimiter */
  i = 0;
  for(end=nb; end<size && i<nb; end++){
    if( data[end]==delim ) i++; else i = 0;
  }
  if( i<nb && end>=size ) return 0; /* no matching delimiter */
  return end;
}

/*
** '\\' backslash escape.
*/
static size_t bl_char_escape(bl_md *md, char *data, size_t offset,
                             size_t size){
  (void)md;
  (void)data;
  (void)offset;
  (void)size;
  return 2;
}

/*
** '&' escaped when it doesn't belong to an entity.
** valid entities are assumed to be anything matching &#?[A-Za-z0-9]+;
*/
static size_t bl_char_entity(bl_md *md, char *data, size_t offset,
                             size_t size){
  size_t end = 1;
  (void)md;
  (void)offset;
  if( end<size && data[end]=='#' ) end++;
  while( end<size
   && ((data[end]>='0' && data[end]<='9')
       || (data[end]>='a' && data[end]<='z')
       || (data[end]>='A' && data[end]<='Z'))
  ){
    end++;
  }
  if( end<size && data[end]==';' ){
    /* real entity */
    end++;
  }else{
    /* lone '&' */
    return 0;
  }
  return end;
}

/*
** '<' when tags or autolinks are allowed. Autolinks and raw HTML tags
** are both accepted without being looked at any further: links are
** only extracted from the [text](target) forms.
*/
static size_t bl_char_langle_tag(bl_md *md, char *data, size_t offset,
                                 size_t size){
  int altype = BL_NOT_AUTOLINK;
  (void)md;
  (void)offset;
  return bl_tag_length(data, size, &altype);
}

/*
** extract inline-style link from parenthesed data. The link's title,
** which fossil(1) also extracts, is not needed here, but finding it
** can change where the link ends.
*/
static void bl_get_link_inline(bl_md * const md, fsl_b *link,
                               char *data, size_t size){
  size_t i = 0, mark;
  size_t link_b, link_e;
  size_t title_b = 0, title_e = 0;

  /* skipping initial whitespace */
  while( i<size && (data[i]==' ' || data[i]=='\t' || data[i]=='\n') ){ i++; }
  link_b = i;

  /* looking for link end: ' " */
  while( i<size && data[i]!='\'' && data[i]!='"' ){ i++; }
  link_e = i;

  /* looking for title end if present */
  if( data[i]=='\'' || data[i]=='"' ){
    i++;
    title_b = i;

    /* skipping whitespaces after title */
    title_e = size-1;
    while( title_e>title_b
     && (data[title_e]==' '
         || data[title_e]=='\t'
         || data[title_e]=='\n')
    ){
      title_e--;
    }

    /* checking for closing quote presence */
    if (data[title_e] != '\'' &&  data[title_e] != '"') {
      title_b = title_e = 0;
      link_e = i;
    }
  }

  /* remove whitespace at the end of the link */
  while( link_e>link_b
   && (data[link_e-1]==' '
       || data[link_e-1]=='\t'
       || data[link_e-1]=='\n')
  ){
    link_e--;
  }

  /* remove optional angle brackets around the link */
  if( data[link_b]=='<' ) link_b += 1;
  if( link_e && data[link_e-1]=='>' ) link_e -= 1;

  /* escape backslashed character from link */
  fsl_b_reuse(link);
  i = link_b;
  while( i<link_e ){
    mark = i;
    while( i<link_e && data[i]!='\\' ){ i++; }
    bl_append(md, link, data+mark, i-mark);
    while( i<link_e && data[i]=='\\' ){ i++; }
  }
}

/*
** extract referenced link from id. Returns 0 on success, else -1.
*/
static int bl_get_link_ref(bl_md * const md, fsl_b *link,
                           char *data, size_t size){
  bl_ref *lr;

  /* find the link from its id (stored temporarily in link) */
  fsl_b_reuse(link);
  if( !md->nRef || bl_build_ref_id(md, link, data, size)<0 ) return -1;
  lr = (bl_ref*)bsearch(link, md->aRef, md->nRef, sizeof(bl_ref),
                        bl_cmp_ref);
  if( !lr ) return -1;

  /* fill the output buffer */
  fsl_b_reuse(link);
  bl_append(md, link, bl_bstr(&lr->link), lr->link.used);
  return 0;
}

/*
** find a footnote by label, invoked during the 2nd pass. If found
** then it is marked as used. A reference to a footnote which does not
** exist is just as much a footnote reference as one which does, so
** there is nothing to return.
*/
static void bl_get_footnote(bl_md * const md, const char *data, size_t size){
  bl_note *fn = 0;
  if( md->notes.nLbled ){
    fsl_b id = fsl_b_empty;
    if( bl_build_ref_id(md, &id, data, size)>=0 ){
      fn = (bl_note*)bsearch(&id, md->notes.a, md->notes.nLbled,
                             sizeof(bl_note), bl_cmp_ref);
    }
    fsl_b_clear(&id);
  }
  if( fn ){
    if( fn->nUsed == 0 ){  /* the first reference to the footnote */
      assert( fn->iMark == 0 );
      fn->iMark = ++(md->notes.nMarks);
    }
    assert( fn->iMark > 0 );
    fn->nUsed++;
  }
}

/*
** Counts characters in the blank prefix within at most nHalfLines.
** A sequence of spaces and tabs counts as odd halfline,
** a newline counts as even halfline.
** If nHalfLines < 0 then proceed without constraints.
*/
static size_t bl_sizeof_blank_prefix(
  const char *data, size_t size, int nHalfLines
){
  const char *p = data;
  const char * const end = data+size;
  if( nHalfLines < 0 ){
    while( p!=end && fsl_isspace(*p) ){
      p++;
    }
  }else while( nHalfLines > 0 ){
    while( p!=end && (*p==' ' || *p=='\t' ) ){ p++; }
    if( p==end || --nHalfLines == 0 ) break;
    if( *p=='\n' || *p=='\r' ){
      p++;
      if( p==end ) break;
      if( *p=='\n' && p[-1]=='\r' ){
        p++;
      }
    }
    nHalfLines--;
  }
  return p-data;
}

/*
** Check if the data starts with a classlist token of the special form.
** If so then return the length of that token, otherwise return 0.
**
** The token must start with a dot and must end with a colon;
** in between of these it must be a dot-separated list of words;
** each word may contain only alphanumeric characters and hyphens.
**
** If `bBlank` is non-zero then a blank character must follow
** the token's ending colon: otherwise function returns 0
** despite the well-formed token.
*/
static size_t bl_is_footnote_classlist(const char * const data, size_t size,
                                       int bBlank){
  const char *p;
  const char * const end = data+size;
  if( data==end || *data != '.' ) return 0;
  for(p=data+1; p!=end; p++){
    if( fsl_isalnum(*p) || *p=='-' ) continue;
    if( p[-1]=='.' ) break;
    if( *p==':' ){
      p++;
      if( bBlank ){
        if( p==end || !fsl_isspace(*p) ) break;
      }
      return p-data;
    }
    if( *p!='.' ) break;
  }
  return 0;
}

/*
** Appends fn to the array of footnotes, which then owns its buffers.
** On allocation failure the buffers are released and the error is
** recorded.
*/
static void bl_note_push(bl_md * const md, bl_note * const fn){
  if( md->notes.n>=md->notes.nAlloc ){
    int const nAlloc = md->notes.nAlloc*2 + 8;
    bl_note * const a =
      (bl_note*)fsl_realloc(md->notes.a, nAlloc*sizeof(bl_note));
    if( !a ){
      bl_err(md, FSL_RC_OOM);
      fsl_b_clear(&fn->id);
      fsl_b_clear(&fn->text);
      fsl_b_clear(&fn->upc);
      return;
    }
    md->notes.a = a;
    md->notes.nAlloc = nAlloc;
  }
  md->notes.a[md->notes.n++] = *fn;
}

/*
** Adds unlabeled footnote to the notes. Returns 1 on success,
** otherwise 0.
*/
static int bl_add_inline_footnote(bl_md * const md, const char *text,
                                  size_t size){
  bl_note fn;
  const char *zUPC = 0;
  size_t nUPC = 0, n = bl_sizeof_blank_prefix(text, size, 3);
  if( n >= size ) return 0;
  text += n;
  size -= n;
  nUPC = bl_is_footnote_classlist(text, size, 1);
  if( nUPC ){
    assert( nUPC<size );
    zUPC = text;
    text += nUPC;
    size -= nUPC;
  }
  if( bl_sizeof_blank_prefix(text,size,-1)==size ){
    if( !nUPC ) return 0; /* empty inline footnote */
    text = zUPC;
    size = nUPC;          /* bare classlist is treated */
    nUPC = 0;             /* as plain text */
  }
  memset(&fn, 0, sizeof(fn));
  fn.text = fn.id = fn.upc = fsl_b_empty;
  fn.iMark = ++(md->notes.nMarks);
  fn.nUsed  = 1;
  fn.index  = md->notes.n;
  assert( fn.iMark > 0 );
  bl_append(md, &fn.text, text, size);
  if(nUPC) bl_append(md, &fn.upc, zUPC, nUPC);
  bl_note_push(md, &fn);
  return BL_OK(md);
}

/*
** Return the byte offset of the matching closing bracket or 0 if not
** found.  begin[0] must be either '[' or '('.
**
** TODO: It seems that things like "\\(" are not handled correctly.
**       That is historical behavior for a corner-case,
**       so it's left as it is until somebody complains.
*/
static size_t bl_matching_bracket_offset(
  const char* begin,
  const char* end
){
  const char *i;
  int level;
  const char bra = *begin;
  const char ket = bra=='[' ? ']' : ')';
  assert( bra=='[' || bra=='(' );
  for(i=begin+1,level=1; i!=end; i++){
    if( *i=='\n' )        /* do nothing */;
    else if( i[-1]=='\\' ) continue;
    else if( *i==bra )     level++;
    else if( *i==ket ){
      if( --level<=0 ) return i-begin;
    }
  }
  return 0;
}

/*
** '(': parsing a standalone inline footnote.
*/
static size_t bl_char_footnote(bl_md *md, char *data, size_t offset,
                               size_t size){
  size_t end;
  (void)offset;

  if( size<4 || data[1]!='^' ) return 0;
  end = bl_matching_bracket_offset(data, data+size);
  if( !end ) return 0;
  if( !bl_add_inline_footnote(md, data+2, end-2) ) return 0;
  return end+1;
}

/*
** '[': parsing a link or an image. Only links are of interest, but
** the content of an image is still skipped over as fossil(1) does.
*/
static size_t bl_char_link(
  bl_md *md,
  char *data,
  size_t offset,
  size_t size     /* bl_parse_inline() ensures that size > 0 */
){
  const int bFsfn = (size>3 && data[1]=='^'); /*free-standing footnote ref*/
  const int bImg = !bFsfn && (offset && data[-1] == '!');
  size_t i, txt_e;
  fsl_b link = fsl_b_empty;
  int isNote = 0;
  int ret;

  /* looking for the matching closing bracket */
  txt_e = bl_matching_bracket_offset(data, data+size);
  if( !txt_e ) return 0;
  i = txt_e + 1;
  ret = 0; /* error if we don't get to the callback */

  /* free-standing footnote reference */
  if( bFsfn ){
    bl_get_footnote(md, data+2, txt_e-2);
    isNote = 1;
  }else{
    /* allocate temporary buffers to store content, link and title */
    bl_enter(md);
    bl_enter(md);
    bl_enter(md);

    if( i<size && data[i]=='(' ){

      if( i+2<size && data[i+1]=='^' ){  /* span-bounded inline footnote */

        const size_t k = bl_matching_bracket_offset(data+i, data+size);
        if( !k ) goto char_link_cleanup;
        isNote = bl_add_inline_footnote(md, data+(i+2), k-2);
        i += k+1;
      }else{                             /* inline style link  */
        size_t span_end = i;
        while( span_end<size
               && !(data[span_end]==')'
                    && (span_end==i || data[span_end-1]!='\\')) ){
          span_end++;
        }
        if( span_end>=size ) goto char_link_cleanup;
        bl_get_link_inline(md, &link, data+i+1, span_end-(i+1));
        i = span_end+1;
      }
    /* reference style link or span-bounded footnote reference */
    }else if( i<size && data[i]=='[' ){
      char *id_data;
      size_t id_size, id_end = i;
      int bFootnote;

      while( id_end<size && data[id_end]!=']' ){ id_end++; }
      if( id_end>=size ) goto char_link_cleanup;
      bFootnote = data[i+1]=='^';
      if( i+1==id_end || (bFootnote && i+2==id_end) ){
        /* implicit id - use the contents */
        id_data = data+1;
        id_size = txt_e-1;
      }else{
        /* explicit id - between brackets */
        id_data = data+i+1;
        id_size = id_end-(i+1);
        if( bFootnote ){
          id_data++;
          id_size--;
        }
      }
      if( bFootnote ){
        bl_get_footnote(md, id_data, id_size);
        isNote = 1;
      }else if( bl_get_link_ref(md, &link, id_data, id_size)<0 ){
        goto char_link_cleanup;
      }
      i = id_end+1;
    /* shortcut reference style link */
    }else{
      if( bl_get_link_ref(md, &link, data+1, txt_e-1)<0 ){
        goto char_link_cleanup;
      }
      /* rewinding an "inter-bracket-whitespace" */
      i = txt_e+1;
    }
  }
  /* The text of a link is parsed, that of an image is not. */
  if( txt_e>1 && !bFsfn && !bImg ){
    bl_parse_inline(md, data+1, txt_e-1);
  }

  /* An image or a footnote reference needs no further attention. */
  ret = 1;
  if( !bImg && !isNote ){
    bl_create(md->sink, bl_bstr(&link), (int)link.used);
  }

  /* cleanup */
char_link_cleanup:
  if( !bFsfn ){
    bl_leave(md);
    bl_leave(md);
    bl_leave(md);
  }
  fsl_b_clear(&link);
  return ret ? i : 0;
}


/*********************************
 * BLOCK-LEVEL PARSING FUNCTIONS *
 *********************************/

/* returns the line length when it is empty, 0 otherwise */
static size_t bl_is_empty(const char *data, size_t size){
  size_t i;
  for(i=0; i<size && data[i]!='\n'; i++){
    if( data[i]!=' ' && data[i]!='\t' ) return 0;
  }
  return i+1;
}

/* returns whether a line is a horizontal rule */
static int bl_is_hrule(char *data, size_t size){
  size_t i = 0, n = 0;
  char c;

  /* skipping initial spaces */
  if( size<3 ) return 0;
  if( data[0]==' ' ){
    i++;
    if( data[1]==' ' ){
      i++;
       if( data[2]==' ' ){
         i++;
       }
     }
   }

  /* looking at the hrule char */
  if( i+2>=size || (data[i]!='*' && data[i]!='-' && data[i]!='_') ) return 0;
  c = data[i];

  /* the whole line must be the char or whitespace */
  while (i < size && data[i] != '\n') {
    if( data[i]==c ){
      n += 1;
    }else if( data[i]!=' ' && data[i]!='\t' ){
      return 0;
    }
    i++;
  }

  return n>=3;
}

/* returns whether the line is a setext-style hdr underline */
static int bl_is_headerline(char *data, size_t size){
  size_t i = 0;

  /* test of level 1 header */
  if( data[i]=='=' ){
    for(i=1; i<size && data[i]=='='; i++);
    while( i<size && (data[i]==' ' || data[i]=='\t') ){ i++; }
    return (i>=size || data[i]=='\n') ? 1 : 0;
  }

  /* test of level 2 header */
  if( data[i]=='-' ){
    for(i=1; i<size && data[i]=='-'; i++);
    while( i<size && (data[i]==' ' || data[i]=='\t') ){ i++; }
    return (i>=size || data[i]=='\n') ? 2 : 0;
  }

  return 0;
}

/* returns whether there is a table separator at pos */
static int bl_is_table_sep(char *data, size_t pos){
  return data[pos]=='|' && (pos==0 || data[pos-1]!='\\');
}

/* returns the number of column tables in the given line */
static int bl_is_tableline(char *data, size_t size){
  size_t i = 0;
  int n_sep = 0, outer_sep = 0;

  /* skip initial blanks */
  while( i<size && (data[i]==' ' || data[i]=='\t') ){ i++; }

  /* check for initial '|' */
  if( i<size && data[i]=='|') outer_sep++;

  /* count the number of pipes in the line */
  for(n_sep=0; i<size && data[i]!='\n'; i++){
    if( bl_is_table_sep(data, i) ) n_sep++;
    if( data[i]=='`' ){
      bl_skip_codespan(data, size, &i);
      i--;
    }
  }

  /* march back to check for optional last '|' before blanks and EOL */
  while( i && (data[i-1]==' ' || data[i-1]=='\t' || data[i-1]=='\n') ){ i--; }
  if( i && bl_is_table_sep(data, i-1) ) outer_sep += 1;

  /* return the number of column or 0 if it's not a table line */
  return (n_sep>0) ? (n_sep-outer_sep+1) : 0;
}

/* returns blockquote prefix length */
static size_t bl_prefix_quote(char *data, size_t size){
  size_t i = 0;
  if( i<size && data[i]==' ' ) i++;
  if( i<size && data[i]==' ' ) i++;
  if( i<size && data[i]==' ' ) i++;
  if( i<size && data[i]=='>' ){
    if( i+1<size && (data[i+1]==' ' || data[i+1]=='\t') ){
      return i + 2;
    }else{
      return i + 1;
    }
  }else{
    return 0;
  }
}

/* returns prefix length for block code */
static size_t bl_prefix_code(char *data, size_t size){
  if( size>0 && data[0]=='\t' ) return 1;
  if( size>3 && data[0]==' ' && data[1]==' ' && data[2]==' ' && data[3]==' ' ){
    return 4;
  }
  return 0;
}

/* Return the number of characters in the delimiter of a fenced code
** block. */
static size_t bl_prefix_fencedcode(char *data, size_t size){
  char c = data[0];
  int nb;
  if( c!='`' && c!='~' ) return 0;
  for(nb=1; nb<(int)size-3 && data[nb]==c; nb++){}
  if( nb<3 ) return 0;
  if( nb>=(int)size-nb ) return 0;
  return nb;
}

/* returns ordered list item prefix */
static size_t bl_prefix_oli(char *data, size_t size){
  size_t i = 0;
  if( i<size && data[i]==' ') i++;
  if( i<size && data[i]==' ') i++;
  if( i<size && data[i]==' ') i++;

  if( i>=size || data[i]<'0' || data[i]>'9' ) return 0;
  while( i<size && data[i]>='0' && data[i]<='9' ){ i++; }

  if( i+1>=size
   || (data[i]!='.' && data[i]!=')')
   || (data[i+1]!=' ' && data[i+1]!='\t')
  ){
   return 0;
  }
  i = i+2;
  while( i<size && (data[i]==' ' || data[i]=='\t') ){ i++; }
  return i;
}

/* returns unordered list item prefix */
static size_t bl_prefix_uli(char *data, size_t size){
  size_t i = 0;
  if( i<size && data[i]==' ') i++;
  if( i<size && data[i]==' ') i++;
  if( i<size && data[i]==' ') i++;
  if( i+1>=size
   || (data[i]!='*' && data[i]!='+' && data[i]!='-')
   || (data[i+1]!=' ' && data[i+1]!='\t')
  ){
    return 0;
  }
  i = i+2;
  while( i<size && (data[i]==' ' || data[i]=='\t') ){ i++; }
  return i;
}


/* parse_block predeclaration */
static void bl_parse_block(bl_md *md, char *data, size_t size);


/* handles parsing of a blockquote fragment */
static size_t bl_parse_blockquote(bl_md *md, char *data, size_t size){
  size_t beg, end = 0, pre, work_size = 0, nb, endFence = 0;
  char *work_data = 0;

  bl_enter(md);

  /* Check to see if this is a quote of a fenced code block, because
  ** if it is, then blank lines do not terminated the quoted text.  Ex:
  **
  **    > ~~~~
  **    First line
  **
  **    Line after blank
  **    ~~~~
  **
  **  If this is a quoted fenced block, then set endFence to be the
  **  offset of the end of the fenced block.
  */
  pre = bl_prefix_quote(data,size);
  pre += bl_is_empty(data+pre,size-pre);
  /* If the quote ends the input then pre is past its end, where
  ** fossil(1) looks anyway and, since the length is then negative, finds
  ** no fence. */
  nb = pre<size ? bl_prefix_fencedcode(data+pre,size-pre) : 0;
  if( nb ){
    size_t i = 0;
    char delim = data[pre];
    for(end=pre+nb; end<size && i<nb; end++){
      if( data[end]==delim ) i++; else i = 0;
    }
    if( i>=nb ) endFence = end;
  }

  beg = 0;
  while( beg<size ){
    for(end=beg+1; end<size && data[end-1]!='\n'; end++);
    pre = bl_prefix_quote(data+beg, end-beg);
    if( pre ){
      beg += pre; /* skipping prefix */
    }else if( bl_is_empty(data+beg, end-beg)
     && (end>=size
         || (end>endFence
             && bl_prefix_quote(data+end, size-end)==0
             && !bl_is_empty(data+end, size-end)))
    ){
      /* empty line followed by non-quote line */
      break;
    }
    if( beg<end ){ /* copy into the in-place working buffer */
      if( !work_data ){
        work_data = data+beg;
      }else if( (data+beg)!=(work_data+work_size) ){
        memmove(work_data+work_size, data+beg, end-beg);
      }
      work_size += end-beg;
    }
    beg = end;
  }

  if( !bl_too_deep(md) ){
    bl_parse_block(md, work_data, work_size);
  }
  bl_leave(md);
  return end;
}


/* handles parsing of a regular paragraph */
static size_t bl_parse_paragraph(bl_md *md, char *data, size_t size){
  size_t i = 0, end = 0;
  int level = 0;
  char *work_data = data;
  size_t work_size = 0;

  while( i<size ){
    char *zEnd = (char*)memchr(data+i, '\n', size-i-1);
    end = zEnd==0 ? size : (size_t)(zEnd - (data-1));
    /* The above is the same as:
    **    for(end=i+1; end<size && data[end-1]!='\n'; end++);
    ** "end" is left with a value such that data[end] is one byte
    ** past the first '\n' or one byte past the end of the string */
    if( bl_is_empty(data+i, size-i)
     || (level = bl_is_headerline(data+i, size-i))!= 0
    ){
      break;
    }
    if( (i && data[i]=='#')
     || bl_is_hrule(data+i, size-i)
     || bl_prefix_uli(data+i, size-i)
     || bl_prefix_oli(data+i, size-i)
    ){
      end = i;
      break;
    }
    i = end;
  }

  work_size = i;
  while( work_size && data[work_size-1]=='\n' ){ work_size--; }

  if( !level ){
    bl_enter(md);
    bl_parse_inline(md, work_data, work_size);
    bl_leave(md);
  }else{
    if( work_size ){
      size_t beg;
      i = work_size;
      work_size -= 1;
      while( work_size && data[work_size]!='\n' ){ work_size--; }
      beg = work_size+1;
      while( work_size && data[work_size-1]=='\n'){ work_size--; }
      if( work_size ){
        bl_enter(md);
        bl_parse_inline(md, work_data, work_size);
        bl_leave(md);
        work_data += beg;
        work_size = i - beg;
      }else{
        work_size = i;
      }
    }

    bl_enter(md);
    bl_parse_inline(md, work_data, work_size);
    bl_leave(md);
  }
  return end;
}


/* handles parsing of a block-level code fragment, which is not
** looked at beyond finding where it ends */
static size_t bl_parse_blockcode(char *data, size_t size){
  size_t beg, end, pre;

  beg = 0;
  while( beg<size ){
    char *zEnd = (char*)memchr(data+beg, '\n', size-beg-1);
    end = zEnd==0 ? size : (size_t)(zEnd - (data-1));
    /* The above is the same as:
    **   for(end=beg+1; end<size && data[end-1]!='\n'; end++);
    ** "end" is left with a value such that data[end] is one byte
    ** past the first \n or past then end of the string. */
    pre = bl_prefix_code(data+beg, end-beg);
    if( pre ){
      beg += pre; /* skipping prefix */
    }else if( !bl_is_empty(data+beg, end-beg) ){
      /* non-empty non-prefixed line breaks the pre */
      break;
    }
    beg = end;
  }
  return beg;
}


/* parsing of a single list item */
/*  assuming initial prefix is already removed */
static size_t bl_parse_listitem(bl_md *md, char *data, size_t size,
                                int *flags){
  fsl_b work = fsl_b_empty;
  size_t beg = 0, end, pre, sublist = 0, orgpre = 0, i;
  int in_empty = 0, has_inside_empty = 0;

  /* keeping track of the first indentation prefix */
  if( size>1 && data[0]==' ' ){
    orgpre = 1;
    if( size>2 && data[1]==' ' ){
      orgpre = 2;
      if( size>3 && data[2]==' ' ){
        orgpre = 3;
      }
    }
   }
  beg = bl_prefix_uli(data, size);
  if( !beg ) beg = bl_prefix_oli(data, size);
  if( !beg ) return 0;
  /* skipping to the beginning of the following line */
  end = beg;
  while( end<size && data[end-1]!='\n' ){ end++; }

  /* getting working buffers: the item's text, and what it renders to */
  bl_enter(md);
  bl_enter(md);

  /* putting the first line into the working buffer */
  bl_append(md, &work, data+beg, end-beg);
  beg = end;

  /* process the following lines */
  while( beg<size && BL_OK(md) ){
    end++;
    while( end<size && data[end-1]!='\n' ){ end++; }

    /* process an empty line */
    if( bl_is_empty(data+beg, end-beg) ){
      in_empty = 1;
      beg = end;
      continue;
    }

    /* computing the indentation */
    i = 0;
    if( end-beg>1 && data[beg]==' ' ){
      i = 1;
      if( end-beg>2 && data[beg+1]==' ' ){
        i = 2;
        if( end-beg>3 && data[beg+2]==' ' ){
          i = 3;
          if( end-beg>3 && data[beg+3]==' ' ){
            i = 4;
          }
        }
      }
    }
    pre = i;
    if( data[beg]=='\t' ){ i = 1; pre = 8; }

    /* checking for a new item */
    if( (bl_prefix_uli(data+beg+i, end-beg-i)
         && !bl_is_hrule(data+beg+i, end-beg-i))
     || bl_prefix_oli(data+beg+i, end-beg-i)
    ){
      if( in_empty ) has_inside_empty = 1;
      if( pre == orgpre ){ /* the following item must have */
        break;             /* the same indentation */
      }
      if( !sublist ) sublist = work.used;

    /* joining only indented stuff after empty lines */
    }else if( in_empty && i<4 && data[beg]!='\t' ){
        *flags |= BL_LI_END;
        break;
    }else if( in_empty ){
      bl_append(md, &work, "\n", 1);
      has_inside_empty = 1;
    }
    in_empty = 0;

    /* adding the line without prefix into the working buffer */
    bl_append(md, &work, data+beg+i, end-beg-i);
    beg = end;
  }

  /* render of li contents */
  if( BL_OK(md) ){
    if( has_inside_empty ) *flags |= BL_LI_BLOCK;
    if( *flags & BL_LI_BLOCK ){
      /* intermediate render of block li */
      if( sublist && sublist<work.used ){
        bl_parse_block(md, bl_bstr(&work), sublist);
        bl_parse_block(md, bl_bstr(&work)+sublist, work.used-sublist);
      }else{
        bl_parse_block(md, bl_bstr(&work), work.used);
      }
    }else{
      /* intermediate render of inline li */
      if( sublist && sublist<work.used ){
        bl_parse_inline(md, bl_bstr(&work), sublist);
        bl_parse_block(md, bl_bstr(&work)+sublist, work.used-sublist);
      }else{
        bl_parse_inline(md, bl_bstr(&work), work.used);
      }
    }
  }

  bl_leave(md);
  bl_leave(md);
  fsl_b_clear(&work);
  return beg;
}


/* parsing ordered or unordered list block */
static size_t bl_parse_list(bl_md *md, char *data, size_t size, int flags){
  size_t i = 0, j;

  bl_enter(md);
  while( i<size && BL_OK(md) ){
    j = bl_parse_listitem(md, data+i, size-i, &flags);
    i += j;
    if( !j || (flags & BL_LI_END) ) break;
  }
  bl_leave(md);
  return i;
}


/* parsing of atx-style headers */
static size_t bl_parse_atxheader(bl_md *md, char *data, size_t size){
  int level = 0;
  size_t i, end, skip, span_beg, span_size;

  if( !size || data[0]!='#' ) return 0;

  while( level<(int)size && level<6 && data[level]=='#' ){ level++; }
  for(i=level; i<size && (data[i]==' ' || data[i]=='\t'); i++);
  if ( (int)i == level ) return bl_parse_paragraph(md, data, size);
  span_beg = i;

  for(end=i; end<size && data[end]!='\n'; end++);
  skip = end;
  if( end<=i ) return bl_parse_paragraph(md, data, size);
  while( end && data[end-1]=='#' ){ end--; }
  while( end && (data[end-1]==' ' || data[end-1]=='\t') ){ end--; }
  if( end<=i ) return bl_parse_paragraph(md, data, size);

  span_size = end-span_beg;
  bl_enter(md);
  bl_parse_inline(md, data+span_beg, span_size);
  bl_leave(md);
  return skip;
}


/* checking end of HTML block : </tag>[ \t]*\n[ \t*]\n */
/*  returns the length on match, 0 otherwise */
static size_t bl_htmlblock_end(
  const struct bl_tag *tag,
  const char *data,
  size_t size
){
  size_t i, w;

  /* assuming data[0]=='<' && data[1]=='/' already tested */

  /* checking tag is a match */
  if( (tag->size+3)>(int)size
    || fsl_strnicmp(data+2, tag->text, tag->size)
    || data[tag->size+2]!='>'
  ){
    return 0;
  }

  /* checking white lines */
  i = tag->size + 3;
  w = 0;
  if( i<size && (w = bl_is_empty(data+i, size-i))==0 ){
    return 0; /* non-blank after tag */
  }
  i += w;
  w = 0;

  if( i<size && (w = bl_is_empty(data + i, size - i))==0 ){
    return 0; /* non-blank line after tag line */
  }
  return i+w;
}


/* parsing of inline HTML block, of which only the length is needed */
static size_t bl_parse_htmlblock(char *data, size_t size){
  size_t i, j = 0;
  const struct bl_tag *curtag;
  int found;

  /* identification of the opening tag */
  if( size<2 || data[0]!='<' ) return 0;
  curtag = bl_find_block_tag(data+1, size-1);

  /* handling of special cases */
  if( !curtag ){

    /* HTML comment, laxist form */
    if( size>5 && data[1]=='!' && data[2]=='-' && data[3]=='-' ){
      i = 5;
      while( i<size && !(data[i-2]=='-' && data[i-1]=='-' && data[i]=='>') ){
        i++;
      }
      i++;
      if( i<size ){
        j = bl_is_empty(data+i, size-i);
        if( j ){
          return i+j;
        }
      }
    }

    /* HR, which is the only self-closing block tag considered */
    if( size>4
      && (data[1]=='h' || data[1]=='H')
      && (data[2]=='r' || data[2]=='R')
    ){
      i = 3;
      while( i<size && data[i]!='>' ){ i++; }
      if( i+1<size ){
        i += 1;
        j = bl_is_empty(data+i, size-i);
        if( j ){
          return i+j;
        }
      }
    }

    /* no special case recognised */
    return 0;
  }

  /* looking for an matching closing tag */
  /* followed by a blank line */
  i = 1;
  found = 0;
  while( i<size ){
    i++;
    while( i<size && !(data[i-1]=='<' && data[i]=='/') ){ i++; }
    if( (i+2+curtag->size)>size ) break;
    j = bl_htmlblock_end(curtag, data+i-1, size-i+1);
    if (j) {
      i += j-1;
      found = 1;
      break;
    }
  }
  if( !found ) return 0;

  /* the end of the block has been found */
  return i;
}


/* parse a cell inside a table */
static void bl_parse_table_cell(bl_md *md, char *data, size_t size){
  bl_enter(md);
  bl_parse_inline(md, data, size);
  bl_leave(md);
}


/* parse an input line into a table row. The alignment of the cells is
** a matter of rendering, so only their content is looked at. */
static size_t bl_parse_table_row(bl_md *md, char *data, size_t size){
  size_t i = 0;
  size_t beg, end, total = 0;

  bl_enter(md);  /* the row's cells */

  /* skip leading blanks and separator */
  while( i<size && (data[i]==' ' || data[i]=='\t') ){ i++; }
  if( i<size && data[i]=='|' ) i++;

  /* go over all the cells */
  while( i<size && total==0 && BL_OK(md) ){
    /* skip optional left/center align marker */
    if( data[i]==':' ){
      i++;
    }

    /* skip blanks */
    while( i<size && (data[i]==' ' || data[i]=='\t') ){ i++; }
    beg = i;

    /* forward to the next separator or EOL */
    while( i<size && !bl_is_table_sep(data, i) && data[i]!='\n' ){
      if( data[i]=='`' ){
        bl_skip_codespan(data, size, &i);
      }else{
        i++;
      }
    }
    end = i;
    if( i<size ){
      i++;
      if( data[i-1]=='\n' ) total = i;
    }

    /* check optional right/center align marker */
    if( i>beg && data[end-1]==':' ){
      end--;
    }

    /* remove trailing blanks */
    while( end>beg && (data[end-1]==' ' || data[end-1]=='\t') ){ end--; }

    /* skip the last cell if it was only blanks */
    /* (because it is only the optional end separator) */
    if( total && end<=beg ) continue;

    /* render cells */
    if( end>=beg ){
      bl_parse_table_cell(md, data+beg, end-beg);
    }
  }

  bl_leave(md);
  return total ? total : size;
}


/* parsing of a whole table */
static size_t bl_parse_table(bl_md *md, char *data, size_t size){
  size_t i = 0, head_end;
  int hasHead = 0;

  bl_enter(md);  /* the rows */

  /* skip the first (presumably header) line */
  while( i<size && data[i]!='\n' ){ i++; }
  head_end = i;

  /* fallback on end of input */
  if( i>=size ){
    bl_parse_table_row(md, data, size);
    bl_leave(md);
    return i;
  }

  /* attempt to parse a table rule, i.e. blanks, dash, colons and sep */
  i++;
  while( i<size
    && (data[i]==' '
      || data[i]=='\t'
      || data[i]=='-'
      || data[i] == ':'
      || data[i] =='|')
  ){
    i += 1;
  }

  if( i<size && data[i]=='\n' ){
    /* render the header row */
    bl_enter(md);
    hasHead = 1;
    bl_parse_table_row(md, data, head_end);

    /* point i to the beginning of next line/row */
    i++;

  }else{
    /* there is no valid ruler, continuing without header */
    i = 0;
  }

  /* render the table body lines */
  while( i<size && bl_is_tableline(data + i, size - i) && BL_OK(md) ){
    i += bl_parse_table_row(md, data+i, size-i);
  }

  /* cleanup */
  if( hasHead ) bl_leave(md);
  bl_leave(md);
  return i;
}


/* parsing of one block, returning next char to parse */
static void bl_parse_block(bl_md *md, char *data, size_t size){
  size_t beg, end, i;
  char *txt_data;
  int has_table;
  if( !size ) return;
  has_table = memchr(data, '|', size)!=0;

  beg = 0;
  while( beg<size && BL_OK(md) ){
    txt_data = data+beg;
    end = size-beg;
    if( data[beg]=='#' ){
      beg += bl_parse_atxheader(md, txt_data, end);
    }else if( data[beg]=='<'
      && (i = bl_parse_htmlblock(txt_data, end))!=0
    ){
      beg += i;
    }else if( (i=bl_is_empty(txt_data, end))!=0 ){
      beg += i;
    }else if( bl_is_hrule(txt_data, end) ){
      while( beg<size && data[beg]!='\n' ){ beg++; }
      beg++;
    }else if( bl_prefix_quote(txt_data, end) ){
      beg += bl_parse_blockquote(md, txt_data, end);
    }else if( bl_prefix_code(txt_data, end) ){
      beg += bl_parse_blockcode(txt_data, end);
    }else if( bl_prefix_uli(txt_data, end) ){
      beg += bl_parse_list(md, txt_data, end, 0);
    }else if( bl_prefix_oli(txt_data, end) ){
      beg += bl_parse_list(md, txt_data, end, BL_LIST_ORDERED);
    }else if( has_table && bl_is_tableline(txt_data, end) ){
      beg += bl_parse_table(md, txt_data, end);
    }else if( bl_prefix_fencedcode(txt_data, end)
             && (i = bl_char_codespan(md, txt_data, 0, end))!=0
    ){
      beg += i;
    }else{
      beg += bl_parse_paragraph(md, txt_data, end);
    }
  }
}


/*********************
 * REFERENCE PARSING *
 *********************/

/*
** Returns whether a line is a link reference definition, and if so
** records it. *last is set to the last character of the definition.
*/
static int bl_is_ref(
  bl_md * const md,
  const char *data,   /* input text */
  size_t beg,         /* offset of the beginning of the line */
  size_t end,         /* offset of the end of the text */
  size_t *last        /* last character of the link */
){
  size_t i = 0;
  size_t id_offset, id_end;
  size_t link_offset, link_end;
  size_t title_offset, title_end;
  size_t line_end;
  bl_ref lr;

  /* up to 3 optional leading spaces */
  if( beg+3>=end ) return 0;
  if( data[beg]==' ' ){
    i = 1;
    if( data[beg+1]==' ' ){
      i = 2;
      if( data[beg+2]==' ' ){
        i = 3;
        if( data[beg+3]==' ' ) return 0;
      }
    }
  }
  i += beg;

  /* id part: anything but a newline between brackets */
  if( data[i]!='[' ) return 0;
  i++;
  if( i>=end || data[i]=='^' ) return 0;  /* see bl_is_footnote() */

  id_offset = i;
  while( i<end && data[i]!='\n' && data[i]!='\r' && data[i]!=']' ){ i++; }
  if( i>=end || data[i]!=']' ) return 0;
  id_end = i;

  /* spacer: colon (space | tab)* newline? (space | tab)* */
  i++;
  if( i>=end || data[i]!=':' ) return 0;
  i++;
  while( i<end && (data[i]==' ' || data[i]=='\t') ){ i++; }
  if( i<end && (data[i]=='\n' || data[i]=='\r') ){
    i++;
    if( i<end && data[i]=='\r' && data[i-1] == '\n' ) i++;
  }
  while( i<end && (data[i]==' ' || data[i]=='\t') ){ i++; }
  if( i>=end ) return 0;

  /* link: whitespace-free sequence, optionally between angle brackets */
  if( data[i]=='<' ) i++;
  link_offset = i;
  while( i<end
   && data[i]!=' '
   && data[i]!='\t'
   && data[i]!='\n'
   && data[i]!='\r'
  ){
    i += 1;
  }
  /* TODO: maybe require both data[i-1]=='>' && data[link_offset-1]=='<' ? */
  if( data[i-1]=='>' ) link_end = i-1; else link_end = i;

  /* optional spacer: (space | tab)* (newline | '\'' | '"' | '(' ) */
  while( i<end && (data[i]==' ' || data[i]=='\t') ){ i++; }
  if( i<end
   && data[i]!='\n'
   && data[i]!='\r'
   && data[i]!='\''
   && data[i]!='"'
   && data[i]!='('
  ){
    return 0;
  }
  line_end = 0;
  /* computing end-of-line */
  if( i>=end || data[i]=='\r' || data[i]=='\n' ) line_end = i;
  if( i+1<end && data[i]=='\n' && data[i+1]=='\r' ) line_end = i+1;

  /* optional (space|tab)* spacer after a newline */
  if( line_end ){
    i = line_end+1;
    while( i<end && (data[i]==' ' || data[i]=='\t') ){ i++; }
  }

  /* optional title: any non-newline sequence enclosed in '"()
          alone on its line. The title itself is not needed, but whether
          there is one decides where the definition ends. */
  title_offset = title_end = 0;
  if( i+1<end && (data[i]=='\'' || data[i]=='"' || data[i]=='(') ){
    i += 1;
    title_offset = i;
    /* looking for EOL */
    while( i<end && data[i]!='\n' && data[i]!='\r' ){ i++; }
    if( i+1<end && data[i]=='\n' && data[i+1]=='\r' ){
      title_end = i + 1;
    }else{
      title_end = i;
    }
    /* stepping back */
    i--;
    while( i>title_offset && (data[i]==' ' || data[i]=='\t') ){ i--; }
    if( i>title_offset && (data[i]=='\'' || data[i]=='"' || data[i]==')') ){
      line_end = title_end;
      title_end = i;
    }
  }
  if( !line_end ) return 0; /* garbage after the link */

  /* a valid ref has been found, filling-in return structures */
  if( last ) *last = line_end;
  lr.id = fsl_b_empty;
  lr.link = fsl_b_empty;
  if( bl_build_ref_id(md, &lr.id, data+id_offset, id_end-id_offset)<0 ){
    fsl_b_clear(&lr.id);
    return 0;
  }
  bl_append(md, &lr.link, data+link_offset, link_end-link_offset);
  if( md->nRef>=md->nRefAlloc ){
    int const nAlloc = md->nRefAlloc*2 + 8;
    bl_ref * const a = (bl_ref*)fsl_realloc(md->aRef, nAlloc*sizeof(bl_ref));
    if( !a ){
      bl_err(md, FSL_RC_OOM);
      fsl_b_clear(&lr.id);
      fsl_b_clear(&lr.link);
      return 1;
    }
    md->aRef = a;
    md->nRefAlloc = nAlloc;
  }
  md->aRef[md->nRef++] = lr;
  return 1;
}

/*********************
 * FOOTNOTE PARSING  *
 *********************/

/*
** Check if data holds a definition of a labeled footnote. If so then
** append the corresponding element to the notes.
*/
static int bl_is_footnote(
  bl_md * const md,
  const char *data,   /* input text */
  size_t beg,         /* offset of the beginning of the line */
  size_t end,         /* offset of the end of the text */
  size_t *last        /* last character of the link */
){
  size_t i, id_offset, id_end, upc_offset, upc_size;
  bl_note fn;

  /* failfast if data is too short */
  if( beg+5>=end ) return 0;
  i = beg;

  /* footnote definition must start at the beginning of a line */
  if( data[i]!='[' ) return 0;
  i++;
  if( data[i]!='^' ) return 0;
  id_offset = ++i;

  /* id part: anything but a newline between brackets */
  while( i<end && data[i]!=']' && data[i]!='\n' && data[i]!='\r' ){ i++; }
  if( i>=end || data[i]!=']' ) return 0;
  id_end = i++;

  /* spacer: colon (space | tab)* */
  if( i>=end || data[i]!=':' ) return 0;
  i++;
  while( i<end && (data[i]==' ' || data[i]=='\t') ){ i++; }

  /* passthrough truncated footnote definition */
  if( i>=end ) return 0;

  memset(&fn, 0, sizeof(fn));
  fn.id = fn.text = fn.upc = fsl_b_empty;
  if( bl_build_ref_id(md, &fn.id, data+id_offset, id_end-id_offset)<0 ){
    fsl_b_clear(&fn.id);
    return 0;
  }

  /* footnote's text may start on the same line after [^id]: */
  upc_offset = upc_size = 0;
  if( data[i]!='\n' && data[i]!='\r' ){
    size_t j;
    upc_size = bl_is_footnote_classlist(data+i, end-i, 1);
    upc_offset = i; /* prevent further checks for a classlist */
    i += upc_size;
    j = i;
    while( i<end && data[i]!='\n' && data[i]!='\r' ){ i++; };
    if( i!=j ) bl_append(md, &fn.text, data+j, i-j);
    if( i<end ){
      bl_append(md, &fn.text, data+i, 1);
      i++;
      if( i<end && data[i]=='\n' && data[i-1]=='\r' ){
        bl_append(md, &fn.text, data+i, 1);
        i++;
      }
    }
  }else{
    i++;
    if( i<end && data[i]=='\n' && data[i-1]=='\r' ) i++;
  }
  if( i<end ){

    /* compute the indentation from the 2nd line  */
    size_t indent = i;
    const char *spaces = data+i;
    while( indent<end && data[indent]==' ' ){ indent++; }
    if( indent>=end ) goto footnote_finish;
    indent -= i;
    if( indent<2 ) goto footnote_finish;

    /* process the 2nd and subsequent lines */
    while( i+indent<end && memcmp(data+i,spaces,indent)==0 ){
      size_t j;
      i += indent;
      if( !upc_offset ){
        /* a classlist must be provided no later than at the 2nd line */
        upc_offset = i + bl_sizeof_blank_prefix(data+i, end-i, 1);
        upc_size = bl_is_footnote_classlist(data+upc_offset,
                                            end-upc_offset, 1);
        if( upc_size ){
          i = upc_offset + upc_size;
        }
      }
      j = i;
      while( i<end && data[i]!='\n' && data[i]!='\r' ){ i++; }
      if( i!=j ) bl_append(md, &fn.text, data+j, i-j);
      if( i>=end ) break;
      bl_append(md, &fn.text, data+i, 1);
      i++;
      if( i<end && data[i]=='\n' && data[i-1]=='\r' ){
        bl_append(md, &fn.text, data+i, 1);
        i++;
      }
    }
  }
footnote_finish:
  if( !fn.text.used ){
    fsl_b_clear(&fn.id);
    fsl_b_clear(&fn.text);
    return 0;
  }
  /* trim whitespace off the end of the text */
  while( fn.text.used>0 && fsl_isspace(fn.text.mem[fn.text.used-1]) ){
    fn.text.mem[--fn.text.used] = 0;
  }
  if( !fn.text.used ){      /* if the content is all-blank */
    if( upc_size ){         /* interpret UPC as plain text */
      bl_append(md, &fn.text, data+upc_offset, upc_size);
      upc_size = 0;
    }else{
      fsl_b_clear(&fn.id);  /* or clean up and fail */
      fsl_b_clear(&fn.text);
      return 0;
    }
  }
  /* a valid note has been found */
  if( last ) *last = i;
  fn.defno = md->notes.n;
  if( upc_size ){
    assert( upc_offset && upc_offset+upc_size<end );
    bl_append(md, &fn.upc, data+upc_offset, upc_size);
  }
  bl_note_push(md, &fn);
  return 1;
}


/**********************
 * EXPORTED FUNCTIONS *
 **********************/

/*
** Scan markdown text for hyperlinks, passing their targets to the
** sink. Port of fossil(1)'s markdown() combined with
** markdown_extract_links(). zSrc is not modified.
*/
static void bl_markdown_extract(bl_sink * const sink, const char *zSrc){
  bl_md md;
  int i;
  size_t beg, end = 0;
  size_t const size = fsl_strlen(zSrc);
  fsl_b text = fsl_b_empty;       /* input after the first pass  */

  memset(&md, 0, sizeof(md));
  md.sink = sink;
  md.active_char[(unsigned char)'*'] = bl_char_emphasis;
  md.active_char[(unsigned char)'_'] = bl_char_emphasis;
  md.active_char[(unsigned char)'`'] = bl_char_codespan;
  md.active_char[(unsigned char)'\n'] = bl_char_linebreak;
  md.active_char[(unsigned char)'['] = bl_char_link;
  md.active_char[(unsigned char)'('] = bl_char_footnote;
  md.active_char[(unsigned char)'<'] = bl_char_langle_tag;
  md.active_char[(unsigned char)'\\'] = bl_char_escape;
  md.active_char[(unsigned char)'&'] = bl_char_entity;

  /* first pass: iterate over lines looking for references,
   * copying everything else into "text" */
  beg = 0;
  while( beg<size && BL_OK(&md) ){
    if( bl_is_ref(&md, zSrc, beg, size, &end) ){
      beg = end;
    }else if( bl_is_footnote(&md, zSrc, beg, size, &end) ){
      beg = end;
    }else{ /* skipping to the next line */
      end = beg;
      while( end<size && zSrc[end]!='\n' && zSrc[end]!='\r' ){
        end += 1;
      }
      /* adding the line body if present */
      if( end>beg ) bl_append(&md, &text, zSrc + beg, end - beg);
      while( end<size && (zSrc[end]=='\n' || zSrc[end]=='\r') ){
        /* add one \n per newline */
        if( zSrc[end]=='\n' || (end+1<size && zSrc[end+1]!='\n') ){
          bl_append(&md, &text, "\n", 1);
        }
        end += 1;
      }
      beg = end;
    }
  }
  if( !BL_OK(&md) ) goto done;

  /* sorting the reference array */
  if( md.nRef ){
    qsort(md.aRef, md.nRef, sizeof(bl_ref), bl_cmp_ref_sort);
  }
  md.notes.nLbled = md.notes.n;

  /* sort footnotes by ID and join duplicates */
  if( md.notes.nLbled > 1 ){
    int nDups = 0;
    bl_note * const fn = md.notes.a;
    qsort(fn, md.notes.nLbled, sizeof(bl_note), bl_cmp_note_id);

    /* concatenate footnotes with equal labels */
    for(i=0; i<md.notes.nLbled ;){
      bl_note * const x = fn + i;
      int j = i+1;
      while( j<md.notes.nLbled && !bl_blob_compare(&x->id, &fn[j].id) ){
        j++;
        nDups++;
      }
      if( i+1<j ){
        fsl_b list = fsl_b_empty;
        int k;
        /* must match _joined_footnote_indicator in html_footnote_item() */
        bl_append(&md, &list, "<ul class='fn-joined'>\n", 23);
        for(k=i; k<j; k++){
          bl_note * const y = fn + k;
          bl_append(&md, &list, "<li>", 4);
          if( y->upc.used ){
            bl_append(&md, &list, bl_bstr(&y->upc), y->upc.used);
            fsl_b_clear(&y->upc);
          }
          bl_append(&md, &list, bl_bstr(&y->text), y->text.used);
          bl_append(&md, &list, "</li>\n", 6);

          /* free memory buffer */
          fsl_b_clear(&y->text);
          if( k!=i ) fsl_b_clear(&y->id);
        }
        bl_append(&md, &list, "</ul>\n", 6);
        x->text = list;
      }
      i = j;
    }
    if( nDups ){  /* clean the notes of invalidated footnotes */
      int const n = md.notes.nLbled - nDups;
      int nKept = 0;
      for(i=0; i<md.notes.nLbled; i++){
        if( fn[i].id.used ){
          fn[nKept++] = fn[i];
        }
      }
      assert( nKept==n );
      md.notes.n = md.notes.nLbled = n;
    }
  }
  for(i=0; i<md.notes.nLbled; i++){
    md.notes.a[i].index = i;
  }
  assert( md.notes.nMarks==0 );
  if( !BL_OK(&md) ) goto done;

  /* second pass: the actual parsing */
  bl_parse_block(&md, bl_bstr(&text), text.used);

  if( md.notes.n && BL_OK(&md) ){
    /* Footnotes must be parsed for the correct discovery of links */
    bl_note *aSorted = 0;
    int nMarks = -1, maxDepth = 5;
    bl_enter(&md);
    bl_enter(&md);

    /* inline notes may get appended to the notes while parsing */
    while( BL_OK(&md) ){
      int const N = md.notes.n;
      bl_note * const a = (bl_note*)fsl_realloc(aSorted, N*sizeof(bl_note));
      if( !a ){
        bl_err(&md, FSL_RC_OOM);
        break;
      }
      aSorted = a;

      /* make a shallow copy of the notes, in order of use */
      memcpy(aSorted, md.notes.a, N*sizeof(bl_note));
      qsort(aSorted, N, sizeof(bl_note), bl_cmp_note_sort);

      if( --maxDepth < 0 || nMarks == md.notes.nMarks ) break;
      nMarks = md.notes.nMarks;

      for(i=0; i<N && BL_OK(&md); i++){
        int const j = aSorted[i].index;
        bl_note * x = md.notes.a + j;
        assert( 0<=j && j<N );
        if( x->bRndred || !x->nUsed ) continue;
        assert( x->iMark > 0 );
        assert( x->text.used );

        /* The notes may be extended through this call, which may
        ** move them but not their text. */
        bl_parse_inline(&md, bl_bstr(&x->text), x->text.used);

        x = md.notes.a + j;
        x->bRndred = 1;
      }
    }
    fsl_free(aSorted);
    bl_leave(&md);
    bl_leave(&md);
  }

  /* clean-up */
  assert( !BL_OK(&md) || md.iDepth==0 );
  done:
  fsl_b_clear(&text);
  for(i=0; i<md.nRef; i++){
    fsl_b_clear(&md.aRef[i].id);
    fsl_b_clear(&md.aRef[i].link);
  }
  fsl_free(md.aRef);
  for(i=0; i<md.notes.n; i++){
    fsl_b_clear(&md.notes.a[i].id);
    fsl_b_clear(&md.notes.a[i].upc);
    fsl_b_clear(&md.notes.a[i].text);
  }
  fsl_free(md.notes.a);
}

int fsl__backlink_mimetype(char const * zMimetype){
  if( zMimetype==0 ) return FSL_BKLNK_MT_NONE;
  if( strstr(zMimetype,"wiki")!=0 )     return FSL_BKLNK_MT_WIKI;
  if( strstr(zMimetype,"markdown")!=0 ) return FSL_BKLNK_MT_MARKDOWN;
  return FSL_BKLNK_MT_UNKNOWN;
}

int fsl__backlink_scan(char const * zSrc, int mimetype, bool wikiHtml,
                       fsl__backlink_f cb, void * cbState){
  bl_sink sink;
  sink.cb = cb;
  sink.cbState = cbState;
  sink.rc = 0;
  assert( FSL_BKLNK_MT_NONE<=mimetype && mimetype<=FSL_BKLNK_MT_UNKNOWN );
  if( mimetype==FSL_BKLNK_MT_NONE || mimetype==FSL_BKLNK_MT_WIKI ){
    /* The scanner modifies its input temporarily. */
    char * const zCopy = fsl_strdup(zSrc);
    if( !zCopy ) return FSL_RC_OOM;
    bl_wiki_extract(&sink, zCopy, wikiHtml);
    fsl_free(zCopy);
  }else if( mimetype==FSL_BKLNK_MT_MARKDOWN ){
    bl_markdown_extract(&sink, zSrc);
  }
  return sink.rc;
}

/*
** State for recording links in the backlink table.
*/
typedef struct {
  fsl_cx * f;
  int srcType;       /* One of FSL_BKLNK_xxx */
  fsl_id_t srcId;
  double mtime;
} bl_ins;

/* fsl__backlink_f() which records a link in the backlink table. */
static int bl_insert_f(void * state, char const * zTarget){
  bl_ins * const p = (bl_ins*)state;
  fsl_stmt * st = 0;
  int rc = fsl_cx_prepare_cached(p->f, &st,
                                 "REPLACE INTO {{dbname.repo}}.backlink"
                                 "(target,srctype,srcid,mtime) "
                                 "VALUES(?1,?2,?3,?4)");
  if( 0==rc ){
    rc = fsl_stmt_bind_step(st, "s^iRf", zTarget, (int32_t)p->srcType,
                            p->srcId, p->mtime);
    if( rc ) rc = fsl_cx_uplift_db_error2(p->f, st->db, rc);
    fsl_stmt_cached_yield(st);
  }
  return rc;
}

int fsl__backlink_extract(fsl_cx * const f, char const * zSrc, int mimetype,
                          fsl_id_t srcId, int srcType, double mtime,
                          bool replace){
  fsl_db * const db = fsl_needs_repo(f);
  bl_ins ins;
  bool wikiHtml = false;
  int rc;
  assert( FSL_BKLNK_COMMENT<=srcType && srcType<=FSL_BKLNK_FORUM );
  if( !db ) return FSL_RC_NOT_A_REPO;
  else if( !fsl_db_table_exists(db, FSL_DBROLE_REPO, "backlink") ){
    /* A repository from before the table existed. */
    return 0;
  }
  if( replace ){
    rc = fsl_cx_exec(f, "DELETE FROM {{dbname.repo}}.backlink "
                     "WHERE srctype=%d AND srcid=%" FSL_ID_T_PFMT,
                     srcType, srcId);
    if( rc ) return rc;
  }
  if( !zSrc ) return 0;
  if( mimetype==FSL_BKLNK_MT_NONE || mimetype==FSL_BKLNK_MT_WIKI ){
    wikiHtml = fsl_config_get_bool(f, FSL_CONFDB_REPO, false, "wiki-use-html");
  }
  ins.f = f;
  ins.srcType = srcType;
  ins.srcId = srcId;
  ins.mtime = mtime;
  return fsl__backlink_scan(zSrc, mimetype, wikiHtml, bl_insert_f, &ins);
}

int fsl__backlink_ticket_reset(fsl_cx * const f, fsl_id_t tagId){
  fsl_db * const db = fsl_needs_repo(f);
  if( !db ) return FSL_RC_NOT_A_REPO;
  else if( !fsl_db_table_exists(db, FSL_DBROLE_REPO, "backlink") ) return 0;
  return fsl_cx_exec(f, "DELETE FROM {{dbname.repo}}.backlink "
                     "WHERE srctype=%d AND srcid IN "
                     "(SELECT rid FROM {{dbname.repo}}.tagxref "
                     "WHERE tagid=%" FSL_ID_T_PFMT ")",
                     FSL_BKLNK_TICKET, tagId);
}

int fsl__backlink_wiki_refresh(fsl_cx * const f, char const * zWikiTitle){
  fsl_db * const db = fsl_needs_repo(f);
  fsl_deck d = fsl_deck_empty;
  fsl_id_t tagid, rid;
  char * zTag;
  int rc;
  if( !db ) return FSL_RC_NOT_A_REPO;
  zTag = fsl_mprintf("wiki-%s", zWikiTitle);
  if( !zTag ) return FSL_RC_OOM;
  tagid = fsl_tag_id(f, zTag, false);
  fsl_free(zTag);
  if( tagid<0 ) return f->error.code;
  else if( 0==tagid ) return 0;
  rid = fsl_db_g_id(db, 0, "SELECT rid FROM {{dbname.repo}}.tagxref "
                    "WHERE tagid=%" FSL_ID_T_PFMT
                    " ORDER BY mtime DESC LIMIT 1", tagid);
  if( rid<0 ) return fsl_cx_uplift_db_error(f, db);
  else if( 0==rid ) return 0;
  rc = fsl_deck_load_rid(f, &d, rid, FSL_SATYPE_WIKI);
  if( FSL_RC_TYPE==rc ){
    /* Not a wiki page: not ours to index. */
    fsl_cx_err_reset(f);
    rc = 0;
  }else if( 0==rc ){
    rc = fsl__backlink_extract(f, d.W.used ? fsl_b_cstr(&d.W) : "",
                               fsl__backlink_mimetype(d.N), tagid,
                               FSL_BKLNK_WIKI, d.D, true);
  }
  fsl_deck_finalize(&d);
  return rc;
}
/* end of file src/backlink.c */
/* start of file src/bag.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/***************************************************************************
  This file houses the code for the fsl_id_bag class.
*/
#include <assert.h>
#include <string.h> /* memset() */

const fsl_id_bag fsl_id_bag_empty = fsl_id_bag_empty_m;

void fsl_id_bag_clear(fsl_id_bag * const p){
  fsl_free(p->list);
  *p = fsl_id_bag_empty;
}

/*
   The hash function
*/
#define fsl_id_bag_hash(i)  (((uint64_t)i)*101)

/*
   Change the size of the hash table on a bag so that
   it contains N slots

   Completely reconstruct the hash table from scratch.  Deleted
   entries (indicated by a -1) are removed. When finished,
   p->entryCount==p->used and p->capacity==newSize.

   Returns on on success, FSL_RC_OOM on allocation error.
*/
static int fsl_id_bag_resize(fsl_id_bag * const p, fsl_size_t newSize){
  fsl_size_t i;
  fsl_id_bag old;
  fsl_size_t nDel = 0;   /* Number of deleted entries */
  fsl_size_t nLive = 0;  /* Number of live entries */
  fsl_id_t * newList;
  assert( newSize > p->entryCount );
  newList = (fsl_id_t*)fsl_malloc( sizeof(p->list[0])*newSize );
  if(!newList) return FSL_RC_OOM;
  old = *p;
  p->list = newList;
  p->capacity = newSize;
  memset(p->list, 0, sizeof(p->list[0])*newSize );
  for(i=0; i<old.capacity; i++){
    fsl_id_t const e = old.list[i];
    if( e>0 ){
      unsigned h = fsl_id_bag_hash(e)%newSize;
      while( p->list[h] ){
        h++;
        if( h==newSize ) h = 0;
      }
      p->list[h] = e;
      nLive++;
    }else if( e<0 ){
      nDel++;
    }
  }
  assert( p->entryCount == nLive );
  assert( p->used == nLive+nDel );
  p->used = p->entryCount;
  fsl_id_bag_clear(&old);
  return 0;
}

fsl_id_bag * fsl_id_bag_reuse(fsl_id_bag * const p){
  p->entryCount = p->used = 0;
  if(p->list){
    memset(p->list, 0, sizeof(p->list[0])*p->capacity);
  }
  return p;
}


int fsl_id_bag_insert(fsl_id_bag * const p, fsl_id_t e){
  fsl_size_t h;
  int rc = 0;
  assert( e>0 );
  if( p->used+1 >= p->capacity/2 ){
    fsl_size_t const n = p->capacity ? p->capacity*2 : 30;
    rc = fsl_id_bag_resize(p,  n );
    if(rc) return rc;
  }
  h = fsl_id_bag_hash(e)%p->capacity;
  while( p->list[h]>0 && p->list[h]!=e ){
    h++;
    if( h>=p->capacity ) h = 0;
  }
  if( p->list[h]<=0 ){
    if( p->list[h]==0 ) ++p->used;
    p->list[h] = e;
    ++p->entryCount;
    rc = 0;
  }
  return rc;
}

bool fsl_id_bag_contains(fsl_id_bag const * const p, fsl_id_t e){
  fsl_size_t h;
  assert( e>0 );
  if( p->capacity==0 || 0==p->used ){
    return false;
  }
  assert(p->list);
  h = fsl_id_bag_hash(e)%p->capacity;
  while( p->list[h] && p->list[h]!=e ){
    h++;
    if( h>=p->capacity ) h = 0
      /*loop around to the start*/
      ;
  }
  return p->list[h]==e;
}

bool fsl_id_bag_remove(fsl_id_bag * const p, fsl_id_t e){
  fsl_size_t h;
  bool rv = false;
  assert( e>0 );
  if( !p->capacity || !p->used ) return rv;
  assert(p->list);
  h = fsl_id_bag_hash(e)%p->capacity;
  while( p->list[h] && p->list[h]!=e ){
    ++h;
    if( h>=p->capacity ) h = 0;
  }
  rv = p->list[h]==e;
  if( p->list[h] ){
    fsl_size_t nx = h+1;
    if( nx>=p->capacity ) nx = 0;
    if( p->list[nx]==0 ){
      p->list[h] = 0;
      --p->used;
    }else{
      p->list[h] = -1;
    }
    --p->entryCount;
    if( p->entryCount==0 ){
      memset(p->list, 0, p->capacity*sizeof(p->list[0]));
      p->used = 0;
    }else if( p->capacity>40 && p->entryCount<p->capacity/8 ){
      fsl_id_bag_resize(p, p->capacity/2)
        /* ignore realloc error and keep the old size. */;
    }
  }
  return rv;
}

fsl_id_t fsl_id_bag_first(fsl_id_bag const * const p){
  if( p->capacity==0 || 0==p->used ){
    return 0;
  }else{
    fsl_size_t i;
    for(i=0; i<p->capacity && p->list[i]<=0; ++i){}
    if( i<p->capacity ){
      return p->list[i];
    }else{
      return 0;
    }
  }
}

fsl_id_t fsl_id_bag_next(fsl_id_bag const * const p, fsl_id_t e){
  fsl_size_t h;
  assert( p->capacity>0 );
  assert( e>0 );
  assert(p->list);
  h = fsl_id_bag_hash(e)%p->capacity;
  while( p->list[h] && p->list[h]!=e ){
    ++h;
    if( h>=p->capacity ) h = 0;
  }
  assert( p->list[h] );
  h++;
  while( h<p->capacity && p->list[h]<=0 ){
    h++;
  }
  return h<p->capacity ? p->list[h] : 0;
}

fsl_size_t fsl_id_bag_count(fsl_id_bag const * const p){
  return p->entryCount;
}

void fsl_id_bag_swap(fsl_id_bag * const lhs, fsl_id_bag * const rhs){
  fsl_id_bag x = *lhs;
  *lhs = *rhs;
  *rhs = x;
}

int fsl_id_bag_copy(fsl_id_bag const * src, fsl_id_bag * dest){
  int rc = 0;
  for( fsl_id_t bid = fsl_id_bag_first(src);
       bid>0 && 0==rc;
       bid = fsl_id_bag_next(src, bid) ){
    rc = fsl_id_bag_insert(dest, bid);
  }
  return rc;
}

void fsl__id_bag_dump(fsl_id_bag const * bag, FILE *to,
                      char const *zHeader){
  if( !to ) to = stdout;
  fprintf(to, "%s:%d:%s() id bag size %d: %s\n",
          __FILE__, __LINE__, __func__, (int)bag->used, zHeader);
  int n = 0;
  for( fsl_id_t bid = fsl_id_bag_first(bag);
       bid>0;
       ++n, bid = fsl_id_bag_next(bag, bid) ){
    fprintf(to,"%"FSL_ID_T_PFMT" ", bid);
  }
  if(n) fprintf(to,"\n");
}
#undef fsl_id_bag_hash
/* end of file src/bag.c */
/* start of file src/buffer.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

#include <assert.h>
#include <limits.h> /* LONG_MAX on darwin */
#include <string.h> /* strlen() */
#include <stddef.h> /* NULL on linux */
#include <errno.h>

#include <zlib.h>


#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

#define buf__is_external(b) (b->mem && 0==b->capacity)

#define buff__errcheck(B) if((B)->errCode) return (B)->errCode
/**
   Materializes external buffer b by allocating b->used+extra+1
   bytes, copying b->used bytes from b->mem to the new block,
   NUL-terminating the block, and replacing b->mem with the new
   block. Returns 0 on success, else FSL_RC_OOM.

   Asserts that b is an external buffer.
*/
static int fsl__b_materialize( fsl_b * const b, fsl_size_t extra ){
  assert(buf__is_external(b));
  buff__errcheck(b);
  fsl_size_t const n = b->used + extra + 1;
  unsigned char * x = (unsigned char *)fsl_malloc(n);
  if(!x) return b->errCode = FSL_RC_OOM;
  memcpy(x, b->mem, b->used);
  b->capacity = n;
  x[b->used] = 0;
  b->mem = x;
  return 0;
}

int fsl_b_err( fsl_b const * b ){
  return b->errCode;
}

void fsl_b_err_clear(fsl_b * const b){
  b->errCode = 0;
}

#define buf__materialize(B,N) (buf__is_external(B) ? fsl__b_materialize((B),(N)) : 0)

int fsl_b_materialize( fsl_b * const b ){
  buff__errcheck(b);
  if( !buf__is_external(b) ) return 0;
  return fsl__b_materialize(b, 0);
}

void fsl_b_external( fsl_b * const b, void const * mem, fsl_int_t n ){
  if(b->mem) fsl_b_clear(b);
  b->used = (n<0) ? fsl_strlen((char const *)mem) : (fsl_size_t)n;
  b->cursor = 0;
  b->errCode = 0;
  b->mem = (unsigned char *)mem;
  b->capacity = 0;
}

fsl_b * fsl_b_reuse( fsl_b * const b ){
  if(buf__is_external(b)){
    *b = fsl_b_empty;
  }else{
    if(b->capacity){
      assert(b->mem);
      b->mem[0] = 0;
      b->used = 0;
    }
    b->cursor = 0;
    b->errCode = 0;
  }
  return b;
}

void fsl_b_clear( fsl_b * const buf ){
  if(buf->capacity) fsl_free(buf->mem);
  *buf = fsl_b_empty;
}

int fsl_b_reserve( fsl_b * const buf, fsl_size_t n ){
  if( 0 == n ){
    if(!buf__is_external(buf)){
      fsl_free(buf->mem);
    }/* else if it has memory, it's owned elsewhere */
    *buf = fsl_b_empty;
    return 0;
  }
  else buff__errcheck(buf);
  else if( !buf__is_external(buf) && buf->capacity >= n ){
    assert(buf->mem);
    return 0;
  }else{
    unsigned char * x;
    bool const isExt = buf__is_external(buf);
    assert((buf->used < n) && "Buffer in-use greater than capacity!");
    if(isExt && n<=buf->used){
      /*For external buffers, always keep at least the initially-pointed-to
        size. */
      n = buf->used + 1;
    }
    x = (unsigned char *)fsl_realloc( isExt ? NULL : buf->mem, n );
    if( !x ) return buf->errCode = FSL_RC_OOM;
    else if(isExt){
      memcpy( x, buf->mem, buf->used );
      x[buf->used] = 0;
    }else{
      memset( x + buf->used, 0, n - buf->used );
    }
    buf->mem = x;
    buf->capacity = n;
    return 0;
  }
}

int fsl_b_resize( fsl_b * const b, fsl_size_t n ){
  buff__errcheck(b);
  else if(n==(fsl_size_t)-1) return b->errCode = FSL_RC_RANGE;
  else if(buf__is_external(b)){
    if(n==b->used) return 0;
    else if(n==0){
      b->capacity = 0;
      fsl_b_external(b, "", 0);
      return 0;
    }
    unsigned char * x = (unsigned char *)fsl_malloc( n+1/*NUL*/ );
    if( !x ) return b->errCode = FSL_RC_OOM;
    memcpy(x, b->mem, n < b->used ? n : b->used);
    x[n] = 0;
    b->mem = x;
    b->capacity = n+1;
    b->used = n;
    return 0;
  }else if(n && (b->capacity == n+1)){
    b->used = n;
    b->mem[n] = 0;
    return 0;
  }else{
    unsigned char * x = (unsigned char *)fsl_realloc( b->mem,
                                                      n+1/*NUL*/ );
    if( ! x ) return b->errCode = FSL_RC_OOM;
    if(n > b->capacity){
      /* zero-fill new parts */
      memset( x + b->capacity, 0, n - b->capacity +1/*NUL*/ );
    }
    b->capacity = n + 1 /*NUL*/;
    b->used = n;
    b->mem = x;
    b->mem[b->used] = 0;
    return 0;
  }
}

int fsl_b_compare(fsl_b const * const lhs, fsl_b const * const rhs){
  fsl_size_t const szL = lhs->used;
  fsl_size_t const szR = rhs->used;
  fsl_size_t const sz = (szL<szR) ? szL : szR;
  int rc = memcmp(lhs->mem, rhs->mem, sz);
  if(0 == rc){
    rc = (szL==szR)
      ? 0
      : ((szL<szR) ? -1 : 1);
  }
  return rc;
}

bool fsl_b_eq(fsl_b const * const b, char const * str,
                   fsl_int_t nStr){
  fsl_b const rhs = {
    .mem = (unsigned char *)str,
    .capacity = 0,
    .used = (nStr<0) ? fsl_strlen(str) : (fsl_size_t)nStr,
    .cursor = 0,
    .errCode = 0
  };
  return 0==fsl_b_compare(b, &rhs);
}

int fsl_b_compare_O1(fsl_b const * const lhs, fsl_b const * const rhs){
  fsl_size_t const szL = lhs->used;
  fsl_size_t const szR = rhs->used;
  fsl_size_t i;
  unsigned char const *buf1;
  unsigned char const *buf2;
  unsigned char rc = 0;
  if( szL!=szR || szL==0 ) return 1;
  buf1 = lhs->mem;
  buf2 = rhs->mem;
  for( i=0; i<szL; i++ ){
    rc = rc | (buf1[i] ^ buf2[i]);
  }
  return rc;
}


int fsl_b_append( fsl_b * const b,
                       void const * const data,
                       fsl_int_t len ){
  if(0==b->errCode){
    fsl_size_t sz = b->used;
    if(len<0) len = (fsl_int_t)fsl_strlen((char const *)data);
    if(buf__materialize(b, (fsl_size_t)len + 1)) return b->errCode;
    assert(b->capacity ? !!b->mem : !b->mem);
    assert(b->used <= b->capacity);
    sz += len + 1/*NUL*/;
    if(b->capacity<sz) fsl_b_reserve( b, sz );
    if(!b->errCode){
      assert(b->capacity >= sz);
      if(len>0) memcpy(b->mem + b->used, data, (size_t)len);
      b->used += len;
      b->mem[b->used] = 0;
    }
  }
  return b->errCode;
}

int fsl_b_appendfv( fsl_b * const b, char const * fmt,
                         va_list args){
  buff__errcheck(b);
  else{
    int const rc = fsl_appendfv( fsl_output_f_b, b, fmt, args );
    return rc ? rc : b->errCode;
  }
}


int fsl_b_appendf( fsl_b * const b,
                        char const * fmt, ... ){
  int rc;
  va_list args;
  va_start(args,fmt);
  rc = fsl_b_appendfv( b, fmt, args );
  va_end(args);
  return rc;
}

char const * fsl_b_cstr(fsl_b const * const b){
  return b->errCode ? NULL : (char const *)b->mem;
}

char const * fsl_b_cstr2(fsl_b const * const b, fsl_size_t * const len){
  char const * rc = NULL;
  if(0==b->errCode){
    rc = (char const *)b->mem;
    if(len) *len = b->used;
  }
  return rc;
}

char * fsl_b_str(fsl_b const * const b){
  return b->errCode ? NULL : (char *)b->mem;
}


#if 0
fsl_size_t fsl_b_size(fsl_b const * const b){
  return b->used;
}

fsl_size_t fsl_b_capacity(fsl_b const * const b){
  return b->capacity;
}
#endif

/** Decode a 4-byte big-endian value from MEM.

   The cast on the first byte is load-bearing: MEM[0] promotes to int,
   so MEM[0]<<24 overflows for MEM[0]>=0x80, which is undefined per
   C11 6.5.7p4 rather than merely implementation-defined. Every
   compiler in practice wraps and then sign-extends into fsl_size_t,
   which happens to fail safe here (the huge result trips the
   FSL_BLOB_MAX_SIZE rule-out in fsl_data_is_compressed()) -- but that
   rule-out is a bound on attacker-supplied data and must not rest on
   de-facto lowering. The remaining operands cannot overflow: MEM[1]
   peaks at 0xff0000. */
#define decode__zsize(MEM) \
  ((fsl_size_t)MEM[0] << 24 | MEM[1] << 16 | MEM[2] << 8 | MEM[3])

/**
   Smallest possible fossil-encoded frame (4-byte size prefix + zlib
   stream) for a payload which decompresses to 0 bytes: 4 + 2-byte
   zlib header + 2-byte final empty block + 4-byte ADLER-32.
*/
#define FSL__EMPTY_ZFRAME_MIN ((fsl_size_t)12)

/**
   Expands to true if the last 4 bytes of MEM (of length LEN) are the
   ADLER-32 checksum of the empty string, which is 1. Every valid zlib
   stream of a 0-byte payload ends this way, regardless of compression
   level, strategy, or how many empty deflate blocks the encoder chose
   to emit: the checksum covers the decompressed output, so the
   encoder's choices cannot affect it.

   Streams which set FDICT are the one apparent exception, and are not
   one: they carry this same trailer but are excluded by the magic
   check in fsl_data_is_compressed(), and are in any case undecodable
   here, as uncompress() fails them with Z_NEED_DICT.

   Callers must ensure LEN>=4. See fsl_data_is_compressed().
*/
#define is__empty_adler(MEM,LEN)                            \
  (0==(MEM)[(LEN)-4] && 0==(MEM)[(LEN)-3]                   \
   && 0==(MEM)[(LEN)-2] && 1==(MEM)[(LEN)-1])

bool fsl_data_is_compressed(unsigned char const * const mem, fsl_size_t len){
  if(!mem || (len<6)) return 0;
  /**
     Adapted from:

     https://blog.2of1.org/2011/03/03/decompressing-zlib-images/

     Remember that fossil-compressed data has a 4-byte big-endian
     header holding the uncompressed size of the data.

     See also:

     https://tools.ietf.org/html/rfc6713

     search for "magic number".
  */
  fsl_size_t const sz = decode__zsize(mem);
  int16_t const head = (((int16_t)mem[4]) << 8) | mem[5];
  /* sz==0 is legitimate for the empty artifact, whose compressed frame
  ** is a 4-byte zero prefix followed by a valid zlib stream, so it
  ** cannot be a blanket disqualifier. It is, however, the single most
  ** likely leading pattern in *uncompressed* data, so require the
  ** ADLER-32 trailer of the empty string as corroboration. That is an
  ** invariant of the encoding rather than a guess about encoders: no
  ** valid empty payload can fail it at any length, so this can only
  ** reject data which is not the empty artifact. */
  if( sz >= FSL_BLOB_MAX_SIZE ){
    return false;
  }
  if( 0==sz
      && (len < FSL__EMPTY_ZFRAME_MIN || !is__empty_adler(mem, len)) ){
    return false;
  }
  switch(head){
    case 0x083c: case 0x087a: case 0x08b8: case 0x08f6:
    case 0x1838: case 0x1876: case 0x18b4: case 0x1872:
    case 0x2834: case 0x2872: case 0x28b0: case 0x28ee:
    case 0x3830: case 0x386e: case 0x38ac: case 0x38ea:
    case 0x482c: case 0x486a: case 0x48a8: case 0x48e6:
    case 0x5828: case 0x5866: case 0x58a4: case 0x58e2:
    case 0x6824: case 0x6862: case 0x68bf: case 0x68fd:
    case 0x7801: case 0x785e: case 0x789c: case 0x78da:
      return true;
    default:
      return false;
  }
}

bool fsl_b_is_compressed(fsl_b const *buf){
  return fsl_data_is_compressed( buf->mem, buf->used );
}

fsl_int_t fsl_data_uncompressed_size(unsigned char const *mem,
                                     fsl_size_t len){
  return fsl_data_is_compressed(mem,len)
    ? (int)decode__zsize(mem)
    : -1;
}

fsl_int_t fsl_b_uncompressed_size(fsl_b const * b){
  return fsl_data_uncompressed_size(b->mem, b->used);
}

/** Convert a zlib result code into an approximate
    fsl_rc_e equivalent. */
static inline int fsl__zerr_to_fsl(int rc){
  switch(rc){
    case 0:            return 0;
    case Z_DATA_ERROR: return FSL_RC_CONSISTENCY;
    case Z_MEM_ERROR:  return FSL_RC_OOM;
    case Z_BUF_ERROR:  return FSL_RC_RANGE;
    //case Z_STREAM_END:  return FSL_RC_RANGE;
    default:           return FSL_RC_ERROR;
  }
}

/**
   If true, do fsl_b_resize() on the results of (un)compression
   like fossil(1) does, else don't. Testing with (f-parseparty -c) and
   valgrind (which triggers lots of decompression but not compression)
   on this code's repo suggests that ...

   ... still waiting...

   That the number of real allocations is identical but the amount
   of total memory is _slightly_ higher with this set to false:

   0: 2,692,618 allocs, 2,692,618 frees, 1,465,843,276 bytes allocated

   1: 2,692,618 allocs, 2,692,618 frees, 1,465,674,951 bytes allocated

   That's probably unsurprising, as these buffers are invariably
   pre-sized larger than they need to be.
*/
#define FSL__RESIZE_COMPRESSED_BUFFERS 1

int fsl_b_compress(fsl_b const *pIn, fsl_b * const pOut){
  buff__errcheck(pIn);
  uint64_t nIn = pIn->used;
  if( nIn >= FSL_BLOB_MAX_SIZE ){
    /* fsl_data_is_compressed() rejects a larger size prefix. */
    return FSL_RC_RANGE;
  }
  uint64_t nOut = 13 + nIn + (nIn+999)/1000;
  fsl_b temp = fsl_b_empty;
  int rc = 0;
  bool const reusedPOut =
    pOut!=pIn && pOut->capacity>nOut+4;
  if( reusedPOut ){
    fsl_b_swap(pOut, &temp);
  }else{
    rc = fsl_b_resize(&temp, nOut+4);
  }
  if(0==rc){
    unsigned long int nOut2;
    unsigned char *outBuf;
    outBuf = temp.mem;
    outBuf[0] = nIn>>24 & 0xff;
    outBuf[1] = nIn>>16 & 0xff;
    outBuf[2] = nIn>>8 & 0xff;
    outBuf[3] = nIn & 0xff;
    nOut2 = (long int)nOut;
    rc = fsl__zerr_to_fsl(
      compress(&outBuf[4], &nOut2, pIn->mem, pIn->used)
    );
    if(0==rc){
      fsl_size_t const outSize = nOut2+4;
#if FSL__RESIZE_COMPRESSED_BUFFERS
      rc = fsl_b_resize(&temp, outSize);
#else
      temp.used = outSize;
      assert( outSize < temp.capacity );
#endif
    }
    if(0==rc || reusedPOut){
      fsl_b_swap(&temp, pOut);
    }
  }
  fsl_b_clear(&temp);
  return rc;
}

int fsl_b_compress2(fsl_b const *pIn1,
                         fsl_b const *pIn2, fsl_b * const pOut){
  buff__errcheck(pIn1);
  else buff__errcheck(pIn2);
  else buff__errcheck(pOut);
  uint64_t nIn = pIn1->used + pIn2->used;
  if( nIn >= FSL_BLOB_MAX_SIZE ){
    /* fsl_data_is_compressed() rejects a larger size prefix. */
    return FSL_RC_RANGE;
  }
  uint64_t nOut = 13 + nIn + (nIn+999)/1000;
  fsl_b temp = fsl_b_empty;
  bool const outSelf = (pOut==pIn1 || pOut==pIn2);
  int rc = 0;
  if( !outSelf && pOut->capacity>=nOut+4 ){
    fsl_b_swap(fsl_b_reuse(pOut), &temp);
  }else{
    rc = fsl_b_resize(&temp, nOut+4);
  }
  if(0==rc){
    unsigned char *outBuf;
    z_stream stream;
    outBuf = temp.mem;
    outBuf[0] = nIn>>24 & 0xff;
    outBuf[1] = nIn>>16 & 0xff;
    outBuf[2] = nIn>>8 & 0xff;
    outBuf[3] = nIn & 0xff;
    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
    stream.opaque = 0;
    stream.avail_out = nOut;
    stream.next_out = &outBuf[4];
    rc = fsl__zerr_to_fsl(deflateInit(&stream, 9));
    if( rc ) goto end;
    stream.avail_in = pIn1->used;
    stream.next_in = pIn1->mem;
    deflate(&stream, 0);
    stream.avail_in = pIn2->used;
    stream.next_in = pIn2->mem;
    deflate(&stream, 0);
    rc = deflate(&stream, Z_FINISH);
    if( Z_STREAM_END==rc ){
      rc = 0;
    }else if( 0==rc ){
      rc = FSL_RC_RANGE/*output too short*/;
    }else{
      rc = fsl__zerr_to_fsl(rc);
    }
    assert(temp.capacity >= stream.total_out+4);
#if FSL__RESIZE_COMPRESSED_BUFFERS
    if( 0==rc ){
      rc = fsl_b_resize(&temp, stream.total_out + 4);
    }
#endif
    {
      int const rcEnd = fsl__zerr_to_fsl(deflateEnd(&stream));
      if( 0==rc ) rc = rcEnd;
    }
    if( 0==rc ){
      temp.used = stream.total_out + 4;
      if( outSelf ){
        fsl_b_reuse(pOut);
        rc = fsl_b_append(pOut, temp.mem, temp.used);
      }else{
        fsl_b_swap(&temp, pOut);
      }
    }
  }
end:
  fsl_b_clear(&temp);
  return rc;
}
#undef FSL__RESIZE_COMPRESSED_BUFFERS

int fsl_b_uncompress(fsl_b const * const pIn, fsl_b * const pOut){
  buff__errcheck(pIn);
  else buff__errcheck(pOut);
  uint64_t nOut;
  unsigned char const *inBuf;
  uint64_t const nIn = pIn->used;
  fsl_b temp = fsl_b_empty;
  int rc = 0;
  unsigned long int nOut2;
  if(nIn<=4 || !fsl_data_is_compressed(pIn->mem, pIn->used)){
    if( pIn!=pOut ){
      rc = pIn->used
        ? fsl_b_append(fsl_b_reuse(pOut), pIn->mem, pIn->used)
        : 0;
    }
    goto end;
  }
  inBuf = pIn->mem;
  nOut = decode__zsize(inBuf);
  /* MARKER(("decompress size: %u\n", nOut)); */
  if(pIn!=pOut && pOut->capacity>nOut/*> b/c of NUL terminator*/){
    assert(pIn->mem != pOut->mem);
    fsl_b_swap(&temp, pOut);
    //MARKER(("Reusing target buffer for decompression.\n"));
  }else{
    rc = fsl_b_reserve(&temp, nOut+1);
    if(rc) goto end;
    temp.mem[nOut] = 0;
  }

  nOut2 = (long int)nOut;
  rc = uncompress(temp.mem, &nOut2, &inBuf[4], nIn - 4)
    /* In some libz versions (<1.2.4, apparently), valgrind says
       there's an uninitialized memory access somewhere under
       uncompress(), _presumably_ for one of these arguments, but i
       can't find it. fsl_b_reserve() always memsets() new bytes
       to 0.

       Turns out it's a known problem:

       https://www.zlib.net/zlib_faq.html#faq36
    */;
  /* Z_BUF_ERROR: the stream decodes to more bytes than the size
     prefix records, so the data are corrupt, as for Z_DATA_ERROR. */
  rc = Z_BUF_ERROR==rc ? FSL_RC_CONSISTENCY : fsl__zerr_to_fsl(rc);
  if( 0==rc ){
      /* this is always true but having this assert
         here makes me nervous: assert(nOut2 == nOut); */
      assert(nOut2<=nOut);
      temp.mem[nOut2] = 0;
      temp.used = (fsl_size_t)nOut2;
      fsl_b_swap(&temp, pOut);
  }
end:
  fsl_b_clear(&temp);
  return pOut->errCode = rc;
}

#undef decode__zsize
#undef FSL__EMPTY_ZFRAME_MIN
#undef is__empty_adler

int fsl_b_fill_from( fsl_b * const dest, fsl_input_f src,
                          void * const state ){
  buff__errcheck(dest);
  int rc;
  enum { BufSize = 512 * 8 };
  char rbuf[BufSize];
  fsl_size_t total = 0;
  fsl_size_t rlen = 0;
  fsl_b_reuse(dest);
  while(1){
    rlen = BufSize;
    rc = src( state, rbuf, &rlen );
    if( rc ) break;
    total += rlen;
    if(total<rlen){
      /* Overflow! */
      rc = FSL_RC_RANGE;
      break;
    }
    if( dest->capacity < (total+1) ){
      rc = fsl_b_reserve( dest,
                               total + ((rlen<BufSize) ? 1 : BufSize)
                               );
      if( 0 != rc ) break;
    }
    memcpy( dest->mem + dest->used, rbuf, rlen );
    dest->used += rlen;
    if( rlen < BufSize ) break;
  }
  if( !rc && dest->used ){
    assert( dest->used < dest->capacity );
    dest->mem[dest->used] = 0;
  }
  return rc;
}

int fsl_b_fill_from_FILE( fsl_b * const dest,
                               FILE * const src ){
  return fsl_b_fill_from( dest, fsl_input_f_FILE, src );
}


int fsl_b_fill_from_filename( fsl_b * const dest,
                                   char const * filename ){
  buff__errcheck(dest);
  int rc;
  FILE * src;
  fsl_fstat st = fsl_fstat_empty;
  /* This stat() is only an optimization to reserve all needed
     memory up front.
  */
  rc = fsl_stat( filename, &st, 1 );
  if(!rc && st.size>0){
    rc = fsl_b_reserve(dest, st.size +1/*NUL terminator*/);
    if(rc) return rc;
  } /* Else it might not be a real file, e.g. "-", so we'll try anyway... */
  src = fsl_fopen(filename,"rb");
  if(!src) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
  else {
    rc = fsl_b_fill_from( dest, fsl_input_f_FILE, src );
    fsl_fclose(src);
  }
  return rc;
}

void fsl_b_swap( fsl_b * const left, fsl_b * const right ){
  fsl_b const tmp = *left;
  *left = *right;
  *right = tmp;
}

void fsl_b_swap_free( fsl_b * const left, fsl_b * const right, int clearWhich ){
  fsl_b_swap(left, right);
  if(0 != clearWhich) fsl_b_reserve((clearWhich<0) ? left : right, 0);
}

int fsl_b_copy( fsl_b * const dest,
                     fsl_b const * const src ){
  fsl_b_reuse(dest);
  return src->used
    ? fsl_b_append( dest, src->mem, src->used )
    : 0;
}

int fsl_b_delta_apply2( fsl_b const * const orig,
                             fsl_b const * const pDelta,
                             fsl_b * const pTarget,
                             fsl_error * const pErr){
  buff__errcheck(orig);
  else buff__errcheck(pDelta);
  else buff__errcheck(pTarget);
  int rc;
  fsl_size_t n = 0;
  fsl_b out = fsl_b_empty;
  rc = fsl_delta_applied_size( pDelta->mem, pDelta->used, &n);
  if(rc){
    if(pErr){
      fsl_error_set(pErr, rc, "cannot read the output size of a "
                    "%" FSL_SIZE_T_PFMT "-byte delta: %R",
                    pDelta->used, rc);
    }
    return rc;
  }
  rc = fsl_b_resize( &out, n );
  if(0==rc){
    /* An empty buffer may have no memory, which fsl_delta_apply2()
       would reject as FSL_RC_MISUSE. */
    unsigned char const * const zEmpty = (unsigned char const *)"";
    rc = fsl_delta_apply2( orig->mem ? orig->mem : zEmpty, orig->used,
                          pDelta->mem, pDelta->used,
                          out.mem, pErr);
    if(0==rc) fsl_b_swap(&out, pTarget);
  }
  fsl_b_clear(&out);
  return rc;
}

int fsl_b_delta_apply( fsl_b const * const orig,
                            fsl_b const * const pDelta,
                            fsl_b * const pTarget){
  return fsl_b_delta_apply2(orig, pDelta, pTarget, NULL);
}

void fsl_b_defossilize( fsl_b * const b ){
  if( 0==buf__materialize(b,0) ){
    fsl_bytes_defossilize( b->mem, &b->used );
  }
}

int fsl_b_to_filename( fsl_b const * const b, char const * fname ){
  FILE * f;
  int rc = 0;
  if(!b || !fname) return FSL_RC_MISUSE;
  buff__errcheck(b);
  f = fsl_fopen(fname, "wb");
  if(!f) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
  else{
    if(b->used) {
      size_t const frc = fwrite(b->mem, b->used, 1, f);
      if(1!=frc) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
    }
    /* fwrite() may buffer the whole write, so a failure such as
       ENOSPC can first appear here. */
    if(0==rc && fflush(f)) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
    /* fsl_fopen() returns stdout for "-", which stays open, else a
       fopen()ed handle. Some file systems (e.g. NFS) report a write
       failure only at close, and fsl_fclose() discards that. */
    if(stdout!=f && fclose(f) && 0==rc){
      rc = fsl_errno_to_rc(errno, FSL_RC_IO);
    }
  }
  return rc;
}

int fsl_b_delta_create( fsl_b const * const src,
                             fsl_b const * const newVers,
                             fsl_b * const delta){
  if((src == newVers)
     || (src==delta)
     || (newVers==delta)) return FSL_RC_MISUSE;
  int rc = fsl_b_reserve( delta, newVers->used + 60 );
  if(!rc){
    delta->used = 0;
    /* An empty buffer may have no memory, which fsl_delta_create()
       would reject as FSL_RC_MISUSE. */
    unsigned char const * const zEmpty = (unsigned char const *)"";
    rc = fsl_delta_create( src->mem ? src->mem : zEmpty, src->used,
                           newVers->mem ? newVers->mem : zEmpty,
                           newVers->used,
                           delta->mem, &delta->used );
  }
  return rc;
}


int fsl_output_f_b( void * state, void const * src, fsl_size_t n ){
  return fsl_b_append((fsl_b*)state, src, n);
}

int fsl_finalizer_f_buffer( void * state fsl__unused, void * mem ){
  fsl_b * const b = (fsl_b*)mem;
  (void)state;
  fsl_b_reserve(b, 0);
  *b = fsl_b_empty;
  return 0;
}

int fsl_b_strftime(fsl_b * const b, char const * format,
                        const struct tm *timeptr){
  if(!b || !format || !*format || !timeptr) return FSL_RC_MISUSE;
  else{
    enum {BufSize = 128};
    char buf[BufSize];
    fsl_size_t const len = fsl_strftime(buf, BufSize, format, timeptr);
    return len ? fsl_b_append(b, buf, (fsl_int_t)len) : FSL_RC_RANGE;
  }
}

int fsl_b_stream_lines(fsl_output_f fTo, void * const toState,
                            fsl_b * const pFrom, fsl_size_t N){
  buff__errcheck(pFrom);
  char *z = (char *)pFrom->mem;
  fsl_size_t i = pFrom->cursor;
  fsl_size_t n = pFrom->used;
  fsl_size_t cnt = 0;
  int rc = 0;
  if( N==0 ) return 0;
  while( i<n ){
    if( z[i]=='\n' ){
      cnt++;
      if( cnt==N ){
        i++;
        break;
      }
    }
    i++;
  }
  if( fTo ){
    rc = fTo(toState, &pFrom->mem[pFrom->cursor], i - pFrom->cursor);
  }
  if(!rc){
    pFrom->cursor = i;
  }
  return rc;
}


int fsl_b_copy_lines(fsl_b * const pTo,
                          fsl_b * const pFrom,
                          fsl_size_t N){
#if 1
  if(pTo) buff__errcheck(pTo);
  return fsl_b_stream_lines( pTo ? fsl_output_f_b : NULL, pTo,
                                  pFrom, N );
#else
  char *z = (char *)pFrom->mem;
  fsl_size_t i = pFrom->cursor;
  fsl_size_t n = pFrom->used;
  fsl_size_t cnt = 0;
  int rc = 0;
  if( N==0 ) return 0;
  while( i<n ){
    if( z[i]=='\n' ){
      ++cnt;
      if( cnt==N ){
        ++i;
        break;
      }
    }
    ++i;
  }
  if( pTo ){
    rc = fsl_b_append(pTo, &pFrom->mem[pFrom->cursor], i - pFrom->cursor);
  }
  if(!rc){
    pFrom->cursor = i;
  }
  return rc;
#endif
}

int fsl_input_f_buffer( void * state, void * dest, fsl_size_t * n ){
  fsl_b * const b = (fsl_b*)state;
  buff__errcheck(b);
  fsl_size_t const from = b->cursor;
  fsl_size_t to;
  fsl_size_t c;
  if(from >= b->used){
    *n = 0;
    return 0;
  }
  to = from + *n;
  if(to>b->used) to = b->used;
  c = to - from;
  if(c){
    memcpy(dest, b->mem+from, c);
    b->cursor += c;
  }
  *n = c;
  return 0;
}

int fsl_b_compare_file( fsl_b const * b, char const * zFile ){
  int rc;
  fsl_fstat fst = fsl_fstat_empty;
  rc = fsl_stat(zFile, &fst, 1);
  if(rc || (FSL_FSTAT_TYPE_FILE != fst.type)) return -1;
  else if(b->used < fst.size) return -1;
  else if(b->used > fst.size) return 1;
  else{
#if 1
    FILE * f;
    f = fsl_fopen(zFile,"r");
    if(!f) rc = -1;
    else{
      fsl_b fc = *b /* so fsl_input_f_buffer() can manipulate its
                            cursor */;
      rc = fsl_stream_compare(fsl_input_f_buffer, &fc,
                              fsl_input_f_FILE, f);
      assert(fc.mem==b->mem);
      fsl_fclose(f);
    }

#else
    fsl_b fc = fsl_b_empty;
    rc = fsl_b_fill_from_filename(&fc, zFile);
    if(rc){
      rc = -1;
    }else{
      rc = fsl_b_compare(b, &fc);
    }
    fsl_b_clear(&fc);
#endif
    return rc;
  }
}

char * fsl_b_take(fsl_b * const b){
  char * z = NULL;
  if(0==buf__materialize(b,0)){
    z = (char *)b->mem;
    *b = fsl_b_empty;
  }
  return z;
}

fsl_size_t fsl_b_seek(fsl_b * const b, fsl_int_t offset,
                           fsl_b_seek_e  whence){
  int64_t c = (int64_t)b->cursor;
  switch(whence){
    case FSL_B_SEEK_SET: c = offset; break;
    case FSL_B_SEEK_CUR: c = (int64_t)b->cursor + offset; break;
    case FSL_B_SEEK_END:
      c = (int64_t)b->used + offset;
      /* ^^^^^ fossil(1) uses (used + offset - 1) but

         That seems somewhat arguable because (used + 0 - 1) is at the
         last-written byte (or 1 before the begining), not the
         one-past-the-end point (which corresponds to the
         "end-of-file" described by the fseek() man page). It then
         goes on, in other algos, to operate on that final byte using
         that position, e.g.  blob_read() after a seek-to-end would
         read that last byte, rather than treating the buffer as being
         at the end.

         So... i'm going to naively remove that -1 bit.

         About 12 years later (2025-08-21): that distinction has never
         been significant in practice, probably because SEEK_END
         support is "for completeness" but not actually used. Funnily
         enough, fossil(1) removed SEEK_END support from that class on
         2021-03-1: https://fossil-scm.org/home/info/6fc730e0c76d4bd2
      */
      break;
  }
  if(!b->used || c<0) b->cursor = 0;
  else if((fsl_size_t)c > b->used) b->cursor = b->used;
  else b->cursor = (fsl_size_t)c;
  return b->cursor;
}

fsl_size_t fsl_b_tell(fsl_b const * const b){
  return b->cursor;
}

void fsl_b_rewind(fsl_b * const b){
  b->cursor = 0;
}

/*
   Like getdelim(3) but for fsl_b structures.
   https://pubs.opengroup.org/onlinepubs/9799919799/functions/getdelim.html
 */
fsl_int_t fsl_b_getdelim(char **ret, size_t *retsz,
                              int delim, fsl_b *buf){
  char *p;
  unsigned char *sep;
  size_t psz, len = 0;
  static const uint8_t allocsz = 128;

  if(ret == NULL || retsz == NULL){
    buf->errCode = FSL_RC_MISUSE;
    return -1;
  }
  if(buf->errCode != 0 || buf->used == 0 || buf->cursor >= buf->used){
    return -1;  /* error or end-of-buffer */
  }
  if(*ret == NULL) *retsz = 0;

  sep = memchr(&buf->mem[buf->cursor], delim, buf->used - buf->cursor);
  if(sep == NULL) len = buf->used - buf->cursor;
  else len = (sep - &buf->mem[buf->cursor]) + 1;

  if(len > LONG_MAX){
    buf->errCode = FSL_RC_RANGE;
    return -1;
  }

  psz = len + 1;  /* NUL terminator */
  if(psz > *retsz){
    if(psz < allocsz){
      /* smallest power of 2 greater than common source code line length */
      psz = allocsz;
    }
    p = fsl_realloc(*ret, psz);
    if(p == NULL){
      buf->errCode = FSL_RC_OOM;
      return -1;
    }
    memset(&p[*retsz], 0, psz - *retsz);
    *ret = p;
    *retsz = psz;
  }

  if(*ret != NULL){
    memcpy(*ret, &buf->mem[buf->cursor], len);
    *(*ret + len) = '\0';
  }
  buf->cursor += len;
  return len;
}

/*
   Like getline(3) but for fsl_b structures.
   https://pubs.opengroup.org/onlinepubs/9799919799/functions/getline.html
 */
fsl_int_t fsl_b_getline(char **ret, size_t *retsz, fsl_b *buf){
  return fsl_b_getdelim(ret, retsz, '\n', buf);
}

int fsl_id_bag_to_buffer(fsl_id_bag const * bag, fsl_b * const b,
                         char const * separator){
  int i = 0;
  fsl_int_t const sepLen = (fsl_int_t)fsl_strlen(separator);
  fsl_b_reserve(b, b->used + (bag->entryCount * 7)
                     + (bag->entryCount * sepLen));
  for(fsl_id_t e = fsl_id_bag_first(bag);
      !b->errCode && e; e = fsl_id_bag_next(bag, e)){
    if(i++) fsl_b_append(b, separator, sepLen);
    fsl_b_appendf(b, "%" FSL_ID_T_PFMT, e);
  }
  return b->errCode;
}

int fsl_b_append_hex( fsl_b * const b, void const * m,
                           fsl_uint_t n, bool upperCase ){
  const char * zdigits = upperCase ? "0123456789ABCDEF" : "0123456789abcdef";
  unsigned char const * z = m;
  fsl_b_reserve(b, b->used + n*2+1);
  for(fsl_uint_t i = 0; i < n && !b->errCode; ++i, ++z){
    fsl_b_appendch(b, zdigits[*z >> 4]);
    fsl_b_appendch(b, zdigits[*z & 0x0f]);
  }
  return b->errCode;
}

int fsl_b_append_tcl_literal(fsl_b * const b,
                                  bool escapeSquigglies,
                                  char const * z, fsl_int_t n){
  int rc;
  if(n<0) n = fsl_strlen(z);
  fsl_b_reserve(b, b->used + (fsl_size_t)n + 3);
  fsl_b_appendch(b, '"');
  for(fsl_int_t i=0; 0==b->errCode && i<n; ++i){
    char c = z[i];
    bool skipSlash = false;
    switch( c ){
      case '\r':  c = 'r'; goto slash;
      case '}': case '{': skipSlash = !escapeSquigglies;
        FSL_SWITCH_FALL_THROUGH;
      case '[':
      case ']':
      case '$':
      case '"':
      case '\\':
      slash:
        if(!skipSlash && (rc = fsl_b_appendch(b, '\\'))) break;
        FSL_SWITCH_FALL_THROUGH;
      default:
        fsl_b_appendch(b, c);
    }
  }
  fsl_b_appendch(b, '"');
  return b->errCode;
}

int fsl_b_appendch(fsl_b * const b, char c){
  buff__errcheck(b);
  else if( buf__materialize(b, 2) ){
    return b->errCode;
  }else if( b->used+1 < b->capacity ){
    assert( !b->errCode );
    b->mem[b->used++] = c;
    b->mem[b->used] = 0;
    return 0;
  }else{
    return fsl_b_append(b, &c, 1);
  }
}

int fsl_b_ensure_eol(fsl_b * const b){
  if(!b->errCode && b->used
     && b->mem[b->used-1] != '\n'){
    fsl_b_reserve(b, b->used+2)/*may materialize b*/;
    fsl_b_appendch(b, '\n');
  }
  return b->errCode;
}

void fsl_b_chomp(fsl_b * const b){
  if(!b->errCode && b->used && b->mem[b->used-1]=='\n'){
    --b->used;
    if( b->used && b->mem[b->used-1]=='\r' ){
      --b->used;
    }
    if( !buf__is_external(b) ){
      b->mem[b->used] = 0;
    }
  }
}

/*
  The following escaping code to support fsl_b_esc_arg_v2()
  was taken verbatim from fossil(1) blob.c on 2025-06-11.
*/
/*
** ASCII (for reference):
**    x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf
** 0x ^`  ^a  ^b  ^c  ^d  ^e  ^f  ^g  \b  \t  \n  ()  \f  \r  ^n  ^o
** 1x ^p  ^q  ^r  ^s  ^t  ^u  ^v  ^w  ^x  ^y  ^z  ^{  ^|  ^}  ^~  ^
** 2x ()  !   "   #   $   %   &   '   (   )   *   +   ,   -   .   /
** 3x 0   1   2   3   4   5   6   7   8   9   :   ;   <   =   >   ?
** 4x @   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O
** 5x P   Q   R   S   T   U   V   W   X   Y   Z   [   \   ]   ^   _
** 6x `   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o
** 7x p   q   r   s   t   u   v   w   x   y   z   {   |   }   ~   ^_
*/

/*
** Meanings for bytes in a filename:
**
**    0      Ordinary character.  No encoding required
**    1      Needs to be escaped
**    2      Illegal character.  Do not allow in a filename
**    3      First byte of a 2-byte UTF-8
**    4      First byte of a 3-byte UTF-8
**    5      First byte of a 4-byte UTF-8
*/
static const char aSafeChar[256] = {
#ifdef _WIN32
/* Windows
** Prohibit:  all control characters, including tab, \r and \n.
** Escape:    (space) " # $ % & ' ( ) * ; < > ? [ ] ^ ` { | }
*/
/*  x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf  */
     2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2, /* 0x */
     2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2, /* 1x */
     1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0, /* 2x */
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  0,  1,  1, /* 3x */
     1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, /* 4x */
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  1,  0, /* 5x */
     1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, /* 6x */
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  0,  1, /* 7x */
#else
/* Unix
** Prohibit:  all control characters, including tab, \r and \n
** Escape:    (space) ! " # $ % & ' ( ) * ; < > ? [ \ ] ^ ` { | }
*/
/*  x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf  */
     2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2, /* 0x */
     2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2, /* 1x */
     1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0, /* 2x */
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  0,  1,  1, /* 3x */
     1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, /* 4x */
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0, /* 5x */
     1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, /* 6x */
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  0,  1, /* 7x */
#endif
    /* all bytes 0x80 through 0xbf are unescaped, being secondary
    ** bytes to UTF8 characters.  Bytes 0xc0 through 0xff are the
    ** first byte of a UTF8 character and do get escaped */
     2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2, /* 8x */
     2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2, /* 9x */
     2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2, /* ax */
     2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2, /* bx */
     3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3, /* cx */
     3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3, /* dx */
     4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4, /* ex */
     5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5  /* fx */
};


int fsl_b_esc_arg(fsl_b * const b, char const *zIn,
                      bool isFilename){
  return fsl_b_esc_arg_v2(b, NULL, zIn, isFilename);
}

int fsl_b_esc_arg_v2(fsl_b * const b,
                          fsl_error * const err,
                          char const *zIn,
                          bool isFilename){
  /* What follows was ported directly from fossil(1)'s
     blob.c:blob_append_escaped_arg(), modified only stylistically,
     not functionally. */
  int i;
  unsigned char c;
  bool needEsc = false;
  fsl_size_t nB;
  char const * zB;

  buff__errcheck(b);
  else if( buf__materialize(b, fsl_strlen(zIn) + 3 ) ){
    return b->errCode;
  }
  if( err ) fsl_error_reset(err);
  zB = fsl_b_cstr2(b, &nB);

  /* Look for illegal byte-sequences and byte-sequences that require
  ** escaping.  No control-characters are allowed.  All spaces and
  ** non-ASCII unicode characters and some punctuation characters require
  ** escaping. */
  for(i=0; (c = (unsigned char)zIn[i])!=0; i++){
    unsigned char const x = aSafeChar[c];
    if( x ){
      needEsc = true;
      if( 2==x ){
        if( err ){
          fsl_error_set(err, FSL_RC_SYNTAX,
                        "Input contains a character (ASCII 0x%02x) "
                        "that is not permitted by %s()",
                        c, __func__);
        }
        return b->errCode = FSL_RC_SYNTAX;
      }else if( x>2 ){
        if( (zIn[i+1] & 0xc0)!=0x80
            || (x>=4 && (zIn[i+2] & 0xc0)!=0x80)
            || (x>=5 && (zIn[i+3] & 0xc0)!=0x80) ){
          if( err ){
            fsl_error_set(err, FSL_RC_SYNTAX,
                          "The input contains an illegal UTF-8 "
                          "character");
          }
          return b->errCode = FSL_RC_SYNTAX;
        }
        i += x-2;
      }
      /* else it's handled below */
    }
  }

  /* Separate it from the previous argument with a space */
  if( nB>0 && !fsl_isspace(zB[nB-1]) ){
    fsl_b_appendch(b, ' ');
  }

  /* Check for characters that need quoting */
  if( !needEsc ){
    if( isFilename && zIn[0]=='-' ){
      fsl_b_appendch(b, '.');
#if defined(_WIN32)
      fsl_b_appendch(b, '\\');
#else
      fsl_b_appendch(b, '/');
#endif
    }
    fsl_b_append(b, zIn, -1);
  }else{
#if defined(_WIN32)
    /* Quoting strategy for windows:
    ** Put the entire name inside of "...".  Any " characters within
    ** the name get doubled. If input looks like a command flag,
    ** prefix it with ".\" so that it does not get mistaken for
    ** one. */
    fsl_b_appendch(b, '"');
    if( isFilename && zIn[0]=='-' ){
      fsl_b_appendch(b, '.');
      fsl_b_appendch(b, '\\');
    }else if( zIn[0]=='/' ){
      fsl_b_appendch(b, '.');
    }
    for(i=0; 0==b->errCode
          && (c = (unsigned char)zIn[i])!=0; i++){
      fsl_b_appendch(b, (char)c);
      if( c=='"' ) fsl_b_appendch(b, '"');
      if( c=='\\' ) fsl_b_appendch(b, '\\');
      if( c=='%' && isFilename ) fsl_b_append(b, "%cd:~,%", 7);
    }
    fsl_b_appendch(b, '"');
#else
    /* Quoting strategy for unix:
    ** If the name does not contain ', then surround the whole thing
    ** with '...'.  If there is one or more ' characters within the
    ** name, then put \ before each special character. If input looks
    ** like a command flag, prefix it with "./" so that it does not
    ** get mistaken for one.
    */
    if( strchr(zIn,'\'') ){
      if( isFilename && zIn[0]=='-' ){
        fsl_b_appendch(b, '.');
        fsl_b_appendch(b, '/');
      }
      for(i=0; 0==b->errCode
            && (c = (unsigned char)zIn[i])!=0; i++){
        if( aSafeChar[c] && aSafeChar[c]!=2 ) fsl_b_appendch(b, '\\');
        fsl_b_appendch(b, (char)c);
      }
    }else{
      fsl_b_appendch(b, '\'');
      if( isFilename && zIn[0]=='-' ){
        fsl_b_appendch(b, '.');
        fsl_b_appendch(b, '/');
      }
      fsl_b_append(b, zIn, -1);
      fsl_b_appendch(b, '\'');
    }
#endif
  }
  if( err && !b->errCode ) b->errCode = err->code;
  return b->errCode;
}

void fsl_b_strip_hash_comments(fsl_b * const b){
  if( !b->used || buf__is_external(b) ) return;
  assert(b->mem);
  unsigned char * zo = b->mem;
  unsigned char const * zi = zo;
  unsigned char const * const zEnd = zi+b->used;
  unsigned char const * zEsc = 0;
  bool bol = true;

  while( zi < zEnd ){
    switch( *zi ){
      case '\\':
        if( zEsc ){
          //*zo++ = *zEsc;
          *zo++ = *zi++;
          zEsc = 0;
        }else{
          zEsc = zi++;
        }
        bol = false;
        break;
      case '#':
        if( zEsc ){
          *zo++ = '#';
          ++zi;
          zEsc = 0;
          assert( !bol );
        }else if(bol){
          while( zi<zEnd && *++zi != '\n' );
          if( zi<zEnd ){
            assert('\n'==*zi);
            //*zo++ = *zi++;
            ++zi;
            bol = true;
          }
          continue;
        }else{
          assert( !zEsc );
          *zo++ = *zi++;
        }
        break;
      case '\n':
        if( zEsc ){
          /* This is superfluous - these do not appear in globs, nor
             should they. */
          ++zi;
          *zo++ = '\\';
          *zo++ = 'n';
          zEsc = 0;
          bol = false;
        }else{
          ++zi;
          *zo++ = '\n';
          bol = true;
        }
        break;
      default:
        /* The current unescaping behavior is to put all backslashes
           back where we got them except for \#. That's a matter of
           development expedience, not necessarily conformance (which,
           as of this writing, has not been looked at closely). */
        if( zEsc ){
          *zo++ = *zEsc;
          *zo++ = *zi++;
          zEsc = 0;
          continue;
        }else{
          *zo++ = *zi++;
          bol = false;
          continue;
        }
        break;
    }
  }
  if( zo<zEnd ){
    assert( zo<zEnd );
    if( zEsc ){
      /* Trailing final backslash. */
      *zo++ = *zEsc;
    }
    assert( b->capacity >= (fsl_size_t)(zo - b->mem) );
    b->used = (fsl_size_t)(zo - b->mem);
    if( zo<zEnd ){
      *zo = 0;
    }
#if !defined(NDEBUG)
    else{
      assert( zo==b->mem+b->used );
      assert( 0==*zo &&
              "API gurantees to keep cmpp_buffer nul-terminated" );
    }
#endif
  }
}

#undef MARKER
#undef buf__is_external
#undef buf__errcheck
#undef buf__materialize
/* end of file src/buffer.c */
/* start of file src/cache.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*****************************************************************************
  This file some of the caching-related APIs.
*/
#include <assert.h>
#include <string.h> /* memmove() */

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

bool fsl__bccache_expire_oldest(fsl__bccache * const c){
  static uint16_t const sentinel = 0xFFFF;
  uint16_t i;
  fsl_uint_t mnAge = c->nextAge;
  uint16_t mn = sentinel;
  for(i=0; i<c->used; i++){
    if( c->list[i].age<mnAge ){
      mnAge = c->list[i].age;
      mn = i;
    }
  }
  if( mn<sentinel ){
    fsl_id_bag_remove(&c->inCache, c->list[mn].rid);
    c->szTotal -= (unsigned)c->list[mn].content.capacity;
    fsl_b_clear(&c->list[mn].content);
    --c->used;
    c->list[mn] = c->list[c->used];
  }
  return sentinel!=mn;
}

int fsl__bccache_insert(fsl__bccache * const c, fsl_id_t rid, fsl_b * const pBlob){
  fsl__bccache_line *p;
  if( c->used>c->usedLimit || c->szTotal>c->szLimit ){
    fsl_size_t szBefore;
    do{
      szBefore = c->szTotal;
      fsl__bccache_expire_oldest(c);
    }while( c->szTotal>c->szLimit && c->szTotal<szBefore );
  }
  if((!c->usedLimit || !c->szLimit)
     || (c->used+1 >= c->usedLimit)){
    fsl_b_clear(pBlob);
    return 0;
  }
  if( c->used>=c->capacity ){
    uint16_t const cap = c->capacity ? (c->capacity*2) : 10;
    if(c->capacity && cap<c->capacity){
      /* Numeric overflow. Bump fsl__bccache::capacity to a larger
         int type if this is ever hit. */
      fsl_b_clear(pBlob);
      return FSL_RC_RANGE;
    }
    void * const remem = c->list
      ? fsl_realloc(c->list, cap*sizeof(c->list[0]))
      : fsl_malloc( cap*sizeof(c->list[0]) );
    if(!remem){
      fsl_b_clear(pBlob) /* for consistency */;
      return FSL_RC_OOM;
    }
    c->capacity = cap;
    c->list = (fsl__bccache_line*)remem;
  }
  int const rc = fsl_id_bag_insert(&c->inCache, rid);
  if(0==rc){
    p = &c->list[c->used++];
    p->rid = rid;
    p->age = c->nextAge++;
    c->szTotal += pBlob->capacity;
    ++c->changeMarker;
    p->content = *pBlob /* Transfer ownership */;
    *pBlob = fsl_b_empty;
  }else{
    fsl_b_clear(pBlob);
  }
  return rc;
}

bool fsl__bccache_remove(fsl__bccache * const c, fsl_id_t rid){
  uint16_t i;
  if( !fsl_id_bag_contains(&c->inCache, rid) ) return false;
  fsl_id_bag_remove(&c->inCache, rid);
  for( i = 0; i < c->used; ++i ){
    if( rid == c->list[i].rid ){
      c->szTotal -= (unsigned)c->list[i].content.capacity;
      fsl_b_clear(&c->list[i].content);
      --c->used;
      c->list[i] = c->list[c->used];
      return true;
    }
  }
  return false;
}

void fsl__bccache_clear(fsl__bccache * const c){
  static const fsl__bccache fsl__bccache_empty = fsl__bccache_empty_m;
#if 0
  while(fsl__bccache_expire_oldest(c)){}
#else
  for(fsl_size_t i=0; i<c->used; ++i){
    fsl_b_clear(&c->list[i].content);
  }
#endif
  fsl_free(c->list);
  fsl_id_bag_clear(&c->inCache);
  *c = fsl__bccache_empty;
}

void fsl__bccache_reuse(fsl__bccache * const c){
  static const fsl__bccache_line line_empty = fsl__bccache_line_empty_m;
  for(fsl_size_t i=0; i<c->used; ++i){
    fsl_b_clear(&c->list[i].content);
    c->list[i] = line_empty;
  }
  c->used = 0;
  c->szTotal = 0;
  c->nextAge = 0;
  fsl_id_bag_reuse(&c->inCache);
}


int fsl__bccache_check_available(fsl_cx * const f, fsl_id_t rid){
  fsl_id_t srcid;
  int depth = 0;  /* Limit to recursion depth */
  static const int limit = 100000 /* historical value=10M */;
  int rc;
  fsl__bccache * const c = &f->cache.blobContent;
  assert(f);
  assert(c);
  assert(rid>0);
  assert(fsl_cx_db_repo(f));
  while( depth++ < limit ){
    fsl_int_t cSize = -1;
    if( fsl__cx_ptl_has(f, fsl__ptl_e_missing, rid) ){
      return FSL_RC_NOT_FOUND;
    }else if( fsl__cx_ptl_has(f, fsl__ptl_e_available, rid) ){
      return 0;
    }
    rc = fsl_content_size_v2(f, rid, &cSize);
    if( rc ) return rc;
    else if( cSize<0 /*phantom*/ ){
      rc = fsl__cx_ptl_insert(f, fsl__ptl_e_missing, rid);
      return rc ? rc : FSL_RC_NOT_FOUND;
    }
    srcid = 0;
    rc = fsl_delta_r2s(f, rid, &srcid);
    if(rc) return rc;
    else if( srcid==0 ){
      return fsl__cx_ptl_insert(f, fsl__ptl_e_available, rid);
    }
    rid = srcid;
  }
  assert(!"apparent delta-loop in repository");
  return fsl_cx_err_set(f, FSL_RC_CONSISTENCY,
                        "Serious problem: apparent delta-loop in repository");
}

static void fsl__ptl_line_clear( fsl__ptl_line * cl ){
  cl->changeMarker = 0;
#define E(X) fsl_id_bag_clear(&cl->X);
  fsl__ptl_line_map(E)
#undef E
}

static void fsl__ptl_line_reuse( fsl__ptl_line * cl ){
  cl->changeMarker = 0;
#define E(X) fsl_id_bag_reuse(&cl->X);
  fsl__ptl_line_map(E)
#undef E
}

static int fsl__ptl_reserve( fsl__ptl * c, uint16_t n ){
  static const struct fsl__ptl_line fsl__ptl_line_empty = {
#define E(X) .X = fsl_id_bag_empty_m,
    fsl__ptl_line_map(E)
#undef E
    .changeMarker = 0
  };

  if( 0==n ){
    if( c->allocated ){
      for( uint16_t i = 0; i < c->allocated; ++i ){
        fsl__ptl_line_clear(&c->stack[i]);
      }
    }
    fsl_b_clear( &c->mem );
    c->allocated = 0;
    c->level = 0;
    c->stack = NULL;
    c->line = 0;
    c->rc = 0;
  }else if( 0==c->rc && n>c->allocated ){
    c->rc = fsl_b_reserve( &c->mem, sizeof(fsl__ptl_line) * n );
    if( 0==c->rc ){
      c->stack = (fsl__ptl_line*)c->mem.mem;
      for( uint16_t i = c->allocated; i < n; ++i ){
        c->stack[i] = fsl__ptl_line_empty;
      }
      c->allocated = n;
    }
  }
  return c->rc;
}

static inline fsl__ptl_line *fsl__ptl_ln( fsl__ptl * const c ){
  assert( c->mem.mem );
  return &c->stack[c->level];
}

static inline fsl__ptl_line * fsl__cx_ptl_line(fsl_cx * const f){
  return fsl__ptl_ln(&f->cache.ptl);
}

fsl_id_bag * fsl__cx_ptl_bag(fsl_cx *f, fsl__ptl_e where){
  fsl__ptl_line * const line = fsl__cx_ptl_line(f);
  switch(where){

#define E(X) case fsl__ptl_e_ ## X: return &line->X;
    fsl__ptl_line_map(E)
#undef E

    default:
      fsl__fatal(FSL_RC_CANNOT_HAPPEN,"Not possible");
      return NULL/*not reached*/;
  }
}

#define fsl__ptl_assert_clean(P)                            \
  assert(!P->level); assert(!P->line); assert(!P->stack);   \
  assert(!P->mem.mem); assert(!P->rc); assert(!P->allocated)

int fsl__ptl_init( fsl__ptl * c, uint16_t prealloc ){
  fsl__ptl_assert_clean(c);
  fsl__ptl_reserve( c, prealloc+1 );
  if( 0==c->rc ){
    c->line = fsl__ptl_ln(c);
  }
#if !defined(NDEBUG)
  else {
    assert( !c->stack );
    assert( !c->mem.mem );
  }
#endif
  return c->rc;
}

/**
   Frees all memory owned by c but does not free c.
*/
void fsl__ptl_clear( fsl__ptl * c ){
  fsl__ptl_reserve(c, 0);
  fsl__ptl_assert_clean(c);
}
#undef fsl__ptl_assert_clean

/**
   Pushes a level to the stack. Returns 0 on success, FSL_RC_OOM on
   allocation error. Returns c->rc and is a no-op if that's non-0 when
   this is called.
*/
static int fsl__ptl_push( fsl__ptl * c ){
  if( 0==c->rc ){
    assert( (int16_t)(c->level+1) > 0 );
    fsl__ptl_reserve( c, c->level+1 );
    if( 0==c->rc ){
      ++c->level;
      c->line = fsl__ptl_ln(c);
    }
  }
  return c->rc;
}

/**
   Pops a level from the stack.

   TODO: we need the fsl_cx instance and a flag telling us whether to
   clean up, e.g. f->cache.blobContent or remove RIDs from a given db
   table. Maybe a callback like:

   void (*callback)(fsl_cx * f, fsl__ptl_e where, fsl_id_bag *theRids)

   which gets called for every being-popped bag.
*/
static void fsl__ptl_pop( fsl__ptl * c ){
  assert( c->level>0 && "Don't pop level 0" );
  assert( c->line );
  fsl__ptl_line_reuse(c->line);
  --c->level;
  c->line = fsl__ptl_ln(c);
}

/**
   Searches all levels of the given cache type for rid, newest
   first. Returns true if found, else false.
*/
bool fsl__ptl_has( fsl__ptl const * c, fsl__ptl_e where, fsl_id_t rid ){
  assert( c->line );
  for( int16_t n = (int16_t)c->level; n >= 0; --n ){
    switch(where){

#define E(X)                                                     \
      case fsl__ptl_e_ ## X:                                     \
      if( fsl_id_bag_contains(&c->stack[n].X, rid) ) return true; \
      break;
      fsl__ptl_line_map(E)
#undef E

      case fsl__ptl_e_dummy:
      fsl__fatal(FSL_RC_CANNOT_HAPPEN,"Not possible");
      break;
    }
  }
  return false;
}

/**
   Adds rid to the given cache for the current stack level. Returns
   c->rc and is a no-op if that's non-0 when this is called.
*/
int fsl__ptl_insert( fsl__ptl * c, fsl__ptl_e where, fsl_id_t rid ){
  if( 0==c->rc ){
    assert( c->line );
    switch(where){

#define E(X) case fsl__ptl_e_ ## X:                     \
      return c->rc = fsl_id_bag_insert(&c->line->X, rid);
      fsl__ptl_line_map(E)
#undef E

      case fsl__ptl_e_dummy:
        fsl__fatal(FSL_RC_CANNOT_HAPPEN,"Not possible");
      break;
    }
  }
  return c->rc;
}

/**
   Removes the rid from the first level of the stack which has it,
   starting at the newest. Returns true if it removed an entry, else
   false.
*/
bool fsl__ptl_remove( fsl__ptl const * c, fsl__ptl_e where, fsl_id_t rid ){
  assert( c->line );
  bool rv = false;
#if 0
  /* (A) this can't happen, right? (B) we don't have access to the
     fsl_cx from here. */
  if( rid==f->db.ckout.rid ){
    fsl__cx_ckout_clear(f);
  }
#endif
  for( int16_t n = (int16_t)c->level; n >= 0; --n ){
    switch(where){

#define E(X) case fsl__ptl_e_ ## X:                           \
      if( fsl_id_bag_remove(&c->stack[n].X, rid) ) rv = true; \
      break;
      fsl__ptl_line_map(E)
#undef E
      /**
         We can very likely get by with stopping at the first found
         entry, but peace of mind requires that we make certain that
         explicitly-removed IDs, as opposed to a per-level wipe like
         fsl__ptl_pop() does, are not left in other levels.
      */
      case fsl__ptl_e_dummy:
      fsl__fatal(FSL_RC_CANNOT_HAPPEN,"Not possible");
      break;
    }
  }
  return rv;
}

int fsl__cx_ptl_push( fsl_cx * f ){
  fsl__ptl * const p = &f->cache.ptl;
  if( 0==fsl__ptl_push(p) ){
    fsl__ptl_ln(p)->changeMarker = f->cache.blobContent.changeMarker;
  }
  return p->rc;
}

int fsl__cx_ptl_pop( fsl_cx * f, bool isCommit ){
  fsl__ptl * const p = &f->cache.ptl;
  fsl__ptl_line * const line = fsl__ptl_ln(p);
  int rc = 0;
  assert( p->level && "Do not pop level 0" );
  fsl__cx_reset_for_txn(f, isCommit);
  if( isCommit ){
    /*
      Migrate all of line's entries into the previous line.  Any
      entries which needed to be cleaned up by now will have already
      been cleaned up if they need it. We always want the
      line->missing and line->available entries to bubble, as they're
      always valid until their corresponding blob records have been
      rolled back.
    */
    fsl__ptl_line * const prev = &p->stack[p->level-1];

#define E(X)                                                            \
    if( 0==rc && line->X.entryCount ) {                                 \
      /*MARKER(("Uplifting RIDs from [" # X "] level %d\n",(int)p->level));*/ \
      if( prev->X.entryCount ) rc = fsl_id_bag_copy(&line->X, &prev->X);\
      else fsl_id_bag_swap(&prev->X, &line->X);                         \
    }

    fsl__ptl_line_map(E)

#undef E
    if( 0==rc && 1==p->level ){
      /* The outermost transaction is committing. Until the next one
         starts, another connection may store or remove content, so
         what this one knows about available and missing content no
         longer holds. fossil(1) clears the same sets at each commit,
         in verify_at_commit() via content_clear_cache(). */
      fsl_id_bag_reuse(&prev->missing);
      fsl_id_bag_reuse(&prev->available);
    }
  }else{
    if( f->cache.blobContent.changeMarker != line->changeMarker ){
      /**
         Entries were added to the content cache since this transaction
         level was started. Invalidate the cache.

         Potential TODO: use
         fsl__bccache_remove(&f->cache.blobContent,rid) for each rid
         in p->(toVerify, available, leafCheck). We know the blob
         cache does not map to any entries in p->missing. However,
         these caches may have arbitrarily many entries, and
         blobContent is an O(N) cache with potentially hundreds of
         entries, so that could become slow.
      */
      fsl__cx_content_caches_clear(f);
      fsl__bccache_reuse(&f->cache.blobContent);
    }
  }
  fsl__ptl_pop(p);
  return rc;
}

bool fsl__cx_ptl_remove( fsl_cx * f, fsl__ptl_e where, fsl_id_t rid ){
  fsl__ptl const * p = &f->cache.ptl;
  switch( where ){
    case fsl__ptl_e_available:
    case fsl__ptl_e_toVerify:
#if 0
      /* UNTESTED */
      fsl__bccache_remove(&f->cache.blobContent, rid);
#else
      fsl__cx_content_caches_clear(f)
        /* This RID could be in the blob cache or the deck cache. */;
#endif
      FSL_SWITCH_FALL_THROUGH;
    case fsl__ptl_e_dephantomize:
    case fsl__ptl_e_leafCheck:
    case fsl__ptl_e_missing:
      return fsl__ptl_remove(p, where, rid);
    case fsl__ptl_e_dummy:
      fsl__fatal(FSL_RC_CANNOT_HAPPEN,"Not possible") /* does not return */;
  }
  return false /* not reached */;
}

#undef MARKER
/* end of file src/cache.c */
/* start of file src/checkin.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/*****************************************************************************
  This file houses the code for checkin-level APIS.
*/
#include <assert.h>


/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


/**
   Expects f to have an opened checkout. Assumes zRelName is a
   checkout-relative simple path. It loads the file's contents and
   stores them into the blob table. If rid is not NULL, *rid is
   assigned the blob.rid (possibly new, possilbly re-used!). If uuid
   is not NULL then *uuid is assigned to the content's UUID. The *uuid
   bytes are owned by the caller, who must eventually fsl_free()
   them. If content with the same UUID already exists, it does not get
   re-imported but rid/uuid will (if not NULL) contain the old values.

   If parentRid is >0 then it must refer to the previous version of
   zRelName's content. The parent version gets deltified vs the new
   one. Note that deltification is a suggestion which the library will
   ignore if (e.g.) the parent content is already a delta of something
   else.

   The wise caller will have a transaction in place when calling this.

   Returns 0 on success. On error rid and uuid are not modified.
*/
static int fsl__checkin_import_file( fsl_cx * const f,
                                     char const * const zRelName,
                                     fsl_id_t parentRid,
                                     bool allowMergeConflict,
                                     fsl_id_t * const rid,
                                     fsl_uuid_str * const uuid){
  fsl_b * const nbuf = fsl_cx_b_borrow(f);
  if( !nbuf ) return f->error.code;
  fsl_size_t const oldSize = nbuf->used;
  fsl_b * const fbuf = &f->cache.fileContent;
  char const * fn;
  int rc;
  fsl_id_t fnid = 0;
  fsl_id_t rcRid = 0;
  bool isLink = false;

  //TODO (2025-08-06): assert( fsl_cx_txn_level(f)>0 );
  assert(!fbuf->used && "Misuse of f->fileContent");
  assert(f->db.ckout.dir);
  rc = fsl__repo_filename_fnid2(f, zRelName, &fnid, 1);
  if(rc) goto end;
  assert(fnid>0);

  rc = fsl_b_appendf(nbuf, "%s%s", f->db.ckout.dir, zRelName);
  nbuf->used = oldSize;
  if(rc) goto end;
  fn = fsl_b_cstr(nbuf) + oldSize;
  /* As fossil(1)'s commit_cmd(): read as RepoFILE, and don't look for
     merge markers in a symlink's target name. */
  rc = fsl__cfs_read_repofile(f, fbuf, fn, &isLink);
  if(rc){
    fsl_cx_err_set(f, rc, "Error %s importing file: %s",
                   fsl_rc_cstr(rc), fn);
    goto end;
  }else if(!allowMergeConflict && !isLink &&
           fsl_b_contains_merge_marker(fbuf)){
    rc = fsl_cx_err_set(f, FSL_RC_CONFLICT,
                        "File contains a merge conflict marker: %s",
                        zRelName);
    goto end;
  }

  rc = fsl__content_put( f, fbuf, &rcRid );
  if(!rc){
    assert(rcRid > 0);
    if(parentRid>0){
      rc = fsl__content_deltify(f, parentRid, rcRid, 0);
    }
    if(!rc){
      if(rid) *rid = rcRid;
      if(uuid){
        *uuid = fsl_rid_to_uuid(f, rcRid);
        if(!*uuid) rc = (f->error.code ? f->error.code : FSL_RC_OOM);
      }
    }
  }
  end:
  fsl_cx_b_return(f, nbuf);
  fsl__cx_content_buffer_yield(f);
  assert(0==fbuf->used);
  return rc;
}

int fsl_filename_to_vfile_ids( fsl_cx * f, fsl_id_t vid,
                               fsl_id_bag * dest, char const * zName,
                               bool changedOnly){
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return FSL_RC_NOT_A_CKOUT;
  fsl_b * const sql = fsl_cx_b_borrow(f);
  if( !sql ) return f->error.code;
  fsl_stmt st = fsl_stmt_empty;
  int rc;
  if(0>=vid) vid = f->db.ckout.rid;
  if(zName && *zName
     && !('.'==*zName && !zName[1])){
    fsl__db_appendf(db, sql,
                       "SELECT id FROM {{dbname.ckout}}.vfile WHERE vid=%"
                       FSL_ID_T_PFMT
                       " AND fsl_match_vfile_or_dir(pathname,%Q)",
                       vid, zName);
  }else{
    fsl__db_appendf(db, sql,
                       "SELECT id FROM {{dbname.ckout}}.vfile WHERE vid=%" FSL_ID_T_PFMT,
                       vid);
  }
  if(changedOnly){
    fsl_b_append(sql, " AND (chnged OR deleted OR rid=0 "
                      "OR (origname IS NOT NULL AND "
                      "    origname<>pathname))", -1);
  }
  rc = fsl_b_appendf(sql, " /* %s() */", __func__);
  if(0==rc) rc = fsl_db_prepare(db, &st, "%b", sql);
  while(!rc && (FSL_RC_STEP_ROW == (rc=fsl_stmt_step(&st)))){
    rc = fsl_id_bag_insert( dest, fsl_stmt_g_id(&st, 0) );
  }
  if(FSL_RC_STEP_DONE==rc) rc = 0;
  fsl_cx_b_return(f, sql);
  fsl_stmt_finalize(&st);
  if(rc && !f->error.code && db->error.code){
    fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}

int fsl_filename_to_vfile_id( fsl_cx * const f, fsl_id_t vid,
                              char const * zName,
                              fsl_id_t * const vfid ){
  fsl_db * db = fsl_needs_ckout(f);
  int rc;
  fsl_stmt st = fsl_stmt_empty;
  assert(db);
  if(!db) return FSL_RC_NOT_A_CKOUT;
  else if(!zName || !fsl_is_simple_pathname(zName, false)){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Filename is not a \"simple\" path: %s",
                          zName);
  }
  if(0>=vid) vid = f->db.ckout.rid;
  rc = fsl_db_prepare(db, &st,
                      "SELECT id FROM {{dbname.ckout}}.vfile WHERE vid=%" FSL_ID_T_PFMT
                      " AND pathname=%Q %s /*%s()*/",
                      vid, zName,
                      fsl_cx_filename_collation(f),
                      __func__);
  if(!rc){
    rc = fsl_stmt_step(&st);
    switch(rc){
      case FSL_RC_STEP_ROW:
        rc = 0;
        *vfid = fsl_stmt_g_id(&st, 0);
        break;
      case FSL_RC_STEP_DONE:
        rc = 0;
        /* fall through */
      default:
        *vfid = 0;
    }
    fsl_stmt_finalize(&st);
  }
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, db, rc);
  }
  return rc;
}

/**
   Internal helper for fsl_checkin_enqueue() and
   fsl_checkin_dequeue(). Prepares, if needed, st with a query to
   fetch a vfile entry where vfile.id=vfid, then passes that name on
   to opt->callback(). Returns 0 on success.
*/
static int fsl__xqueue_callback(fsl_cx * f, fsl_stmt * const st,
                                fsl_id_t vfid,
                                fsl_checkin_queue_opt const * opt){

  int rc;
  assert(opt->callback);
  if(!st->stmt){
    rc = fsl_cx_prepare(f, st,
                        "SELECT pathname FROM {{dbname.ckout}}.vfile "
                        "WHERE id=?1 /*%s()*/", __func__)
      /* TODO?: cache this. It's not called all that
         often. */;
    if(rc) return rc;
  }
  rc = fsl_stmt_bind_step(st, "R", vfid);
  switch(rc){
    case FSL_RC_STEP_ROW:{
      char const * zName = fsl_stmt_g_text(st, 0, NULL);
      rc = opt->callback(zName, opt->callbackState);
      break;
    }
    case 0:
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "Very unexpectedly did "
                          "not find vfile.pathname for vfile.id %"
                          FSL_ID_T_PFMT ".", vfid);
      break;
    default:
      rc = fsl_cx_uplift_db_error2(f, st->db, rc);
      break;
  }
  fsl_stmt_reset(st);
  return rc;
}

int fsl_checkin_enqueue(fsl_cx * f, fsl_checkin_queue_opt const * opt){
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  fsl_b * const canon = opt->vfileIds ? 0 : fsl_cx_b_borrow(f);
  if( !opt->vfileIds && !canon ) return f->error.code;
  fsl_stmt qName = fsl_stmt_empty;
  fsl_id_bag _vfileIds = fsl_id_bag_empty;
  fsl_id_bag const * const vfileIds =
    opt->vfileIds ? opt->vfileIds : &_vfileIds;
  bool openedTransaction = false;
  int rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) goto end;
  openedTransaction = true;
  if(opt->vfileIds){
    if(!fsl_id_bag_count(opt->vfileIds)){
      rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "fsl_checkin_queue_opt::vfileIds "
                          "may not be empty.")
        /* Is this too strict? Maybe just not enqueue anything? */;
      goto end;
    }
  }else{
    rc = fsl_ckout_filename_check(f, opt->relativeToCwd,
                                  opt->filename, canon);
    if(rc) goto end;
    fsl_b_strip_slashes(canon);
  }
  if(opt->scanForChanges){
    rc = fsl_vfile_changes_scan(f, -1, 0);
    if(rc) goto end;
  }
  if(opt->vfileIds){
    assert(vfileIds == opt->vfileIds);
  }else{
    assert(vfileIds == &_vfileIds);
    rc = fsl_filename_to_vfile_ids(f, 0, &_vfileIds,
                                   fsl_b_cstr(canon),
                                   opt->onlyModifiedFiles);
  }
  if(rc) goto end;
  /* Walk through each found ID and queue up any which are not already
     enqueued. */
  for(fsl_id_t vfid = fsl_id_bag_first(vfileIds);
      !rc && vfid; vfid = fsl_id_bag_next(vfileIds, vfid)){
    fsl_size_t const entryCount = f->ckin.selectedIds.entryCount;
    rc = fsl_id_bag_insert(&f->ckin.selectedIds, vfid);
    if(!rc
       && entryCount < f->ckin.selectedIds.entryCount
       /* Was enqueued */
       && opt->callback){
      rc = fsl__xqueue_callback(f, &qName, vfid, opt);
    }
  }
  end:
  if(opt->vfileIds){
    assert(!canon);
    assert(!_vfileIds.list);
  }else{
    assert(canon);
    fsl_cx_b_return(f, canon);
    fsl_id_bag_clear(&_vfileIds);
  }
  if( openedTransaction ){
    fsl_stmt_finalize(&qName);
    int const rc2 = fsl_cx_txn_end(f, !!rc);
    if( !rc ) rc = rc2;
  }
  return rc;
}

int fsl_checkin_dequeue(fsl_cx * const f, fsl_checkin_queue_opt const * opt){
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  int rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) return rc;
  fsl_id_bag list = fsl_id_bag_empty;
  fsl_b * canon = 0;
  char const * fn;
  fsl_stmt qName = fsl_stmt_empty;
  if(opt->filename && *opt->filename){
    canon = fsl_cx_b_borrow(f);
    rc = canon
      ? fsl_ckout_filename_check(f, opt->relativeToCwd,
                                 opt->filename, canon)
      : f->error.code;
    if(rc) goto end;
    else fsl_b_strip_slashes(canon);
  }
  fn = canon ? fsl_b_cstr(canon) : opt->filename;
  rc = fsl_filename_to_vfile_ids(f, 0, &list, fn, false);
  if(!rc && list.entryCount){
    /* Walk through each found ID and dequeue up any which are
       enqueued. */
    for( fsl_id_t nid = fsl_id_bag_first(&list);
         !rc && nid;
         nid = fsl_id_bag_next(&list, nid)){
      if(fsl_id_bag_remove(&f->ckin.selectedIds, nid)
         && opt->callback){
        rc = fsl__xqueue_callback(f, &qName, nid, opt);
      }
    }
  }
  end:
  fsl_cx_b_return(f, canon);
  fsl_stmt_finalize(&qName);
  fsl_id_bag_clear(&list);
  if(rc) fsl_cx_txn_end(f, true);
  else rc = fsl_cx_txn_end(f, false);
  return rc;
}

bool fsl_checkin_is_enqueued(fsl_cx * const f, char const * zName,
                             bool relativeToCwd){
  if(!zName || !*zName) return false;
  else if(!fsl_cx_db_ckout(f)) return false;
  else if(!f->ckin.selectedIds.entryCount){
    /* Behave like fsl_is_enqueued() SQL function. */
    return true;
  }
  else {
    bool rv = false;
    fsl_b * const canon = fsl_cx_b_borrow(f);
    int rc = canon
      ? fsl_ckout_filename_check(f, relativeToCwd, zName, canon)
      : f->error.code;
    if(!rc){
      fsl_id_t vfid = 0;
      rc = fsl_filename_to_vfile_id(f, 0, fsl_b_cstr(canon),
                                    &vfid);
      rv = (rc && (vfid>0))
        ? false
        : ((vfid>0)
           ? fsl_id_bag_contains(&f->ckin.selectedIds, vfid)
           /* ^^^^ asserts that arg2!=0*/
           : false);
    }
    fsl_cx_b_return(f, canon);
    return rv;
  }
}

void fsl_checkin_discard(fsl_cx * const f){
  if(f){
    fsl_id_bag_clear(&f->ckin.selectedIds);
    fsl_deck_finalize(&f->ckin.mf);
  }
}

/**
   Calculates the F-cards for deck d based on the commit file
   selection list and the contents of the vfile table (where vid==the
   vid parameter). vid is the version to check against, and this code
   assumes that the vfile table has been populated with that version
   and its state represents a recent scan (with no filesystem-level
   changes made since the scan).

   If pBaseline is not NULL then d is calculated as being a delta
   from pBaseline, but d->B is not modified by this routine.

   On success, d->F.list will contain "all the F-cards it needs."

   If changeCount is not NULL, then on success it is set to the number
   of F-cards added to d due to changes queued via the checkin process
   (as opposed to those added solely for delta inheritance reasons).
*/
static
int fsl__checkin_calc_F_cards2( fsl_cx * f, fsl_deck * d,
                                fsl_deck * pBaseline, fsl_id_t vid,
                                fsl_size_t * changeCount,
                                fsl_checkin_opt const * ciOpt){
  int rc = 0;
  fsl_db * dbR = fsl_needs_repo(f);
  fsl_db * dbC = fsl_needs_ckout(f);
  fsl_stmt stUpdateFileRid = fsl_stmt_empty;
  fsl_stmt stmt = fsl_stmt_empty;
  fsl_stmt * q = &stmt;
  char * fUuid = NULL;
  fsl_card_F const * pFile = NULL;
  fsl_size_t changeCounter = 0;
  fsl_b * fullName = NULL;
  bool allowSymlinks;
  if(!f) return FSL_RC_MISUSE;
  else if(!dbR) return FSL_RC_NOT_A_REPO;
  else if(!dbC) return FSL_RC_NOT_A_CKOUT;
  fullName = fsl_cx_b_borrow(f);
  if(!fullName) return f->error.code;
  allowSymlinks = fsl_cx_allows_symlinks(f, false);
  assert( (!pBaseline || !pBaseline->B.uuid) && "Baselines must not have a baseline." );
  assert( d->B.baseline ? (!pBaseline || pBaseline==d->B.baseline) : 1 );
  assert(vid>=0);
  //TODO (2025-08-06): assert( fsl_cx_txn_level(f)>0 );
#define RC if(rc) goto end

  if(pBaseline){
    assert(!d->B.baseline);
    assert(0!=vid);
    rc = fsl_deck_F_rewind(pBaseline);
    RC;
    fsl_deck_F_next( pBaseline, &pFile );
  }

  rc = fsl_db_prepare(dbC, &stUpdateFileRid,
                      "UPDATE {{dbname.ckout}}.vfile SET mrid=?1, rid=?1, "
                      "mhash=NULL WHERE id=?2");
  RC;

  rc = fsl_db_prepare( dbC, q,
                       "SELECT "
                       /*0*/"fsl_is_enqueued(vf.id) as isSel, "
                       /*1*/"vf.id,"
                       /*2*/"vf.vid,"
                       /*3*/"vf.chnged,"
                       /*4*/"vf.deleted,"
                       /*5*/"vf.isexe,"
                       /*6*/"vf.islink,"
                       /*7*/"vf.rid,"
                       /*8*/"mrid,"
                       /*9*/"pathname,"
                       /*10*/"origname, "
                       /*11*/"b.rid, "
                       /*12*/"b.uuid "
                       "FROM {{dbname.ckout}}.vfile vf LEFT JOIN {{dbname.repo}}.blob b ON vf.mrid=b.rid "
                       "WHERE"
                       " vf.vid=%"FSL_ID_T_PFMT" AND"
#if 0
                       /* Historical (fossil(1)). This introduces an interesting
                          corner case which i would like to avoid here because
                          it causes a "no files changed" error in the checkin
                          op. The behaviour is actually correct (and the deletion
                          is picked up) but fsl_checkin_commit() has no mechanism
                          for catching this particular case. So we'll try a
                          slightly different approach...
                       */
                       " (NOT deleted OR NOT isSel)"
#else
                       " ((NOT deleted OR NOT isSel)"
                       "  OR (deleted AND isSel))" /* workaround to allow
                                                     us to count deletions via
                                                     changeCounter. */
#endif
                       " ORDER BY fsl_if_enqueued(vf.id, pathname, origname)",
                       (fsl_id_t)vid);
  RC;
  /* MARKER(("SQL:\n%s\n", (char const *)q->sql.mem)); */
  while( FSL_RC_STEP_ROW==(rc = fsl_stmt_step(q)) ){
    rc = 0;
    int const isSel = fsl_stmt_g_int32(q,0);
    fsl_id_t const id = fsl_stmt_g_id(q,1);
#if 0
    fsl_id_t const vid = fsl_stmt_g_id(q,2);
#endif
    int const changed = fsl_stmt_g_int32(q,3);
    int const deleted = fsl_stmt_g_int32(q,4);
    int const isExe = fsl_stmt_g_int32(q,5);
    int const isLink = fsl_stmt_g_int32(q,6);
    fsl_id_t const rid = fsl_stmt_g_id(q,7);
    fsl_id_t const mergeRid = fsl_stmt_g_id(q,8);
    char const * zName = fsl_stmt_g_text(q, 9, NULL);
    char const * zOrig = fsl_stmt_g_text(q, 10, NULL);
    fsl_id_t const frid = fsl_stmt_g_id(q,11);
    char const * zUuid = fsl_stmt_g_text(q, 12, NULL);
    fsl_fileperm_e perm = FSL_FILE_PERM_REGULAR;
    int cmp;
    fsl_id_t fileBlobRid = rid;
    int const renamed = (zOrig && *zOrig) ? fsl_strcmp(zName,zOrig) : 0
      /* For some as-yet-unknown reason, some fossil(1) code
         sets (origname=pathname WHERE origname=NULL). e.g.
         the 'mv' command does that.
      */;
    if(zOrig && !renamed) zOrig = NULL;
    fUuid = NULL;
    if(!isSel && !zUuid){
      assert(!rid);
      assert(!mergeRid);
      /* An unselected ADDed file. Skip it. */
      continue;
    }
    if(0 && changed){
      MARKER(("vfid=%"FSL_ID_T_PFMT", isExe=%d, changed=%d\n",
              id, isExe, changed));
    }
    if(isExe){
      perm = FSL_FILE_PERM_EXE;
    }else if(isLink){
      perm = FSL_FILE_PERM_LINK;
    }
#if !defined(_WIN32)
    if(isSel && !deleted){
      /* As fossil(1)'s create_manifest(): a selected file's perms
         come from disk, which is how exec-bit and symlink changes
         (vfile.chnged 6..9) get committed. vfile.isexe and
         vfile.islink describe the baseline, so the perms of other
         files, and all files on Windows, are left as they were. */
      fsl_fstat fst = fsl_fstat_empty;
      fsl_b_reuse(fullName);
      rc = fsl_b_appendf(fullName, "%s%s", f->db.ckout.dir, zName);
      RC;
      perm = 0==fsl__cfs_stat(f, fsl_b_cstr(fullName), &fst,
                              !allowSymlinks)
        ? fsl__fstat_perm(&fst, allowSymlinks)
        : FSL_FILE_PERM_REGULAR;
    }
#endif

    if(!f->cache.markPrivate){
      rc = fsl_content_make_public(f, frid);
      if(rc) break;
    }

#if 0
    if(mergeRid && (mergeRid != rid)){
      fsl__fatal(FSL_RC_NYI, "This code does not yet deal "
                "with merges. file: %s", zName)
        /* does not return */;
    }
#endif
    while(pFile && fsl_strcmp(pFile->name, zName)<0){
      /* Baseline has files with lexically smaller names.
         Interesting corner case:

         f-rm th1ish/makefile.gnu
         f-checkin ... th1ish/makefile.gnu

         makefile.gnu does not get picked up by the historical query
         but gets picked up here. We really need to ++changeCounter in
         that case, but we don't know we're in that case because we're
         now traversing a filename which is not in the result set.
         The end result (because we don't increment changeCounter) is
         that fsl_checkin_commit() thinks we have not made any changes
         and errors out. If we ++changeCounter for all deletions we
         have a different corner case, where a no-change commit is not
         seen as such because we've counted deletions from (other)
         versions between the baseline and the checkout.
      */
      rc = fsl__deck_F_add2(d, pFile->name, NULL, pFile->perm, NULL, false);
      if(rc) break;
      fsl_deck_F_next(pBaseline, &pFile);
    }
    if(rc) goto end;
    else if(isSel && (changed || deleted || renamed)){
      /* MARKER(("isSel && (changed||deleted||renamed): %s\n", zName)); */
      ++changeCounter;
      if(deleted){
        zOrig = NULL;
      }else if(changed){
        rc = fsl__checkin_import_file(f, zName, rid,
                                      ciOpt->allowMergeConflict,
                                      &fileBlobRid, &fUuid);
        if(!rc) rc = fsl__unsent_rid_add(f, fileBlobRid);
        RC;
        /* MARKER(("New content: %d / %s / %s\n", (int)fileBlobRid, fUuid, zName)); */
        if(0 != fsl_uuidcmp(zUuid, fUuid)){
          zUuid = fUuid;
        }
        fsl_stmt_reset(&stUpdateFileRid);
        fsl_stmt_bind_id(&stUpdateFileRid, 1, fileBlobRid);
        fsl_stmt_bind_id(&stUpdateFileRid, 2, id);
        if(FSL_RC_STEP_DONE!=fsl_stmt_step(&stUpdateFileRid)){
          rc = fsl_cx_uplift_db_error(f, stUpdateFileRid.db);
          assert(rc);
          goto end;
        }
      }else{
        assert(renamed);
        assert(zOrig);
      }
    }
    assert(!rc);
    cmp = 1;
    if(!pFile
       || (cmp = fsl_strcmp(pFile->name,zName))!=0
       /* ^^^^ the cmp assignment must come right after (!pFile)! */
       || deleted
       || (perm != pFile->perm)/* permissions change */
       || fsl_strcmp(pFile->uuid, zUuid)!=0
       /* ^^^^^ file changed somewhere between baseline and delta */
       ){
      if(isSel && deleted){
        if(pBaseline /* d is-a delta */){
          /* Deltas mark deletions with F-cards having only
             a file name (no UUID or permission).
          */
          rc = fsl__deck_F_add2(d, zName, NULL, perm, NULL, false);
        }/*else elide F-card to mark a deletion in a baseline.*/
      }else{
        if(zOrig && !isSel){
          /* File is renamed in vfile but is not being committed, so
             make sure we use the original name for the F-card.
          */
          zName = zOrig;
          zOrig = NULL;
        }
        assert(zUuid);
        assert(fileBlobRid);
        if( !zOrig || !renamed ){
          rc = fsl__deck_F_add2(d, zName, zUuid, perm, NULL, false);
        }else{
          /* Rename this file */
          rc = fsl__deck_F_add2(d, zName, zUuid, perm, zOrig, false);
        }
      }
    }
    fsl_free(fUuid);
    fUuid = NULL;
    RC;
    if( 0 == cmp ){
      fsl_deck_F_next(pBaseline, &pFile);
    }
  }/*while step()*/
  if(FSL_RC_STEP_DONE==rc) rc = 0;
  /* Any other step result is an error left in dbC's error state,
     which fsl__checkin_calc_manifest() uplifts. */

  while( !rc && pFile ){
    /* Baseline has remaining files with lexically larger names. Let's import them. */
    rc = fsl__deck_F_add2(d, pFile->name, NULL, pFile->perm, NULL, false);
    if(!rc) fsl_deck_F_next(pBaseline, &pFile);
  }

  end:
#undef RC
  fsl_free(fUuid);
  fsl_cx_b_return(f, fullName);
  fsl_stmt_finalize(q);
  fsl_stmt_finalize(&stUpdateFileRid);
  if(!rc && changeCount) *changeCount = changeCounter;
  return rc;
}

/**
   Cancels all symbolic tags (branches) on the given version by
   adding one T-card to d for each active branch tag set on vid.
   When creating a branch, d would represent the branch and vid
   would be the version being branched from.

   Returns 0 on success.
*/
static int fsl_cancel_sym_tags( fsl_deck * d, fsl_id_t vid ){
  int rc;
  fsl_stmt q = fsl_stmt_empty;
  fsl_db * db = fsl_needs_repo(d->f);
  assert(db);
  rc = fsl_db_prepare(db, &q,
                      "SELECT tagname FROM {{dbname.repo}}.tagxref AS tagxref, {{dbname.repo}}.tag AS tag"
                      " WHERE tagxref.rid=%"FSL_ID_T_PFMT
                      " AND tagxref.tagid=tag.tagid"
                      "   AND tagtype>0 AND tagname GLOB 'sym-*'"
                      " ORDER BY tagname",
                      (fsl_id_t)vid);
  while( !rc && fsl__cx_stmt_step_each(d->f, &q, &rc) ){
    const char *zTag = fsl_stmt_g_text(&q, 0, NULL);
    rc = fsl_deck_T_add(d, FSL_TAGTYPE_CANCEL,
                        NULL, zTag, "Cancelled by branch.");
  }
  fsl_stmt_finalize(&q);
  return rc;
}

#if 0
static int fsl_leaf_set( fsl_cx * f, fsl_id_t rid, char isLeaf ){
  int rc;
  fsl_stmt * st = NULL;
  fsl_db * db = fsl_needs_repo(f);
  assert(db);
  rc = fsl_db_prepare_cached(db, &st, isLeaf
                             ? "INSERT OR IGNORE INTO {{dbname.repo}}.leaf(rid) VALUES(?)"
                             : "DELETE FROM {{dbname.repo}}.leaf WHERE rid=?");
  if(!rc){
    fsl_stmt_bind_id(st, 1, rid);
    fsl_stmt_step(st);
    fsl_stmt_cached_yield(st);
  }
  if(rc){
    fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}
#endif

/**
   Checks vfile for any files (where chnged in (2,3,4,5)), i.e.
   having something to do with a merge. If either all of those
   changes are enqueued for checkin, or none of them are, then
   this function returns 0, otherwise it sets f's error
   state and returns non-0.
*/
static int fsl_check_for_partial_merge(fsl_cx * f){
  if(!f->ckin.selectedIds.entryCount){
    /* All files are considered enqueued. */
    return 0;
  }else{
    fsl_db * db = fsl_cx_db_ckout(f);
    int32_t counter = 0;
    int rc =
      fsl_db_get_int32(db, &counter,
                       "SELECT COUNT(*) FROM ("
#if 1
                       "SELECT DISTINCT fsl_is_enqueued(id)"
                       " FROM {{dbname.ckout}}.vfile WHERE chnged IN (2,3,4,5)"
#else
                       "SELECT fsl_is_enqueued(id) isSel "
                       "FROM {{dbname.ckout}}.vfile WHERE chnged IN (2,3,4,5) "
                       "GROUP BY isSel"
#endif
                       ")"
                       );
    /**
       Result is 0 if no merged files are in vfile, 1 row if isSel is
       the same for all merge-modified files, and 2 if there is a mix
       of selected/unselected merge-modified files.
     */
    if(!rc && (counter>1)){
      assert(2==counter);
      rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Only Chuck Norris can commit "
                          "a partial merge. Commit either all "
                          "or none of it.");
    }
    return rc;
  }
}

/**
   Unless opt->allowOlder is true, returns FSL_RC_RANGE and sets f's
   error state if the ancestor check-in rid, whose hash is zUuid, is
   newer than d's D-card. The times are compared at millisecond
   precision, the precision of a D-card. Returns 0 if rid is not newer,
   or a db error code.

   fossil(1) refuses such a check-in in checkin_verify_younger()
   unless --allow-older is given.
*/
static int fsl__checkin_verify_younger(fsl_cx * const f,
                                       fsl_deck const * const d,
                                       fsl_checkin_opt const * const opt,
                                       fsl_id_t rid,
                                       char const * zUuid){
  fsl_db * const dbR = fsl_cx_db_repo(f);
  bool newer = false;
  int rc;
  if( opt->allowOlder ) return 0;
  rc = fsl_db_exists2(dbR, &newer,
                      "SELECT 1 FROM {{dbname.repo}}.event"
                      " WHERE objid=%"FSL_ID_T_PFMT" AND type='ci'"
                      " AND strftime('%%Y-%%m-%%dT%%H:%%M:%%f',mtime)"
                      " > strftime('%%Y-%%m-%%dT%%H:%%M:%%f',"
                      "%"FSL_JULIAN_T_PFMT")",
                      rid, d->D);
  if( rc ) return fsl_cx_uplift_db_error2(f, dbR, rc);
  if( newer ){
    char zDate[32];
    fsl_julian_to_iso8601(d->D, zDate, true);
    rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Ancestor check-in [%.12s] is "
                        "newer than this check-in's time (%s). Set "
                        "fsl_checkin_opt::allowOlder to override.",
                        zUuid, zDate);
  }
  return rc;
}

/**
   Populates d with the contents for a FSL_SATYPE_CHECKIN manifest
   based on repository version basedOnVid.

   d is the deck to populate.

   basedOnVid must currently be f->db.ckout.rid OR the vfile table must
   be current for basedOnVid (see fsl_vfile_changes_scan() and
   fsl_vfile_load()). It "should" work with basedOnVid==0 but
   that's untested so far.

   opt is the options object passed to fsl_checkin_commit().
*/
static int fsl__checkin_calc_manifest( fsl_cx * f, fsl_deck * d,
                                      fsl_id_t basedOnVid,
                                      fsl_checkin_opt const * opt ){
  int rc;
  fsl_db * dbR = fsl_cx_db_repo(f);
  fsl_db * dbC = fsl_cx_db_ckout(f);
  fsl_stmt q = fsl_stmt_empty;
  fsl_deck dBase = fsl_deck_empty;
  char const * zColor;
  int deltaPolicy = opt->deltaPolicy;

  //TODO (2025-08-06): assert( fsl_cx_txn_level(f)>0 );
  assert(d->f == f);
  assert(FSL_SATYPE_CHECKIN==d->type);
#define RC if(rc) goto end
  /* assert(basedOnVid>0); */
  rc = (opt->message && *opt->message)
    ? 0
    : fsl_cx_err_set(f, FSL_RC_MISSING_INFO,
                     "Cowardly refusing to commit with "
                     "empty checkin comment.");
  RC;
  {
    /* Artifact text is UTF-8. A comment in another encoding would be
       stored as it is and shown as mojibake, so refuse it, as fossil(1)
       refuses a comment file or editor text that is not UTF-8. */
    fsl_b const msg = {
      .mem = (unsigned char *)opt->message, .capacity = 0U,
      .used = fsl_strlen(opt->message), .cursor = 0U, .errCode = 0
    };
    if(fsl_invalid_utf8(&msg)){
      rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                          "The checkin comment is not valid UTF-8.");
      goto end;
    }
  }
  rc = fsl_deck_C_set( d, opt->message, -1 );
  RC;

  if(deltaPolicy!=0 && fsl_repo_forbids_delta_manifests(f)){
    deltaPolicy = 0;
  }else if(deltaPolicy<0 && f->cache.seenDeltaManifest<=0){
    deltaPolicy = 0;
  }
  {
    char const * zUser = opt->user ? opt->user : fsl_cx_user_get(f);
    rc = (zUser && *zUser)
      ? fsl_deck_U_set( d, zUser )
      : fsl_cx_err_set(f, FSL_RC_MISSING_INFO,
                       "Cowardly refusing to commit without "
                       "a user name.");
    RC;
  }

  rc = fsl_check_for_partial_merge(f);
  RC;

  rc = fsl_deck_D_set( d, (opt->julianTime>0)
                       ? opt->julianTime
                       : fsl_db_julian_now(dbR) );
  RC;

  if(opt->messageMimeType && *opt->messageMimeType){
    rc = fsl_deck_N_set( d, opt->messageMimeType, -1 );
    RC;
  }


  { /* F-cards */
    static char const * errNoFilesMsg =
      "No files have changed. Cowardly refusing to commit.";
    static int const errNoFilesRc = FSL_RC_NOOP;
    fsl_deck * pBase = NULL /* baseline for delta generation purposes */;
    fsl_size_t szD = 0, szB = 0 /* see commentary below */;
    if(basedOnVid && deltaPolicy!=0){
      /* Figure out a baseline for a delta manifest... */
      fsl_uuid_str bUuid = NULL /* UUID for d's B-card */;
      rc = fsl_deck_load_rid(f, &dBase, basedOnVid, FSL_SATYPE_CHECKIN);
      RC;
      if(dBase.B.uuid){
        /* dBase is a delta. Let's use its baseline for manifest
           generation. */
        fsl_id_t const baseRid = fsl_uuid_to_rid(f, dBase.B.uuid);
        fsl_deck_finalize(&dBase);
        if(baseRid>0){
          rc = fsl_deck_load_rid(f, &dBase, baseRid,
                                 FSL_SATYPE_CHECKIN);
        }else if(!f->error.code){
          rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                              "Cannot find the baseline manifest of "
                              "checkout version rid %" FSL_ID_T_PFMT
                              ".", basedOnVid);
        }
        RC;
      }else{
        /* dBase version is a suitable baseline. */
        bUuid = fsl_rid_to_uuid(f, basedOnVid);
        if(!bUuid){
          assert(f->error.code);
          rc = f->error.code;
          RC;
        }
      }
      /* MARKER(("Baseline = %d / %s\n", (int)pBase->rid, pBase->uuid)); */
      assert(dBase.B.uuid || bUuid);
      rc = fsl_deck_B_set(d, dBase.B.uuid ? dBase.B.uuid : bUuid);
      fsl_free(bUuid);
      RC;
      pBase = &dBase;
    }
    rc = fsl__checkin_calc_F_cards2(f, d, pBase, basedOnVid,
                                   &szD, opt);
    /*MARKER(("szD=%d\n", (int)szD));*/
    RC;
    if(basedOnVid && !szD){
      rc = fsl_cx_err_set(f, errNoFilesRc, errNoFilesMsg);
      goto end;
    }
    szB = pBase ? pBase->F.used : 0;
    /* The following text was copied verbatim from fossil(1). It does
       not apply 100% here (because we use a slightly different
       manifest generation approach) but it clearly describes what's
       going on after the comment block....
    */
    /*
    ** At this point, two manifests have been constructed, either of
    ** which would work for this checkin.  The first manifest (held
    ** in the "manifest" variable) is a baseline manifest and the second
    ** (held in variable named "delta") is a delta manifest.  The
    ** question now is: which manifest should we use?
    **
    ** Let B be the number of F-cards in the baseline manifest and
    ** let D be the number of F-cards in the delta manifest, plus one for
    ** the B-card.  (B is held in the szB variable and D is held in the
    ** szD variable.)  Assume that all delta manifests adds X new F-cards.
    ** Then to minimize the total number of F- and B-cards in the repository,
    ** we should use the delta manifest if and only if:
    **
    **      D*D < B*X - X*X
    **
    ** X is an unknown here, but for most repositories, we will not be
    ** far wrong if we assume X=3.
    */
    ++szD /* account for the d->B card */;
    if(pBase){
      /* For this calculation, i believe the correct approach is to
         simply count the F-cards, including those changed between the
         baseline and the delta, as opposed to only those changed in
         the delta itself.
      */
      szD = 1 + d->F.used;
    }
    /* MARKER(("szB=%d szD=%d\n", (int)szB, (int)szD)); */
    if(pBase && (deltaPolicy<0/*non-force-mode*/
                 && !(((int)(szD*szD)) < (((int)szB*3)-9))
                 /* ^^^ see comments above */
                 )
       ){
      /* Too small of a delta to be worth it. Re-calculate
         F-cards with no baseline.

         Maintenance reminder: i initially wanted to update vfile's
         status incrementally as F-cards are calculated, but this
         discard/retry breaks on the retry because vfile's state has
         been modified. Thus instead of updating vfile incrementally,
         we re-scan it after the checkin completes.
      */
      fsl_deck tmp = fsl_deck_empty;
      /* Free up d->F using a kludge... */
      tmp.F = d->F;
      d->F = fsl_deck_empty.F;
      fsl_deck_finalize(&tmp);
      fsl_deck_B_set(d, NULL);
      /* MARKER(("Delta is too big - re-calculating F-cards for a baseline.\n")); */
      szD = 0;
      rc = fsl__checkin_calc_F_cards2(f, d, NULL, basedOnVid,
                                     &szD, opt);
      RC;
      if(basedOnVid && !szD){
        rc = fsl_cx_err_set(f, errNoFilesRc, errNoFilesMsg);
        goto end;
      }
    }
  }/* F-cards */

  /* parents... */
  if( basedOnVid ){
    char * zParentUuid = fsl_rid_to_artifact_uuid(f, basedOnVid, FSL_SATYPE_CHECKIN);
    if(!zParentUuid){
      assert(f->error.code);
      rc = f->error.code
        ? f->error.code
        : fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                         "Could not find checkin UUID "
                         "for RID %"FSL_ID_T_PFMT".",
                         basedOnVid);
      goto end;
    }
    rc = fsl_deck_P_add(d, zParentUuid)
      /* pedantic side-note: we could alternately transfer ownership
         of zParentUuid by fsl_list_append()ing it to d->P, but that
         would bypass e.g. any checking that routine chooses to apply.
      */;
    if( 0==rc ){
      rc = fsl__checkin_verify_younger(f, d, opt, basedOnVid, zParentUuid);
    }
    fsl_free(zParentUuid);
    /* if(!rc) rc = fsl_leaf_set(f, basedOnVid, 0); */
    RC;
    rc = fsl_db_prepare(dbC, &q, "SELECT merge FROM {{dbname.ckout}}.vmerge WHERE id=0 OR id<-2");
    RC;
    while( fsl__cx_stmt_step_each(f, &q, &rc) ){
      char *zMergeUuid;
      fsl_id_t const mid = fsl_stmt_g_id(&q, 0);
      //MARKER(("merging? %d\n", (int)mid));
      if( (mid == basedOnVid)
          || (!f->cache.markPrivate && fsl_content_is_private(f,mid))){
        continue;
      }
      zMergeUuid = fsl_rid_to_uuid(f, mid)
        /* FIXME? Adjust the query to join on blob and return the UUID? */
        ;
      //MARKER(("merging %d %s\n", (int)mid, zMergeUuid));
      if(zMergeUuid){
        rc = fsl_deck_P_add(d, zMergeUuid);
        if( 0==rc ){
          rc = fsl__checkin_verify_younger(f, d, opt, mid, zMergeUuid);
        }
        fsl_free(zMergeUuid);
      }else{
        /* fsl_rid_to_uuid() has set f's error state. */
        rc = f->error.code ? f->error.code : FSL_RC_OOM;
      }
      RC;
    }
    fsl_stmt_finalize(&q);
    RC;
  }

  { /* Q-cards... */
    rc = fsl_db_prepare(dbR, &q,
                        "SELECT "
                        "CASE vmerge.id WHEN -1 THEN '+' ELSE '-' END || mhash,"
                        "  merge"
                        "  FROM {{dbname.ckout}}.vmerge AS vmerge"
                        " WHERE vmerge.id IN (-1, -2)"
                        " ORDER BY 1");
    while( !rc && (fsl__cx_stmt_step_each(f, &q, &rc)) ){
      fsl_id_t const mid = fsl_stmt_g_id(&q, 1);
      /*
        The is-private check is taken from:

        https://fossil-scm.org/home/info/52a66829d655ff35dc52:

        noting that that patch also has (!g.markPrivate), a flag we do
        not currently have in fsl_cx but perhaps should, so that we
        can flag privacy at a higher level when doing a checkin. As of
        this writing (2023-02-02), we do not have any infrastructure
        for making private checkins.
      */
      if( mid != basedOnVid && !fsl_content_is_private(f, mid) ){
        const char *zCherrypickUuid = fsl_stmt_g_text(&q, 0, NULL);
        int const qType = '+'==*(zCherrypickUuid++) ? 1 : -1;
        rc = fsl_deck_Q_add( d, qType, zCherrypickUuid, NULL );
      }
    }
    fsl_stmt_finalize(&q);
    RC;
  }

  zColor = opt->bgColor;
  if(opt->branch && *opt->branch){
    char * sym = fsl_mprintf("sym-%s", opt->branch);
    if(!sym){
      rc = FSL_RC_OOM;
      goto end;
    }
    rc = fsl_deck_T_add( d, FSL_TAGTYPE_PROPAGATING,
                         NULL, sym, NULL );
    fsl_free(sym);
    RC;
    if(opt->bgColor && *opt->bgColor){
      zColor = NULL;
      rc = fsl_deck_T_add( d, FSL_TAGTYPE_PROPAGATING,
                           NULL, "bgcolor", opt->bgColor);
      RC;
    }
    rc = fsl_deck_T_add( d, FSL_TAGTYPE_PROPAGATING,
                         NULL, "branch", opt->branch );
    RC;
    if(basedOnVid){
      rc = fsl_cancel_sym_tags(d, basedOnVid);
      RC;
    }
  }
  if(zColor && *zColor){
    /* One-shot background color */
    rc = fsl_deck_T_add( d, FSL_TAGTYPE_ADD,
                         NULL, "bgcolor", opt->bgColor);
    RC;
  }

  if(opt->closeBranch){
    rc = fsl_deck_T_add( d, FSL_TAGTYPE_ADD,
                         NULL, "closed",
                         *opt->closeBranch
                         ? opt->closeBranch
                         : NULL);
    RC;
  }

  {
    /*
      Close any INTEGRATE merges if !op->integrate, or type-0 and
      integrate merges if opt->integrate.
    */
    rc = fsl_db_prepare(dbC, &q,
                        "SELECT mhash, merge FROM {{dbname.ckout}}.vmerge "
                        " WHERE id %s ORDER BY 1",
                        opt->integrate ? "IN(0,-4)" : "=(-4)");
    while( !rc && fsl__cx_stmt_step_each(f, &q, &rc) ){
      fsl_id_t const rid = fsl_stmt_g_id(&q, 1);
      //MARKER(("Integrating %d? opt->integrate=%d\n",(int)rid, opt->integrate));
      if( fsl_rid_is_leaf(f, rid)
          && !fsl_db_exists(dbR, /* Is not closed already... */
                            "SELECT 1 FROM {{dbname.repo}}.tagxref "
                            "WHERE tagid=%d AND rid=%"FSL_ID_T_PFMT
                            " AND tagtype>0",
                            FSL_TAGID_CLOSED, rid)){
        const char *zIntegrateUuid = fsl_stmt_g_text(&q, 0, NULL);
        //MARKER(("Integrating %d %s\n",(int)rid, zIntegrateUuid));
        rc = fsl_deck_T_add( d, FSL_TAGTYPE_ADD, zIntegrateUuid,
                             "closed", "Closed by integrate-merge." );
      }
    }
    fsl_stmt_finalize(&q);
    RC;
  }

  end:
#undef RC
  fsl_stmt_finalize(&q);
  fsl_deck_finalize(&dBase);
  assert(NULL==d->B.baseline || &dBase==d->B.baseline);
  d->B.baseline = NULL /* if it was set, it was &dBase */;
  if(rc && !f->error.code){
    if(dbR->error.code) fsl_cx_uplift_db_error(f, dbR);
    else if(dbC->error.code) fsl_cx_uplift_db_error(f, dbC);
    else if(f->dbMain->error.code) fsl_cx_uplift_db_error(f, f->dbMain);
  }
  return rc;
}

int fsl_checkin_T_add2( fsl_cx * f, fsl_card_T * t){
  /* The deck reports a rejected tag via its f member. */
  f->ckin.mf.f = f;
  return fsl_deck_T_add2( &f->ckin.mf, t );
}

int fsl_checkin_T_add( fsl_cx * f, fsl_tagtype_e tagType,
                       fsl_uuid_cstr uuid, char const * name,
                       char const * value){
  f->ckin.mf.f = f;
  return fsl_deck_T_add( &f->ckin.mf, tagType, uuid, name, value );
}

/**
   Returns true if the given blob RID is has a "closed" tag. This is
   generally intended only to be passed the RID of the current
   checkout, before attempting to perform a commit against it.
*/
static bool fsl_leaf_is_closed(fsl_cx * f, fsl_id_t rid){
  fsl_db * const dbR = fsl_needs_repo(f);
  return dbR
    ? fsl_db_exists(dbR, "SELECT 1 FROM {{dbname.repo}}.tagxref"
                    " WHERE tagid=%d "
                    " AND rid=%"FSL_ID_T_PFMT" AND tagtype>0",
                    FSL_TAGID_CLOSED, rid)
    : false;
}

/**
   Returns true if the given name is the current branch
   for the given checkin version.
 */
static bool fsl_is_current_branch(fsl_db * dbR, fsl_id_t vid,
                                  char const * name){
  return fsl_db_exists(dbR,
                       "SELECT 1 FROM {{dbname.repo}}.tagxref"
                       " WHERE tagid=%d AND rid=%"FSL_ID_T_PFMT
                       " AND tagtype>0"
                       " AND value=%Q",
                       FSL_TAGID_BRANCH, vid, name);
}

/**
   Interal helper for fsl_checkin_commit().

   Update vfile.isexe and vfile.islink to match d's F-cards. We should
   arguably do this while calculating the F-cards, as that would not
   require iterating over d's F-cards again, but having it here is
   currently simpler (and incidentally matches how fossil(1) does it).
*/
static int fsl__commit_update_exelink( fsl_cx * const f,
                                       fsl_db * const dbC,
                                       fsl_deck * const d ) {
  int rc = 0;
  fsl_stmt q = fsl_stmt_empty;
  fsl_card_F const * pFile = NULL;
  assert( dbC );
  assert( d->rid );
  /*
    For reference's sake, the fossil(1) counterpart code:

    // Update the isexe and islink columns of the vfile table
    db_prepare(&q,
      "UPDATE {{dbname.ckout}}.vfile SET isexe=:exec, islink=:link"
      " WHERE vid=:vid AND pathname=:path AND (isexe!=:exec OR islink!=:link)"
    );
    db_bind_int(&q, ":vid", nvid);
    pManifest = manifest_get(nvid, CFTYPE_MANIFEST, 0);
    manifest_file_rewind(pManifest);
    while( (pFile = manifest_file_next(pManifest, 0)) ){
      db_bind_int(&q, ":exec", pFile->zPerm && strstr(pFile->zPerm, "x"));
      db_bind_int(&q, ":link", pFile->zPerm && strstr(pFile->zPerm, "l"));
      db_bind_text(&q, ":path", pFile->zName);
      db_step(&q);
      db_reset(&q);
    }
    db_finalize(&q);
  */
  rc = fsl_db_prepare(
    dbC, &q,
    "UPDATE {{dbname.ckout}}.vfile SET isexe=?1, islink=?2 "
    "WHERE vid=?4 AND pathname=?3 AND (isexe!=?1 OR islink!=?2)"
    /* yes, ?4 and ?3 are intentionally out of order to simplify
       code below */
  );
  if(rc){
    fsl_cx_uplift_db_error(f, dbC);
    return rc;
  }
  fsl_stmt_bind_id(&q, 4, d->rid);
  rc = fsl_deck_F_rewind(d);
  fsl_deck_F_each(d, pFile, rc){
    rc = fsl_stmt_bind_fmt(
      &q, "iis",
      FSL_FILE_PERM_EXE==pFile->perm,
      FSL_FILE_PERM_LINK==pFile->perm,
      pFile->name
    );
    if(0==rc
       && FSL_RC_STEP_DONE==(rc = fsl_stmt_step(&q)) ){
      rc = fsl_stmt_reset(&q)
        /* sqlite3_reset() can, it turns out, fail after an
           UPDATE/INSERT step if a pending write of that step
           fails. */;
    }else{
      fsl_stmt_reset(&q);
    }
  }
  fsl_stmt_finalize(&q);
  if(rc) rc = fsl_cx_uplift_db_error2(f, dbC, rc);
  return rc;
}/* vfile.isexe/islink updates */

/**
   Returns 0 if db's journal mode and synchronous settings let SQLite
   commit a check-in to the repository and checkout dbs together: the
   checkout db in a rollback journal mode, the repository db in a rollback
   journal mode or in WAL mode at synchronous=FULL.
   Otherwise sets f's error state and returns FSL_RC_UNSUPPORTED. If
   both are tables of the host's main db, SQLite commits them together
   in any journal mode, so there is nothing to check.
*/
static int fsl__checkin_atomic_check(fsl_cx * const f, fsl_db * const db){
  static const fsl_dbrole_e aRole[] = {FSL_DBROLE_CKOUT, FSL_DBROLE_REPO};
  int rc = 0;
  unsigned i;
  if( 0==fsl_strcmp(fsl__db_schema(db, FSL_DBROLE_CKOUT),
                    fsl__db_schema(db, FSL_DBROLE_REPO)) ){
    return 0;
  }
  for( i = 0; 0==rc && i < sizeof(aRole)/sizeof(aRole[0]); ++i ){
    char const * const zSchema = fsl__db_schema(db, aRole[i]);
    char * zMode = NULL;
    int32_t nSync = -1;
    bool isWal;
    rc = fsl_db_get_text(db, &zMode, NULL, "PRAGMA %s.journal_mode",
                         zSchema);
    if( 0==rc ){
      rc = fsl_db_get_int32(db, &nSync, "PRAGMA %s.synchronous", zSchema);
    }
    if( rc ){
      fsl_free(zMode);
      break;
    }
    isWal = zMode && 0==fsl_stricmp(zMode, "wal");
    if( !zMode || 0==fsl_stricmp(zMode, "memory")
        || 0==fsl_stricmp(zMode, "off") || 0==nSync
        || (isWal && (FSL_DBROLE_CKOUT==aRole[i] || nSync<2)) ){
      rc = fsl_cx_err_set(f, FSL_RC_UNSUPPORTED,
                          "Cannot check in with the %s db in %s journal "
                          "mode at synchronous=%d: SQLite would not "
                          "commit the repository and checkout dbs "
                          "together.", zSchema, zMode ? zMode : "unknown",
                          (int)nSync);
    }
    fsl_free(zMode);
  }
  if( rc && !f->error.code ) rc = fsl_cx_uplift_db_error2(f, db, rc);
  return rc;
}

int fsl_checkin_commit(fsl_cx * f, fsl_checkin_opt const * opt,
                       fsl_id_t * newRid, fsl_uuid_str * newUuid ){
  int rc;
  fsl_deck deck = fsl_deck_empty;
  fsl_deck *d = &deck;
  fsl_db * dbC;
  fsl_db * dbR;
  bool inTrans = 0;
  bool oldPrivate;
  int const oldFlags = f ? f->flags : 0;
  fsl_id_t const vid = f ? f->db.ckout.rid : 0;
#if FSL_API_ARMOR
  if(!f || !opt) return FSL_RC_MISUSE;
  else
#endif
  if(!(dbC = fsl_needs_ckout(f))) return FSL_RC_NOT_A_CKOUT;
  else if(!(dbR = fsl_needs_repo(f))) return FSL_RC_NOT_A_REPO;
  assert(vid>=0);
  rc = fsl__checkin_atomic_check(f, dbC);
  if( rc ) return rc;

  /* Testing dry-run */
  if( opt->dryRun ){
    MARKER(("WARNING: dry-run mode of checkin is not yet "
            "working due to a stale cache bug\n"));
  }

  /**
     Do not permit a checkin to a closed leaf unless opt->branch would
     switch us to a new branch.
  */
  if( fsl_leaf_is_closed(f, vid)
      && (!opt->branch || !*opt->branch
          || fsl_is_current_branch(dbR, vid, opt->branch))){
    /* This is arguably being too strict, but it's normally the
       behavior we want. We could add a force flag to skip this. No
       harm is done if a closed leaf is derived from, and it's
       actually easy to do by syncing with a remote in which such a
       commit is made on top of that (what was formerly) a local
       closed leaf. We don't _generally_ want it do be possible on
       interactive checkins, though. This strict approach means that
       users will have to first re-open the branch (remove the
       'closed' tag) to be able to commit, which is not great UX.

       TODO, then, is to add a fsl_checkin_opt::iAmChuckNorris flag
       which decides the policy here.
    */
    return fsl_cx_err_set(f, FSL_RC_ACCESS,
                          "Cannot commit against a closed leaf "
                          "(checkout version rid %" FSL_ID_T_PFMT
                          ").", vid);
  }

  if(vid && opt->scanForChanges){
    /* We need to ensure this state is current in order to determine
       whether a given file is locally modified vis-a-vis the
       commit-time vfile state. */
    rc = fsl_vfile_changes_scan(f, vid, 0);
    if(rc) return rc;
  }

  fsl_cx_err_reset(f) /* avoid propagating an older error by accident.
                         Did that in test code. */;
  oldPrivate = f->cache.markPrivate;
  if(!f->cache.markPrivate
     && (opt->isPrivate || fsl_content_is_private(f, vid))){
    f->cache.markPrivate = true;
  }

#define RC if(rc) goto end

  fsl_deck_init(f, d, FSL_SATYPE_CHECKIN);
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO | FSL_DBROLE_CKOUT);
  RC;
  inTrans = true;
  //TODO (2025-08-06): assert( fsl_cx_txn_level(f)>0 );
  if(f->ckin.mf.T.used){
    /* Transfer accumulated tags. */
    assert(!f->ckin.mf.content.used);
    d->T = f->ckin.mf.T;
    f->ckin.mf.T = fsl_deck_empty.T;
  }
  rc = fsl__checkin_calc_manifest(f, d, vid, opt);
  RC;
  if(!d->F.used){
    rc = fsl_cx_err_set(f, FSL_RC_NOOP,
                        "Cowardly refusing to generate an empty commit.");
    RC;
  }

  if(opt->calcRCard) f->flags |= FSL_CX_F_CALC_R_CARD;
  else f->flags &= ~FSL_CX_F_CALC_R_CARD;
  rc = fsl_deck_save( d, opt->isPrivate || f->cache.markPrivate );
  RC;
  assert(d->rid>0);
  /* Now get vfile back into shape. We do not do a vfile scan
     because that loses state like add/rm-queued files. */
  rc = fsl_db_exec_multi(dbC,
                         "DELETE FROM {{dbname.ckout}}.vfile WHERE vid<>"
                         "%" FSL_ID_T_PFMT ";"
                         "UPDATE {{dbname.ckout}}.vfile SET vid=%" FSL_ID_T_PFMT ";"
                         "DELETE FROM {{dbname.ckout}}.vfile WHERE deleted AND "
                         "fsl_is_enqueued(id); "
                         "UPDATE {{dbname.ckout}}.vfile SET rid=mrid, mhash=NULL, "
                         "chnged=0, deleted=0, origname=NULL "
                         "WHERE fsl_is_enqueued(id)",
                         vid, d->rid);
  if( rc ){
    fsl_cx_uplift_db_error2(f, dbC, rc);
    goto end;
  }
  if(!rc) rc = fsl__ckout_version_write(f, d->rid, NULL);
  RC;
  assert(d->f == f);
  rc = fsl__unsent_rid_add(f, d->rid);
  RC;
  rc = fsl__ckout_clear_merge_state(f, FSL__MERGE_CLEAR_ALL);
  RC;
  rc = fsl__commit_update_exelink(f, dbC, d);
  RC;
  /*
    todo(?) from fossil(1) follows. Most of this seems to be what the
    vfile handling does (above).

    db_multi_exec("PRAGMA %s.application_id=252006673;", db_name("repository"));
    db_multi_exec("PRAGMA %s.application_id=252006674;", db_name("localdb"));

    // Update the vfile and vmerge tables
    db_multi_exec(
      "DELETE FROM {{dbname.ckout}}.vfile WHERE (vid!=%d OR deleted) AND is_selected(id);"
      "DELETE FROM {{dbname.ckout}}.vmerge;"
      "UPDATE {{dbname.ckout}}.vfile SET vid=%d;"
      "UPDATE {{dbname.ckout}}.vfile SET rid=mrid, chnged=0, deleted=0, origname=NULL"
      " WHERE is_selected(id);"
      , vid, nvid
    );
    db_lset_int("checkout", nvid);
  */

  if(opt->dumpManifestFile){
    FILE * out;
    /* MARKER(("Dumping generated manifest to file [%s]:\n", opt->dumpManifestFile)); */
    out = fsl_fopen(opt->dumpManifestFile, "w");
    if(out){
      rc = fsl_deck_output( d, fsl_output_f_FILE, out );
      fsl_fclose(out);
    }else{
      rc = fsl_cx_err_set(f, FSL_RC_IO, "Could not open output "
                          "file for writing: %s", opt->dumpManifestFile);
    }
    RC;
  }
  //fsl__id_bag_dump(&f->cache.toVerify, NULL, "checkin pre-end");

#undef RC
  end:

  f->flags = oldFlags;
  f->cache.markPrivate = oldPrivate;
  /* fsl_b_reuse(&f->fileContent); */
  if(inTrans){
    if(rc) fsl_cx_txn_end_v2(
      f, false, false/*2026-06-18: why is this false?*/
    );
    else{
      rc = fsl_cx_txn_end_v2(f, !opt->dryRun, false);
      if(!rc){
        if( opt->dryRun ){
          /* We need to roll back manifest file changes to avoid
             potential major confusion later. Ignore errors in this
             step, as failure to update this file is (A) outstandingly
             rare and (B) not relevant to the SCM's workings. This has
             to come _after_ the rollback and it won't work unless the
             checkout ID is first reverted back to its pre-call
             state.

             f-ci.c does something similar (or did before this
             function started doing it).
          */
          fsl__ckout_version_write(f, vid, NULL);
          fsl_ckout_manifest_write(f, -1, -1, -1, 0);
        }
        if(newRid) *newRid = d->rid;
        if(newUuid){
          if(NULL==(*newUuid = fsl_rid_to_uuid(f, d->rid))){
            rc = f->error.code ? f->error.code : FSL_RC_OOM;
          }
        }
      }
    }
  }
  if(rc && !f->error.code){
    if(f->dbMain->error.code) fsl_cx_uplift_db_error(f, f->dbMain);
    else fsl_cx_err_set(f, rc, "Check-in failed with %R.", rc);
  }
  fsl_checkin_discard(f);
  fsl_deck_finalize(d);
  return rc;
}/*fsl_checkin_commit()*/


#undef MARKER
/* end of file src/checkin.c */
/* start of file src/checkout.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*
  *****************************************************************************
  This file houses the code for checkout-level APIS.
*/
#include <assert.h>

#include <string.h> /* memcmp() */

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

/**
    Kludge for type-safe strncmp/strnicmp inconsistency.
*/
static int fsl_strnicmp_int(char const *zA, char const * zB, fsl_size_t nByte){
  return fsl_strnicmp( zA, zB, (fsl_int_t)nByte);
}

int fsl_ckout_filename_check( fsl_cx * const f, bool relativeToCwd,
                              char const * zOrigName, fsl_b * const pOut ){
  int rc;
  if(!zOrigName || !*zOrigName){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Empty file name passed to %s().", __func__);
  }else if(!fsl_needs_ckout(f)/* will update f's error state*/){
    return FSL_RC_NOT_A_CKOUT;
  }
#if 0
  /* Is this sane? */
  else if(fsl_is_simple_pathname(zOrigName,1)){
    rc = 0;
    if(pOut){
      rc = fsl_b_append(pOut, zOrigName, fsl_strlen(zOrigName));
    }
  }
#endif
  else{
    char const * zLocalRoot;
    char const * zFull;
    fsl_size_t nLocalRoot;
    fsl_size_t nFull = 0;
    fsl_b * const full = fsl__cx_scratchpad(f);
    int (*xCmp)(char const *, char const *,fsl_size_t);
    bool endsWithSlash;
    assert(f->db.ckout.dir);
    zLocalRoot = f->db.ckout.dir;
    assert(zLocalRoot);
    assert(*zLocalRoot);
    nLocalRoot = f->db.ckout.dirLen;
    assert(nLocalRoot);
    assert('/' == zLocalRoot[nLocalRoot-1]);
    rc = fsl_file_canonical_name2(relativeToCwd ? NULL : zLocalRoot,
                                  zOrigName, full, 1);
#if 0
    MARKER(("canon2: %p (%s) %s ==> %s\n", (void const *)full->mem,
            relativeToCwd ? "cwd" : "ckout", zOrigName, fsl_b_cstr(full)));
#endif
    if(rc){
      if(FSL_RC_OOM != rc){
        rc = fsl_cx_err_set(f, rc, "Error %R canonicalizing "
                            "file name: %s",
                            rc, zOrigName);
      }
      goto end;
    }
    zFull = fsl_b_cstr2(full, &nFull);
    xCmp = fsl_cx_is_case_sensitive(f,false)
      ? fsl_strncmp
      : fsl_strnicmp_int;
    assert(zFull);
    assert(nFull>0);
    endsWithSlash = '/' == zFull[nFull-1];
    if( ((nFull==nLocalRoot-1 || (nFull==nLocalRoot && endsWithSlash))
         && xCmp(zLocalRoot, zFull, nFull)==0)
        || (nFull==1 && zFull[0]=='/' && nLocalRoot==1 && zLocalRoot[0]=='/') ){
      /* Special case.  zOrigName refers to zLocalRoot directory.

         Outputing "." instead of nothing is a historical decision
         which may be worth re-evaluating. Currently fsl_cx_stat() relies
         on it.
      */
      if(pOut){
        char const * zOut;
        fsl_size_t nOut;
        if(endsWithSlash){ /* retain trailing slash */
          zOut = "./";
          nOut = 2;
        }else{
          zOut = ".";
          nOut = 1;
        };
        rc = fsl_b_append(pOut, zOut, nOut);
      }else{
        rc = 0;
      }
      goto end;
    }

    if( nFull<=nLocalRoot || xCmp(zLocalRoot, zFull, nLocalRoot) ){
      rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                          "File is outside of checkout tree: %s",
                          zOrigName);
      goto end;
    }

    if(pOut){
      rc = fsl_b_append(pOut, zFull + nLocalRoot, nFull - nLocalRoot);
    }

    end:
    fsl__cx_scratchpad_yield(f, full);
  }
  return rc;
}


/**
    Returns a fsl_ckout_change_e value for the given
    fsl_vfile_change_e value.

    Why are these not consolidated into one enum?  2021-03-13: because
    there are more checkout-level change codes than vfile-level
    changes. We could still consolidate them, giving the vfile changes
    their hard-coded values and leaving room in the enum for upward
    growth of that set.
*/
static fsl_ckout_change_e fsl__vfile_to_ckout_change(int vChange){
  switch((fsl_vfile_change_e)vChange){
#define EE(X) case FSL_VFILE_CHANGE_##X: return FSL_CKOUT_CHANGE_##X
    EE(NONE);
    EE(MOD);
    EE(MERGE_MOD);
    EE(MERGE_ADD);
    EE(INTEGRATE_MOD);
    EE(INTEGRATE_ADD);
    EE(IS_EXEC);
    EE(BECAME_SYMLINK);
    EE(NOT_EXEC);
    EE(NOT_SYMLINK);
#undef EE
    default:
       assert(!"Unhandled fsl_vfile_change_e value!");
      return FSL_CKOUT_CHANGE_NONE;
  }
}

int fsl_ckout_changes_visit( fsl_cx * f, fsl_id_t vid,
                             bool doScan,
                             fsl_ckout_changes_f visitor,
                             void * state ){
  int rc;
  fsl_db * db;
  fsl_stmt st = fsl_stmt_empty;
  fsl_ckout_change_e coChange;
  fsl_fstat fstat;
  if(!f || !visitor) return FSL_RC_MISUSE;
  db = fsl_needs_ckout(f);
  if(!db) return FSL_RC_NOT_A_CKOUT;
  if(vid<0){
    vid = f->db.ckout.rid;
    assert(vid>=0);
  }
  if(doScan){
    rc = fsl_vfile_changes_scan(f, vid, 0);
    if(rc) goto end;
  }
  rc = fsl_db_prepare(db, &st,
                      "SELECT chnged, deleted, rid, "
                      "pathname, origname "
                      "FROM {{dbname.ckout}}.vfile WHERE vid=%" FSL_ID_T_PFMT
                      " /*%s()*/",
                      vid,__func__);
  assert(!rc);
  while( fsl__cx_stmt_step_each(f, &st, &rc) ){
    int const changed = fsl_stmt_g_int32(&st, 0);
    int const deleted = fsl_stmt_g_int32(&st,1);
    fsl_id_t const vrid = fsl_stmt_g_id(&st,2);
    char const * name;
    char const * oname = NULL;
    name = fsl_stmt_g_text(&st, 3, NULL);
    oname = fsl_stmt_g_text(&st,4,NULL);
    if(oname && (0==fsl_strcmp(name, oname))){
      /* Work around a fossil oddity which sets origname=pathname
         during a 'mv' operation.
      */
      oname = NULL;
    }
    coChange = FSL_CKOUT_CHANGE_NONE;
    if(deleted){
      coChange = FSL_CKOUT_CHANGE_REMOVED;
    }else if(0==vrid){
      coChange = FSL_CKOUT_CHANGE_ADDED;
    }else if(!changed && NULL != oname){
      /* In fossil ^^, the "changed" state trumps the "renamed" state
       for status view purposes, so we'll do that here. */
      coChange = FSL_CKOUT_CHANGE_RENAMED;
    }else{
      fstat = fsl_fstat_empty;
      if( fsl_cx_stat(f, false, name, &fstat ) ){
        coChange = FSL_CKOUT_CHANGE_MISSING;
        fsl_cx_err_reset(f) /* keep FSL_RC_NOT_FOUND from bubbling
                               up to the client! */;
      }else if(FSL_FSTAT_TYPE_FILE!=fstat.type
               && FSL_FSTAT_TYPE_LINK!=fstat.type){
        /* As fossil(1)'s status_report(): it exists but is not
           a file or link. */
        coChange = FSL_CKOUT_CHANGE_NOT_A_FILE;
      }else if(!changed){
        continue;
      }else{
        coChange = fsl__vfile_to_ckout_change(changed);
      }
    }
    if(!coChange){
      MARKER(("INTERNAL ERROR: unhandled vfile.chnged "
              "value %d for file [%s]\n",
              changed, name));
      continue;
    }
    rc = visitor(state, coChange, name, oname);
    if(rc){
      if(FSL_RC_BREAK==rc){
        rc = 0;
        break;
      }else if(!f->error.code && (FSL_RC_OOM!=rc)){
        fsl_cx_err_set(f, rc, "Error %s returned from changes callback.",
                       fsl_rc_cstr(rc));
      }
      break;
    }
  }
  end:
  fsl_stmt_finalize(&st);
  if(rc && db->error.code && !f->error.code){
    fsl_cx_uplift_db_error(f, db);
  }

  return rc;
}

static bool fsl_co_is_in_vfile(fsl_cx *f,
                               char const *zFilename){
  return fsl_db_exists(fsl_cx_db_ckout(f),
                       "SELECT 1 FROM {{dbname.ckout}}.vfile"
                       " WHERE vid=%"FSL_ID_T_PFMT
                       " AND pathname=%Q %s",
                       f->db.ckout.rid, zFilename,
                       fsl_cx_filename_collation(f));
}


/** Initialized-with-defaults fsl_ckout_manage_state structure, intended for
    const-copy initialization. */
#define fsl_ckout_manage_state_empty_m {NULL,NULL,NULL}
/** Initialized-with-defaults fsl_ckout_manage_state structure, intended for
    non-const copy initialization. */
static const fsl_ckout_manage_state fsl_ckout_manage_state_empty
= fsl_ckout_manage_state_empty_m;

/**
   Internal machinery for fsl_ckout_manage(). zFilename MUST
   be a checkout-relative file which is known to exist. fst MUST
   be an object populated by fsl__cfs_stat(f, )'ing zFilename. isInVFile
   MUST be the result of having passed zFilename to fsl_co_is_in_vfile().
 */
static int fsl_ckout_manage_impl(fsl_cx * const f, char const *zFilename,
                                 fsl_fstat const *fst,
                                 bool isInVFile){
  int rc = 0;
  fsl_db * const db = fsl_needs_ckout(f);
  assert(fsl_is_simple_pathname(zFilename, true));
  if( isInVFile ){
    rc = fsl_db_exec(db, "UPDATE {{dbname.ckout}}.vfile SET deleted=0,"
                     " mtime=%"PRIi64
                     " WHERE vid=%"FSL_ID_T_PFMT
                     " AND pathname=%Q %s",
                     (int64_t)fst->mtime,
                     f->db.ckout.rid, zFilename,
                     fsl_cx_filename_collation(f));
  }else{
    int const chnged = FSL_VFILE_CHANGE_MOD
      /* fossil(1) sets chnged=0 on 'add'ed vfile records, but then the 'status'
         command updates the field to 1. To avoid down-stream inconsistencies
         (such as the ones which lead me here), we'll go ahead and set it to
         1 here.
      */;
    rc = fsl_db_exec(db,
                     "INSERT INTO "
                     "{{dbname.ckout}}.vfile(vid,chnged,deleted,rid,mrid,pathname,isexe,islink,mtime)"
                     "VALUES(%"FSL_ID_T_PFMT",%d,0,0,0,%Q,%d,%d,%"PRIi64")",
                     f->db.ckout.rid, chnged, zFilename,
                     (FSL_FSTAT_PERM_EXE==fst->perm) ? 1 : 0,
                     (FSL_FSTAT_TYPE_LINK==fst->type) ? 1 : 0,
                     (int64_t)fst->mtime
                     );
  }
  if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  return rc;
}

/**
   Internal state for the recursive file-add process.
*/
struct CoAddState {
  fsl_cx * f;
  fsl_ckout_manage_opt * opt;
  fsl_b * absBuf; // absolute path of file to check
  fsl_b * coRelBuf; // checkout-relative path of absBuf
  fsl_fstat fst; // fsl__cfs_stat(f, ) state of absBuf's file
};
typedef struct CoAddState CoAddState;
static const CoAddState CoAddState_empty =
  {NULL, NULL, NULL, NULL, fsl_fstat_empty_m};

/**
   fsl_dircrawl_f() impl for recursively adding files to a
   repo. state must be a (CoAddState*)/
*/
static int fsl_dircrawl_f_add(fsl_dircrawl_state const *);

/**
   Attempts to add file or directory (recursively) cas->absBuf to the
   current repository. isCrawling must be true if this is a
   fsl__cfs_dircrawl(f, )-invoked call, else false.
*/
static int fsl__ckout_nondir_file_check(fsl_cx *f, char const * zFilename,
                                        fsl_size_t * errLen)
  /* Documented and defined further down. */;
static int co_add_one(CoAddState * const cas, bool isCrawling){
  int rc = 0;
  fsl_b_reuse(cas->coRelBuf);
  rc = fsl_cx_stat2(cas->f, cas->opt->relativeToCwd,
                    fsl_b_cstr(cas->absBuf), &cas->fst,
                    fsl_b_reuse(cas->coRelBuf), false)
    /* Reminder: will fail if file is outside of the checkout tree */;
  if(rc) return rc;
  if(FSL_FSTAT_TYPE_DIR==cas->fst.type
     && !fsl_cx_allows_symlinks(cas->f, false)){
    /* Without allow-symlinks, fsl_cx_stat2() reports a symlink to a
       directory as that directory. fossil(1) refuses to add anything
       beneath a symlink (file_nondir_objects_on_path()), so don't
       crawl it. */
    fsl_b * const full = fsl_cx_b_borrow(cas->f);
    bool isLink = false;
    if(!full) return cas->f->error.code;
    rc = fsl_b_appendf(full, "%s%b", cas->f->db.ckout.dir, cas->coRelBuf);
    if(!rc) isLink = fsl__cfs_is_symlink(cas->f, fsl_b_cstr(full));
    fsl_cx_b_return(cas->f, full);
    if(rc) return rc;
    if(isLink){
      return fsl_cx_err_set(cas->f, FSL_RC_TYPE, "Cannot add symlink %b: "
                            "the allow-symlinks setting is off and it "
                            "points to a directory.", cas->coRelBuf);
    }
  }
  switch(cas->fst.type){
    case FSL_FSTAT_TYPE_LINK:
      /* fsl_cx_stat2() reports a link only with allow-symlinks, and
         then it is added as itself. */
    case FSL_FSTAT_TYPE_FILE:{
      bool skipped = false;
      /**
         Potential TODO: integrate fsl_filename_preferred_case() here,
         to properly case both the being-added file name AND the
         directory leading up to it, noting that the latter part has
         to be done somewhere above this call.  Currently we require
         the client to pass in file names already translated with that
         routine, if needed.
      */
      char const * zCoRel = fsl_b_cstr(cas->coRelBuf);
      bool const isInVFile = fsl_co_is_in_vfile(cas->f, zCoRel);
      if(!isInVFile){
        if(fsl_reserved_fn_check(cas->f, zCoRel,-1,false)){
          /* ^^^ we need to use fsl_reserved_fn_check(), instead of
             fsl_is_reserved_fn(), so that we will inherit any
             new checks which require a context object. If that
             check fails, though, it updates cas->f with an error
             message which we need to suppress here to avoid it
             accidentally propagating and causing downstream
             confusion. */
          fsl_cx_err_reset(cas->f);
          skipped = true;
        }else if(cas->opt->checkIgnoreGlobs){
          char const * m =
            fsl_cx_glob_matches(cas->f, FSL_GLOBS_IGNORE, zCoRel);
          if(m) skipped = true;
        }
        if(!skipped){
          /* As fossil(1)'s add_one_file(): skip a file which has a
             symlink, or any other non-directory, in its directory
             part (file_nondir_objects_on_path()). */
          fsl_size_t errLen = 0;
          fsl_b * const full = fsl_cx_b_borrow(cas->f);
          if(!full){
            rc = cas->f->error.code;
            goto end;
          }
          rc = fsl_b_appendf(full, "%s%s", cas->f->db.ckout.dir, zCoRel);
          if(!rc){
            rc = fsl__ckout_nondir_file_check(cas->f, fsl_b_cstr(full),
                                              &errLen);
          }
          fsl_cx_b_return(cas->f, full);
          if(rc) goto end;
          if(errLen) skipped = true;
        }
        if(!skipped && cas->opt->callback){
          bool yes = false;
          fsl_ckout_manage_state mst = fsl_ckout_manage_state_empty;
          mst.opt = cas->opt;
          mst.filename = zCoRel;
          mst.f = cas->f;
          rc = cas->opt->callback( &mst, &yes );
          if(rc){
            if(!cas->f->error.code && FSL_RC_OOM!=rc){
              rc = fsl_cx_err_set(cas->f, rc, "Error %R returned from "
                                  "add callback for file: %s",
                                  rc, zCoRel);
            }
            goto end;
          }
          else if(!yes) skipped = true;
        }
      }
      if(skipped){
        ++cas->opt->counts.skipped;
      }else{
        rc = fsl_ckout_manage_impl(cas->f, zCoRel, &cas->fst,
                                        isInVFile);
        if(!rc){
          if(isInVFile) ++cas->opt->counts.updated;
          else ++cas->opt->counts.added;
        }
      }
      break;
    }
    case FSL_FSTAT_TYPE_DIR:
      if(!isCrawling){
        /* Reminder to self: fsl_dircrawl() copies its first argument
           for canonicalizing it, so this is safe even though
           cas->absBuf may be reallocated during the recursive
           call. We're done with these particular contents of
           cas->absBuf at this point. */
        rc = fsl__cfs_dircrawl(cas->f, fsl_b_cstr(cas->absBuf),
                          fsl_dircrawl_f_add, cas);
        if(rc && !cas->f->error.code && FSL_RC_OOM!=rc){
          /* On a directory-level failure, absBuf holds the directory
             fsl__cfs_dircrawl(f, ) was entering. */
          rc = fsl_cx_err_set(cas->f, rc, "Error %R while scanning "
                              "directory: %b", rc, cas->absBuf);
        }
      }else{
        assert(!"Cannot happen - caught higher up");
        fsl__fatal(FSL_RC_ERROR, "Internal API misuse in/around %s().",
                  __func__);
      }
      break;
    default:
      rc = fsl_cx_err_set(cas->f, FSL_RC_TYPE,
                          "Unhandled filesystem entry type "
                          "(fsl_fstat_type_e #%d) for file: %b",
                          cas->fst.type, cas->absBuf);
      break;
  }
  end:
  return rc;
}

/**
   fsl_dircrawl_f() impl for fsl_ckout_manage().
*/
static int fsl_dircrawl_f_add(fsl_dircrawl_state const *dst){
  switch(dst->entryType){
    case FSL_FSTAT_TYPE_DIR:
    case FSL_FSTAT_TYPE_LINK:
    case FSL_FSTAT_TYPE_FILE:{
      CoAddState * const cas = (CoAddState*)dst->callbackState;
      int const rc = fsl_b_appendf(fsl_b_reuse(cas->absBuf),
                                        "%s/%s", dst->absoluteDir, dst->entryName);
      if(rc) return rc;
      switch(dst->entryType){
        case FSL_FSTAT_TYPE_DIR:
          return fsl_is_top_of_ckout(fsl_b_cstr(cas->absBuf))
            /* Never recurse into nested checkouts */
            ? FSL_RC_NOOP : 0;
        case FSL_FSTAT_TYPE_LINK:
          if(!fsl_cx_allows_symlinks(cas->f, false)){
            /* Without allow-symlinks, fossil(1)'s vfile_scan() and
               add_one_file() add a link to a file as that file,
               ignore a dangling link, and refuse everything beneath
               a link to a directory. Skipping the other links here
               adds the same files. */
            fsl_fstat tgt = fsl_fstat_empty;
            if(fsl__cfs_stat(cas->f, fsl_b_cstr(cas->absBuf), &tgt, true)
               || FSL_FSTAT_TYPE_FILE!=tgt.type){
              return 0;
            }
          }
          /* fall through */
        case FSL_FSTAT_TYPE_FILE:
          return co_add_one(cas, true);
        default:
          fsl__fatal(FSL_RC_ERROR,"Not possible: caught above.");
          return 0;
      }
    }
    default:
      return 0;
  }
}

/**
   Returns true if the absolute path zAbsName is f->db.ckout.dir, disregarding
   an optional trailing slash on zAbsName.
*/
static bool fsl__is_ckout_dir(fsl_cx * const f, char const * const zAbsName){
  /* Keeping in mind that f->db.ckout.dir is always slash-terminated...*/
  assert(f->db.ckout.dirLen>0);
  return (0==fsl_strncmp(zAbsName, f->db.ckout.dir, f->db.ckout.dirLen-1)
          && 0==zAbsName[f->db.ckout.dirLen-1]
          /* ==> matches except that zAbsName is NUL-terminated where
             ckout.dir has a trailing slash. */)
    || 0==fsl_strcmp(zAbsName, f->db.ckout.dir);
}

int fsl_ckout_manage( fsl_cx * const f, fsl_ckout_manage_opt * const opt_ ){
  int rc = 0;
  CoAddState cas = CoAddState_empty;
  fsl_ckout_manage_opt opt;
  if(!f) return FSL_RC_MISUSE;
  else if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  assert(f->db.ckout.rid>=0);
  opt = *opt_
    /*use a copy in case the user manages to modify
      opt_ from a callback. */;
  cas.absBuf = fsl__cx_scratchpad(f);
  cas.coRelBuf = fsl__cx_scratchpad(f);
  rc = fsl_file_canonical_name2(opt.relativeToCwd ? NULL : f->db.ckout.dir,
                                opt.filename, cas.absBuf, false);
  if(rc){
    if(FSL_RC_OOM!=rc){
      rc = fsl_cx_err_set(f, rc, "Error %R canonicalizing file name: %s",
                          rc, opt.filename);
    }
  }else{
    char const * const zAbs = fsl_b_cstr(cas.absBuf);
    if(!fsl_is_top_of_ckout(zAbs) || fsl__is_ckout_dir(f, zAbs)){
      cas.f = f;
      cas.opt = &opt;
      rc = co_add_one(&cas, false);
      opt_->counts = opt.counts;
    }
  }
  fsl__cx_scratchpad_yield(f, cas.absBuf);
  fsl__cx_scratchpad_yield(f, cas.coRelBuf);
  return rc;
}

/**
   Creates, if needed, a TEMP TABLE named [tableName] with a single
   [id] field and populates it with all ids from the given bag.

   Returns 0 on success, any number of non-0 codes on error.
*/
static int fsl__ckout_bag_to_ids(fsl_cx * const f, fsl_db * const db,
                                 char const * tableName,
                                 fsl_id_bag const * bag){
  /* tableName is a {{temp.NAME}} placeholder, which must be in the
     format strings to be expanded for db's context. */
  fsl_stmt insId = fsl_stmt_empty;
  char * const zCreate = fsl_mprintf("CREATE TEMP TABLE IF NOT EXISTS "
                                     "%s(id); DELETE FROM %s /* %s() */;",
                                     tableName, tableName, __func__);
  char * const zInsert = fsl_mprintf("INSERT INTO %s(id) values(?1) "
                                     "/* %s() */", tableName, __func__);
  int rc = (zCreate && zInsert) ? 0 : FSL_RC_OOM;
  if(0==rc) rc = fsl_db_exec_multi(db, zCreate);
  if(0==rc) rc = fsl_db_prepare(db, &insId, zInsert);
  fsl_free(zCreate);
  fsl_free(zInsert);
  if(FSL_RC_OOM==rc) return fsl_cx_err_set(f, rc, NULL);
  if(rc) goto dberr;
  for(fsl_id_t e = fsl_id_bag_first(bag);
      e; e = fsl_id_bag_next(bag, e)){
    fsl_stmt_bind_id(&insId, 1, e);
    rc = fsl_stmt_step(&insId);
    switch(rc){
      case FSL_RC_STEP_DONE:
        rc = 0;
        break;
      default:
        fsl_stmt_finalize(&insId);
        goto dberr;
    }
    fsl_stmt_reset(&insId);
  }
  assert(!rc);
  end:
  fsl_stmt_finalize(&insId);
  return rc;
  dberr:
  assert(rc);
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  goto end;
}

/** Initialized-with-defaults fsl_ckout_unmanage_state structure, intended for
    const-copy initialization. */
#define fsl_ckout_unmanage_state_empty_m {NULL,NULL,NULL}
/** Initialized-with-defaults fsl_ckout_unmanage_state structure, intended for
    non-const copy initialization. */
static const fsl_ckout_unmanage_state fsl_ckout_unmanage_state_empty
= fsl_ckout_unmanage_state_empty_m;

int fsl_ckout_unmanage(fsl_cx * const f, fsl_ckout_unmanage_opt const * opt){
  int rc;
  fsl_db * const db = fsl_needs_ckout(f);
  fsl_b * fname = 0;
  fsl_id_t const vid = f->db.ckout.rid;
  fsl_stmt q = fsl_stmt_empty;
  bool inTrans = false;
  if(!db) return FSL_RC_NOT_A_CKOUT;
  else if((!opt->filename || !*opt->filename)
          && !opt->vfileIds){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Empty file set is not legal for %s()",
                          __func__);
  }
  assert(vid>=0);
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) goto dberr;
  inTrans = true;
  if(opt->vfileIds){
    rc = fsl__ckout_bag_to_ids(f, db, "{{temp.fx_unmanage_id}}",
                               opt->vfileIds);
    if(rc) goto end;
    rc = fsl_db_exec(db,
                     "UPDATE {{dbname.ckout}}.vfile SET deleted=1 "
                     "WHERE vid=%" FSL_ID_T_PFMT " "
                     "AND NOT deleted "
                     "AND id IN {{temp.fx_unmanage_id}} /* %s() */",
                     vid, __func__);
    if(rc) goto dberr;
    if(opt->callback){
      rc = fsl_db_prepare(db,&q,
                          "SELECT pathname FROM {{dbname.ckout}}.vfile "
                          "WHERE vid=%" FSL_ID_T_PFMT " "
                          "AND deleted "
                          "AND id IN {{temp.fx_unmanage_id}} "
                          "/* %s() */",
                          vid, __func__);
      if(rc) goto dberr;
    }
  }else{// Process opt->filename
    fname = fsl__cx_scratchpad(f);
    rc = fsl_ckout_filename_check(f, opt->relativeToCwd,
                                  opt->filename, fname);
    if(rc) goto end;
    char const * zNorm = fsl_b_cstr(fname);
    /* MARKER(("fsl_ckout_unmanage(%d, %s) ==> %s\n", relativeToCwd, zFilename, zNorm)); */
    assert(zNorm);
    if(fname->used){
      fsl_b_strip_slashes(fname);
      if(1==fname->used && '.'==*zNorm){
        /* Special case: handle "." from ckout root intuitively */
        fsl_b_reuse(fname);
        assert(0==*zNorm);
      }
    }
    rc = fsl_db_exec(db,
                     "UPDATE {{dbname.ckout}}.vfile SET deleted=1 "
                     "WHERE vid=%" FSL_ID_T_PFMT " "
                     "AND NOT deleted "
                     "AND CASE WHEN %Q='' THEN 1 "
                     "ELSE fsl_match_vfile_or_dir(pathname,%Q) "
                     "END /*%s()*/",
                     vid, zNorm, zNorm, __func__);
    if(rc) goto dberr;
    if(opt->callback){
      rc = fsl_db_prepare(db,&q,
                          "SELECT pathname FROM {{dbname.ckout}}.vfile "
                          "WHERE vid=%" FSL_ID_T_PFMT " "
                          "AND deleted "
                          "AND CASE WHEN %Q='' THEN 1 "
                          "ELSE fsl_match_vfile_or_dir(pathname,%Q) "
                          "END "
                          "UNION "
                          "SELECT pathname FROM {{dbname.ckout}}.vfile "
                          "WHERE vid=%" FSL_ID_T_PFMT " "
                          "AND rid=0 AND deleted "
                          "/*%s()*/",
                          vid, zNorm, zNorm, vid, __func__);
      if(rc) goto dberr;
    }
  }/*opt->filename*/

  if(q.stmt){
    fsl_ckout_unmanage_state ust = fsl_ckout_unmanage_state_empty;
    ust.opt = opt;
    ust.f = f;
    while(fsl__cx_stmt_step_each(f, &q, &rc)){
      rc = fsl_stmt_get_text(&q, 0, &ust.filename, NULL);
      if(rc){
        rc = fsl_cx_uplift_db_error2(f, db, rc);
        goto end;
      }
      rc = opt->callback(&ust);
      if(rc){
        if(!f->error.code && FSL_RC_OOM!=rc){
          rc = fsl_cx_err_set(f, rc, "Error %R returned from "
                              "unmanage callback for file: %s",
                              rc, ust.filename);
        }
        goto end;
      }
    }
    fsl_stmt_finalize(&q);
    if(rc) goto end;
  }
  /* Remove rm'd ADDed-but-not-yet-committed entries... */
  rc = fsl_db_exec(db,
                   "DELETE FROM {{dbname.ckout}}.vfile WHERE vid=%" FSL_ID_T_PFMT
                   " AND rid=0 AND deleted",
                   vid);
  if(rc) goto dberr;
  end:
  if(fname) fsl__cx_scratchpad_yield(f, fname);
  fsl_stmt_finalize(&q);
  if(opt->vfileIds){
    fsl__db_temp_drop(db, "fx_unmanage_id")
      /* Ignoring result code */;
  }
  if(inTrans){
    int const rc2 = fsl_db_txn_end(db, !!rc);
    if(!rc && rc2) rc = fsl_cx_uplift_db_error2(f, db, rc2);
  }
  return rc;
  dberr:
  assert(rc);
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  goto end;

}

int fsl_ckout_changes_scan(fsl_cx * const f){
  return fsl_vfile_changes_scan(f, -1, 0);
}

int fsl__ckout_install_schema(fsl_cx * const f, bool dropIfExists){
  char const * tNames[] = {
  "vvar", "vfile", "vmerge", 0
  };
  int rc = 0;
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return f->error.code;
  if(dropIfExists){
    char const * t;
    int i;
    fsl_b nameBuf = fsl_b_empty;
    fsl_b * const name = &nameBuf;
    for(i=0; 0!=(t = tNames[i]); ++i){
      fsl_b_reuse(name);
      rc = fsl__db_table_name(db, FSL_DBROLE_CKOUT, t, true, name);
      if(!rc) rc = fsl_db_exec(db, "DROP TABLE IF EXISTS %b /*%s()*/",
                               name, __func__);
      if(rc) break;
    }
    if(!rc){
      fsl_b_reuse(name);
      rc = fsl__db_table_name(db, FSL_DBROLE_CKOUT, "vmerge_ck1", true,
                              name);
      if(!rc) rc = fsl_db_exec(db, "DROP TRIGGER IF EXISTS "
                               "%b /*%s()*/", name, __func__);
    }
    fsl_b_clear(name);
    if(rc) return fsl_cx_uplift_db_error2(f, db, rc);
  }else{
    if(fsl_db_table_exists(db, FSL_DBROLE_CKOUT,
                           tNames[0])){
      return 0;
    }
  }
  rc = fsl_db_exec_multi(db, fsl_schema_ckout())
    /* the format string, so that its schema placeholders expand */;
  if(!rc && !fsl__db_ckout_prefix(db)){
    /* Identifier for this file type, the same integer as 'FSLC'. Not
       for checkout tables in a host's main db, which is the host's. */
    rc = fsl_db_exec(db, "PRAGMA {{dbname.ckout}}.application_id"
                     "=252006674");
  }
  return fsl_cx_uplift_db_error2(f, db, rc);
}

bool fsl_ckout_has_changes(fsl_cx *f){
  fsl_db * const db = fsl_cx_db_ckout(f);
  if(!db) return false;
  return fsl_db_exists(db,
                       "SELECT 1 FROM {{dbname.ckout}}.vfile WHERE "
                       "vid=%" FSL_ID_T_PFMT " "
                       "AND (chnged OR deleted "
                       "OR coalesce(origname != pathname, 0)) "
                       "/*%s()*/", f->db.ckout.rid,  __func__)
    || fsl_db_exists(db,"SELECT 1 FROM {{dbname.ckout}}.vmerge /*%s()*/", __func__);
}

/**
   Clears the vmerge table per the given mode. FSL__MERGE_CLEAR_ALL
   wipes all contents. The other modes perform a partial wipe: only
   the per-file rows (vmerge.id>0) of unchanged vfile entries.

   FSL__MERGE_CLEAR_SCAN stops there. The checkout-level markers
   (vmerge.id<=0: merge, cherry-pick, backout, integrate) are not tied
   to any single vfile row, so they must survive a file-change rescan
   until a commit consumes them (FSL__MERGE_CLEAR_ALL). A scan cannot
   tell from vfile.chnged whether merge involvement is left: it
   demotes a hand-edited merged file from MERGE_MOD(2) to MOD(1), and
   one which became or stopped being a symlink to BECAME_SYMLINK(7)
   or NOT_SYMLINK(9). Sweeping on that basis silently dropped the
   pending commit's merge parent or Q-card.

   In FSL__MERGE_CLEAR_REVERT mode those markers are also swept once
   no vfile entry has a merge-related chnged
   (FSL_VFILE_CHANGE_MERGE_MOD through FSL_VFILE_CHANGE_INTEGRATE_ADD)
   and no per-file merge state is left: that is the user abandoning
   the pending merge, and keeping the marker would attach a bogus
   merge parent or Q-card to whatever unrelated change gets committed
   next.

   Returns non-0 on db error.
*/
int fsl__ckout_clear_merge_state( fsl_cx * const f,
                                  enum fsl__ckout_merge_clear_e mode ){
  int rc;
  if(FSL__MERGE_CLEAR_ALL==mode){
    rc = fsl_cx_exec(f,"DELETE FROM {{dbname.ckout}}.vmerge /*%s()*/", __func__);
  }else{
    rc = fsl_cx_exec(f,
                     "DELETE FROM {{dbname.ckout}}.vmerge WHERE id IN("
                     "SELECT vm.id FROM {{dbname.ckout}}.vmerge vm, {{dbname.ckout}}.vfile vf "
                     "WHERE vm.id=vf.id AND vf.chnged=0"
                     ") /*%s()*/", __func__);
  }
  if(0==rc && FSL__MERGE_CLEAR_REVERT==mode){
    rc = fsl_cx_exec(f,
                     "DELETE FROM {{dbname.ckout}}.vmerge WHERE "
                     "NOT EXISTS("
                     "SELECT 1 FROM {{dbname.ckout}}.vmerge WHERE id>0"
                     ") AND NOT EXISTS ("
                     /* Only these chnged values are merge involvement:
                        higher ones are executable-bit and symlink
                        changes. */
                     "SELECT 1 FROM {{dbname.ckout}}.vfile"
                     " WHERE chnged BETWEEN %d AND %d"
                     ")"
                     "/*%s()*/",
                     (int)FSL_VFILE_CHANGE_MERGE_MOD,
                     (int)FSL_VFILE_CHANGE_INTEGRATE_ADD,
                     __func__ );
  }
  return rc;
}

int fsl_ckout_clear_db(fsl_cx *f){
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return f->error.code;
  int const rc = fsl_db_exec_multi(db,
                                   "DELETE FROM {{dbname.ckout}}.vfile;"
                                   "DELETE FROM {{dbname.ckout}}.vmerge;"
                                   "DELETE FROM {{dbname.ckout}}.vvar WHERE name IN"
                                   "('checkout','checkout-hash') "
                                   "/*%s()*/", __func__);
  return rc ? fsl_cx_uplift_db_error2(f, db, rc) : 0;
}

/**
   Updates f->db.ckout.dir and dirLen based on the current state of
   f->db.ckout.db. Returns 0 on success, FSL_RC_OOM on allocation error,
   some other code if canonicalization of the name fails
   (e.g. filesystem error or cwd cannot be resolved).
*/
static int fsl_update_ckout_dir(fsl_cx *f){
  int rc;
  fsl_b ckDir = fsl_b_empty;
  fsl_db * dbC = fsl__cx_db_for_role(f, FSL_DBROLE_CKOUT);
  assert(dbC->filename);
  assert(*dbC->filename);
  rc = fsl_file_canonical_name(dbC->filename, &ckDir, false);
  if(rc){
    fsl_b_clear(&ckDir);
    return FSL_RC_OOM==rc
      ? rc
      : fsl_cx_err_set(f, rc, "Error %R canonicalizing checkout "
                       "db name: %s", rc, dbC->filename);
  }
  char * zCanon = fsl_b_take(&ckDir);
  //MARKER(("dbC->filename=%s\n", dbC->filename));
  //MARKER(("zCanon=%s\n", zCanon));
  rc = fsl_file_dirpart(zCanon, -1, &ckDir, true);
  fsl_free(zCanon);
  if(rc){
    fsl_b_clear(&ckDir);
  }else{
    fsl_free(f->db.ckout.dir);
    f->db.ckout.dirLen = ckDir.used;
    f->db.ckout.dir = fsl_b_take(&ckDir);
    assert('/'==f->db.ckout.dir[f->db.ckout.dirLen-1]);
    /*MARKER(("Updated ckout.dir: %d %s\n",
      (int)f->db.ckout.dirLen, f->db.ckout.dir));*/
  }
  return rc;
}


/**
   The checks of fsl_repo_open_ckout() on its target directory dir:
   if checkEmpty, that it is empty unless opt->fileOverwritePolicy
   allows otherwise, and, if opt->checkForOpenedCkout, that neither it
   nor a parent directory has a checkout db.
*/
static int fsl__ckout_open_dir_policy(fsl_cx * const f,
                                      fsl_repo_open_ckout_opt const * opt,
                                      fsl_b const * dir, bool checkEmpty){
  int rc = 0;
  if(checkEmpty && fsl__cfs_dir_is_empty(f, fsl_b_cstr(dir)) > 0) {
    /* fsl_dir_is_empty() returns 0 for an empty dir, so the previous
       test (!fsl_dir_is_empty(...)) fired for an empty dir and passed
       a non-empty one. */
    switch(opt->fileOverwritePolicy){
      case FSL_OVERWRITE_ALWAYS:
      case FSL_OVERWRITE_NEVER: break;
      default:
        assert(FSL_OVERWRITE_ERROR==opt->fileOverwritePolicy);
        return fsl_cx_err_set(f, FSL_RC_ACCESS,
                              "Directory is not empty and "
                              "fileOverwritePolicy is "
                              "FSL_OVERWRITE_ERROR: "
                              "%b", dir);
    }
  }
  if(opt->checkForOpenedCkout){
    /* Check the target and its parent dirs for a checkout and bail
       out if we find one. If opt->checkForOpenedCkout is false then
       we will use the dbOverwritePolicy to determine what to do if we
       find a checkout db in the target (as opposed to a parent). */
    fsl_b * const foundAt = fsl__cx_scratchpad(f);
    if (!fsl_ckout_db_search(fsl_b_cstr(dir), true, foundAt)) {
      rc = fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                          "There is already a checkout db at %b",
                          foundAt);
    }
    fsl__cx_scratchpad_yield(f, foundAt);
  }
  return rc;
}

/** The count of main's tables named zPre followed by zName, ignoring
    case, or -1 on error. */
static int32_t fsl__ckout_prefixed_table_count(fsl_db * const db,
                                               char const * zPre,
                                               char const * zName){
  int32_t n = -1;
  if(fsl_db_get_int32(db, &n, "SELECT count(*) FROM main.sqlite_schema"
                      " WHERE type='table' AND lower(name)=lower(%Q||%Q)",
                      zPre, zName)){
    n = -1;
  }
  return n;
}

int fsl__host_prefix_recorded_check(fsl_cx * const f, fsl_db * const db,
                                    fsl_dbrole_e r, char const * zPre){
  fsl_stmt q = fsl_stmt_empty;
  int rc = fsl_db_prepare(db, &q,
    "SELECT name, substr(name, 1, length(name)-4) AS p,"
    " lower(substr(name, -4)) AS k"
    " FROM main.sqlite_schema"
    " WHERE type='table' AND length(name)>4 AND k IN ('vvar','blob')"
    " AND (lower(substr(p, 1, length(%Q)))=lower(%Q)"
    "      OR lower(substr(%Q, 1, length(p)))=lower(p))"
    " ORDER BY 1", zPre, zPre, zPre);
  if(rc) return fsl_cx_uplift_db_error2(f, db, rc);
  while(0==rc && FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q))){
    char const * const zTab = fsl_stmt_g_text(&q, 0, NULL);
    char const * const zP = fsl_stmt_g_text(&q, 1, NULL);
    bool const isRepo = 'b'==*fsl_stmt_g_text(&q, 2, NULL);
    bool found;
    rc = 0;
    if(0==fsl_stricmp(zP, zPre) && isRepo==(FSL_DBROLE_REPO==r)){
      continue /* zPre's own tables */;
    }
    found = 1==fsl__ckout_prefixed_table_count(db, zP,
                                               isRepo ? "config" : "vfile");
    if(found){
      /* A host table so named need not have the columns. */
      char * const zConfig = isRepo ? fsl_mprintf("%sconfig", zP) : NULL;
      if(isRepo && !zConfig){
        rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
        break;
      }
      found = isRepo
        ? fsl_db_exists(db, "SELECT 1 FROM main.%!Q"
                        " WHERE name='content-schema'", zConfig)
        : fsl_db_exists(db, "SELECT 1 FROM main.%!Q"
                        " WHERE name='ckout-root'", zTab);
      fsl_db_err_reset(db);
      fsl_free(zConfig);
    }
    if(found){
      rc = fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                          "%s table prefix %s overlaps prefix %s "
                          "of a %s in the host db.",
                          FSL_DBROLE_REPO==r ? "Repository" : "Checkout",
                          zPre, zP, isRepo ? "repository" : "working copy");
    }
  }
  if(FSL_RC_STEP_DONE==rc) rc = 0;
  else if(rc && !f->error.code) rc = fsl_cx_uplift_db_error2(f, db, rc);
  fsl_stmt_finalize(&q);
  return rc;
}

/**
   For a reopen in fsl__repo_open_ckout_prefixed(): checks that the
   working copy with prefix zPre has its core tables, belongs to f's
   repository (by project-code, and its version's rid has the hash it
   recorded, which a clone, with the same project-code but rids of its
   own, need not have), and has the directory zDir (canonical, with a
   trailing slash; compared with symbolic links resolved, and without
   regard to case if f's file names are case-insensitive). Sets
   *pMoved to true if the repository's file name is not the one
   recorded. Sets f's error state on error.
*/
static int fsl__ckout_prefixed_reopen_check(fsl_cx * const f,
                                            char const * zPre,
                                            char const * zDir,
                                            bool * const pMoved){
  static char const * const azCore[] = {"vfile", "vmerge", NULL};
  fsl_db * const db = f->dbMain;
  fsl_db * const dbR = fsl__cx_db_for_role(f, FSL_DBROLE_REPO);
  char * zCode = NULL, * zMyCode = NULL, * zRoot = NULL, * zHash = NULL,
    * zUuid = NULL, * zRepo = NULL;
  fsl_id_t rid = 0;
  fsl_b * const r1 = fsl__cx_scratchpad(f);
  fsl_b * const r2 = fsl__cx_scratchpad(f);
  int rc = 0;
  for(int i = 0; azCore[i]; ++i){
    int32_t const n = fsl__ckout_prefixed_table_count(db, zPre, azCore[i]);
    if(n<0){
      rc = fsl_cx_uplift_db_error(f, db);
      goto end;
    }else if(!n){
      rc = fsl_cx_err_set(f, FSL_RC_CONSISTENCY,
                          "The working copy with checkout table prefix "
                          "%s has no %s table.", zPre, azCore[i]);
      goto end;
    }
  }
  /* zPre is an identifier (fsl__cx_ckout_prefix_check()). */
#define VVAR(Z,NAME) \
  if(!rc) rc = fsl_db_get_text(db, &(Z), NULL, "SELECT value FROM"    \
                               " main.\"%svvar\" WHERE name=%Q", zPre, \
                               NAME)
  VVAR(zCode, "project-code");
  VVAR(zRoot, "ckout-root");
  VVAR(zHash, "checkout-hash");
  VVAR(zRepo, "repository");
#undef VVAR
  if(!rc) rc = fsl_db_get_id(db, &rid, "SELECT value FROM main.\"%svvar\""
                             " WHERE name='checkout'", zPre);
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, db, rc);
    goto end;
  }
  zMyCode = fsl_config_get_text(f, FSL_CONFDB_REPO, "project-code", NULL);
  if(!zCode || !zMyCode || 0!=fsl_strcmp(zCode, zMyCode)){
    rc = fsl_cx_err_set(f, FSL_RC_REPO_MISMATCH,
                        "The working copy with checkout table prefix %s "
                        "belongs to the repository with project-code %s, "
                        "not %s (%s).", zPre, zCode ? zCode : "(none)",
                        zMyCode ? zMyCode : "(none)", dbR->filename);
    goto end;
  }
  if(rid>0){
    zUuid = fsl_rid_to_uuid(f, rid);
    if(!zUuid) fsl_cx_err_reset(f);
  }
  if(rid>0 ? (!zUuid || !zHash || 0!=fsl_strcmp(zUuid, zHash))
     : !!zHash){
    rc = fsl_cx_err_set(f, FSL_RC_REPO_MISMATCH,
                        "The working copy with checkout table prefix %s "
                        "has version %s, which repository %s does not "
                        "have as rid %" FSL_ID_T_PFMT " (a clone?).",
                        zPre, zHash ? zHash : "(none)", dbR->filename,
                        rid);
    goto end;
  }
  if(zRoot){
    /* The same directory, however it is spelled. */
    rc = fsl_b_append(r1, zRoot, -1);
    if(!rc) rc = fsl_b_append(r2, zDir, -1);
    for(int i = 0; !rc && i < 2; ++i){
      fsl_b * const b = i ? r2 : r1;
      while(b->used>1 && '/'==b->mem[b->used-1]) b->mem[--b->used] = 0;
      rc = fsl__file_realpath(b);
    }
    if(rc){
      rc = fsl_cx_err_set(f, rc, NULL);
      goto end;
    }
  }
  if(!zRoot || 0!=fsl_cx_filename_cmp(f, fsl_b_cstr(r1), fsl_b_cstr(r2))){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                        "The working copy with checkout table prefix %s "
                        "has the directory %s, not %s.", zPre,
                        zRoot ? zRoot : "(none)", zDir);
    goto end;
  }
  {
    char * const zRef = fsl__cx_repo_ref(f);
    if(!zRef){
      rc = f->error.code;
      goto end;
    }
    *pMoved = !zRepo || 0!=fsl_strcmp(zRepo, zRef);
    fsl_free(zRef);
  }
  end:
  fsl__cx_scratchpad_yield(f, r1);
  fsl__cx_scratchpad_yield(f, r2);
  fsl_free(zCode); fsl_free(zMyCode); fsl_free(zRoot); fsl_free(zHash);
  fsl_free(zUuid); fsl_free(zRepo);
  return rc;
}

/**
   fsl_repo_open_ckout() for opt->hostTablePrefix: dir is the
   canonical target directory, without a trailing slash. Reopens the
   working copy whose tables have that prefix, if its vvar table
   exists, else creates them, in a namespace which must be empty, so
   that no table of the host's or of another working copy is adopted
   or dropped. Either way the prefix may not overlap another working
   copy's, open or recorded in the main db. The checks and writes run
   in one transaction, which for a creation holds the main db's write
   lock from the start (fsl__db_main_write_lock()), so that no other
   connection creates an overlapping working copy in between. The working copy's vvar records its repository's
   project-code and its directory, which a reopen must match. On
   error, nothing is left attached.
*/
static int fsl__repo_open_ckout_prefixed(fsl_cx * const f,
                                         fsl_repo_open_ckout_opt const * opt,
                                         fsl_b * const dir){
  char const * const zPre = opt->hostTablePrefix;
  fsl_db * const db = f->dbMain;
  fsl_db * const dbR = fsl__cx_db_for_role(f, FSL_DBROLE_REPO);
  int32_t nVvar = 0;
  bool reopen, inTxn = false, moved = false;
  char * zRef = NULL;
  int rc = fsl__cx_ckout_prefix_check(f, zPre);
  if(rc) return rc;
  if(opt->dbOverwritePolicy){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "dbOverwritePolicy is not for prefixed "
                          "checkout tables: drop the tables instead.");
  }
  assert(dbR->filename);
  /* The directory, with a trailing slash, is not derived from a db
     file's name. */
  rc = '/'==dir->mem[dir->used-1] ? 0 : fsl_b_append(dir, "/", 1);
  if(rc) return fsl_cx_err_set(f, rc, NULL);
  rc = fsl__cx_repo_sync_full(f);
  if(rc) return rc;
  nVvar = fsl__ckout_prefixed_table_count(db, zPre, "vvar");
  if(nVvar<0) return fsl_cx_uplift_db_error(f, db);
  reopen = nVvar>0;
  rc = fsl_cx_txn_begin(f);
  inTxn = 0==rc;
  if(!rc && !reopen){
    rc = fsl__db_main_write_lock(db);
    if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
    else{
      /* Again, now that no other connection can write. */
      nVvar = fsl__ckout_prefixed_table_count(db, zPre, "vvar");
      if(nVvar<0) rc = fsl_cx_uplift_db_error(f, db);
      else if(nVvar){
        rc = fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS, "A working copy "
                            "with checkout table prefix %s was just "
                            "created.", zPre);
      }
    }
  }
  if(!rc) rc = fsl__host_prefix_recorded_check(f, db, FSL_DBROLE_CKOUT,
                                               zPre);
  if(!rc && reopen){
    rc = fsl__ckout_prefixed_reopen_check(f, zPre, fsl_b_cstr(dir), &moved);
  }else if(!rc){
    char * const zList = fsl_db_g_text(db, NULL,
      "SELECT group_concat(name, ', ') FROM main.sqlite_schema"
      " WHERE lower(substr(name, 1, %d))=lower(%Q)",
      (int)fsl_strlen(zPre), zPre);
    if(db->error.code) rc = fsl_cx_uplift_db_error(f, db);
    else if(zList && *zList){
      rc = fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                          "The host db already has objects whose names "
                          "start with checkout table prefix %s: %s",
                          zPre, zList);
    }
    fsl_free(zList);
  }
  if(!rc) rc = fsl__ckout_open_dir_policy(f, opt, dir, !reopen);
  if(!rc){
    fsl_free(f->db.ckout.dir);
    f->db.ckout.dirLen = dir->used;
    f->db.ckout.dir = fsl_b_take(dir);
    if(!f->db.ckout.dir) rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  }
  if(!rc){
    fsl_cx_err_reset(f);
    rc = fsl__cx_attach_ckout_prefixed(f, zPre);
  }
  if(!rc && (moved || !reopen)){
    zRef = fsl__cx_repo_ref(f);
    if(!zRef) rc = f->error.code;
  }
  if(!rc && moved){
    /* The repository was moved: record its current name, writing only
       then, so that a read-only host db reopens. */
    rc = fsl_config_set_text(f, FSL_CONFDB_CKOUT, "repository", zRef);
  }else if(!rc && !reopen){
    char * const zCode =
      fsl_config_get_text(f, FSL_CONFDB_REPO, "project-code", NULL);
    rc = fsl__ckout_install_schema(f, false);
    if(!rc){
      rc = fsl_db_exec(db, "INSERT OR IGNORE INTO "
                       "{{dbname.ckout}}.vvar (name,value) "
                       "VALUES('checkout',0),"
                       "('checkout-hash',null)");
      if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
    }
    if(!rc) rc = fsl_config_set_text(f, FSL_CONFDB_CKOUT, "repository",
                                     zRef);
    if(!rc) rc = fsl_config_set_text(f, FSL_CONFDB_CKOUT, "project-code",
                                     zCode);
    if(!rc) rc = fsl_config_set_text(f, FSL_CONFDB_CKOUT, "ckout-root",
                                     f->db.ckout.dir);
    fsl_free(zCode);
  }
  fsl_free(zRef);
  if(inTxn){
    int const rc2 = fsl_cx_txn_end(f, 0!=rc);
    if(!rc) rc = rc2;
  }
  if(!rc && reopen) rc = fsl__cx_after_open(f);
  if(!rc) return 0;
  if(fsl_cx_db_ckout(f)) fsl__cx_detach_ckout(f);
  fsl_free(f->db.ckout.dir);
  f->db.ckout.dir = NULL;
  f->db.ckout.dirLen = 0;
  fsl__cx_ckout_clear(f);
  return rc;
}

int fsl_repo_open_ckout(fsl_cx * const f, const fsl_repo_open_ckout_opt *opt){
  fsl_db *dbC = 0;
  fsl_b *dir = 0, *dbPath = 0;
  int rc = 0;
  if(!opt){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "%s() requires an options object.", __func__);
  }else if(!fsl_needs_repo(f)){
    return f->error.code;
  }else if(fsl_cx_db_ckout(f)){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "A checkout is already attached.");
  }else if(opt->hostTablePrefix
           && (!fsl__db_is_borrowed(f->dbMain) || opt->ckoutDbFile)){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "hostTablePrefix is only for a context on a "
                          "host db handle, without a ckoutDbFile.");
  }
  /* Work with the target directory's full name rather than chdir()ing
     into it, so that the process's current directory never changes
     and the directory is reached through the checkout's storage
     (fsl_cx_ckout_fs()) like every other part of the working copy. */
  dir = fsl__cx_scratchpad(f);
  dbPath = fsl__cx_scratchpad(f);
  rc = fsl_file_canonical_name((opt->targetDir && *opt->targetDir)
                               ? opt->targetDir : ".", dir, false);
  if(rc){
    rc = fsl_cx_err_set(f, rc, "Error %R resolving the checkout "
                        "directory.", rc);
    goto end;
  }
  while(dir->used>1 && '/'==dir->mem[dir->used-1]){
    dir->mem[--dir->used] = 0;
  }
  if(fsl__cfs_dir_check(f, fsl_b_cstr(dir))<=0){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "Directory not found or inaccessible: %b", dir);
    goto end;
  }
  if(opt->hostTablePrefix){
    rc = fsl__repo_open_ckout_prefixed(f, opt, dir);
    goto end_prefixed;
  }
  rc = fsl__ckout_open_dir_policy(f, opt, dir, true);
  if(rc) goto end;

  /**
     Create and attach ckout db, named relative to the target
     directory unless it is given as an absolute name.
  */
  assert(!fsl_cx_db_ckout(f));
  const char * dbName = opt->ckoutDbFile
    ? opt->ckoutDbFile : fsl_preferred_ckout_db_name();
  if(!fsl_is_absolute_path(dbName)){
    rc = fsl_file_canonical_name2(fsl_b_cstr(dir), dbName, dbPath, false);
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Error %R resolving the checkout "
                          "db name.", rc);
      goto end;
    }
    dbName = fsl_b_cstr(dbPath);
  }
  fsl_cx_err_reset(f);
  rc = fsl__cx_attach_role(f, dbName, FSL_DBROLE_CKOUT, true);
  if(rc) goto end;
  fsl_db * const theDbC = fsl_cx_db_ckout(f);
  dbC = fsl__cx_db_for_role(f, FSL_DBROLE_CKOUT);
  assert(dbC->name);
  assert(dbC->filename);
  rc = fsl__ckout_install_schema(f, opt->dbOverwritePolicy);
  if(!rc){
    rc = fsl_db_exec(theDbC,"INSERT OR IGNORE INTO "
                     "{{dbname.ckout}}.vvar (name,value) "
                     "VALUES('checkout',0),"
                     "('checkout-hash',null)");
  }
  if(rc) rc = fsl_cx_uplift_db_error2(f, theDbC, rc);
  end:
  fsl__cx_scratchpad_yield(f, dir);
  fsl__cx_scratchpad_yield(f, dbPath);
  if(!rc){
    char * const zRef = fsl__cx_repo_ref(f);
    rc = zRef ? fsl_config_set_text(f, FSL_CONFDB_CKOUT, "repository",
                                    zRef) : f->error.code;
    fsl_free(zRef);
  }
  if(!rc && fsl__db_repo_prefix(f->dbMain)){
    /* Which a reopen checks (fsl_ckout_open_dir()), since the
       repository is not a file of its own. */
    char * const zCode =
      fsl_config_get_text(f, FSL_CONFDB_REPO, "project-code", NULL);
    rc = fsl_config_set_text(f, FSL_CONFDB_CKOUT, "project-code", zCode);
    fsl_free(zCode);
  }
  if(!rc){
    rc = fsl_update_ckout_dir(f);
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Cannot determine the directory of "
                          "checkout db [%s]: %R",
                          fsl_cx_db_file_ckout(f, NULL), rc);
    }
  }
  return rc;
  end_prefixed:
  fsl__cx_scratchpad_yield(f, dir);
  fsl__cx_scratchpad_yield(f, dbPath);
  return rc;
}

int fsl__is_locally_modified(fsl_cx * const f,
                            const char * zFilename,
                            fsl_size_t origSize,
                            const char * zOrigHash,
                            fsl_int_t zOrigHashLen,
                            fsl_fileperm_e origPerm,
                            int * isModified){
  int rc = 0;
  int const hashLen = zOrigHashLen>=0
    ? zOrigHashLen : fsl_is_uuid(zOrigHash);
  fsl_b * hash = 0;
  fsl_b * fname;
  fsl_fstat * const fst = &f->cache.fstat;
  int mod = 0;
  if(!fsl_is_uuid_len(hashLen)){
    return fsl_cx_err_set(f, FSL_RC_RANGE, "%s(): invalid hash length "
                          "%d for file: %s", __func__, hashLen, zFilename);
  }else if(!f->db.ckout.dir){
    return fsl_cx_err_set(f, FSL_RC_NOT_A_CKOUT,
                          "%s() requires a checkout.", __func__);
  }
  fname = fsl__cx_scratchpad(f);
  if(!fsl_is_absolute_path(zFilename)){
    rc = fsl_file_canonical_name2(f->db.ckout.dir, zFilename, fname, false);
    if(rc){
      if(FSL_RC_OOM!=rc){
        rc = fsl_cx_err_set(f, rc, "%s(): error %R canonicalizing "
                            "file name: %s", __func__, rc, zFilename);
      }
      goto end;
    }
    zFilename = fsl_b_cstr(fname);
  }
  rc = fsl__cfs_stat(f, zFilename, fst, false);
  if(0==rc){
    if(origSize!=fst->size){
      mod |= FSL__LOCALMOD_CONTENT;
    }
    if((FSL_FILE_PERM_EXE==origPerm &&
        FSL_FSTAT_PERM_EXE!=fst->perm)
       || (FSL_FILE_PERM_EXE!=origPerm &&
           FSL_FSTAT_PERM_EXE==fst->perm)){
      mod |= FSL__LOCALMOD_PERM;
    }else if((FSL_FILE_PERM_LINK==origPerm &&
              FSL_FSTAT_TYPE_LINK!=fst->type)
             || (FSL_FILE_PERM_LINK!=origPerm &&
                 FSL_FSTAT_TYPE_LINK==fst->type)){
      mod |= FSL__LOCALMOD_LINK;
    }
    if(mod & (FSL__LOCALMOD_LINK | FSL__LOCALMOD_CONTENT)) goto end;
    /* ^^^^^^^^^^ else we unfortunately need, for behavioral
       consistency, to fall through and determine whether the file
       contents differ. */
  }else{
    if(FSL_RC_NOT_FOUND==rc){
      rc = 0;
      mod = FSL__LOCALMOD_NOTFOUND;
    }else{
      rc = fsl_cx_err_set(f, rc, "%s(): stat() failed with %R "
                          "for file: %s", __func__, rc, zFilename);
    }
    goto end;
  }
  hash = fsl__cx_scratchpad(f);
  switch(hashLen){
    case FSL_STRLEN_SHA1:
      rc = fsl__cfs_sha1sum(f, zFilename, hash);
      break;
    case FSL_STRLEN_K256:
      rc = fsl__cfs_sha3sum(f, zFilename, hash);
      break;
    default:
      fsl__fatal(FSL_RC_UNSUPPORTED, "This cannot happen. %s()",
                 __func__);
  }
  if(rc){
    rc = fsl_cx_err_set(f, rc, "%s(): error %R hashing file: %s",
                        __func__, rc, zFilename);
  }else{
    assert(hashLen==(int)hash->used);
    mod |= memcmp(hash->mem, zOrigHash, (size_t)hashLen)
      ? FSL__LOCALMOD_CONTENT : 0;
    /*MARKER(("%d: %s %s %s\n", *isModified, zOrigHash,
      (char const *)hash.mem, zFilename));*/
  }
  end:
  if(!rc && isModified) *isModified = mod;
  fsl__cx_scratchpad_yield(f, fname);
  if(hash) fsl__cx_scratchpad_yield(f, hash);
  return rc;
}

/**
   Infrastructure for fsl_repo_ckout(),
   fsl_ckout_update(), and fsl_ckout_merge().
*/
typedef struct {
  /** The pre-checkout vfile.vid. 0 if no version was checked out. */
  fsl_id_t originRid;
  fsl_repo_extract_opt const * eOpt;
  fsl_ckup_opt const * cOpt;
  /* Checkout root. We re-use this when internally converting to
     absolute paths. */
  fsl_b * tgtDir;
  /* Initial length of this->tgtDir, including trailing slash */
  fsl_size_t tgtDirLen;
  /* Number of files we've written out so far. Used for adapting
     some error reporting. */
  fsl_size_t fileWriteCount;
  /* Stores the most recent fsl_cx_confirm() answer for questions
     about overwriting/removing modified files. (Exactly which answer
     it represents depends on the current phase of processing.)
  */
  fsl_confirm_response confirmAnswer;
  /* Is-changed vis-a-vis vfile query. */
  fsl_stmt stChanged;
  /* Is-same-filename-and-rid-in-vfile query. */
  fsl_stmt stIsInVfile;
  /* blob.size for vfile.rid query. */
  fsl_stmt stRidSize;
} RepoExtractCkup;

static const RepoExtractCkup RepoExtractCkup_empty = {
0/*originRid*/,NULL/*eOpt*/, NULL/*cOpt*/,
NULL/*tgtDir*/, 0/*tgtDirLen*/,
0/*fileWriteCount*/,
fsl_confirm_response_empty_m/*confirmAnswer*/,
fsl_stmt_empty_m/*stChanged*/,
fsl_stmt_empty_m/*stIsInVfile*/,
fsl_stmt_empty_m/*stRidSize*/
};

static const fsl_ckup_state fsl_ckup_state_empty = {
NULL/*xState*/, NULL/*callbackState*/,
FSL_CKUP_FCHANGE_INVALID/*fileChangeType*/,
FSL_CKUP_RM_NOT/*fileRmInfo*/,
0/*mtime*/,0/*size*/,
false/*dryRun*/
};

/**
   File modification types reported by
   fsl_reco_is_file_modified().
 */
typedef enum {
// Sentinel value
FSL_RECO_MOD_UNKNOWN,
// Not modified
FSL_RECO_MOD_NO,
// Modified
FSL_RECO_MOD_YES,
// "Unmanaged replaced by managed"
FSL_RECO_MOD_UnReMa
} fsl_ckup_localmod_e;

/**
   Determines whether the file referred to by the given
   checkout-root-relative file name, which is assumed to be known to
   exist, has been modified. It simply looks to the vfile state,
   rather than doing its own filesystem-level comparison. Returns 0 on
   success and stores its answer in *modType. Errors must be
   considered unrecoverable.
*/
static int fsl_reco_is_file_modified(fsl_cx *f, fsl_stmt * st,
                                     char const *zName,
                                     fsl_ckup_localmod_e * modType){
  int rc = 0;
  if(!st->stmt){ // no prior version
    *modType = FSL_RECO_MOD_NO;
    return 0;
  }
  fsl_stmt_reset(st);
  rc = fsl_stmt_bind_text(st, 1, zName, -1, false);
  if(rc){
    return fsl_cx_uplift_db_error2(f, st->db, rc);
  }
  rc = fsl_stmt_step(st);
  switch(rc){
    case FSL_RC_STEP_DONE:
      /* This can happen when navigating from a version in which a
         file was SCM-removed/unmanaged, but on disk, to a version
         where that file was in SCM. For now we'll mark these as
         modified but we need a better way of handling this case, and
         maybe a new FSL_CEVENT_xxx ID. */
      *modType = FSL_RECO_MOD_UnReMa;
      rc = 0;
      break;
    case FSL_RC_STEP_ROW:
      *modType = fsl_stmt_g_int32(st,0)>0
        ? FSL_RECO_MOD_YES : FSL_RECO_MOD_NO;
      rc = 0;
      break;
    default:
      rc = fsl_cx_uplift_db_error2(f, st->db, rc);
      break;
  }
  return rc;
}

/**
   Sets *isInVfile to true if the given combination of filename and
   file content RID are in the vfile table, as per
   RepoExtractCkup::stIsInVfile, else false. Returns non-0 on
   catastrophic failure.
*/
static int fsl_repo_co_is_in_vfile(fsl_stmt * st,
                                   char const *zFilename,
                                   fsl_id_t fileRid,
                                   bool *isInVfile){
  int rc = 0;
  if(st->stmt){
    fsl_stmt_reset(st);
    rc = fsl_stmt_bind_text(st, 1, zFilename, -1, false);
    if(!rc) rc = fsl_stmt_bind_id(st, 2, fileRid);
    if(!rc) *isInVfile = (FSL_RC_STEP_ROW==fsl_stmt_step(st));
  }else{ // no prior version
    *isInVfile = false;
  }
  return rc;
}

/**
   Infrastructure for fsl_repo_ckout(). This is the fsl_repo_extract_f
   impl which fsl_repo_extract() calls to give us the pieces we want to
   check out.

   When this is run (once for each row of the new checkout version),
   the vfile table still holds the state for the previous version, and
   we use that to determine whether a file is changed or new.
*/
static int fsl_repo_extract_f_ckout( fsl_repo_extract_state const * xs ){
  int rc = 0;
  fsl_cx * const f = xs->f;
  RepoExtractCkup * const rec = (RepoExtractCkup *)xs->callbackState;
  const char * zFilename;
  fsl_ckup_state coState = fsl_ckup_state_empty;
  fsl_time_t mtime = 0;
  fsl_fstat fst = fsl_fstat_empty;
  fsl_ckup_localmod_e modType = FSL_RECO_MOD_UNKNOWN;
  bool loadedContent = false;
  fsl_b * const content = &f->cache.fileContent;
  assert(0==content->used
         && "Internal Misuse of fsl_cx::fileContent buffer.");
  //assert(xs->content);
  assert(xs->fCard->uuid && "We shouldn't be getting deletions "
         "via delta manifests.");
  rc = fsl_b_append(rec->tgtDir, xs->fCard->name, -1);
  if(rc) return rc;
  fsl_b_reuse(content);
  coState.dryRun = rec->cOpt->dryRun;
  coState.fileRmInfo = FSL_CKUP_RM_NOT;
  coState.fileChangeType = FSL_CKUP_FCHANGE_INVALID;
  zFilename = fsl_b_cstr(rec->tgtDir);
  rc = fsl__cfs_stat(f, zFilename, &fst, 0);
  switch(rc){
    case 0:
      /* File exists. If it is modified, as reported by vfile, get
         confirmation before overwriting it, otherwise just overwrite
         it (or keep it - that's much more efficient). */
      mtime = fst.mtime;
      if(rec->confirmAnswer.response!=FSL_CRESPONSE_ALWAYS){
        rc = fsl_reco_is_file_modified(f, &rec->stChanged,
                                       xs->fCard->name, &modType);
        if(rc) goto end;
        switch(modType){
          case FSL_RECO_MOD_YES:
          case FSL_RECO_MOD_UnReMa:
            if(rec->confirmAnswer.response!=FSL_CRESPONSE_NEVER){
              fsl_confirm_detail detail = fsl_confirm_detail_empty;
              detail.eventId = FSL_RECO_MOD_YES==modType
                ? FSL_CEVENT_OVERWRITE_MOD_FILE
                : FSL_CEVENT_OVERWRITE_UNMGD_FILE;
              detail.filename = xs->fCard->name;
              rec->confirmAnswer.response = FSL_CRESPONSE_INVALID;
              rc = fsl_cx_confirm(f, &detail, &rec->confirmAnswer);
              if(rc) goto end;
            }
            break;
          case FSL_RECO_MOD_NO:{
            /** If vfile says that the content of this exact
                combination of filename and file RID is unchanged, we
                already have this content. If so, skip rewriting
                it. */
            bool isSameFile = false;
            rc = fsl_repo_co_is_in_vfile(&rec->stIsInVfile, xs->fCard->name,
                                         xs->fileRid, &isSameFile);
            if(rc) goto end;
            rec->confirmAnswer.response = isSameFile
              ? FSL_CRESPONSE_NO // We already have this content
              : FSL_CRESPONSE_YES; // Overwrite it
            coState.fileChangeType = isSameFile
              ? FSL_CKUP_FCHANGE_NONE
              : FSL_CKUP_FCHANGE_UPDATED;
            break;
          }
          default:
            fsl__fatal(FSL_RC_UNSUPPORTED,"Internal error: invalid "
                      "fsl_reco_is_file_modified() response.");
        }
      }
      switch(rec->confirmAnswer.response){
        case FSL_CRESPONSE_NO:
        case FSL_CRESPONSE_NEVER:
          // Keep existing.
          coState.fileChangeType = FSL_CKUP_FCHANGE_NONE;
          goto do_callback;
        case FSL_CRESPONSE_YES:
        case FSL_CRESPONSE_ALWAYS:
          // Overwrite it.
          coState.fileChangeType = FSL_CKUP_FCHANGE_UPDATED;
          break;
        case FSL_CRESPONSE_CANCEL:
          rc = fsl_cx_err_set(f, FSL_RC_BREAK,
                              "Checkout operation cancelled by "
                              "confirmation callback.%s",
                              rec->fileWriteCount
                              ? " Filesystem contents may now be "
                                "in an inconsistent state!"
                              : "");
          goto end;
        default:
          rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                              "Invalid response from confirmation "
                              "callback.");
          goto end;
      }
      break;
    case FSL_RC_NOT_FOUND:
      rc = 0;
      coState.fileChangeType = FSL_CKUP_FCHANGE_UPDATED;
      // Write it
      break;
    default:
      rc = fsl_cx_err_set(f, rc, "Error %s stat()'ing file: %s",
                          fsl_rc_cstr(rc), zFilename);
      goto end;
  }
  assert(FSL_CKUP_FCHANGE_INVALID != coState.fileChangeType);
  if(coState.dryRun){
    mtime = time(0);
  }else{
    if((rc=fsl__cfs_mkdir_for_file(f, zFilename, true))){
      rc = fsl_cx_err_set(f, rc, "Error %R creating directory "
                          "for file: %s", rc, zFilename);
      goto end;
    }
    assert(!xs->content);
    /* xs->fileRid is the rid of xs->fCard->uuid, which is what
       fsl_card_F_content() used to look up and read here. */
    bool writeFailed = false;
    rc = fsl__cfs_write_blob(f, zFilename, xs->fileRid, content,
                             false, &writeFailed);
    if(rc){
      if(writeFailed){
        rc = fsl_cx_err_set(f, rc, "Error %s writing to file: %s",
                            fsl_rc_cstr(rc), zFilename);
      }
      goto end;
    }else{
      /* Unless the storage wrote the blob itself, content holds it.
         If it is empty, the callback's size comes from the db. */
      loadedContent = content->used>0;
      ++rec->fileWriteCount;
      mtime = time(0);
    }
    rc = fsl__cfs_exec_set(f, zFilename,
                           FSL_FILE_PERM_EXE == xs->fCard->perm);
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Error %s changing file permissions: %s",
                          fsl_rc_cstr(rc), xs->fCard->name);
      goto end;
    }
  }
  if(rec->cOpt->setMtime){
    rc = fsl_mtime_of_manifest_file(xs->f, xs->checkinRid,
                                    xs->fileRid, &mtime);
    if(rc){
      if(!f->error.code && FSL_RC_OOM!=rc){
        rc = fsl_cx_err_set(f, rc, "Error %R finding the checkin time "
                            "of file %s in checkin RID %" FSL_ID_T_PFMT ".",
                            rc, xs->fCard->name, xs->checkinRid);
      }
      goto end;
    }
    if(!coState.dryRun){
      rc = fsl__cfs_mtime_set(f, zFilename, mtime);
      if(rc){
        rc = fsl_cx_err_set(f, rc, "Error %s setting mtime of file: %s",
                            fsl_rc_cstr(rc), zFilename);
        goto end;
      }
    }
  }
  do_callback:
  assert(0==rc);
  if(rec->cOpt->callback){
    assert(mtime);
    coState.mtime = mtime;
    coState.extractState = xs;
    coState.callbackState = rec->cOpt->callbackState;
    if(loadedContent){
      coState.size = content->used;
    }else{
      fsl_stmt_reset(&rec->stRidSize);
      fsl_stmt_bind_id(&rec->stRidSize, 1, xs->fileRid);
      coState.size =
        (FSL_RC_STEP_ROW==fsl_stmt_step(&rec->stRidSize))
        ? (fsl_int_t)fsl_stmt_g_int64(&rec->stRidSize, 0)
        : -1;
    }
    rc = rec->cOpt->callback( &coState );
    if(rc && !f->error.code && FSL_RC_OOM!=rc){
      rc = fsl_cx_err_set(f, rc, "Error %R returned from checkout "
                          "callback for file: %s", rc, xs->fCard->name);
    }
  }
  end:
  fsl_b_reuse(content);
  rec->tgtDir->used = rec->tgtDirLen;
  rec->tgtDir->mem[rec->tgtDirLen] = 0;
  return rc;
}

/**
   For each file in vfile(vid=rec->originRid) which is not in the
   current vfile(vid=rec->cOpt->checkinRid), remove it from disk (or
   not, depending on confirmer response). Afterwards, try to remove
   any dangling directories left by that removal.

   Returns 0 on success. Ignores any filesystem-level errors during
   removal because, frankly, we have no recovery strategy for that
   case.

   TODO: do not remove dirs from the 'empty-dirs' config setting.
*/
static int fsl_repo_ckout_rm_list_fini(fsl_cx * f,
                                       RepoExtractCkup * rec){
  int rc;
  fsl_db * db = fsl_cx_db_ckout(f);
  fsl_stmt q = fsl_stmt_empty;
  fsl_b * absPath = fsl__cx_scratchpad(f);
  fsl_size_t const ckdirLen = f->db.ckout.dirLen;
  char const *zAbs;
  int rmCounter = 0;
  fsl_ckup_opt const * cOpt = rec->cOpt;
  fsl_ckup_state cuState = fsl_ckup_state_empty;
  fsl_repo_extract_state rxState = fsl_repo_extract_state_empty;
  fsl_card_F fCard = fsl_card_F_empty;
  
  assert(db);
  rc = fsl_b_append(absPath, f->db.ckout.dir,
                         (fsl_int_t)f->db.ckout.dirLen);
  if(rc) goto end;
  /* Select files which were in the previous version
     (rec->originRid) but are not in the newly co'd version
     (cOpt->checkinRid). */
  rc = fsl_db_prepare(db, &q,
                      "SELECT "
                      /*0*/"v.rid frid,"
                      /*1*/"v.pathname fn,"
                      /*2*/"b.uuid,"
                      /*3*/"v.isexe,"
                      /*4*/"v.islink,"
                      /*5*/"v.chnged, "
                      /*6*/"b.size "
                      "FROM {{dbname.ckout}}.vfile v, {{dbname.repo}}.blob b "
                      "WHERE v.vid=%" FSL_ID_T_PFMT " "
                      "AND v.rid=b.rid "
                      "AND fn NOT IN "
                      "(SELECT pathname FROM {{dbname.ckout}}.vfile "
                      " WHERE vid=%" FSL_ID_T_PFMT
                      ") "
                      "ORDER BY fn %s /*%s()*/",
                      rec->originRid,
                      cOpt->checkinRid
                      /*new checkout version resp. update target
                        version*/,
                      fsl_cx_filename_collation(f),
                      __func__);
  if(rc) goto end;

  rec->confirmAnswer.response = FSL_CRESPONSE_INVALID;
  cuState.mtime = 0;
  cuState.size = -1;
  cuState.callbackState = cOpt->callbackState;
  cuState.extractState = &rxState;
  cuState.dryRun = cOpt->dryRun;
  cuState.fileChangeType = FSL_CKUP_FCHANGE_RM;
  rxState.f = f;
  rxState.fCard = &fCard;
  rxState.checkinRid = cOpt->checkinRid;
  while(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q))){
    /**
       Each row is one file listed in vfile (the old checkout
       version) which is not in vfile (the new checkout).
    */
    fsl_size_t nFn = 0;
    fsl_size_t hashLen = 0;
    char const * fn = fsl_stmt_g_text(&q, 1, &nFn);
    char const * hash = fsl_stmt_g_text(&q, 2, &hashLen);
    bool const isChanged = fsl_stmt_g_int32(&q, 5)!=0;
    int64_t const fSize = fsl_stmt_g_int64(&q, 6);
    if(FSL_CRESPONSE_ALWAYS!=rec->confirmAnswer.response){
      /**
         If the user has previously responded to
         FSL_CEVENT_RM_MOD_UNMGD_FILE, keep that response, else
         ask again if the file was flagged as changed in the
         vfile table before all of this started.
      */
      if(isChanged){
        // Modified: ask user unless they've already answered NEVER.
        if(FSL_CRESPONSE_NEVER!=rec->confirmAnswer.response){
          fsl_confirm_detail detail = fsl_confirm_detail_empty;
          detail.eventId = FSL_CEVENT_RM_MOD_UNMGD_FILE;
          detail.filename = fn;
          rec->confirmAnswer.response = FSL_CRESPONSE_INVALID;
          rc = fsl_cx_confirm(f, &detail, &rec->confirmAnswer);
          if(rc) goto end;
        }
      }else{
        // Not modified. Nuke it.
        rec->confirmAnswer.response = FSL_CRESPONSE_YES;
      }
    }
    absPath->used = ckdirLen;
    rc = fsl_b_append(absPath, fn, nFn);
    if(rc) break;
    zAbs = fsl_b_cstr(absPath);
    /* Ignore deletion errors. We cannot roll back previous deletions,
       so failing here, which would roll back the transaction, could
       leave the checkout in a weird state, potentially with some
       files missing and others not. */
    switch(rec->confirmAnswer.response){
      case FSL_CRESPONSE_YES:
      case FSL_CRESPONSE_ALWAYS:
        //MARKER(("Unlinking: %s\n",zAbs));
        if(!cOpt->dryRun && 0==fsl__cfs_unlink(f, zAbs)){
          ++rmCounter;
        }
        cuState.fileRmInfo = FSL_CKUP_RM;
        break;
      case FSL_CRESPONSE_NO:
      case FSL_CRESPONSE_NEVER:
        //assert(FSL_RECO_MOD_YES==modType);
        //MARKER(("NOT removing locally-modified file: %s\n", zN));
        cuState.fileRmInfo = FSL_CKUP_RM_KEPT;
        break;
      case FSL_CRESPONSE_CANCEL:
        rc = fsl_cx_err_set(f, FSL_RC_BREAK,
                            "Checkout operation cancelled by "
                            "confirmation callback. "
                            "Filesystem contents may now be "
                            "in an inconsistent state!");
        goto end;
      default:
        rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                            "Invalid response from confirmation "
                            "callback.");
        goto end;
    }
    if(!cOpt->callback) continue;
    /* Now report the deletion to the callback... */
    fsl_id_t const frid = fsl_stmt_g_id(&q, 0);
    const bool isExe = 0!=fsl_stmt_g_int32(&q, 3);
    const bool isLink = 0!=fsl_stmt_g_int32(&q, 4);
    cuState.size = (FSL_CKUP_RM==cuState.fileRmInfo) ? -1 : fSize;
    rxState.fileRid = frid;
    fCard = fsl_card_F_empty;
    fCard.name = (char *)fn;
    fCard.uuid = (char *)hash;
    fCard.perm = isExe ? FSL_FILE_PERM_EXE :
      (isLink ? FSL_FILE_PERM_LINK : FSL_FILE_PERM_REGULAR);
    rc = cOpt->callback( &cuState );
    if(rc){
      if(!f->error.code && FSL_RC_OOM!=rc){
        rc = fsl_cx_err_set(f, rc, "Error %R returned from checkout "
                            "callback for removed file: %s", rc, fn);
      }
      goto end;
    }
  }
  if(FSL_RC_STEP_DONE==rc) rc = 0;
  else goto end;
  if(rmCounter>0){
    /* Clean up any empty directories left over by removal of
       files... */
    assert(!cOpt->dryRun);
    fsl_stmt_finalize(&q);
    /* Select dirs which were in the previous version
       (rec->originRid) but are not in the newly co'd version
       (cOpt->checkinRid). Any of these may _potentially_
       be empty now. This query could be improved to filter 
       out more in advance. */
    rc = fsl_db_prepare(db, &q,
                        "SELECT DISTINCT(fsl_dirpart(pathname,0)) dir "
                        "FROM {{dbname.ckout}}.vfile "
                        "WHERE vid=%" FSL_ID_T_PFMT " "
                        "AND pathname NOT IN "
                        "(SELECT pathname FROM {{dbname.ckout}}.vfile "
                        "WHERE vid=%" FSL_ID_T_PFMT ") "
                        "AND dir IS NOT NULL "
                        "ORDER BY length(dir) DESC /*%s()*/",
                        /*get deepest dirs first*/
                        rec->originRid, cOpt->checkinRid,
                        __func__);
    if(rc) goto end;
    while(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q))){
      fsl_size_t nFn = 0;
      char const * fn = fsl_stmt_g_text(&q, 0, &nFn);
      absPath->used = ckdirLen;
      rc = fsl_b_append(absPath, fn, nFn);
      if(rc) break;
      fsl__ckout_rm_empty_dirs(f, absPath)
        /* To see this in action, use (f-co tip) to check out the tip of
           a repo, then use (f-co rid:1) to back up to the initial empty
           checkin. It "should" leave you with a directory devoid of
           anything but .fslckout and any non-SCM'd content.
        */;
    }
    if(FSL_RC_STEP_DONE==rc) rc = 0;
  }
  end:
  fsl_stmt_finalize(&q);
  fsl__cx_scratchpad_yield(f, absPath);
  return fsl_cx_uplift_db_error2(f, db, rc);
}

int fsl_repo_ckout(fsl_cx * f, fsl_ckup_opt const * cOpt){
  int rc = 0;
  fsl_id_t const prevRid = f->db.ckout.rid;
  fsl_db * const dbR = fsl_needs_repo(f);
  RepoExtractCkup rec = RepoExtractCkup_empty;
  fsl_confirmer oldConfirm = fsl_confirmer_empty;
  if(!dbR) return f->error.code;
  else if(!fsl_needs_ckout(f)) return f->error.code;
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) return rc;
  rec.tgtDir = fsl__cx_scratchpad(f);
  if(cOpt->confirmer.callback){
    fsl_cx_confirmer(f, &cOpt->confirmer, &oldConfirm);
  }
  //MARKER(("ckout.rid=%d\n",(int)prevRid));
  if(prevRid>=0 && cOpt->scanForChanges){
    /* We need to ensure this state is current in order to determine
       whether a given file is locally modified vis-a-vis the
       pre-extract checkout state. */
    rc = fsl_vfile_changes_scan(f, prevRid, 0);
    if(rc) goto end;
  }
  if(0){
    fsl_db_each(dbR,fsl_stmt_each_f_dump, f,
                "SELECT * FROM {{dbname.ckout}}.vfile ORDER BY pathname");
  }
  assert(f->db.ckout.dirLen);
  fsl_repo_extract_opt eOpt = fsl_repo_extract_opt_empty;
  rc = fsl_b_append(rec.tgtDir, f->db.ckout.dir,
                         (fsl_int_t)f->db.ckout.dirLen);
  if(rc) goto end;
  if(prevRid){
    rc = fsl_db_prepare(dbR, &rec.stChanged,
                        "SELECT chnged FROM {{dbname.ckout}}.vfile "
                        "WHERE vid=%" FSL_ID_T_PFMT
                        " AND pathname=? %s",
                        prevRid,
                        fsl_cx_filename_collation(f));
  }
  if(!rc && prevRid){
    /* Optimization: before we load content for a blob and write it to
       a file, check this query for whether we already have the same
       name/rid combination in vfile, and skip loading/writing the
       content if we do. */
    rc = fsl_db_prepare(dbR, &rec.stIsInVfile,
                        "SELECT 1 FROM {{dbname.ckout}}.vfile "
                        "WHERE vid=%" FSL_ID_T_PFMT
                        " AND pathname=? AND rid=? %s",
                        prevRid, fsl_cx_filename_collation(f));
  }
  if(!rc){
    /* Files for which we don't load content (see rec.stIsInVfile)
       still have a size we need to report via fsl_ckup_state,
       and we fetch that with this query. */
    rc = fsl_db_prepare(dbR, &rec.stRidSize,
                        "SELECT size FROM {{dbname.repo}}.blob WHERE rid=?");
  }
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, dbR, rc);
    goto end;
  }
  rec.originRid = prevRid;
  rec.tgtDirLen = f->db.ckout.dirLen;
  eOpt.checkinRid = cOpt->checkinRid;
  eOpt.extractContent = false;
  eOpt.callbackState = &rec;
  eOpt.callback = fsl_repo_extract_f_ckout;
  rec.eOpt = &eOpt;
  rec.cOpt = cOpt;
  rc = fsl_repo_extract(f, &eOpt);
  if(!rc){
    /*
      We need to call fsl_vfile_load(f, cOpt->vid) to
      populate vfile but we also need to call
      fsl_vfile_changes_scan(f, cOpt->vid, 0) to set the vfile.mtime
      fields. The latter calls the former, so...
    */
    rc = fsl_vfile_changes_scan(f, cOpt->checkinRid,
                                FSL_VFILE_CKSIG_WRITE_CKOUT_VERSION
                                |
                                (prevRid==0
                                 ? 0 : FSL_VFILE_CKSIG_KEEP_OTHERS)
                                |
                                (cOpt->setMtime
                                 ? 0 : FSL_VFILE_CKSIG_SETMTIME)
                                /* Note that mtimes were set during
                                   extraction if cOpt->setMtime is
                                   true. */);
    if(rc) goto end;
    assert(f->db.ckout.rid==cOpt->checkinRid);
    assert(f->db.ckout.rid ? !!f->db.ckout.uuid : 1);
  }
  if(!rc && prevRid!=0){
    rc = fsl_repo_ckout_rm_list_fini(f, &rec);
    if(rc) goto end;
  }
  if(!rc) rc = fsl_ckout_manifest_write(f, -1, -1, -1, NULL)
    /* Unconditional, this replaced an extraction error with 0, so a
       checkout with missing content reported success. */;

  end:
  if(!rc){
    rc = fsl_vfile_unload_except(f, cOpt->checkinRid);
    if(!rc) rc = fsl__ckout_clear_merge_state(f, FSL__MERGE_CLEAR_ALL);
  }
  /*
    TODO: if "repo-cksum" config db setting is set, confirm R-card of
    cOpt->checkinRid against on-disk contents.
  */
  if(cOpt->confirmer.callback){
    fsl_cx_confirmer(f, &oldConfirm, NULL);
  }
  fsl_stmt_finalize(&rec.stChanged);
  fsl_stmt_finalize(&rec.stIsInVfile);
  fsl_stmt_finalize(&rec.stRidSize);
  fsl__cx_scratchpad_yield(f, rec.tgtDir);
  int const rc2 = fsl_cx_txn_end(f, rc || cOpt->dryRun);
  return rc ? rc : rc2;
}

/**
   Copies the unmanaged file zFullPath to zFullPath-original or, if
   that exists, to the first zFullPath-original-N which does not, as
   fossil(1)'s update does before overwriting such a file.
*/
static int fsl__ckout_backup_unmanaged(fsl_cx * const f,
                                       char const * zFullPath){
  fsl_b * const b = fsl_cx_b_borrow(f);
  int rc = b ? fsl_b_appendf(b, "%s-original", zFullPath) : f->error.code;
  int n = 0;
  while( 0==rc && fsl__cfs_size(f, fsl_b_cstr(b))>=0 ){
    fsl_b_reuse(b);
    rc = fsl_b_appendf(b, "%s-original-%d", zFullPath, n++);
  }
  if( 0==rc ){
    rc = fsl__cfs_copy(f, zFullPath, fsl_b_cstr(b));
    if( rc ){
      rc = fsl_cx_err_set(f, rc, "Error %R copying %s to %b",
                          rc, zFullPath, b);
    }
  }
  if( b ) fsl_cx_b_return(f, b);
  return rc;
}

static int fsl__ckout_update_impl(fsl_cx * f, fsl_ckup_opt const *cuOpt){
  fsl_db * const dbR = fsl_needs_repo(f);
  fsl_db * const dbC = dbR ? fsl_needs_ckout(f) : 0;
  if(!dbR) return FSL_RC_NOT_A_REPO;
  else if(!dbC) return FSL_RC_NOT_A_CKOUT;
  fsl_cx_err_reset(f);
  int rc = 0, rc2 = 0;
  bool inTrans = false;
  char const * collation = fsl_cx_filename_collation(f);
  fsl_id_t const ckRid = f->db.ckout.rid /* current version */;
  fsl_id_t const tid = cuOpt->checkinRid /* target version */;
  fsl_stmt q = fsl_stmt_empty;
  fsl_stmt mtimeXfer = fsl_stmt_empty;
  fsl_stmt mtimeGet = fsl_stmt_empty;
  fsl_stmt mtimeSet = fsl_stmt_empty;
  fsl_b * bFullPath = 0;
  fsl_b * bFullNewPath = 0;
  fsl_b * bFileUuid = 0;
  fsl_repo_extract_opt eOpt = fsl_repo_extract_opt_empty
    /* We won't actually use fsl_repo_extract() here because it's a
       poor fit for the update selection algorithm, but in order to
       consolidate some code between the ckout/update cases we need to
       behave as if we were using it. */;
  fsl_repo_extract_state xState = fsl_repo_extract_state_empty;
  fsl_card_F fCard = fsl_card_F_empty;
  fsl_ckup_state uState = fsl_ckup_state_empty;
  RepoExtractCkup rec = RepoExtractCkup_empty;
  enum { MergeBufCount = 4 };
  fsl_b * bufMerge[MergeBufCount] = {
    fsl_cx_b_borrow(f)/* pivot: ridv */,
    fsl_cx_b_borrow(f)/* local file to merge into */,
    fsl_cx_b_borrow(f)/* update-to: ridt */,
    fsl_cx_b_borrow(f)/* merged copy */
  };
  if( f->error.code /* OOM via buffer borrow */ ){
    rc = f->error.code;
    goto end;
  }

  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) goto dberr;
  inTrans = true;
  if(cuOpt->scanForChanges){
    rc = fsl_vfile_changes_scan(f, ckRid, FSL_VFILE_CKSIG_ENOTFILE);
    if(rc) goto end;
  }
  if(tid != ckRid){
    uint32_t missingCount = 0;
    rc = fsl_vfile_load(f, tid, false,
                                 &missingCount);
    if(rc) goto end;
    else if(missingCount/* && !forceMissing*/){
      char * const zTid = fsl_rid_to_uuid(f, tid);
      rc = fsl_cx_err_set(f, FSL_RC_PHANTOM,
                          "Unable to update to version [%S] due to "
                          "missing content in %"PRIu32" blob(s).",
                          zTid, missingCount);
      fsl_free(zTid);
      goto end;
    }
  }
  /*
  ** The record.fn field is used to match files against each other.  The
  ** FV table contains one row for each each unique filename in
  ** in the current checkout, the pivot, and the version being merged.
  */
  rc = fsl_db_exec_multi(dbC,
    "CREATE TEMP TABLE IF NOT EXISTS {{temp.fv}}("
    "  fn TEXT %s PRIMARY KEY,"   /* The filename relative to root */
    "  idv INTEGER,"              /* VFILE entry for current version */
    "  idt INTEGER,"              /* VFILE entry for target version */
    "  chnged BOOLEAN,"           /* True if current version has been edited */
    "  islinkv BOOLEAN,"          /* True if current file is a link */
    "  islinkt BOOLEAN,"          /* True if target file is a link */
    "  ridv INTEGER,"             /* Record ID for current version */
    "  ridt INTEGER,"             /* Record ID for target */
    "  isexe BOOLEAN,"            /* Does target have execute permission? */
    "  deleted BOOLEAN DEFAULT 0,"/* File marked by "rm" to become unmanaged */
    "  fnt TEXT %s"               /* Filename of same file on target version */
    ") /*%s()*/; "
    "DELETE FROM {{temp.fv}};",
    collation, collation, __func__ );
  if(rc) goto dberr;
  /* Add files found in the current version
  */
  rc = fsl_db_exec_multi(dbC,
    "INSERT OR IGNORE INTO {{temp.fv}}("
            "fn,fnt,idv,idt,ridv,"
            "ridt,isexe,chnged,deleted"
    ") SELECT pathname, pathname, id, 0, rid, 0, "
       "isexe, chnged, deleted "
       "FROM {{dbname.ckout}}.vfile WHERE vid=%" FSL_ID_T_PFMT
       "/*%s()*/",
    ckRid, __func__
  );
  if(rc) goto dberr;

  /* Compute file name changes on V->T.  Record name changes in files that
  ** have changed locally.
  */
  if( ckRid ){
    uint32_t nChng = 0;
    fsl_id_t * aChng = 0;
    rc = fsl__find_filename_changes(f, ckRid, tid,
                                    true, &nChng, &aChng);
    if(rc){
      assert(!aChng);
      assert(!nChng);
      goto end;
    }
    if( nChng ){
      for(uint32_t i=0; i<nChng; ++i){
        rc = fsl_db_exec_multi(dbC,
          "UPDATE {{temp.fv}}"
          "   SET fnt=(SELECT name FROM {{dbname.repo}}.filename WHERE fnid=%"
              FSL_ID_T_PFMT ")"
          " WHERE fn=(SELECT name FROM {{dbname.repo}}.filename WHERE fnid=%"
            FSL_ID_T_PFMT ") AND chnged /*%s()*/",
          aChng[i*2+1], aChng[i*2], __func__
        );
        if(rc) goto dberr;
      }
      fsl_free(aChng);
    }else{
      assert(!aChng);
    }
  }/*ckRid!=0*/

  /* Add files found in the target version T but missing from the current
  ** version V.
  */
  rc = fsl_db_exec_multi(dbC,
    "INSERT OR IGNORE INTO {{temp.fv}}(fn,fnt,idv,idt,ridv,ridt,isexe,chnged)"
    " SELECT pathname, pathname, 0, 0, 0, 0, isexe, 0 FROM {{dbname.ckout}}.vfile"
    "  WHERE vid=%" FSL_ID_T_PFMT
    "    AND pathname %s NOT IN (SELECT fnt FROM {{temp.fv}}) /*%s()*/",
    tid, collation, __func__
  );
  if(rc) goto dberr;

  /*
  ** Compute the file version ids for T
  */
  rc = fsl_db_exec_multi(dbC,
    "UPDATE {{temp.fv}} SET"
    " idt=coalesce((SELECT id FROM {{dbname.ckout}}.vfile WHERE vid=%"
                   FSL_ID_T_PFMT " AND fnt=pathname),0),"
    " ridt=coalesce((SELECT rid FROM {{dbname.ckout}}.vfile WHERE vid=%"
                    FSL_ID_T_PFMT " AND fnt=pathname),0) /*%s()*/",
    tid, tid, __func__
  );
  if(rc) goto dberr;

  /*
  ** Add islink information
  */
  rc = fsl_db_exec_multi(dbC,
    "UPDATE {{temp.fv}} SET"
    " islinkv=coalesce((SELECT islink FROM {{dbname.ckout}}.vfile"
                       " WHERE vid=%" FSL_ID_T_PFMT
                         " AND fnt=pathname),0),"
    " islinkt=coalesce((SELECT islink FROM {{dbname.ckout}}.vfile"
                       " WHERE vid=%" FSL_ID_T_PFMT
                         " AND fnt=pathname),0) /*%s()*/",
    ckRid, tid, __func__
  );
  if(rc) goto dberr;

  /**
     Right here, fossil(1) permits passing on a subset of
     filenames/dirs to update, but it's apparently a little-used
     feature and we're going to skip it for the time being:

     https://fossil-scm.org/forum/forumpost/1da828facf
  */

  /*
  ** Alter the content of the checkout so that it conforms with the
  ** target
  */
  rc = fsl_db_prepare(dbC, &q,
                      "SELECT fn, idv, ridv, "/* 0..2  */
                      "idt, ridt, chnged, "   /* 3..5  */
                      "fnt, isexe, islinkv, " /* 6..8  */
                      "islinkt, deleted "     /* 9..10 */
                      "FROM {{temp.fv}} ORDER BY 1 /*%s()*/",
                      __func__);
  if(rc) goto dberr;
  rc = fsl_db_prepare(dbC, &mtimeXfer,
                      "UPDATE {{dbname.ckout}}.vfile SET mtime=(SELECT mtime FROM {{dbname.ckout}}.vfile "
                      "WHERE id=?1/*idv*/) "
                      "WHERE id=?2/*idt*/ /*%s()*/",
                      __func__);
  if(rc) goto dberr;
  rc = fsl_db_prepare(dbR, &rec.stChanged,
                      "SELECT chnged FROM {{dbname.ckout}}.vfile "
                      "WHERE vid=%" FSL_ID_T_PFMT
                      " AND pathname=? %s /*%s()*/",
                      ckRid, collation, __func__);
  if(rc) goto dberr;
  if(cuOpt->callback){
    /* Queries we need only if we need to collect info for a
       callback... */
    rc = fsl_db_prepare(dbC, &mtimeGet,
                        "SELECT mtime FROM {{dbname.ckout}}.vfile WHERE id=?1"/*idt*/);
    if(rc) goto dberr;
    rc = fsl_db_prepare(dbC, &mtimeSet,
                        "UPDATE {{dbname.ckout}}.vfile SET mtime=?2 WHERE id=?1"/*idt*/);
    if(rc) goto dberr;
    /* Files for which we don't load content still have a size we need
       to report via fsl_ckup_state, and we fetch that with this
       query. */
    rc = fsl_db_prepare(dbR, &rec.stRidSize,
                        "SELECT size FROM {{dbname.repo}}.blob WHERE rid=?");
    if(rc) goto dberr;
  }

  xState.f = f;
  xState.fCard = &fCard;
  xState.checkinRid = eOpt.checkinRid = tid;
  xState.count.fileCount =
    (uint32_t)fsl_db_g_int32(dbC, 0, "SELECT COUNT(*) FROM {{dbname.ckout}}.vfile "
                             "WHERE vid=%" FSL_ID_T_PFMT,
                             tid);
  uState.extractState = &xState;
  uState.callbackState = cuOpt->callbackState;
  uState.dryRun = cuOpt->dryRun;
  uState.fileRmInfo = FSL_CKUP_RM_NOT;
  rec.originRid = ckRid;
  rec.eOpt = &eOpt;
  rec.cOpt = cuOpt;
  rec.tgtDir = fsl__cx_scratchpad(f);
  rec.tgtDirLen = f->db.ckout.dirLen;
  rc = fsl_b_append(rec.tgtDir, f->db.ckout.dir,
                         (fsl_int_t)f->db.ckout.dirLen);
  if(rc) goto end;

  /**
     Missing features from fossil we still need for this include,
     but are not limited to:

     - file_unsafe_in_tree_path() (done, untested)
     - file_nondir_objects_on_path() (done, untested)
     - symlink_create() (done, untested)
     - ...
  */
  bFullPath = fsl__cx_scratchpad(f);
  bFullNewPath = fsl__cx_scratchpad(f);
  bFileUuid = fsl__cx_scratchpad(f);
  rc = fsl_b_append(bFullPath, f->db.ckout.dir,
                         (fsl_int_t)f->db.ckout.dirLen);
  if(rc) goto end;
  rc = fsl_b_append(bFullNewPath, f->db.ckout.dir,
                         (fsl_int_t)f->db.ckout.dirLen);
  if(rc) goto end;
  unsigned int nConflict = 0;
  while( fsl__cx_stmt_step_each(f, &q, &rc) ){
    const char *zName = fsl_stmt_g_text(&q, 0, NULL)
      /* The filename from root */;
    fsl_id_t const idv = fsl_stmt_g_id(&q, 1)
      /* VFILE entry for current */;
    fsl_id_t const ridv = fsl_stmt_g_id(&q, 2)
      /* RecordID for current */;
    fsl_id_t const idt = fsl_stmt_g_id(&q, 3)
      /* VFILE entry for target */;
    fsl_id_t const ridt = fsl_stmt_g_id(&q, 4)
      /* RecordID for target */;
    int const chnged = fsl_stmt_g_int32(&q, 5)
      /* Current is edited */;
    const char *zNewName = fsl_stmt_g_text(&q,6, NULL)
      /* New filename */;
    int const isexe = fsl_stmt_g_int32(&q, 7)
      /* EXE perm for new file */;
    int const islinkv = fsl_stmt_g_int32(&q, 8)
      /* Is current file is a link */;
    int const islinkt = fsl_stmt_g_int32(&q, 9)
      /* Is target file is a link */;
    int const deleted = fsl_stmt_g_int32(&q, 10)
      /* Marked for deletion */;
    char const *zFullPath /* Full pathname of the file */;
    char const *zFullNewPath /* Full pathname of dest */;
    bool const nameChng = !!fsl_strcmp(zName, zNewName)
      /* True if the name changed */;
    int wasWritten = 0
      /* 1=perms written to disk, 2=content written */;
    fsl_fstat fst = fsl_fstat_empty;
    if(chnged || isexe || islinkv || islinkt){/*unused*/}
    bFullPath->used = bFullNewPath->used = f->db.ckout.dirLen;
    rc = fsl_b_appendf(bFullPath, zName, -1);
    if(!rc) rc = fsl_b_appendf(bFullNewPath, zNewName, -1);
    if(rc) goto end;
    zFullPath = fsl_b_cstr(bFullPath);
    zFullNewPath = fsl_b_cstr(bFullNewPath);
    uState.mtime = 0;
    uState.fileChangeType = FSL_CKUP_FCHANGE_INVALID;
    uState.fileRmInfo = FSL_CKUP_RM_NOT;
    ++xState.count.fileNumber;
    //MARKER(("#%03u/%03d %s\n", xState.count.fileNumber, xState.count.fileCount, zName));
    if( deleted ){
      /* Carry over pending file deletions from the current version
         into the target version. If the file was already deleted in
         the target version, that will be picked up by the file-deletion
         loop later on. */
      uState.fileChangeType = FSL_CKUP_FCHANGE_RM_PROPAGATED;
      rc = fsl_db_exec(dbC, "UPDATE {{dbname.ckout}}.vfile SET deleted=1 "
                       "WHERE id=%" FSL_ID_T_PFMT" /*%s()*/",
                       idt, __func__);
      if(rc) goto dberr;
    }
    if( idv>0 && ridv==0 && idt>0 && ridt>0 ){
      /* Conflict.  This file has been added to the current checkout
      ** but also exists in the target checkout.  Use the current version.
      */
      uState.fileChangeType = FSL_CKUP_FCHANGE_CONFLICT_ADDED;
      //fossil_print("CONFLICT %s\n", zName);
      nConflict++;
    }else if( idt>0 && idv==0 ){
      /* File added in the target. */
      if( fsl__cfs_is_file_or_link(f, zFullPath) ){
        //fossil_print("ADD %s - overwrites an unmanaged file\n", zName);
        uState.fileChangeType =
          FSL_CKUP_FCHANGE_CONFLICT_ADDED_UNMANAGED;
        //nOverwrite++;
        /* TODO/FIXME: if the files have the same content, treat this
           as FSL_CKUP_FCHANGE_ADDED. If they don't, use confirmer to
           ask the user what to do. */
        if( !cuOpt->dryRun ){
          rc = fsl__ckout_backup_unmanaged(f, zFullPath);
          if(rc) goto end;
        }
      }else{
        //fsl_outputf(f, "ADD %s\n", zName);
        uState.fileChangeType = FSL_CKUP_FCHANGE_ADDED;
      }
      //if( !dryRunFlag && !internalUpdate ) undo_save(zName);
      if( !cuOpt->dryRun ){
        rc = fsl__vfile_to_ckout(f, idt, &wasWritten);
        if(rc) goto end;
      }
    }else if( idt>0 && idv>0 && ridt!=ridv && (chnged==0 || deleted) ){
      /* The file is unedited.  Change it to the target version */
      if( deleted ){
        //fossil_print("UPDATE %s - change to unmanaged file\n", zName);
        uState.fileChangeType = FSL_CKUP_FCHANGE_RM;
      }else{
        //fossil_print("UPDATE %s\n", zName);
        uState.fileChangeType = FSL_CKUP_FCHANGE_UPDATED;
      }
      if( !cuOpt->dryRun ){
        rc = fsl__vfile_to_ckout(f, idt, &wasWritten);
        if(rc) goto end;
      }
    }else if( idt>0 && idv>0 && !deleted &&
              0!=fsl__cfs_stat(f, zFullPath, NULL, false) ){
      /* The file is missing from the local check-out. Restore it to
      ** the version that appears in the target. */
      uState.fileChangeType = FSL_CKUP_FCHANGE_UPDATED;
      if( !cuOpt->dryRun ){
        rc = fsl__vfile_to_ckout(f, idt, &wasWritten);
        if(rc) goto end;
      }
    }else if( idt==0 && idv>0 ){
      /* Is in the current version but not in the target. */
      if( ridv==0 ){
        /* Added in current checkout.  Continue to hold the file as
        ** as an addition */
        uState.fileChangeType = FSL_CKUP_FCHANGE_ADD_PROPAGATED;
        rc = fsl_db_exec(dbC, "UPDATE {{dbname.ckout}}.vfile SET vid=%" FSL_ID_T_PFMT
                         " WHERE id=%" FSL_ID_T_PFMT " /*%s()*/",
                         tid, idv, __func__);
        if(rc) goto dberr;
      }else if( chnged ){
        /* Edited locally but deleted from the target.  Do not track the
        ** file but keep the edited version around. */
        uState.fileChangeType = FSL_CKUP_FCHANGE_CONFLICT_RM;
        ++nConflict;
        uState.fileRmInfo = FSL_CKUP_RM_KEPT;
        /* Delete idv from vfile so that the post-processing rm
           loop will not delete this file. */
        rc = fsl_db_exec(dbC, "DELETE FROM {{dbname.ckout}}.vfile WHERE id=%"
                         FSL_ID_T_PFMT " /*%s()*/",
                         idv, __func__);
        if(rc) goto dberr;

      }else{
        uState.fileChangeType = FSL_CKUP_FCHANGE_RM;
        if( !cuOpt->dryRun ){
          fsl__cfs_unlink(f, zFullPath)/*ignore errors*/;
          /* At this point fossil(1) adds each directory to the
             dir_to_delete table. We can probably use the same
             infrastructure which ckout uses, though. One
             hiccup there is that our infrastructure does not
             handle the locally-modified-removed case from the
             block above this one. */
        }
      }
    }else if( idt>0 && idv>0 && ridt!=ridv && chnged ){
      /* Merge the changes in the current tree into the target version */
      if( islinkv || islinkt ){
        uState.fileChangeType = FSL_CKUP_FCHANGE_CONFLICT_SYMLINK;
        ++nConflict;
      }else{
        unsigned int conflictCount = 0;
        for(int i = 0; i < MergeBufCount; ++i){
          fsl_b_reuse(bufMerge[i]);
        }
        rc = fsl_content_get(f, ridv, bufMerge[0]);
        if(!rc) rc = fsl_content_get(f, ridt, bufMerge[2]);
        if(rc){
          if(!f->error.code && FSL_RC_OOM!=rc){
            rc = fsl_cx_err_set(f, rc, "Error %R loading content of "
                                "%s (blob RIDs %" FSL_ID_T_PFMT
                                " and %" FSL_ID_T_PFMT ") for merging.",
                                rc, zName, ridv, ridt);
          }
          goto end;
        }
        rc = fsl__cfs_read(f, bufMerge[1], zFullPath);
        if(rc){
          rc = fsl_cx_err_set(f, rc, "Error %R reading file: %s",
                              rc, zFullPath);
          goto end;
        }
        rc = fsl_b_merge3(bufMerge[0], bufMerge[1],
                               bufMerge[2], bufMerge[3],
                               &conflictCount);
        if(FSL_RC_DIFF_BINARY==rc || FSL_RC_TYPE==rc){
          /* Binary content: we can't merge this, so use target
             version. fsl_b_merge3() reports binary input as
             FSL_RC_DIFF_BINARY. */
          rc = 0;
          uState.fileChangeType = FSL_CKUP_FCHANGE_UPDATED_BINARY;
          if( !cuOpt->dryRun ){
            /* bufMerge[2] holds blob ridt: a storage which writes
               blobs itself records it, else these bytes are written. */
            rc = fsl__cfs_write_blob(f, zFullNewPath, ridt, bufMerge[2],
                                     true, NULL);
            if(!rc) fsl__cfs_exec_set(f, zFullNewPath, !!isexe);
          }
        }else if(!rc){
          if( !cuOpt->dryRun ){
            rc = fsl__cfs_write(f, bufMerge[3], zFullNewPath);
            if(!rc) fsl__cfs_exec_set(f, zFullNewPath, !!isexe);
          }
          uState.fileChangeType = conflictCount
            ? FSL_CKUP_FCHANGE_CONFLICT_MERGED
            : FSL_CKUP_FCHANGE_MERGED;
          if(conflictCount) ++nConflict;
        }else if(FSL_RC_OOM!=rc){
          rc = fsl_cx_err_set(f, rc, "Error %R merging local changes "
                              "to %s into version RID #%" FSL_ID_T_PFMT ".",
                              rc, zName, tid);
          goto end;
        }
        if(rc){
          if(FSL_RC_OOM!=rc){
            rc = fsl_cx_err_set(f, rc, "Error %R writing to file: %s",
                                rc, zFullNewPath);
          }
          goto end;
        }
      }
      if( nameChng && !cuOpt->dryRun ){
        fsl__cfs_unlink(f, zFullPath);
      }
    }else{
      if( chnged ){
        if( !deleted ){
          uState.fileChangeType = FSL_CKUP_FCHANGE_EDITED;
        }else{
          assert(FSL_CKUP_FCHANGE_RM_PROPAGATED==uState.fileChangeType);
        }
      }else{
        uState.fileChangeType = FSL_CKUP_FCHANGE_NONE;
        rc = fsl_stmt_bind_step(&mtimeXfer, "RR", idv, idt);
        if(rc) goto dberr;
      }
    }
    if(wasWritten && cuOpt->setMtime){
      if(0==fsl_mtime_of_manifest_file(f, tid, ridt, &uState.mtime)){
        fsl__cfs_mtime_set(f, zFullNewPath, uState.mtime);
        rc = fsl_stmt_bind_step(&mtimeSet, "RI", idt, uState.mtime);
        if(rc) goto dberr;
      }else{
        /* Leaving the mtime as-is is harmless, but an error left on f
           would make later fsl_cx_b_borrow() calls fail. */
        uState.mtime = 0;
        fsl_cx_err_reset(f);
      }
    }
    assert(FSL_CKUP_FCHANGE_INVALID != uState.fileChangeType);
    assert(!rc);
    if(cuOpt->callback
       && (FSL_CKUP_FCHANGE_RM != uState.fileChangeType)
       /* removals are reported separately in the file
          deletion phase */){
      if(FSL_CKUP_FCHANGE_ADD_PROPAGATED==uState.fileChangeType){
        /* This file is not yet in SCM, so its size is not in
           the db. */
        if(0==fsl__cfs_stat(f, zFullNewPath, &fst, false)){
          uState.size = (fsl_int_t)fst.size;
          uState.mtime = fst.mtime;
        }else{
          uState.size = -1;
        }
      }else{
        /* If we have the record's size in the db, use that. */
        fsl_stmt_bind_id(&rec.stRidSize, 1, ridt);
        if(FSL_RC_STEP_ROW==fsl_stmt_step(&rec.stRidSize)){
          uState.size = fsl_stmt_g_int32(&rec.stRidSize, 0);
        }else{
          uState.size = -1;
        }
        fsl_stmt_reset(&rec.stRidSize);
      }
      if(!uState.mtime){
        fsl_stmt_bind_id(&mtimeGet, 1, idt);
        if(FSL_RC_STEP_ROW==fsl_stmt_step(&mtimeGet)){
          uState.mtime = fsl_stmt_g_id(&mtimeGet, 0);
        }
        if(0==uState.mtime && 0==fsl__cfs_stat(f, zFullNewPath, &fst, false)){
          uState.mtime = fst.mtime;
        }
        fsl_stmt_reset(&mtimeGet);
      }
      xState.fileRid = ridt;
      fCard.name = (char *)zNewName;
      fCard.priorName = (char *)(nameChng ? zName : NULL);
      fCard.perm = islinkt ? FSL_FILE_PERM_LINK
        : (isexe ? FSL_FILE_PERM_EXE : FSL_FILE_PERM_REGULAR);
      if(ridt){
        rc = fsl_rid_to_uuid2(f, ridt, bFileUuid);
        if(rc) goto end;
        fCard.uuid = fsl_b_str(bFileUuid);
      }else{
        //MARKER(("ridt=%d uState.fileChangeType=%d name=%s\n",
        //        ridt, uState.fileChangeType, fCard.name));
        assert(FSL_CKUP_FCHANGE_CONFLICT_RM==uState.fileChangeType
               || FSL_CKUP_FCHANGE_ADD_PROPAGATED==uState.fileChangeType
               || FSL_CKUP_FCHANGE_EDITED==uState.fileChangeType
               );
        fCard.uuid = 0;
      }
      rc = cuOpt->callback( &uState );
      if(rc){
        if(!f->error.code && FSL_RC_OOM!=rc){
          rc = fsl_cx_err_set(f, rc, "Error %R returned from update "
                              "callback for file: %s", rc, zNewName);
        }
        goto end;
      }
      uState.mtime = 0;
    }
  }/*fsl_stmt_step(&q)*/
  fsl_stmt_finalize(&q);
  if(rc) goto end;
  if(nConflict){/*unused*/}
  /*
    At this point, fossil(1) does:

    ensure_empty_dirs_created(1);
    checkout_set_all_exe();
  */
  assert(!rc);
  rc = fsl_repo_ckout_rm_list_fini(f, &rec);
  if(!rc){
    rc = fsl_vfile_unload_except(f, tid);
  }
  if(!rc){
    rc = fsl__ckout_version_write(f, tid, 0);
  }

  end:
  /* clang bug? If we declare rc2 here, it says "expression expected".
     Moving the decl to the top resolves it. Wha? */
  if(rec.tgtDir) fsl__cx_scratchpad_yield(f, rec.tgtDir);
  if(bFullPath) fsl__cx_scratchpad_yield(f, bFullPath);
  if(bFullNewPath) fsl__cx_scratchpad_yield(f, bFullNewPath);
  if(bFileUuid) fsl__cx_scratchpad_yield(f, bFileUuid);
  for(int i = 0; i < MergeBufCount; ++i){
    fsl_cx_b_return(f, bufMerge[i]);
  }
  fsl_stmt_finalize(&rec.stRidSize);
  fsl_stmt_finalize(&rec.stChanged);
  fsl_stmt_finalize(&mtimeGet);
  fsl_stmt_finalize(&mtimeSet);
  fsl_stmt_finalize(&q);
  fsl_stmt_finalize(&mtimeXfer);
  if(inTrans){
    fsl__db_temp_drop(dbC, "fv");
    rc2 = fsl_db_txn_end(dbC, !!rc);
    if(!rc && rc2) rc = fsl_cx_uplift_db_error2(f, dbC, rc2);
  }
  return rc;
  dberr:
  assert(rc);
  rc = fsl_cx_uplift_db_error2(f, dbC, rc);
  goto end;
}


/** Helper for generating a list of ambiguous leaf UUIDs. */
struct AmbiguousLeavesOutput {
  int count;
  int rc;
  fsl_b * buffer;
};
typedef struct AmbiguousLeavesOutput AmbiguousLeavesOutput;
static const AmbiguousLeavesOutput AmbiguousLeavesOutput_empty =
  {0, 0, NULL};

static int fsl_stmt_each_f_ambiguous_leaves( fsl_stmt * stmt, void * state ){
  AmbiguousLeavesOutput * alo = (AmbiguousLeavesOutput*)state;
  if(alo->count++){
    alo->rc = fsl_b_append(alo->buffer, ", ", 2);
  }
  if(!alo->rc){
    fsl_size_t n = 0;
    char const * uuid = fsl_stmt_g_text(stmt, 0, &n);
    assert(n==FSL_STRLEN_SHA1 || n==FSL_STRLEN_K256);
    alo->rc = fsl_b_append(alo->buffer, uuid, 16);
  }
  return alo->rc;
}

int fsl_ckout_calc_update_version(fsl_cx * f, fsl_id_t * outRid){
  fsl_db * const dbRepo = fsl_needs_repo(f);
  if(!dbRepo) return FSL_RC_NOT_A_REPO;
  else if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  int rc = 0;
  fsl_id_t tgtRid = 0;
  fsl_leaves_compute_e leafMode = FSL_LEAVES_COMPUTE_OPEN;
  fsl_id_t const ckRid = f->db.ckout.rid;
  rc = fsl_leaves_compute(f, ckRid, leafMode);
  if(rc) goto end;
  if( !fsl_leaves_computed_has(f) ){
    leafMode = FSL_LEAVES_COMPUTE_ALL;
    rc = fsl_leaves_compute(f, ckRid, leafMode);
    if(rc) goto end;
  }
  /* Delete [leaves] entries from any branches other than
     ckRid's... */
  rc = fsl_db_exec_multi(dbRepo,
        "DELETE FROM {{temp.leaves}} WHERE rid NOT IN"
        " (SELECT leaves.rid FROM {{temp.leaves}} AS leaves, {{dbname.repo}}.tagxref AS tagxref"
        "  WHERE leaves.rid=tagxref.rid "
        "    AND tagxref.tagid=%d /*FSL_TAGID_BRANCH*/"
        "    AND tagxref.value=="
        "      (SELECT value FROM {{dbname.repo}}.tagxref"
        "       WHERE tagid=%d /*FSL_TAGID_BRANCH*/ AND rid=%"
        FSL_ID_T_PFMT "))",
        FSL_TAGID_BRANCH, FSL_TAGID_BRANCH, ckRid
  );
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, dbRepo, rc);
    goto end;
  }
  else if( fsl_leaves_computed_count(f)>1 ){
    AmbiguousLeavesOutput alo = AmbiguousLeavesOutput_empty;
    alo.buffer = fsl__cx_scratchpad(f);
    rc = fsl_b_append(alo.buffer,
                           "Multiple viable descendants found: ", -1);
    if(!rc){
      fsl_stmt q = fsl_stmt_empty;
      rc = fsl_db_prepare(dbRepo, &q, "SELECT uuid FROM {{dbname.repo}}.blob "
                          "WHERE rid IN {{temp.leaves}} ORDER BY uuid");
      if(!rc){
        rc = fsl_stmt_each(&q, fsl_stmt_each_f_ambiguous_leaves, &alo);
        if(!rc){
          rc = fsl_cx_err_set(f, FSL_RC_AMBIGUOUS, "%b", alo.buffer);
        }
      }
      fsl_stmt_finalize(&q);
      if(rc && FSL_RC_AMBIGUOUS!=rc){
        rc = fsl_cx_uplift_db_error2(f, dbRepo, rc);
      }
    }
    fsl__cx_scratchpad_yield(f, alo.buffer);
  }
  end:
  if(!rc){
    tgtRid = fsl_leaves_computed_latest(f);
    *outRid = tgtRid;
    //MARKER(("ckRid=%d tgtRid=%d\n", (int)ckRid, (int)tgtRid));
    fsl_leaves_computed_cleanup(f)
      /* We might want to keep [leaves] around for the case where we
         return FSL_RC_AMBIGUOUS, to give the client a way to access
         that list in its raw form. Higher-level code could join that
         with the event table to give the user more context. */;
  }
  return rc;
}

void fsl_ckout_manifest_setting(fsl_cx *f, int *m){
  if(!m){
    f->cache.manifestSetting = -1;
    return;
  }else if(f->cache.manifestSetting>=0){
    *m = f->cache.manifestSetting;
    return;
  }
  char * str = fsl_config_get_text(f, FSL_CONFDB_VERSIONABLE,
                                   "manifest", NULL);
  if(!str){
    str = fsl_config_get_text(f, FSL_CONFDB_REPO,
                              "manifest", NULL);
  }
  *m = 0;
  if(str){
    char const * z = str;
    if('1'==*z || 0==fsl_strncmp(z,"on",2)
       || 0==fsl_strncmp(z,"true",4)){
      z = "ru"/*historical default*/;
    }else if(!fsl_str_bool(z)){
      z = "";
    }
    for(;*z;++z){
      switch(*z){
        case 'r': *m |= FSL_MANIFEST_MAIN; break;
        case 'u': *m |= FSL_MANIFEST_UUID; break;
        case 't': *m |= FSL_MANIFEST_TAGS; break;
        default: break;
      }
    }
    fsl_free(str);
  }
  f->cache.manifestSetting = (short)*m;
}

int fsl_ckout_manifest_write(fsl_cx * const f, int manifest, int manifestUuid,
                             int manifestTags, int * const wrote){
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return FSL_RC_NOT_A_CKOUT;
  else if(!f->db.ckout.rid){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Checkout RID is 0, so it has no manifest.");
  }
  int W = 0;
  int rc = 0;
  fsl_b * const b = fsl__cx_scratchpad(f);
  fsl_b * const content = fsl__cx_content_buffer(f);
  char * str = 0;
  fsl_time_t const mtime = f->db.ckout.mtime>0
    ? fsl_julian_to_unix(f->db.ckout.mtime)
    : 0;
  fsl_b_reuse(content);
  if(manifest<0 || manifestUuid<0 || manifestTags<0){
    int setting = 0;
    fsl_ckout_manifest_setting(f, &setting);
    if(manifest<0 && setting & FSL_MANIFEST_MAIN) manifest=1;
    if(manifestUuid<0 && setting & FSL_MANIFEST_UUID) manifestUuid=1;
    if(manifestTags<0 && setting & FSL_MANIFEST_TAGS) manifestTags=1;
  }
  rc = fsl_b_append(b, f->db.ckout.dir, (fsl_int_t)f->db.ckout.dirLen);
  if(rc) goto end;
  if(manifest>0){
    rc = fsl_b_append(b, "manifest", 8);
    if(rc) goto end;
    bool writeFailed = false;
    rc = fsl__cfs_write_blob(f, fsl_b_cstr(b), f->db.ckout.rid, content,
                             false, &writeFailed);
    if(rc){
      if(writeFailed){
        rc = fsl_cx_err_set(f, rc, "Error %R writing file: %b", rc, b);
      }
      goto end;
    }
    if(mtime) fsl__cfs_mtime_set(f, fsl_b_cstr(b), mtime);
    W |= FSL_MANIFEST_MAIN;
  }else{
    bool managed = false;
    rc = fsl_db_exists2(db, &managed,
                        "SELECT 1 FROM {{dbname.ckout}}.vfile WHERE "
                        "pathname='manifest' /*%s()*/",
                        __func__);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      goto end;
    }
    if(!managed){
      b->used = f->db.ckout.dirLen;
      rc = fsl_b_append(b, "manifest", 8);
      if(rc) goto end;
      fsl__cfs_unlink(f, fsl_b_cstr(b));
    }
  }

  if(manifestUuid>0){
    b->used = f->db.ckout.dirLen;
    fsl_b_reuse(content);
    rc = fsl_b_append(b, "manifest.uuid", 13);
    if(rc) goto end;
    assert(f->db.ckout.uuid);
    rc = fsl_b_append(content, f->db.ckout.uuid, -1);
    if(!rc) rc = fsl_b_append(content, "\n", 1);
    if(rc) goto end;
    rc = fsl__cfs_write(f, content, fsl_b_cstr(b));
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Error %R writing file: %b", rc, b);
      goto end;
    }
    if(mtime) fsl__cfs_mtime_set(f, fsl_b_cstr(b), mtime);
    W |= FSL_MANIFEST_UUID;
  }else{
    bool managed = false;
    rc = fsl_db_exists2(db, &managed,
                        "SELECT 1 FROM {{dbname.ckout}}.vfile WHERE "
                        "pathname='manifest.uuid' /*%s()*/",
                        __func__);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      goto end;
    }
    if(!managed){
      b->used = f->db.ckout.dirLen;
      rc = fsl_b_append(b, "manifest.uuid", 13);
      if(rc) goto end;
      fsl__cfs_unlink(f, fsl_b_cstr(b));
    }
  }

  if(manifestTags>0){
    fsl_stmt q = fsl_stmt_empty;
    fsl_db * const db = fsl_cx_db_repo(f);
    assert(db && "We can't have a checkout w/o a repo.");
    b->used = f->db.ckout.dirLen;
    fsl_b_reuse(content);
    rc = fsl_b_append(b, "manifest.tags", 13);
    if(rc) goto end;
    str = fsl_db_g_text(db, NULL, "SELECT VALUE FROM {{dbname.repo}}.tagxref "
                        "WHERE rid=%" FSL_ID_T_PFMT
                        " AND tagid=%d /*%s()*/",
                        f->db.ckout.rid, FSL_TAGID_BRANCH, __func__);
    rc = fsl_b_appendf(content, "branch %z\n", str);
    str = 0;
    if(rc) goto end;
    rc = fsl_db_prepare(db, &q,
                        "SELECT substr(tagname, 5)"
                        "  FROM {{dbname.repo}}.tagxref AS tagxref, {{dbname.repo}}.tag AS tag"
                        " WHERE tagxref.rid=%" FSL_ID_T_PFMT
                        "   AND tagxref.tagtype>0"
                        "   AND tag.tagid=tagxref.tagid"
                        "   AND tag.tagname GLOB 'sym-*'"
                        " /*%s()*/",
                        f->db.ckout.rid, __func__);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      goto end;
    }
    while( fsl__cx_stmt_step_each(f, &q, &rc) ){
      const char *zName = fsl_stmt_g_text(&q, 0, NULL);
      rc = fsl_b_appendf(content, "tag %s\n", zName);
      if(rc) break;
    }
    fsl_stmt_finalize(&q);
    if(!rc){
      rc = fsl__cfs_write(f, content, fsl_b_cstr(b));
      if(rc){
        rc = fsl_cx_err_set(f, rc, "Error %R writing file: %b", rc, b);
      }
    }
    if(rc) goto end;
    if(mtime) fsl__cfs_mtime_set(f, fsl_b_cstr(b), mtime);
    W |= FSL_MANIFEST_TAGS;
  }else{
    bool managed = false;
    rc = fsl_db_exists2(db, &managed,
                        "SELECT 1 FROM {{dbname.ckout}}.vfile WHERE "
                        "pathname='manifest.tags' /*%s()*/",
                        __func__);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      goto end;
    }
    if(!managed){
      b->used = f->db.ckout.dirLen;
      rc = fsl_b_append(b, "manifest.tags", 13);
      if(rc) goto end;
      fsl__cfs_unlink(f, fsl_b_cstr(b));
    }
  }

  end:
  if(wrote) *wrote = W;
  fsl__cx_scratchpad_yield(f, b);
  fsl__cx_content_buffer_yield(f);
  return rc;
}

/**
   Check every sub-directory of f's current checkout dir along the
   path to zFilename. If any sub-directory part is really an ordinary file
   or a symbolic link, set *errLen to the length of the prefix of zFilename
   which is the name of that object.

   Returns 0 except on allocation error, in which case it returns
   FSL_RC_OOM.  If it finds nothing untowards about the path, *errLen
   will be set to 0 (noting (much later) that that's technically
   ambiguous for files with single-letter names which are checked out
   into the system root dir (never do that)).

   Example:  Given inputs

   ckout     = /home/alice/project1
   zFilename = /home/alice/project1/main/src/js/fileA.js

   Look for objects in the following order:

   /home/alice/project/main
   /home/alice/project/main/src
   /home/alice/project/main/src/js

   If any of those objects exist and are something other than a
   directory then *errLen will be the length of the name of the first
   non-directory object seen.

   If a given element of the path does not exist in the filesystem,
   traversal stops without an error.
*/
static int fsl__ckout_nondir_file_check(fsl_cx *f, char const * zFilename,
                                        fsl_size_t * errLen);

int fsl__ckout_nondir_file_check(fsl_cx *f, char const * zFilename,
                                 fsl_size_t * errLen){
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  int rc = 0;
  int frc;
  fsl_b * const fn = fsl__cx_scratchpad(f);
  if(!fsl_is_rooted_in_ckout(f, zFilename)){
    assert(!"Misuse of this API. This condition should never fail.");
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "Path is not rooted at the "
                        "current checkout directory: %s", zFilename);
    goto end;
  }
  rc = fsl_b_append(fn, zFilename, -1);
  if(rc) goto end;
  char * z = fsl_b_str(fn);
  fsl_size_t i = f->db.ckout.dirLen;
  fsl_size_t j;
  fsl_fstat fst = fsl_fstat_empty;
  char const * const zRoot = f->db.ckout.dir;
  if(i && '/'==zRoot[i-1]) --i;
  *errLen = 0;
  while( z[i]=='/' ){
    for(j=i+1; z[j] && z[j]!='/'; ++j){}
    if( z[j]!='/' ) break;
    z[j] = 0;
    frc = fsl__cfs_stat(f, z, &fst, false);
    if(frc){
      /* A not[-yet]-existing path element is okay */
      break;
    }
    if(FSL_FSTAT_TYPE_DIR!=fst.type){
      *errLen = j;
      break;
    }
    z[j] = '/';
    i = j;
  }
  end:
  fsl__cx_scratchpad_yield(f, fn);
  return rc;
}

int fsl__ckout_safe_file_check(fsl_cx * const f, char const * zFilename){
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  int rc = 0;
  fsl_b * const fn = fsl__cx_scratchpad(f);
  if(!fsl_is_absolute_path(zFilename)){
    rc = fsl_file_canonical_name2(f->db.ckout.dir, zFilename, fn, false);
    if(rc) goto end;
    zFilename = fsl_b_cstr(fn);
  }else if(!fsl_is_rooted_in_ckout(f, zFilename)){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "Path is not rooted at the "
                        "current checkout directory: %s", zFilename);
    goto end;
  }

  fsl_size_t errLen = 0;
  rc = fsl__ckout_nondir_file_check(f, zFilename, &errLen);
  if(rc) goto end /* OOM */;
  else if(errLen){
    rc = fsl_cx_err_set(f, FSL_RC_TYPE, "Directory part of path refers "
                        "to a non-directory: %.*s",
                        (int)errLen, zFilename);
  }
  end:
  fsl__cx_scratchpad_yield(f, fn);
  return rc;
}

bool fsl_is_rooted_in_ckout(fsl_cx * const f, char const * const zAbsPath){
  return f->db.ckout.dir
    ? 0==fsl_strncmp(zAbsPath, f->db.ckout.dir, f->db.ckout.dirLen)
    /* ^^^ fossil(1) uses stricmp() there, but that's a bug. However,
       NOT using stricmp() on case-insensitive filesystems is arguably
       also a bug. */
    : false;
}

int fsl_is_rooted_in_ckout2(fsl_cx * const f, char const * const zAbsPath){
  int rc = 0;
  if(!fsl_is_rooted_in_ckout(f, zAbsPath)){
    rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Path is not rooted "
                        "in the current checkout: %s",
                        zAbsPath);
  }
  return rc;
}

int fsl__ckout_symlink_create(fsl_cx * const f, char const *zTgtFile,
                             char const * zLinkFile){
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  int rc = 0;
  fsl_b * fn = 0;
  if(!fsl_is_absolute_path(zLinkFile)){
    fn = fsl_cx_b_borrow(f);
    rc = fn
      ? fsl_file_canonical_name2(f->db.ckout.dir, zLinkFile, fn, false)
      : f->error.code;
    if(rc) goto end;
    zLinkFile = fsl_b_cstr(fn);
  }else if(0!=(rc = fsl_is_rooted_in_ckout2(f, zLinkFile))){
    goto end;
  }
  /* As fossil(1)'s vfile_to_disk(): remove whatever is there first,
     as symlink(2) will not replace it and writing a file would write
     through a link. */
  fsl__cfs_unlink(f, zLinkFile);
  rc = fsl__cfs_symlink_create(f, zTgtFile, zLinkFile,
                               fsl_cx_allows_symlinks(f, false));
  if(rc){
    rc = fsl_cx_err_set(f, rc, "Error %R writing symlink: %s",
                        rc, zLinkFile);
  }
  end:
  fsl_cx_b_return(f, fn);
  return rc;
}

/**
   Queues the directory part of the given filename into temp table
   fx_revert_rmdir for an eventual rmdir() attempt on it in
   fsl_revert_rmdir_fini().
*/
static int fsl__revert_rmdir_queue(fsl_cx * const f, fsl_db * const db,
                                   fsl_stmt * const st,
                                   char const * zFilename){
  int rc = 0;
  if( !st->stmt ){
    rc = fsl_cx_exec(f, "CREATE TEMP TABLE IF NOT EXISTS "
                     "{{temp.fx_revert_rmdir}}(n TEXT PRIMARY KEY) "
                     "WITHOUT ROWID /* %s() */", __func__);
    if(0==rc) rc = fsl_cx_prepare(f, st, "INSERT OR IGNORE INTO "
                                  "{{temp.fx_revert_rmdir}}(n) "
                                  "VALUES(fsl_dirpart(?,0)) /* %s() */",
                                  __func__);
  }
  if(0==rc){
    rc = fsl_stmt_bind_step(st, "s", zFilename);
    if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  }
  return rc;
}

/**
   Attempts to rmdir all dirs queued by fsl__revert_rmdir_queue(). Silently
   ignores rmdir failure but will return non-0 for db errors.
*/
static int fsl__revert_rmdir_fini(fsl_cx * const f){
  int rc;
  fsl_stmt st = fsl_stmt_empty;
  fsl_b * const b = fsl__cx_scratchpad(f);
  rc = fsl_cx_prepare(f, &st,
                      "SELECT fsl_ckout_dir()||n "
                      "FROM {{temp.fx_revert_rmdir}} "
                      "ORDER BY length(n) DESC /* %s() */",
                      __func__);
  while(0==rc && fsl__cx_stmt_step_each(f, &st, &rc)){
    fsl_size_t nDir = 0;
    char const * zDir = fsl_stmt_g_text(&st, 0, &nDir);
    fsl_b_reuse(b);
    rc = fsl_b_append(b, zDir, (fsl_int_t)nDir);
    if(0==rc) fsl__ckout_rm_empty_dirs(f, b);
  }
  fsl__cx_scratchpad_yield(f, b);
  fsl_stmt_finalize(&st);
  return rc;
}

static int fsl__ckout_revert_impl( fsl_cx * const f,
                                    fsl_ckout_revert_opt const * opt ){
  /**
     Reminder to whoever works on this code: the initial
     implementation was done almost entirely without the benefit of
     looking at fossil's implementation, thus this code is notably
     different from fossil's. If any significant misbehaviors are
     found here, vis a vis fossil, it might be worth reverting (as it
     were) to that implementation.
  */
  int rc;
  fsl_db * const db = fsl_needs_ckout(f);
  fsl_b * fname = 0;
  char const * zNorm = 0;
  fsl_id_t const vid = f->db.ckout.rid;
  bool inTrans = false;
  fsl_stmt q = fsl_stmt_empty;
  fsl_stmt vfUpdate = fsl_stmt_empty;
  fsl_stmt qRmdir = fsl_stmt_empty;
  fsl_b * sql = 0;
  fsl_deck vDeck = fsl_deck_empty;
  bool haveDeck = false;
  if(!db) return FSL_RC_NOT_A_CKOUT;
  assert(vid>=0);
  if(!opt->vfileIds && opt->filename && *opt->filename){
    fname = fsl__cx_scratchpad(f);
    rc = fsl_ckout_filename_check(f, opt->relativeToCwd,
                                  opt->filename, fname);
    if(rc){
      fsl__cx_scratchpad_yield(f, fname);
      return rc;
    }
    zNorm = fsl_b_cstr(fname);
    /* MARKER(("fsl_ckout_unmanage(%d, %s) ==> %s\n", opt->relativeToCwd, opt->filename, zNorm)); */
    assert(zNorm);
    if(fname->used) fsl_b_strip_slashes(fname);
    if(1==fname->used && '.'==*zNorm){
      /* Special case: handle "." from ckout root intuitively */
      fsl_b_reuse(fname);
      assert(0==*zNorm);
    }
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) goto end;
  inTrans = true;
  if(opt->scanForChanges){
    rc = fsl_vfile_changes_scan(f, 0, 0);
    if(rc) goto end;
  }
  sql = fsl__cx_scratchpad(f);
  rc = fsl__db_appendf(db, sql,
                          "SELECT id, rid, deleted, "
                          "fsl_ckout_dir()||pathname, "
                          "fsl_ckout_dir()||origname, chnged "
                          "FROM {{dbname.ckout}}.vfile WHERE vid=%" FSL_ID_T_PFMT " ",
                          vid);
  if(rc) goto end;
  if(zNorm && *zNorm){
    rc = fsl_b_appendf(sql,
                            "AND CASE WHEN %Q='' THEN 1 "
                            "ELSE ("
                            "     fsl_match_vfile_or_dir(pathname,%Q) "
                            "  OR fsl_match_vfile_or_dir(origname,%Q)"
                            ") END",
                            zNorm, zNorm, zNorm);
    if(rc) goto end;
  }else if(opt->vfileIds){
    rc = fsl__ckout_bag_to_ids(f, db, "{{temp.fx_revert_id}}",
                               opt->vfileIds);
    if(rc) goto end;
    rc = fsl__db_appendf(db, sql, "AND id IN {{temp.fx_revert_id}}");
    if(rc) goto end;
  }else{
    rc = fsl_b_append(sql,
                           "AND ("
                           " chnged<>0"
                           " OR deleted<>0"
                           " OR rid=0"
                           " OR coalesce(origname,pathname)"
                           "    <>pathname"
                           ")", -1);
  }
  assert(!rc);
  rc = fsl_cx_prepare(f, &q, "%b /* %s() */", sql, __func__);
  fsl__cx_scratchpad_yield(f, sql);
  sql = 0;
  if(rc) goto end;
  while((fsl__cx_stmt_step_each(f, &q, &rc))){
    fsl_id_t const id = fsl_stmt_g_id(&q, 0);
    fsl_id_t const rid = fsl_stmt_g_id(&q, 1);
    int32_t const deleted = fsl_stmt_g_int32(&q, 2);
    char const * const zName = fsl_stmt_g_text(&q, 3, NULL);
    char const * const zNameOrig = fsl_stmt_g_text(&q, 4, NULL);
    bool const renamed =
      zNameOrig ? !!fsl_strcmp(zName, zNameOrig) : false;
    int32_t const chnged = fsl_stmt_g_int32(&q, 5);
    fsl_ckout_revert_e changeType = FSL_REVERT_NONE;
    bool notInVersion = FSL_VFILE_CHANGE_MERGE_ADD==chnged
      || FSL_VFILE_CHANGE_INTEGRATE_ADD==chnged;
    if(!notInVersion && rid && vid>0){
      /* A merge-added file which was edited afterwards has lost its
         MERGE_ADD change type, so check the checkout's version
         itself, as fossil(1)'s revert does. */
      if(!haveDeck){
        rc = fsl_deck_load_rid(f, &vDeck, vid, FSL_SATYPE_CHECKIN);
        if(rc) goto end;
        haveDeck = true;
      }
      fsl_card_F const * fc = NULL;
      rc = fsl_deck_F_search2(&vDeck,
        &(renamed ? zNameOrig : zName)[f->db.ckout.dirLen], &fc);
      if(rc) goto end;
      notInVersion = !fc;
    }
    if(notInVersion && rid){
      /* Added by a merge: not in the checkout's version, so remove it
         from the checkout, as fossil(1) does. */
      rc = fsl_cx_exec(f, "DELETE FROM {{dbname.ckout}}.vfile WHERE id=%" FSL_ID_T_PFMT,
                       id);
      if(rc) goto end;
      fsl__cfs_unlink(f, zName);
      changeType = FSL_REVERT_UNMANAGE;
    }else if(!rid){ // Added but not yet checked in.
      rc = fsl_cx_exec(f, "DELETE FROM {{dbname.ckout}}.vfile WHERE id=%" FSL_ID_T_PFMT,
                       id);
      if(rc) goto end;
      changeType = FSL_REVERT_UNMANAGE;
    }else{
      int wasWritten = 0;
      if(renamed){
        if((rc=fsl__cfs_mkdir_for_file(f, zNameOrig, true))){
          rc = fsl_cx_err_set(f, rc, "Error %R creating directory "
                              "for file: %s", rc, zNameOrig);
          break;
        }
        /* Move, if possible, the new name back over the original
           name. This will possibly allow fsl__vfile_to_ckout() to
           avoid having to load that file's contents and overwrite
           it. */
        int mvCheck = fsl__cfs_stat(f, zName, NULL, false);
        if(0==mvCheck || FSL_RC_NOT_FOUND==mvCheck){
          mvCheck = fsl__cfs_unlink(f, zNameOrig);
          if(0==mvCheck || FSL_RC_NOT_FOUND==mvCheck){
            if(0==fsl__cfs_rename(f, zName, zNameOrig)){
              rc = fsl__revert_rmdir_queue(f, db, &qRmdir, zName);
              if(rc) break;
            }
          }
        }
        /* Ignore most errors: this operation is an optimization, not
           a requirement. Worse case, the entry with the old name is
           left in the filesystem. */
      }
      if(!vfUpdate.stmt){
        rc = fsl_cx_prepare(f, &vfUpdate,
                            "UPDATE {{dbname.ckout}}.vfile SET chnged=0, deleted=0, "
                            "mrid=rid, mhash=NULL, "
                            "pathname=coalesce(origname,pathname), "
                            "origname=NULL "
                            "WHERE id=?1 /*%s()*/", __func__);
        if(rc) goto end;
      }
      rc = fsl_stmt_bind_step(&vfUpdate, "R", id)
        /* Has to be done before fsl__vfile_to_ckout() because that
           function writes to vfile.pathname. */;
      if(rc) goto dberr;
      rc = fsl__vfile_to_ckout(f, id, &wasWritten);
      if(rc) break;
      //MARKER(("wasWritten=%d zName=%s\n", wasWritten, zName));
      if(opt->callback){
        if(renamed){
          changeType = FSL_REVERT_RENAME;
        }else if(wasWritten){
          changeType = (2==wasWritten)
            ? FSL_REVERT_CONTENTS
            : FSL_REVERT_PERMISSIONS;
        }else{
          if(deleted){
            changeType = FSL_REVERT_REMOVE;
          }else{
            /* This is a workaround for the fact that
               fsl__is_locally_modified(), via fsl__vfile_to_ckout(),
               does not see a modified-(only-)by-merge file as
               modified. Whether that's a bug in the former or the
               latter is unclear. Even so, it properly reverts the
               contents, which is, quite frankly, somewhat of a
               mystery at the moment. */
            assert( !wasWritten );
            changeType = FSL_REVERT_CONTENTS;
          }
        }
      }
    }/*rid!=0*/
    if(opt->callback && FSL_REVERT_NONE!=changeType){
      char const * name = renamed ? zNameOrig : zName;
      rc = opt->callback(&name[f->db.ckout.dirLen],
                         changeType, opt->callbackState);
      if(rc){
        if(!f->error.code && FSL_RC_OOM!=rc){
          rc = fsl_cx_err_set(f, rc, "Error %R returned from revert "
                              "callback for file: %s",
                              rc, &name[f->db.ckout.dirLen]);
        }
        break;
      }
    }
  }/*step() loop*/
  end:
  if(haveDeck) fsl_deck_finalize(&vDeck);
  if(fname) fsl__cx_scratchpad_yield(f, fname);
  if(sql) fsl__cx_scratchpad_yield(f, sql);
  fsl_stmt_finalize(&q);
  fsl_stmt_finalize(&vfUpdate);
  if(qRmdir.stmt){
    fsl_stmt_finalize(&qRmdir);
    if(!rc) rc = fsl__revert_rmdir_fini(f);
    fsl__db_temp_drop(db, "fx_revert_rmdir");
  }
  if(opt->vfileIds){
    fsl__db_temp_drop(db, "fx_revert_id")
      /* Ignoring result code */;
  }
  if(0==rc){
    rc = fsl__ckout_clear_merge_state(
      f, fsl_ckout_has_changes(f)
      ? FSL__MERGE_CLEAR_REVERT
      : FSL__MERGE_CLEAR_ALL
    ) /* [tag:bug:revert-merge-hiccup] */;
  }
  if(inTrans){
    int const rc2 = fsl_db_txn_end(db, !!rc);
    if(!rc && rc2) rc = fsl_cx_uplift_db_error2(f, db, rc2);
  }
  return rc;
  dberr:
  assert(rc);
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  goto end;
}

int fsl_ckout_vfile_ids( fsl_cx * const f, fsl_id_t vid,
                         fsl_id_bag * const dest, char const * zName,
                         bool relativeToCwd, bool changedOnly ) {
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  fsl_b * const canon = fsl__cx_scratchpad(f);
  int rc = fsl_ckout_filename_check(f, relativeToCwd, zName, canon);
  if(!rc){
    fsl_b_strip_slashes(canon);
    rc = fsl_filename_to_vfile_ids(f, vid, dest,
                                   fsl_b_cstr(canon),
                                   changedOnly);
  }
  fsl__cx_scratchpad_yield(f, canon);
  return rc;
}

int fsl_ckout_file_content(fsl_cx * const f, bool relativeToCwd, char const * zName,
                           fsl_b * const dest ){
  int rc;
  fsl_b * fname;
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  fname = fsl__cx_scratchpad(f);
  rc = fsl_file_canonical_name2( relativeToCwd
                                 ? NULL
                                 : fsl_cx_ckout_dir_name(f, NULL),
                                 zName, fname, 1 );
  if(!rc){
    assert(fname->used);
    if('/'==fname->mem[fname->used-1]){
      rc = fsl_cx_err_set(f, FSL_RC_MISUSE,"Filename may not have a trailing slash.");
      /* If we don't do this, we might end up reading a directory entry in raw form.
         Well, we still might. */
    }else{
      fsl_fstat fstat = fsl_fstat_empty;
      const char * zCanon = fsl_b_cstr(fname);
      rc = fsl__cfs_stat(f, zCanon, &fstat, true);
      if(rc){
        rc = fsl_cx_err_set(f, rc, "Cannot stat file %b: %R",
                            fname, rc);
      }else if(FSL_FSTAT_TYPE_FILE!=fstat.type){
        rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                            "Not a regular file: %b", fname);
      }else{
        dest->used =0;
        rc = fsl__cfs_read(f, dest, fsl_b_cstr(fname));
        if(rc){
          rc = fsl_cx_err_set(f, rc, "Error %R reading file: %b",
                              rc, fname);
        }
      }
    }
  }
  fsl__cx_scratchpad_yield(f, fname);
  return rc;
}

int fsl_card_F_ckout_mtime(fsl_cx * const f,
                           fsl_id_t vid,
                           fsl_card_F const * fc,
                           fsl_time_t * const repoMtime,
                           fsl_time_t * const localMtime){

  int rc = 0;
  fsl_id_t fid = 0;
  fsl_fstat fst = fsl_fstat_empty;
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  if(0>=vid){
    fsl_ckout_version_info(f, &vid, NULL);
  }
  fid = fsl_repo_filename_fnid(f, fc->name);
  if(fid<=0){
    rc = fsl_cx_err_get(f, NULL, NULL);
    return rc ? rc : fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                                    "Could not resolve filename: %s",
                                    fc->name);
  }
  else if(!fid){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Could not resolve filename: %s",
                          fc->name);
  }
  if(localMtime){
    rc = fsl_cx_stat(f, 0, fc->name, &fst);
    if(rc){
      /* fsl_cx_stat() has set an error naming the file and the
         stat() result. */
      return rc;
    }
    *localMtime = fst.mtime;
  }
  if(repoMtime){
    rc = fsl_mtime_of_manifest_file(f, vid, fid, repoMtime);
    if(rc && !f->error.code && FSL_RC_OOM!=rc){
      rc = fsl_cx_err_set(f, rc, "Error %R finding the checkin time "
                          "of file %s in checkin RID %" FSL_ID_T_PFMT ".",
                          rc, fc->name, vid);
    }
  }
  return rc;
}


char const ** fsl_ckout_dbnames(void){
  static char const *dbNames[] = {".fslckout", "_FOSSIL_", NULL};
  return dbNames;
}

char const * fsl_is_top_of_ckout(char const *zDirName){
  // counterpart of fossil(1)'s vfile_top_of_checkout()
  enum {BufLen = 2048};
  char nameBuf[BufLen];
  char * z = &nameBuf[0];
  fsl_size_t sz = fsl_strlcpy(z, zDirName, BufLen);
  if(sz>=(fsl_size_t)BufLen - 11/*_FOSSIL_/.fslckout suffix*/) return NULL;
  char const **dbNames = fsl_ckout_dbnames();
  char const * dbName;
  z[sz++] = '/';
  z[sz] = 0;
  for( int i = 0; NULL!=(dbName=dbNames[i]); ++i){
    fsl_strlcpy(z + sz , dbName, (fsl_size_t)BufLen - sz);
    if(fsl_file_size(z)>=1024) return dbName;
  }
  return NULL;
}

/**
   Internal helper for fsl_ckout_rename(). Performs the vfile update
   for renaming zFrom to zTo, taking into account certain
   vfile-semantics error conditions.
*/
static int fsl__mv_one_file(fsl_cx * const f, char const * zFrom,
                            char const * zTo, bool dryRun){
  fsl_db * const db = fsl_cx_db_ckout(f);
  int deleted = fsl_db_g_int32(db, -1,
                               "SELECT deleted FROM {{dbname.ckout}}.vfile WHERE vid=%"FSL_ID_T_PFMT
                               " AND pathname=%Q %s",
                               f->db.ckout.rid, zTo, fsl_cx_filename_collation(f));
  if(deleted>=0){
    if(0==deleted){
      if( !fsl_cx_is_case_sensitive(f,false) &&
          0==fsl_stricmp(zFrom, zTo) ){
        /* Case change only */
      }else{
        return fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                              "Cannot rename '%s' to '%s' because "
                              "another file named '%s' is already "
                              "under management.", zFrom, zTo, zTo);
      }
    }else{
      return fsl_cx_err_set(f, FSL_RC_CONSISTENCY,
                            "Cannot rename '%s' to '%s' because "
                            "a pending deletion of '%s' has not "
                            "yet been checked in.", zFrom, zTo, zTo);
    }
  }
  int rc = 0;
  if( !dryRun ){
    rc = fsl_cx_exec(f, "UPDATE {{dbname.ckout}}.vfile SET pathname=%Q WHERE "
                     "pathname=%Q %s AND vid=%"FSL_ID_T_PFMT,
                     zTo, zFrom, fsl_cx_filename_collation(f),
                     f->db.ckout.rid);
  }
  return rc;
}

/**
   Internal helper for fsl_ckout_rename(). Performs the filesystem-level
   moving of all files in the TEMP.ckout_mv table. All fs-level errors
   _are ignored_.
*/
static int fsl__rename_process_fmove(fsl_cx * const f){
  int rc = 0;
  fsl_stmt q = fsl_stmt_empty;
  bool const allowSymlinks = fsl_cx_allows_symlinks(f, false);
  rc = fsl_cx_prepare(f, &q, "SELECT fsl_ckout_dir()||f, "
                      "fsl_ckout_dir()||t "
                      "FROM {{temp.ckout_mv}} ORDER BY 1");
  while(0==rc && fsl__cx_stmt_step_each(f, &q, &rc)){
    char const * zFrom = fsl_stmt_g_text(&q, 0, NULL);
    char const * zTo = fsl_stmt_g_text(&q, 1, NULL);
    if(!zFrom || !zTo){fsl_report_oom; rc = FSL_RC_OOM; break;}
    //MARKER(("MOVING: %s ==> %s\n", zFrom, zTo));
    int const fromDirCheck = fsl__cfs_dir_check(f, zFrom);
    int fsrc;
    if(fromDirCheck>0){
      /* This case is "impossible." Unless... perhaps... a user
         somehow moves things around in the filesystem during the
         fsl_ckout_rename(), such that a to-be-renamed entry which was
         formerly a file is not a directory. */
#if 0
      assert(!"This case cannot possibly happen.");
      fsl__fatal(FSL_RC_CANNOT_HAPPEN,
                "Input name for a file-rename is a directory: %s",
                zFrom)/*does not return*/;
#endif
      int const toDirCheck = fsl__cfs_dir_check(f, zTo);
      if(0==toDirCheck){
        fsl__cfs_rename(f, zFrom, zTo);
      }
    }else if(fromDirCheck<0){
      if(fsl__cfs_is_symlink(f, zFrom)){
        fsrc = fsl__cfs_symlink_copy(f, zFrom, zTo, allowSymlinks);
      }else{
        fsrc = fsl__cfs_copy(f, zFrom, zTo);
      }
      if(0==fsrc){
        /* fossil(1) unconditionally unlinks zFrom if zFrom is not a
           directory. Maybe we should too? */
        fsl__cfs_unlink(f, zFrom);
      }
    }
  }
  fsl_stmt_finalize(&q);
  return rc;
}

int fsl_ckout_rename(fsl_cx * const f, fsl_ckout_rename_opt const * opt){
  int rc = 0;
  bool inTrans = false;
  fsl_b * const bDest = fsl__cx_scratchpad(f)
    /* Destination directory */;
  fsl_b * const bSrc = fsl__cx_scratchpad(f)
    /* One source file/dir */;
  fsl_stmt qName = fsl_stmt_empty;
  fsl_stmt qMv = fsl_stmt_empty;
  int origType = 0
    /* -1 == multiple input files, 0 == one file, 1 == directory */;
  int destType = 0
    /* >0==directory, 0==does not exist, <0==non-dir */;
  uint32_t srcCount = 0;

  if(!opt->src->used){
    rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                        "Expecting 1 or more source files/directories.");
    goto end;
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) goto end;
  inTrans = true;
  rc = fsl_ckout_filename_check(f, opt->relativeToCwd, opt->dest,
                                bDest);
  if(rc) goto end;
  fsl_b_strip_slashes(bDest);

  rc = fsl__db_temp_drop(fsl_cx_db(f), "ckout_mv");
  if(0==rc) rc = fsl_cx_exec(f, "CREATE TEMP TABLE IF NOT EXISTS {{temp.ckout_mv}}("
                             "f TEXT UNIQUE ON CONFLICT IGNORE, t TEXT)");
  else rc = fsl_cx_uplift_db_error2(f, fsl_cx_db(f), rc);
  if(rc) goto end;
  rc = fsl_cx_exec(f, "UPDATE {{dbname.ckout}}.vfile SET origname=pathname "
                   "WHERE origname IS NULL");
  if(rc) goto end;

  if(opt->src->used > 1){
    origType = -1;
  }else{
    /* Make opt->src->list[0] absolute and see if it resolves to an
       existing dir. */
    char const * zSrc= (char const *)opt->src->list[0];
    rc = fsl_ckout_filename_check(f, opt->relativeToCwd, zSrc, bSrc);
    if(rc) goto end;
    fsl_b * const bCheck = fsl__cx_scratchpad(f);
    int oCheck = 0;
    rc = fsl_b_append(bCheck, f->db.ckout.dir, f->db.ckout.dirLen);
    if(0==rc) rc = fsl_b_append(bCheck, bSrc->mem, bSrc->used);
    if(0==rc) oCheck = fsl__cfs_dir_check(f, fsl_b_cstr(bCheck));
    fsl__cx_scratchpad_yield(f, bCheck);
    if(rc){fsl_report_oom; goto end;}
    if(oCheck>0) origType = 1;
    else if(oCheck<0) origType = 0;
  }
  {
    /* Make bDest absolute and see if it resolves to an existing dir. */
    fsl_b * const bCheck = fsl__cx_scratchpad(f);
    rc = fsl_b_append(bCheck, f->db.ckout.dir, f->db.ckout.dirLen);
    if(0==rc) rc = fsl_b_append(bCheck, bDest->mem, bDest->used);
    if(0==rc) destType = fsl__cfs_dir_check(f, fsl_b_cstr(bCheck));
    fsl__cx_scratchpad_yield(f, bCheck);
    if(rc){fsl_report_oom; goto end;}
  }
  if(-1==origType && destType<=0){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                        "Multiple source files provided, so "
                        "destination must be an existing directory.");
    goto end;
  }else if(1==origType && destType<0){
    rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                        "Cannot rename '%s' to '%s' "
                        "because a non-directory named '%s' already exists.",
                        (char const *)opt->src->list[0],
                        opt->dest, opt->dest);
    goto end;
  }else if( 0==origType && destType<=0 ){
    /* Move single file to dest. */
    fsl_id_t vfidCheck = 0;
    rc = fsl_filename_to_vfile_id(f, 0, fsl_b_cstr(bSrc),
                                  &vfidCheck);
    if(rc) goto end;
    else if(!vfidCheck){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "File not under SCM management: %B",
                          bSrc);
      goto end;
    }
    rc = fsl_cx_exec(f, "INSERT INTO {{temp.ckout_mv}}(f,t) VALUES(%B,%B)",
                     bSrc, bDest);
    if(rc) goto end;
    else ++srcCount;
  } else {
    if(fsl_b_eq(bDest, ".", 1)){
      fsl_b_reuse(bDest);
    }else{
      rc = fsl_b_append(bDest, "/", 1);
      if(rc){fsl_report_oom; goto end;}
    }
    rc = fsl_cx_prepare(f, &qName, "SELECT pathname FROM {{dbname.ckout}}.vfile"
                        " WHERE vid=%"FSL_ID_T_PFMT
                        " AND fsl_match_vfile_or_dir(pathname,?1)"
                        " ORDER BY 1", f->db.ckout.rid);
    if(rc) goto end;
    rc = fsl_cx_prepare(f, &qMv, "INSERT INTO {{temp.ckout_mv}}(f,t) VALUES("
                        "?1, ?2||?3)");
    if(rc) goto end;
    for(fsl_size_t i = 0; i < opt->src->used; ++i){
      uint32_t nFound = 0;
      char const * zSrc = (char const *)opt->src->list[i];
      fsl_b_reuse(bSrc);
      rc = fsl_ckout_filename_check(f, opt->relativeToCwd,
                                    zSrc, bSrc);
      if(rc) goto end;
      fsl_size_t nOrig = 0;
      char const * const zOrig = fsl_b_cstr2(bSrc, &nOrig);
      rc = fsl_stmt_bind_text(&qName, 1, zOrig, (fsl_int_t)nOrig, false);
      if(rc) goto end;
      while(fsl__cx_stmt_step_each(f, &qName, &rc)){
        fsl_size_t nPath = 0;
        char const * zPath = NULL;
        ++nFound;
        rc = fsl_stmt_get_text(&qName, 0, &zPath, &nPath);
        if(rc){fsl_cx_uplift_db_error(f, qName.db); goto end;}
        else if(!zPath){fsl_report_oom; rc = FSL_RC_OOM; goto end;}
        char const * zTail;
        if(nPath==nOrig){
          zTail = fsl_file_tail(zPath);
        }else if(origType!=0 && destType>0 ){
          zTail = &zPath[nOrig-fsl_strlen(fsl_file_tail(zOrig))];
        }else{
          zTail = &zPath[nOrig+1];
        }
        rc = fsl_stmt_bind_step(&qMv, "sbs", zPath, bDest, zTail);
        if(0!=rc){
          fsl_cx_uplift_db_error(f, qMv.db);
          goto end;
        }
      }
      srcCount += nFound;
      fsl_stmt_reset(&qName);
      if(rc) goto end;
      if(!nFound){
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Name does not resolve to any "
                            "SCM-managed files: %B",
                            bSrc);
        goto end;
      }
    }/*for each opt->src*/
  }
  assert(0==rc);
  fsl_stmt_finalize(&qName);
  fsl_stmt_finalize(&qMv);
  if(0==srcCount){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "Source name(s) do not resolve to "
                        "any managed files.");
    goto end;
  }
  rc = fsl_cx_prepare(f, &qName, "SELECT f, t FROM {{temp.ckout_mv}} ORDER BY f");
  if(rc) goto end;
  //rc = fsl_cx_prepare(f, &qMv, "INSERT
  while(fsl__cx_stmt_step_each(f, &qName, &rc)){
    char const * zFrom = fsl_stmt_g_text(&qName, 0, NULL);
    char const * zTo = fsl_stmt_g_text(&qName, 1, NULL);
    rc = fsl__mv_one_file(f, zFrom, zTo, opt->dryRun);
    if(rc) goto end;
    if(opt->callback){
      rc = opt->callback(f, opt, zFrom, zTo);
      if(rc){
        if(!f->error.code && FSL_RC_OOM!=rc){
          rc = fsl_cx_err_set(f, rc, "Error %R returned from rename "
                              "callback for file: %s", rc, zFrom);
        }
        goto end;
      }
    }
  }
  end:
  fsl_stmt_finalize(&qName);
  fsl_stmt_finalize(&qMv);
  fsl__cx_scratchpad_yield(f, bDest);
  fsl__cx_scratchpad_yield(f, bSrc);
  if(0==rc){
    assert(inTrans);
    if(!opt->dryRun && opt->doFsMv){
      rc = fsl__rename_process_fmove(f);
    }
    fsl__db_temp_drop(fsl_cx_db(f), "ckout_mv");
  }
  if(inTrans){
    if(rc) fsl_cx_txn_end(f, true);
    else rc = fsl_cx_txn_end(f, false);
  }
  return rc;
}


int fsl_ckout_rename_revert(fsl_cx * const f, char const *zNewName,
                            bool relativeToCwd, bool doFsMv,
                            bool *didSomething){
  fsl_b * const bufFName = fsl__cx_scratchpad(f);
  int rc = 0;
  bool inTrans = false;
  fsl_db * const dbC = fsl_needs_ckout(f);
  fsl_stmt q = fsl_stmt_empty;
  if(!dbC) return FSL_RC_NOT_A_CKOUT;
  rc = fsl_ckout_filename_check(f, relativeToCwd, zNewName, bufFName);
  if(rc) goto end;
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) goto end;
  inTrans = true;
  rc = fsl_cx_prepare(f, &q,
                      "SELECT id FROM {{dbname.ckout}}.vfile "
                      "WHERE pathname=%Q AND origname<>pathname "
                      "and origname IS NOT NULL %s",
                      fsl_b_cstr(bufFName),
                      fsl_cx_filename_collation(f));
  if(rc) goto end;
  switch(fsl_stmt_step(&q)){
    case FSL_RC_STEP_ROW: {
      char const * zNameP = NULL;
      char const * zNameO = NULL;
      fsl_id_t const vfid = fsl_stmt_g_id(&q, 0);
      assert(vfid>0);
      fsl_stmt_finalize(&q);
      if(doFsMv){
        rc = fsl_cx_prepare(f, &q, "SELECT fsl_ckout_dir()||pathname, "
                            "fsl_ckout_dir()||origname FROM {{dbname.ckout}}.vfile "
                            "WHERE id=%"FSL_ID_T_PFMT, vfid);
        if(rc) goto end;
        rc = fsl_stmt_step(&q);
        assert(FSL_RC_STEP_ROW==rc && "We _just_ confirmed that these are there.");
        zNameP = fsl_stmt_g_text(&q, 0, NULL);
        zNameO = fsl_stmt_g_text(&q, 1, NULL);
        if(!zNameP || !zNameO) {fsl_report_oom; rc = FSL_RC_OOM; goto end;}
      }
      rc = fsl_cx_exec(f, "UPDATE {{dbname.ckout}}.vfile SET pathname=origname, origname=NULL "
                       "WHERE id=%"FSL_ID_T_PFMT, vfid);
      if(rc) goto end;
      if(didSomething) *didSomething = true;
      if(doFsMv && fsl__cfs_is_file(f, zNameP)){
        assert(zNameO && zNameP);
        fsl__cfs_unlink(f, zNameO);
        rc = fsl__cfs_mkdir_for_file(f, zNameO, false);
        if( rc ){
          rc = fsl_cx_err_set(f, rc, "fsl_mkdir_for_file(%!Q) failed with %R",
                              zNameO + f->db.ckout.dirLen, rc);
          break;
        }
        rc = fsl__cfs_rename(f, zNameP, zNameO);
        if(rc){
          rc = fsl_cx_err_set(f, rc, "File rename failed with code %R: "
                              "%!Q => %!Q", rc,
                              zNameP + f->db.ckout.dirLen,
                              zNameO + f->db.ckout.dirLen);
        }
      }
      break;
    }
    case FSL_RC_STEP_DONE:
      if(didSomething) *didSomething = false;
      goto end;
    default:
      rc = fsl_cx_uplift_db_error(f, dbC);
      goto end;
  }

  end:
  fsl_stmt_finalize(&q);
  fsl__cx_scratchpad_yield(f, bufFName);
  if(inTrans){
    if(0==rc) rc = fsl_cx_txn_end_v2(f, 0==rc, 0!=rc);
    else fsl_cx_txn_end_v2(f, false, true);
  }
  return rc;

}

char * fsl_ckout_current_branch(fsl_cx * f){
  fsl_db * const db = fsl_needs_ckout(f);
  if( !db ) return 0;
  fsl_id_t rid = 0;
  fsl_ckout_version_info(f, &rid, 0);
  if( rid<=0 ){
    fsl_cx_err_set(f, FSL_RC_RANGE,
                   "Cannot determine checkout version.");
    return 0;
  }
  char * z = 0;
  fsl_branch_of_rid(f, rid, false, &z);
  return z;
}

#undef MARKER

int fsl_ckout_update(fsl_cx * f, fsl_ckup_opt const *cuOpt){
  bool undoOwner = false;
  int rc = cuOpt->dryRun ? 0 : fsl__undo_begin(f, "update", &undoOwner);
  if(!rc) rc = fsl__ckout_update_impl(f, cuOpt);
  return fsl__undo_end(f, rc, undoOwner);
}

int fsl_ckout_revert( fsl_cx * const f,
                      fsl_ckout_revert_opt const * opt ){
  bool undoOwner = false;
  int rc = fsl__undo_begin(f, "revert", &undoOwner);
  if(!rc) rc = fsl__ckout_revert_impl(f, opt);
  return fsl__undo_end(f, rc, undoOwner);
}
/* end of file src/checkout.c */
/* start of file src/ckout_fs.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**
   Checkout file storage (fsl_ckout_fs): the fsl__cfs_xxx() file
   operations of the checkout code. Each does what the fs.c function
   it is named after does, through the context's storage, which is
   fsl_ckout_fs_os (the fs.c functions themselves) unless another one
   is installed. The derived operations (creating a file's
   directories, copying, crawling a directory, symlinks as files) are
   written once here, in terms of the storage's members, so every
   storage gets the same behaviour.
*/
#include <string.h> /* memcpy() */
#include <stddef.h> /* offsetof() */
#include <time.h>   /* time() */
#include <errno.h>  /* ENOTDIR */

const fsl_ckout_fs fsl_ckout_fs_empty = fsl_ckout_fs_empty_m;

/* fsl_ckout_fs_os's members: the fs.c functions. */
static int fsl__cfs_os_stat(void * state, char const * zName,
                            fsl_fstat * tgt, bool derefLinks){
  (void)state;
  return fsl_stat(zName, tgt, derefLinks);
}
static int fsl__cfs_os_read(void * state, char const * zName, fsl_b * tgt){
  (void)state;
  return fsl_b_fill_from_filename(tgt, zName);
}
static int fsl__cfs_os_write(void * state, char const * zName,
                             void const * src, fsl_size_t n){
  fsl_b b = fsl_b_empty;
  fsl_b_external(&b, src, n);
  return fsl_b_to_filename(&b, zName);
}
static int fsl__cfs_os_unlink(void * state, char const * zName){
  (void)state;
  return fsl_file_unlink(zName);
}
static int fsl__cfs_os_rename(void * state, char const * zFrom,
                              char const * zTo){
  (void)state;
  return fsl_file_rename(zFrom, zTo);
}
static int fsl__cfs_os_mkdir(void * state, char const * zName){
  (void)state;
  return fsl_mkdir(zName, false);
}
static int fsl__cfs_os_rmdir(void * state, char const * zName){
  (void)state;
  return fsl_rmdir(zName);
}
static int fsl__cfs_os_dirlist(void * state, char const * zDir,
                               fsl_ckout_fs_dir_f cb, void * cbState){
  (void)state;
  return fsl__dir_list(zDir, cb, cbState);
}
static int fsl__cfs_os_exec_set(void * state, char const * zName,
                                bool isExec){
  (void)state;
  return fsl_file_exec_set(zName, isExec);
}
static int fsl__cfs_os_mtime_set(void * state, char const * zName,
                                 fsl_time_t mtime){
  (void)state;
  return fsl_file_mtime_set(zName, mtime);
}
static int fsl__cfs_os_symlink_read(void * state, char const * zName,
                                    fsl_b * tgt){
  (void)state;
  return fsl_symlink_read(tgt, zName);
}
static int fsl__cfs_os_symlink_create(void * state, char const * zTarget,
                                      char const * zName){
  (void)state;
  return fsl_symlink_create(zTarget, zName, true);
}
static int fsl__cfs_os_copy(void * state, char const * zFrom,
                            char const * zTo){
  (void)state;
  return fsl_file_copy(zFrom, zTo);
}
static int fsl__cfs_os_hash(void * state, char const * zName, bool sha3,
                            fsl_b * tgt){
  (void)state;
  return sha3
    ? fsl_sha3sum_filename(zName, tgt)
    : fsl_sha1sum_filename(zName, tgt);
}

/* xWriteBlob is NULL: the library reads the blob and calls xWrite,
   as it always did. */
const fsl_ckout_fs fsl_ckout_fs_os = {
  FSL_CKOUT_FS_VERSION,
  fsl__cfs_os_stat, fsl__cfs_os_read, fsl__cfs_os_write,
  fsl__cfs_os_unlink, fsl__cfs_os_rename, fsl__cfs_os_mkdir,
  fsl__cfs_os_rmdir, fsl__cfs_os_dirlist, fsl__cfs_os_exec_set,
  fsl__cfs_os_mtime_set, fsl__cfs_os_symlink_read,
  fsl__cfs_os_symlink_create, fsl__cfs_os_copy, fsl__cfs_os_hash, NULL,
  NULL
};

/** Returns f's storage: the installed one, else fsl_ckout_fs_os. */
static fsl_ckout_fs const * fsl__cfs_get(fsl_cx const * const f){
  return f->ckoutFs.iVersion ? &f->ckoutFs : &fsl_ckout_fs_os;
}
#define CFS(F) fsl__cfs_get(F)

int fsl_cx_ckout_fs(fsl_cx * const f, fsl_ckout_fs const * pNew,
                    fsl_ckout_fs * pPrev){
  if( pNew && ((1!=pNew->iVersion && 2!=pNew->iVersion)
               || !pNew->xStat || !pNew->xRead || !pNew->xWrite
               || !pNew->xUnlink || !pNew->xRename || !pNew->xMkdir
               || !pNew->xRmdir || !pNew->xDirList
               || !pNew->xSymlinkRead != !pNew->xSymlinkCreate) ){
    return FSL_RC_MISUSE;
  }
  if( fsl_cx_txn_level(f) ) return FSL_RC_MISUSE;
  if( pPrev ) fsl_cx_ckout_fs_get(f, pPrev);
  f->ckoutFs = fsl_ckout_fs_empty;
  if( pNew ){
    /* A version 1 struct ends before xWriteBlob: copy no more. */
    memcpy(&f->ckoutFs, pNew, 1==pNew->iVersion
           ? offsetof(fsl_ckout_fs, xWriteBlob) : sizeof(fsl_ckout_fs));
  }
  return 0;
}

void fsl_cx_ckout_fs_get(fsl_cx const * const f, fsl_ckout_fs * dest){
  fsl_ckout_fs const * const s = f->ckoutFs.iVersion
    ? &f->ckoutFs : &fsl_ckout_fs_os;
  if( dest->iVersion>=2 ){
    *dest = *s;
  }else{
    /* The caller's struct may end before xWriteBlob: fill only the
       version 1 members, and say so. */
    memcpy(dest, s, offsetof(fsl_ckout_fs, xWriteBlob));
    dest->iVersion = 1;
  }
}

int fsl__cfs_stat(fsl_cx * const f, char const *zName, fsl_fstat * fst,
                  bool derefLinks){
  fsl_ckout_fs const * const s = CFS(f);
  fsl_fstat tmp = fsl_fstat_empty;
  fsl_size_t n = fsl_strlen(zName);
  char * zCopy = NULL;
  int rc;
  if( n>1 && '/'==zName[n-1] ){
    /* A name with a trailing slash, e.g. the checkout's root. A
       storage's names have none, so strip it and keep what it means
       to stat() (on Windows, fsl_stat() only strips it). */
    while( n>1 && '/'==zName[n-1] ) --n;
    zCopy = fsl_strndup(zName, (fsl_int_t)n);
    if( !zCopy ) return FSL_RC_OOM;
  }
  rc = s->xStat(s->state, zCopy ? zCopy : zName, &tmp, derefLinks);
#if !defined(_WIN32)
  if( zCopy && 0==rc ){
    /* POSIX: a trailing slash resolves a final symlink even for
       lstat(), and fails with ENOTDIR unless the name is a
       directory. */
    if( FSL_FSTAT_TYPE_LINK==tmp.type ){
      rc = s->xStat(s->state, zCopy, &tmp, true);
    }
    if( 0==rc && FSL_FSTAT_TYPE_DIR!=tmp.type ){
      rc = fsl_errno_to_rc(ENOTDIR, FSL_RC_IO);
    }
  }
#endif
  fsl_free(zCopy);
  if( 0==rc && fst ) *fst = tmp;
  return rc;
}

fsl_int_t fsl__cfs_size(fsl_cx * const f, char const *zName){
  fsl_fstat fst;
  return 0==fsl__cfs_stat(f, zName, &fst, true) ? (fsl_int_t)fst.size : -1;
}

fsl_time_t fsl__cfs_mtime(fsl_cx * const f, char const *zName){
  fsl_fstat fst;
  return 0==fsl__cfs_stat(f, zName, &fst, true) ? fst.mtime : -1;
}

bool fsl__cfs_is_file(fsl_cx * const f, char const *zName){
  fsl_fstat fst;
  return 0==fsl__cfs_stat(f, zName, &fst, true)
    && FSL_FSTAT_TYPE_FILE==fst.type;
}

bool fsl__cfs_is_file_or_link(fsl_cx * const f, char const *zName){
  fsl_fstat fst;
  return 0==fsl__cfs_stat(f, zName, &fst, false)
    && (FSL_FSTAT_TYPE_FILE==fst.type || FSL_FSTAT_TYPE_LINK==fst.type);
}

bool fsl__cfs_is_symlink(fsl_cx * const f, char const *zName){
  fsl_ckout_fs const * const s = CFS(f);
  fsl_fstat fst;
  return s->xSymlinkRead
    && 0==fsl__cfs_stat(f, zName, &fst, false)
    && FSL_FSTAT_TYPE_LINK==fst.type;
}

bool fsl__cfs_isexec(fsl_cx * const f, char const *zName){
  fsl_fstat fst;
  return 0==fsl__cfs_stat(f, zName, &fst, true)
    && 0!=(fst.perm & FSL_FSTAT_PERM_EXE);
}

int fsl__cfs_dir_check(fsl_cx * const f, char const *zName){
  fsl_fstat fst;
  if( !zName || fsl__cfs_stat(f, zName, &fst, true) ) return 0;
  return FSL_FSTAT_TYPE_DIR==fst.type ? 1 : -1;
}

/** xDirList() callback for fsl__cfs_dir_is_empty(): stop at the
    first entry. */
static int fsl__cfs_dir_any(void * cbState, char const * zEntry){
  (void)zEntry;
  *(int*)cbState = 1;
  return FSL_RC_BREAK;
}

int fsl__cfs_dir_is_empty(fsl_cx * const f, char const *zName){
  fsl_ckout_fs const * const s = CFS(f);
  int any = 0, rc;
  rc = s->xDirList(s->state, zName, fsl__cfs_dir_any, &any);
  if( rc && FSL_RC_BREAK!=rc ) return -1;
  return any;
}

int fsl__cfs_read(fsl_cx * const f, fsl_b * const dest, char const *zName){
  fsl_ckout_fs const * const s = CFS(f);
  fsl_b_reuse(dest);
  return s->xRead(s->state, zName, dest);
}

int fsl__cfs_write(fsl_cx * const f, fsl_b const * const b,
                   char const *zName){
  fsl_ckout_fs const * const s = CFS(f);
  if( !b || !zName ) return FSL_RC_MISUSE;
  if( b->errCode ) return b->errCode /* as fsl_b_to_filename() */;
  return s->xWrite(s->state, zName, b->mem, b->used);
}

int fsl__cfs_write_blob(fsl_cx * const f, char const *zName,
                        fsl_id_t rid, fsl_b * const content,
                        bool loaded, bool * const pWriteFailed){
  fsl_ckout_fs const * const s = CFS(f);
  int rc;
  if( pWriteFailed ) *pWriteFailed = false;
  if( !zName || rid<=0 || !content ) return FSL_RC_MISUSE;
  if( s->xWriteBlob ){
    rc = s->xWriteBlob(s->state, zName, rid);
  }else{
    rc = loaded ? 0 : fsl_content_get(f, rid, content);
    if( rc ) return rc;
    rc = fsl__cfs_write(f, content, zName);
  }
  if( rc && pWriteFailed ) *pWriteFailed = true;
  return rc;
}

int fsl__cfs_unlink(fsl_cx * const f, char const *zName){
  fsl_ckout_fs const * const s = CFS(f);
  return s->xUnlink(s->state, zName);
}

int fsl__cfs_rename(fsl_cx * const f, char const *zFrom, char const *zTo){
  fsl_ckout_fs const * const s = CFS(f);
  return s->xRename(s->state, zFrom, zTo);
}

int fsl__cfs_rmdir(fsl_cx * const f, char const *zName){
  fsl_ckout_fs const * const s = CFS(f);
  int rc;
  /* As fsl_rmdir(). */
  rc = fsl__cfs_dir_check(f, zName);
  if( rc<1 ) return rc ? FSL_RC_TYPE : FSL_RC_NOT_FOUND;
  return s->xRmdir(s->state, zName);
}

/** fsl_mkdir() through the storage. */
static int fsl__cfs_mkdir(fsl_cx * const f, char const *zName,
                          bool forceFlag){
  fsl_ckout_fs const * const s = CFS(f);
  int rc = fsl__cfs_dir_check(f, zName);
  if( rc<0 ){
    if( !forceFlag ) return FSL_RC_TYPE;
    rc = s->xUnlink(s->state, zName);
    if( rc ) return rc;
  }else if( 0==rc ){
    return s->xMkdir(s->state, zName);
  }
  return 0;
}

int fsl__cfs_mkdir_for_file(fsl_cx * const f, char const *zName,
                            bool forceFlag){
  fsl_b * const b = fsl_cx_b_borrow(f);
  fsl_size_t n, i;
  char * zCan;
  int rc;
  /* As fsl_mkdir_for_file(). */
  if( !b ) return f->error.code;
  n = fsl_strlen(zName);
  if( n==0 ) return FSL_RC_RANGE;
  else if( n<2 ) return 0;
  rc = fsl_file_canonical_name(zName, b, true);
  zCan = fsl_b_str(b);
  n = b->used;
  for( i = 1; 0==rc && i<n; ++i ){
    if( '/'==zCan[i] ){
#if defined(_WIN32) || defined(__CYGWIN__)
      /* Skip a drive letter, e.g. the C: of C:/dir/file.txt. */
      if( 2==i && ':'==zCan[1] ) continue;
#endif
      zCan[i] = 0;
      rc = fsl__cfs_dir_check(f, zCan);
      rc = (0>=rc) ? fsl__cfs_mkdir(f, zCan, forceFlag) : 0;
      zCan[i] = '/';
    }
  }
  fsl_cx_b_return(f, b);
  return rc;
}

int fsl__cfs_exec_set(fsl_cx * const f, char const *zName, bool isExec){
  fsl_ckout_fs const * const s = CFS(f);
  fsl_fstat fst;
  if( !s->xExecSet ) return 0;
  /* As fsl_file_exec_set(): only regular files have the bit. */
  {
    int const rc = fsl__cfs_stat(f, zName, &fst, true);
    if( FSL_RC_NOT_FOUND==rc ){
      /* The storage answers for a missing file as it would without
         this check: fsl_file_exec_set() fails on Unix but is a no-op
         returning 0 on Windows. */
      return s->xExecSet(s->state, zName, isExec);
    }
    if( rc ) return rc;
  }
  if( FSL_FSTAT_TYPE_FILE!=fst.type ) return 0;
  return s->xExecSet(s->state, zName, isExec);
}

int fsl__cfs_mtime_set(fsl_cx * const f, char const *zName,
                       fsl_time_t mtime){
  fsl_ckout_fs const * const s = CFS(f);
  if( !zName || !*zName ) return FSL_RC_MISUSE;
  if( !s->xMtimeSet ) return 0;
  if( mtime<0 ) mtime = (fsl_time_t)time(0);
  return s->xMtimeSet(s->state, zName, mtime);
}

int fsl__cfs_copy(fsl_cx * const f, char const *zFrom, char const *zTo){
  fsl_ckout_fs const * const s = CFS(f);
  fsl_b b = fsl_b_empty;
  int rc;
  if( s->xCopy ) return s->xCopy(s->state, zFrom, zTo);
  /* As fsl_file_copy(): create zTo's directory, copy the bytes, and
     carry over the executable bit. */
  rc = fsl__cfs_read(f, &b, zFrom);
  if( 0==rc ) rc = fsl__cfs_mkdir_for_file(f, zTo, false);
  if( 0==rc ) rc = fsl__cfs_write(f, &b, zTo);
  if( 0==rc && fsl__cfs_isexec(f, zFrom) ){
    fsl__cfs_exec_set(f, zTo, true);
  }
  fsl_b_clear(&b);
  return rc;
}

/** fsl__cfs_sha1sum() and fsl__cfs_sha3sum(). */
static int fsl__cfs_hash(fsl_cx * const f, char const *zName, bool sha3,
                         fsl_b * const tgt){
  fsl_ckout_fs const * const s = CFS(f);
  fsl_b b = fsl_b_empty;
  int rc;
  if( !zName || !tgt ) return FSL_RC_MISUSE;
  if( s->xHash ){
    fsl_b_reuse(tgt);
    return s->xHash(s->state, zName, sha3, tgt);
  }
  rc = fsl__cfs_read(f, &b, zName);
  if( 0==rc ){
    rc = sha3 ? fsl_sha3sum_buffer(&b, tgt) : fsl_sha1sum_buffer(&b, tgt);
  }
  fsl_b_clear(&b);
  return rc;
}

int fsl__cfs_sha1sum(fsl_cx * const f, char const *zName, fsl_b * const tgt){
  return fsl__cfs_hash(f, zName, false, tgt);
}

int fsl__cfs_sha3sum(fsl_cx * const f, char const *zName, fsl_b * const tgt){
  return fsl__cfs_hash(f, zName, true, tgt);
}

/** xDirList() callback for fsl__cfs_dircrawl_impl(): collects each
    entry's name, NUL-terminated, into the fsl_b passed as cbState. */
static int fsl__cfs_dir_collect(void * cbState, char const * zEntry){
  fsl_b * const b = (fsl_b*)cbState;
  if( '.'==zEntry[0]
      && (!zEntry[1] || ('.'==zEntry[1] && !zEntry[2])) ){
    return 0;
  }
  return fsl_b_append(b, zEntry, (fsl_int_t)fsl_strlen(zEntry)+1);
}

/**
   fsl_dircrawl_impl() through the storage. The directory's entries
   are collected before any of them is visited, so that the storage's
   xDirList() never runs re-entrantly.
*/
static int fsl__cfs_dircrawl_impl(fsl_cx * const f, fsl_b * const dbuf,
                                  fsl_dircrawl_f cb,
                                  fsl_dircrawl_state * const dst,
                                  unsigned int depth){
  fsl_ckout_fs const * const s = CFS(f);
  fsl_size_t const dPos = dbuf->used;
  fsl_b names = fsl_b_empty;
  fsl_fstat fst = fsl_fstat_empty;
  fsl_size_t i;
  int rc;
  if( depth>20 ) return FSL_RC_RANGE;
  rc = s->xDirList(s->state, fsl_b_cstr(dbuf), fsl__cfs_dir_collect, &names);
  for( i = 0; 0==rc && i<names.used; ){
    char const * const z = (char const *)names.mem + i;
    fsl_size_t newLen;
    i += fsl_strlen(z) + 1;
    dbuf->used = dPos;
    rc = fsl_b_appendf(dbuf, "/%s", z);
    if( rc ) break;
    newLen = dbuf->used;
    if( fsl__cfs_stat(f, fsl_b_cstr(dbuf), &fst, false) ){
      continue /* As fsl_dircrawl(): skip stat errors. */;
    }
    switch( fst.type ){
      case FSL_FSTAT_TYPE_LINK:
      case FSL_FSTAT_TYPE_DIR:
      case FSL_FSTAT_TYPE_FILE:
        break;
      default:
        continue;
    }
    dbuf->mem[dbuf->used = dPos] = 0;
    dst->absoluteDir = (char const *)dbuf->mem;
    dst->entryName = z;
    dst->entryType = fst.type;
    dst->depth = depth;
    rc = cb(dst);
    if( 0==rc ){
      dbuf->mem[dbuf->used] = '/';
      dbuf->used = newLen;
      if( FSL_FSTAT_TYPE_DIR==fst.type ){
        rc = fsl__cfs_dircrawl_impl(f, dbuf, cb, dst, depth+1);
      }
    }else if( FSL_RC_NOOP==rc ){
      rc = 0;
    }
  }
  dbuf->used = dPos;
  if( dbuf->mem ) dbuf->mem[dPos] = 0;
  fsl_b_clear(&names);
  return rc;
}

int fsl__cfs_dircrawl(fsl_cx * const f, char const *zDir,
                      fsl_dircrawl_f callback, void * cbState){
  fsl_b dbuf = fsl_b_empty;
  fsl_fstat fst = fsl_fstat_empty;
  fsl_dircrawl_state dst;
  int rc;
  /* As fsl_dircrawl(). */
  rc = fsl_file_canonical_name(zDir, &dbuf, false);
  if( 0==rc && dbuf.used && '/'==dbuf.mem[dbuf.used-1] ){
    dbuf.mem[--dbuf.used] = 0;
  }
  memset(&dst, 0, sizeof(dst));
  dst.callbackState = cbState;
  if( 0==rc ) rc = fsl__cfs_stat(f, fsl_b_cstr(&dbuf), &fst, false);
  if( 0==rc && FSL_FSTAT_TYPE_DIR!=fst.type ) rc = FSL_RC_TYPE;
  if( 0==rc ){
    rc = fsl__cfs_dircrawl_impl(f, &dbuf, callback, &dst, 1);
    if( FSL_RC_BREAK==rc ) rc = 0;
  }
  fsl_b_clear(&dbuf);
  return rc;
}

int fsl__cfs_symlink_read(fsl_cx * const f, fsl_b * const tgt,
                          char const *zName){
  fsl_ckout_fs const * const s = CFS(f);
  if( !s->xSymlinkRead ) return fsl__cfs_read(f, tgt, zName);
  fsl_b_reuse(tgt);
  return s->xSymlinkRead(s->state, zName, tgt);
}

int fsl__cfs_read_repofile(fsl_cx * const f, fsl_b * const tgt,
                           char const *zName, bool * isLink){
  bool const link = fsl_cx_allows_symlinks(f, false)
    && fsl__cfs_is_symlink(f, zName);
  if( isLink ) *isLink = link;
  return link
    ? fsl__cfs_symlink_read(f, tgt, zName)
    : fsl__cfs_read(f, tgt, zName);
}

fsl_fileperm_e fsl__fstat_perm(fsl_fstat const * fst, bool allowSymlinks){
  if( allowSymlinks && FSL_FSTAT_TYPE_LINK==fst->type ){
    return FSL_FILE_PERM_LINK;
  }else if( FSL_FSTAT_TYPE_FILE==fst->type
            && FSL_FSTAT_PERM_EXE==fst->perm ){
    return FSL_FILE_PERM_EXE;
  }
  return FSL_FILE_PERM_REGULAR;
}

int fsl__cfs_symlink_create(fsl_cx * const f, char const *zTarget,
                            char const *zLink, bool realLink){
  int rc;
  fsl_ckout_fs const * const s = CFS(f);
  rc = fsl__cfs_mkdir_for_file(f, zLink, false);
  if( 0==rc && realLink && s->xSymlinkCreate ){
    rc = s->xSymlinkCreate(s->state, zTarget, zLink);
  }else if( 0==rc ){
    /* As fsl_symlink_create() with realLink false. */
    fsl_b content = fsl_b_empty;
    fsl_b_external(&content, zTarget, -1);
    fsl__cfs_unlink(f, zLink);
    rc = fsl__cfs_write(f, &content, zLink);
  }
  return rc;
}

int fsl__cfs_symlink_copy(fsl_cx * const f, char const *zFrom,
                          char const *zTo, bool realLink){
  fsl_b b = fsl_b_empty;
  int rc;
  rc = fsl__cfs_symlink_read(f, &b, zFrom);
  if( 0==rc ) rc = fsl__cfs_symlink_create(f, fsl_b_cstr(&b), zTo,
                                           realLink);
  fsl_b_clear(&b);
  return rc;
}

#undef CFS
/* end of file src/ckout_fs.c */
/* start of file src/stash.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**
   The checkout stash (see stash.h). This is a port of fossil(1)'s
   src/stash.c, using Mark Jamsek's stash implementation in
   client/fnc/fnc.c as the guide to the equivalent libfossil APIs.
*/
#include <assert.h>
#include <string.h>

const fsl_stash_save_opt fsl_stash_save_opt_empty =
  fsl_stash_save_opt_empty_m;
const fsl_stash_apply_opt fsl_stash_apply_opt_empty =
  fsl_stash_apply_opt_empty_m;

/**
   fossil(1)'s stash schema, as of its 2019-01-19 change which added
   the hash columns. The vid and rid columns are kept for older
   fossil(1) versions but are not used here. The tables are qualified
   with the checkout db's name, "ckout", so that they land in the
   checkout db even when the main db is a host application's
   (fsl_cx_host_db()), or are that db's prefixed tables
   (fsl_repo_open_ckout_opt::hostTablePrefix).
*/
static char const * const fsl__stash_schema =
  "CREATE TABLE IF NOT EXISTS {{dbname.ckout}}.stash("
  "  stashid INTEGER PRIMARY KEY,"
  "  vid INTEGER,"
  "  hash TEXT,"
  "  comment TEXT,"
  "  ctime TIMESTAMP"
  ");"
  "CREATE TABLE IF NOT EXISTS {{dbname.ckout}}.stashfile("
  "  stashid INTEGER REFERENCES {{bare.ckout.stash}},"
  "  isAdded BOOLEAN,"
  "  isRemoved BOOLEAN,"
  "  isExec BOOLEAN,"
  "  isLink BOOLEAN,"
  "  rid INTEGER,"
  "  hash TEXT,"
  "  origname TEXT,"
  "  newname TEXT,"
  "  delta BLOB,"
  "  PRIMARY KEY(newname, stashid)"
  ");";

/**
   Ensures that the stash tables exist in the checkout db and have
   fossil(1)'s current schema, creating or upgrading them as needed,
   as fossil(1)'s stash_tables_exist_and_current() does.
*/
static int fsl__stash_tables(fsl_cx * const f, fsl_db * const db){
  int rc;
  if(fsl__db_table_has_column(db, FSL_DBROLE_CKOUT, "stashfile", "hash")){
    /* Current schema, but an older fossil(1) may have added rows
       without hashes since it was upgraded. */
    if(fsl_db_g_int32(db, 0, "SELECT hash IS NULL FROM {{dbname.ckout}}.stash"
                      " ORDER BY stashid DESC LIMIT 1")){
      rc = fsl_cx_exec_multi(f,
        "UPDATE {{dbname.ckout}}.stash AS stash"
        "   SET hash=(SELECT uuid FROM {{dbname.repo}}.blob AS blob WHERE blob.rid=stash.vid)"
        " WHERE hash IS NULL;"
        "UPDATE {{dbname.ckout}}.stashfile AS stashfile"
        "   SET hash=(SELECT uuid FROM {{dbname.repo}}.blob AS blob WHERE blob.rid=stashfile.rid)"
        " WHERE hash IS NULL AND rid>0");
      if(rc) return rc;
    }
    return 0;
  }
  if(!fsl_db_table_exists(db, FSL_DBROLE_CKOUT, "stashfile")
     || !fsl_db_table_exists(db, FSL_DBROLE_CKOUT, "stash")){
    rc = fsl_cx_exec_multi(f, "DROP TABLE IF EXISTS {{dbname.ckout}}.stash;"
                           "DROP TABLE IF EXISTS {{dbname.ckout}}.stashfile;");
    return rc ? rc : fsl_cx_exec_multi(f, fsl__stash_schema);
  }
  /* Tables from before 2019-01-19: rebuild them with hash columns. */
  rc = fsl_cx_exec_multi(f,
    "ALTER TABLE {{dbname.ckout}}.stash RENAME TO {{bare.ckout.old_stash}};"
    "ALTER TABLE {{dbname.ckout}}.stashfile"
    " RENAME TO {{bare.ckout.old_stashfile}};");
  if(!rc) rc = fsl_cx_exec_multi(f, fsl__stash_schema);
  if(!rc) rc = fsl_cx_exec_multi(f,
    "INSERT INTO {{dbname.ckout}}.stash(stashid,vid,hash,comment,ctime)"
    " SELECT stashid, vid,"
    "   (SELECT uuid FROM {{dbname.repo}}.blob AS blob WHERE blob.rid=old_stash.vid),"
    "   comment, ctime FROM {{dbname.ckout}}.old_stash AS old_stash;"
    "DROP TABLE {{dbname.ckout}}.old_stash;"
    "INSERT INTO {{dbname.ckout}}.stashfile(stashid,isAdded,isRemoved,isExec,"
    "                      isLink,rid,hash,origname,newname,delta)"
    " SELECT stashid, isAdded, isRemoved, isExec, isLink, rid,"
    "   (SELECT uuid FROM {{dbname.repo}}.blob AS blob WHERE blob.rid=old_stashfile.rid),"
    "   origname, newname, delta FROM {{dbname.ckout}}.old_stashfile"
    "   AS old_stashfile;"
    "DROP TABLE {{dbname.ckout}}.old_stashfile;");
  return rc;
}

/**
   Resolves *stashId: 0 means the most recent stash. Returns
   FSL_RC_NOT_FOUND, with f's error state set, if there is no such
   stash.
*/
static int fsl__stash_resolve(fsl_cx * const f, fsl_db * const db,
                              fsl_id_t * const stashId){
  if(*stashId<=0){
    *stashId = fsl_db_g_id(db, 0, "SELECT max(stashid) FROM {{dbname.ckout}}.stash");
    if(*stashId<=0){
      return fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "The stash is empty.");
    }
  }else if(!fsl_db_exists(db, "SELECT 1 FROM {{dbname.ckout}}.stash WHERE stashid=%"
                          FSL_ID_T_PFMT, *stashId)){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "No such stash: %" FSL_ID_T_PFMT, *stashId);
  }
  return 0;
}

/**
   Reads a checkout file as fossil(1) reads repository content: with
   the allow-symlinks setting on, a symlink's content is its target
   name, else the symlink is followed. A missing file reads as empty,
   as in fossil(1).
*/
static int fsl__stash_read_file(fsl_cx * const f, char const * zPath,
                                fsl_b * const tgt){
  int rc = fsl__cfs_read_repofile(f, tgt, zPath, NULL);
  if(FSL_RC_NOT_FOUND==rc){
    fsl_b_reuse(tgt);
    rc = 0;
  }
  return rc ? fsl_cx_err_set(f, rc, "Error %R reading file: %s",
                             rc, zPath) : 0;
}

/**
   Writes content to zPath as a regular file, or as a symlink to the
   name in content if isLink is true, and sets its executable bit.
*/
static int fsl__stash_write_file(fsl_cx * const f, char const * zPath,
                                 fsl_b const * content, bool isLink,
                                 bool isExec){
  int rc;
  if(isLink){
    rc = fsl__cfs_symlink_create(f, fsl_b_cstr(content), zPath,
                            fsl_cx_allows_symlinks(f, false));
  }else{
    rc = fsl__cfs_mkdir_for_file(f, zPath, true);
    if(!rc) rc = fsl__cfs_write(f, content, zPath);
    if(!rc) rc = fsl__cfs_exec_set(f, zPath, isExec);
  }
  return rc ? fsl_cx_err_set(f, rc, "Error %R writing file: %s",
                             rc, zPath) : 0;
}

static int fsl__stash_save_impl(fsl_cx * const f,
                                fsl_stash_save_opt const * opt,
                                fsl_id_t * stashId){
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return f->error.code;

  fsl_id_t const vid = f->db.ckout.rid;
  fsl_id_t sid = 0;
  fsl_id_bag ids = fsl_id_bag_empty;
  fsl_stmt q = fsl_stmt_empty;
  fsl_stmt ins = fsl_stmt_empty;
  fsl_b orig = fsl_b_empty;
  fsl_b delta = fsl_b_empty;
  char const * const * zNames =
    (opt->filenames && opt->filenames[0]) ? opt->filenames : NULL;
  bool inTxn = false;
  bool const allowSymlinks = fsl_cx_allows_symlinks(f, false);
  int rc;
  fsl_b * const sql = fsl_cx_b_borrow(f);
  fsl_b * const fname = fsl_cx_b_borrow(f);
  fsl_b * const disk = fsl_cx_b_borrow(f);
  fsl_b * absPath = 0;
  if( !sql || !fname || !disk ){
    rc = f->error.code;
    assert( rc );
    goto end;
  }

  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) goto end;
  inTxn = true;
  rc = fsl__stash_tables(f, db);
  if(!rc) rc = fsl_vfile_changes_scan(f, vid, 0);
  if(rc) goto end;
  sid = fsl_config_get_id(f, FSL_CONFDB_CKOUT, 1, "stash-next");
  rc = fsl_config_set_id(f, FSL_CONFDB_CKOUT, "stash-next", sid+1);
  if(!rc) rc = fsl_cx_exec(f,
    "INSERT INTO {{dbname.ckout}}.stash(stashid,vid,hash,comment,ctime)"
    " VALUES(%" FSL_ID_T_PFMT ",%" FSL_ID_T_PFMT ","
    "(SELECT uuid FROM {{dbname.repo}}.blob WHERE rid=%" FSL_ID_T_PFMT "),"
    "%Q,julianday('now'))", sid, vid, vid, opt->comment);
  if(rc) goto end;
  /* The changed files, as fossil(1)'s stash_add_file_or_dir() selects
     them. With names given, each one matches a file or anything under
     a directory, by either its current or original name. */
  rc = fsl__db_appendf(db, sql,
    "SELECT id, deleted, isexe, islink, mrid, pathname,"
    " coalesce(origname,pathname) FROM {{dbname.ckout}}.vfile"
    " WHERE vid=%" FSL_ID_T_PFMT
    " AND (chnged OR deleted OR origname NOT NULL OR mrid==0)", vid);
  for(int i = 0; !rc && zNames && zNames[i]; ++i){
    /* A name which is the checkout root means all changes. */
    fsl_b_reuse(fname);
    rc = fsl_ckout_filename_check(f, opt->relativeToCwd, zNames[i], fname);
    if(rc) break;
    fsl_b_strip_slashes(fname);
    if(0==fname->used || (1==fname->used && '.'==fname->mem[0])){
      zNames = NULL;
    }
  }
  for(int i = 0; !rc && zNames && zNames[i]; ++i){
    fsl_b_reuse(fname);
    rc = fsl_ckout_filename_check(f, opt->relativeToCwd, zNames[i], fname);
    if(rc) break;
    fsl_b_strip_slashes(fname);
    rc = fsl_b_appendf(sql, " %s fsl_match_vfile_or_dir(pathname,%Q)"
                       " OR fsl_match_vfile_or_dir(origname,%Q)",
                       i ? "OR" : "AND (", fsl_b_cstr(fname),
                       fsl_b_cstr(fname));
  }
  if(!rc && zNames) rc = fsl_b_append(sql, ")", 1);
  if(!rc) rc = fsl_cx_prepare(f, &q, "%b", sql);
  if(!rc) rc = fsl_cx_prepare(f, &ins,
    "INSERT INTO {{dbname.ckout}}.stashfile(stashid,isAdded,isRemoved,isExec,isLink,"
    "rid,hash,origname,newname,delta)"
    " VALUES(%" FSL_ID_T_PFMT ",?1,?2,?3,?4,?5,"
    "(SELECT uuid FROM {{dbname.repo}}.blob WHERE rid=?5),?6,?7,?8)", sid);
  if(rc) goto end;
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    fsl_id_t const id = fsl_stmt_g_id(&q, 0);
    bool const deleted = !!fsl_stmt_g_int32(&q, 1);
    bool isExe = !!fsl_stmt_g_int32(&q, 2);
    fsl_id_t const mrid = fsl_stmt_g_id(&q, 4);
    char const * const zName = fsl_stmt_g_text(&q, 5, NULL);
    char const * const zOrig = fsl_stmt_g_text(&q, 6, NULL);
    rc = fsl_id_bag_insert(&ids, id);
    if( rc ) break;
    if( !absPath && !(absPath = fsl_cx_b_borrow(f)) ){
      rc = f->error.code;
      break;
    }
    fsl_b_reuse(absPath);
    rc = fsl_b_appendf(absPath, "%s%s", f->db.ckout.dir, zName);
    if( rc ) break;
    char const * const zPath = fsl_b_cstr(absPath);
#if !defined(_WIN32)
    if(!deleted){
      /* vfile.isexe is the baseline's bit, so take the file's own, as
         fsl_checkin_commit() does. fossil(1)'s stash_add_file_or_dir()
         uses vfile.isexe, losing an exec-bit change. */
      fsl_fstat fst = fsl_fstat_empty;
      isExe = 0==fsl__cfs_stat(f, zPath, &fst, !allowSymlinks)
        && FSL_FILE_PERM_EXE==fsl__fstat_perm(&fst, allowSymlinks);
    }
#endif
    if(0==mrid){
      /* An added file: the whole content. */
      rc = fsl__stash_read_file(f, zPath, disk);
      if(!rc) rc = fsl_stmt_bind_blob(&ins, 8, disk->mem ? (void*)disk->mem
                                      : (void*)"", (int)disk->used, false);
    }else if(deleted){
      rc = fsl_stmt_bind_null(&ins, 8);
    }else{
      /* A modified file: a delta from its baseline version. */
      rc = fsl__stash_read_file(f, zPath, disk);
      if(!rc) rc = fsl_content_get(f, mrid, &orig);
      if(!rc) rc = fsl_b_delta_create(&orig, disk, &delta);
      if(!rc) rc = fsl_stmt_bind_blob(&ins, 8, delta.mem,
                                      (int)delta.used, false);
    }
    if(!rc) rc = fsl_stmt_bind_int32(&ins, 1, 0==mrid);
    if(!rc) rc = fsl_stmt_bind_int32(&ins, 2, deleted);
    if(!rc) rc = fsl_stmt_bind_int32(&ins, 3, isExe);
    if(!rc) rc = fsl_stmt_bind_int32(&ins, 4,
                                     allowSymlinks
                                     && fsl__cfs_is_symlink(f, zPath));
    if(!rc) rc = fsl_stmt_bind_id(&ins, 5, mrid);
    if(!rc) rc = fsl_stmt_bind_text(&ins, 6, zOrig, -1, false);
    if(!rc) rc = fsl_stmt_bind_text(&ins, 7, zName, -1, false);
    if(!rc) rc = fsl_stmt_step(&ins)==FSL_RC_STEP_DONE
      ? 0 : fsl_cx_uplift_db_error2(f, db, FSL_RC_DB);
    fsl_stmt_reset(&ins);
    if(rc) break;
  }
  if(rc) goto end;
  if(0==fsl_id_bag_count(&ids)){
    rc = fsl_cx_err_set(f, FSL_RC_NOOP, zNames
                        ? "No changed files match the given names."
                        : "There are no changes to stash.");
    goto end;
  }
  /* Commit the stash before reverting, as fossil(1) does, so that a
     failed revert cannot lose changes which it already reverted on
     disk. (Inside a caller's transaction, the caller decides.) */
  inTxn = false;
  rc = fsl_cx_txn_end(f, false);
  if(!rc && stashId) *stashId = sid;
  if(!rc && !opt->keepChanges){
    fsl_ckout_revert_opt ropt = fsl_ckout_revert_opt_empty;
    ropt.vfileIds = &ids;
    ropt.scanForChanges = false;
    ropt.callback = opt->revertCallback;
    ropt.callbackState = opt->revertCallbackState;
    rc = fsl_ckout_revert(f, &ropt);
  }
  end:
  fsl_stmt_finalize(&q);
  fsl_stmt_finalize(&ins);
  fsl_id_bag_clear(&ids);
  fsl_b_clear(&orig);
  fsl_b_clear(&delta);
  fsl_cx_b_return(f, absPath);
  fsl_cx_b_return(f, sql);
  fsl_cx_b_return(f, fname);
  fsl_cx_b_return(f, disk);
  if(inTxn){
    int const rc2 = fsl_cx_txn_end(f, !!rc);
    if(!rc) rc = rc2;
  }
  return rc;
}

/**
   Queues for adding the files which fsl_stash_apply() wrote
   for added stash entries, as fossil(1)'s add_files_in_sfile() does,
   skipping any under a managed symlink and reserved names.
*/
static int fsl__stash_add_files(fsl_cx * const f){
  fsl_stmt q = fsl_stmt_empty;
  int rc = fsl_cx_prepare(f, &q,
    "SELECT pathname FROM {{temp.fx_stash_sfile}}"
    " WHERE pathname NOT IN ("
    "  SELECT s.pathname FROM {{dbname.ckout}}.vfile v, {{temp.fx_stash_sfile}} s"
    "  WHERE v.islink AND NOT v.deleted"
    "  AND s.pathname>(v.pathname||'/')"
    "  AND s.pathname<(v.pathname||'0'))"
    " ORDER BY pathname");
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    char const * const zName = fsl_stmt_g_text(&q, 0, NULL);
    fsl_ckout_manage_opt mopt = fsl_ckout_manage_opt_empty;
    if(fsl_is_reserved_fn(zName, -1)) continue;
    mopt.filename = zName;
    mopt.relativeToCwd = false;
    mopt.checkIgnoreGlobs = false;
    rc = fsl_ckout_manage(f, &mopt);
  }
  fsl_stmt_finalize(&q);
  return rc;
}

/**
   Applies one modified stash entry to its file, as fossil(1)'s
   stash_apply() does: overwrite the file if it is unchanged since
   the baseline, else merge the stashed changes into it. isLink is
   whether the stashed version is a symlink and wasLink whether the
   baseline version is one. Sets *change and *nConflict.
*/
static int fsl__stash_apply_modified(fsl_cx * const f, fsl_id_t rid,
                                     fsl_b const * delta,
                                     char const * zOPath,
                                     char const * zNPath,
                                     bool wasLink,
                                     bool isLink, bool isExec,
                                     fsl_stash_e * const change,
                                     unsigned * const nConflict){
  fsl_b a = fsl_b_empty;
  fsl_b b = fsl_b_empty;
  fsl_b out = fsl_b_empty;
  fsl_b * const disk = fsl_cx_b_borrow(f);
  if( !disk ) return f->error.code;
  bool const isDiskLink = fsl_cx_allows_symlinks(f, false)
    && fsl__cfs_is_symlink(f, zOPath);
  int rc = fsl__stash_read_file(f, zOPath, disk);
  if(!rc) rc = fsl_content_get(f, rid, &a);
  if(!rc){
    fsl_error err = fsl_error_empty;
    rc = fsl_b_delta_apply2(&a, delta, &b, &err);
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Error %R applying the stashed delta "
                          "for %s: %b", rc, zNPath, &err.msg);
    }
    fsl_error_clear(&err);
  }
  if(rc) goto end;
  *nConflict = 0;
  if(wasLink==isDiskLink && 0==fsl_b_compare(disk, &a)){
    /* Unchanged since the baseline. Compare the disk's link state
       with the baseline's, not the stash's: a stashed change to or
       from a link is otherwise never restored. */
    if(isLink || isDiskLink) fsl__cfs_unlink(f, zNPath);
    rc = fsl__stash_write_file(f, zNPath, &b, isLink, isExec);
    *change = FSL_STASH_UPDATE;
  }else if(wasLink || isLink || isDiskLink){
    *change = FSL_STASH_UNMERGEABLE;
  }else{
    unsigned int nc = 0;
    rc = fsl_b_merge3(&a, disk, &b, &out, &nc);
    if(FSL_RC_DIFF_BINARY==rc){
      rc = 0;
      *change = FSL_STASH_UNMERGEABLE;
    }else if(!rc){
      rc = fsl__stash_write_file(f, zNPath, &out, false, isExec);
      *nConflict = nc;
      *change = nc ? FSL_STASH_CONFLICT : FSL_STASH_MERGE;
    }else{
      rc = fsl_cx_err_set(f, rc, "Error %R merging %s", rc, zNPath);
    }
  }
  end:
  fsl_b_clear(&a);
  fsl_b_clear(&b);
  fsl_b_clear(&out);
  fsl_cx_b_return(f, disk);
  return rc;
}

/**
   fsl_ckup_f() for the update which (fossil stash goto) runs first:
   counts the files the update left in conflict, which fossil(1) adds
   to the apply's conflict count.
*/
static int fsl__stash_goto_ckup_f(fsl_ckup_state const * st){
  switch(st->fileChangeType){
    case FSL_CKUP_FCHANGE_CONFLICT_MERGED:
    case FSL_CKUP_FCHANGE_CONFLICT_ADDED:
    case FSL_CKUP_FCHANGE_CONFLICT_ADDED_UNMANAGED:
    case FSL_CKUP_FCHANGE_CONFLICT_RM:
    case FSL_CKUP_FCHANGE_CONFLICT_SYMLINK:
      ++*((unsigned *)st->callbackState);
      break;
    default: break;
  }
  return 0;
}

static int fsl__stash_apply_impl(fsl_cx * const f,
                                 fsl_stash_apply_opt const * opt,
                                 unsigned * nConflicts){
  fsl_db * const db = fsl_needs_ckout(f);
  fsl_id_t sid = opt->stashId;
  fsl_stmt q = fsl_stmt_empty;
  unsigned nConflict = 0;
  bool haveSfile = false;
  fsl_deck dBase = fsl_deck_empty;
  int rc;
  if(!db) return FSL_RC_NOT_A_CKOUT;
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) return rc;
  /* From here on the transaction is ours to end. */
  rc = fsl__stash_tables(f, db);
  if(!rc) rc = fsl__stash_resolve(f, db, &sid);
  if(rc) goto end;
  if(opt->gotoBaseline){
    /* Like (fossil stash goto): update to the stash's baseline
       first. */
    fsl_ckup_opt uopt = fsl_ckup_opt_empty;
    uopt.checkinRid = fsl_db_g_id(db, 0,
      "SELECT blob.rid FROM {{dbname.ckout}}.stash AS stash, {{dbname.repo}}.blob AS blob WHERE stashid=%" FSL_ID_T_PFMT
      " AND blob.uuid=stash.hash", sid);
    if(uopt.checkinRid<=0){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "The baseline of stash %"
                          FSL_ID_T_PFMT " is not in the repository.", sid);
      goto end;
    }
    uopt.callback = fsl__stash_goto_ckup_f;
    uopt.callbackState = &nConflict;
    rc = fsl_ckout_update(f, &uopt);
    if(rc) goto end;
  }
  rc = fsl_cx_exec(f, "CREATE TEMP TABLE IF NOT EXISTS {{temp.fx_stash_sfile}}("
                   "pathname TEXT PRIMARY KEY %s)",
                   fsl_cx_filename_collation(f));
  if(rc) goto end;
  haveSfile = true;
  rc = fsl_cx_exec(f, "DELETE FROM {{temp.fx_stash_sfile}}");
  if(!rc) rc = fsl_cx_prepare(f, &q,
    "SELECT blob.rid, isRemoved, isExec, isLink, origname, newname, delta"
    "  FROM {{dbname.ckout}}.stashfile AS stashfile, {{dbname.repo}}.blob AS blob"
    " WHERE stashid=%" FSL_ID_T_PFMT " AND blob.uuid=stashfile.hash"
    " UNION ALL SELECT 0, isRemoved, isExec, isLink, origname, newname,"
    " delta FROM {{dbname.ckout}}.stashfile AS stashfile"
    " WHERE stashid=%" FSL_ID_T_PFMT " AND stashfile.hash IS NULL",
    sid, sid);
  if(rc) goto end;
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    fsl_id_t const rid = fsl_stmt_g_id(&q, 0);
    bool const isRemoved = !!fsl_stmt_g_int32(&q, 1);
    bool const isExec = !!fsl_stmt_g_int32(&q, 2);
    bool const isLink = !!fsl_stmt_g_int32(&q, 3);
    char const * const zOrig = fsl_stmt_g_text(&q, 4, NULL);
    char const * const zNew = fsl_stmt_g_text(&q, 5, NULL);
    void const * pDelta = NULL;
    fsl_size_t nDelta = 0;
    fsl_b delta = fsl_b_empty;
    fsl_stash_e change = FSL_STASH_NONE;
    unsigned nc = 0;
    char * const zOPath = fsl_mprintf("%s%s", f->db.ckout.dir, zOrig);
    char * const zNPath = fsl_mprintf("%s%s", f->db.ckout.dir, zNew);
    if(!zOPath || !zNPath){
      fsl_free(zOPath);
      fsl_free(zNPath);
      rc = FSL_RC_OOM;
      break;
    }
    fsl_stmt_get_blob(&q, 6, &pDelta, &nDelta);
    fsl_b_external(&delta, pDelta, (fsl_int_t)nDelta);
    if(0==rid){
      /* An added file. */
      rc = fsl_cx_exec(f, "INSERT OR IGNORE INTO {{temp.fx_stash_sfile}}(pathname)"
                       " VALUES(%Q)", zNew);
      if(!rc) rc = fsl__stash_write_file(f, zNPath, &delta, false, isExec);
      change = FSL_STASH_ADD;
    }else if(isRemoved){
      /* The save's revert un-deleted it, so mark it removed again, as
         (fossil rm) does. The stash does not record whether the file
         was left on disk, so remove it, as fossil(1) does. */
      fsl__cfs_unlink(f, zOPath);
      rc = fsl_cx_exec(f,
        "UPDATE {{dbname.ckout}}.vfile SET deleted=1"
        " WHERE pathname=%Q %s AND vid=%" FSL_ID_T_PFMT,
        zOrig, fsl_cx_filename_collation(f), f->db.ckout.rid);
      change = FSL_STASH_DELETE;
    }else if((rc = fsl__ckout_safe_file_check(f, zNPath))){
      if(FSL_RC_OOM!=rc){
        fsl_cx_err_reset(f);
        rc = 0;
        change = FSL_STASH_UNSAFE;
      }
    }else{
      bool wasLink = false;
      if(fsl_cx_allows_symlinks(f, false)){
        /* With the setting off, a link is a regular file on disk, so
           there is no need to know. */
        fsl_card_F const * fc = NULL;
        if(!dBase.rid){
          fsl_id_t const baseRid = fsl_db_g_id(db, 0,
            "SELECT blob.rid FROM {{dbname.ckout}}.stash, {{dbname.repo}}.blob"
            " WHERE stashid=%" FSL_ID_T_PFMT " AND blob.uuid=stash.hash",
            sid);
          rc = baseRid>0
            ? fsl_deck_load_rid(f, &dBase, baseRid, FSL_SATYPE_CHECKIN)
            : fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "The baseline of stash %"
                             FSL_ID_T_PFMT " is not in the repository.",
                             sid);
        }
        if(!rc) rc = fsl_deck_F_search2(&dBase, zOrig, &fc);
        wasLink = fc && FSL_FILE_PERM_LINK==fc->perm;
      }
      if(!rc) rc = fsl__stash_apply_modified(f, rid, &delta, zOPath,
                                             zNPath, wasLink, isLink,
                                             isExec, &change, &nc);
      if(!rc && (FSL_STASH_CONFLICT==change
                 || FSL_STASH_UNMERGEABLE==change)) ++nConflict;
    }
    if(!rc && fsl_strcmp(zOrig, zNew)){
      /* A rename: drop the old name, and point vfile at the new one
         with the old one as its origname. */
      fsl__cfs_unlink(f, zOPath);
      rc = fsl_cx_exec(f,
        "UPDATE {{dbname.ckout}}.vfile SET pathname=%Q, origname=%Q"
        " WHERE pathname=%Q %s AND vid=%" FSL_ID_T_PFMT,
        zNew, zOrig, zOrig, fsl_cx_filename_collation(f),
        f->db.ckout.rid);
    }
    if(!rc && opt->callback){
      rc = opt->callback(zNew, zOrig, change, nc, opt->callbackState);
    }
    fsl_free(zOPath);
    fsl_free(zNPath);
  }
  fsl_stmt_finalize(&q);
  if(!rc) rc = fsl__stash_add_files(f);
  if(!rc){
    /* Force the next changes scan to look at every stashed file, as
       (fossil stash goto) does. Without this, a file written in the
       same second as its recorded mtime looks unchanged to fossil(1),
       which trusts an unchanged mtime. */
    rc = fsl_cx_exec(f,
      "UPDATE {{dbname.ckout}}.vfile SET mtime=0 WHERE pathname IN"
      " (SELECT newname FROM {{dbname.ckout}}.stashfile WHERE stashid=%" FSL_ID_T_PFMT ")",
      sid);
  }
  if(!rc && opt->pop) rc = fsl_stash_drop(f, sid);
  end:
  fsl_stmt_finalize(&q);
  fsl_deck_finalize(&dBase);
  if(haveSfile) fsl__db_temp_drop(db, "fx_stash_sfile");
  {
    int const rc2 = fsl_cx_txn_end(f, !!rc);
    if(!rc) rc = rc2;
  }
  if(!rc && nConflicts) *nConflicts = nConflict;
  return rc;
}

static int fsl__stash_drop_impl(fsl_cx * const f, fsl_id_t stashId){
  fsl_db * const db = fsl_needs_ckout(f);
  int rc;
  if(!db) return FSL_RC_NOT_A_CKOUT;
  rc = fsl__stash_tables(f, db);
  if(rc) return rc;
  if(stashId<0){
    rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
    if(rc) return rc;
    rc = fsl_cx_exec_multi(f, "DELETE FROM {{dbname.ckout}}.stash; DELETE FROM {{dbname.ckout}}.stashfile;");
    {
      int const rc2 = fsl_cx_txn_end(f, !!rc);
      if(!rc) rc = rc2;
    }
    return rc;
  }
  if(0==stashId || !fsl_db_exists(db, "SELECT 1 FROM {{dbname.ckout}}.stash WHERE stashid=%"
                                  FSL_ID_T_PFMT, stashId)){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "No such stash: %" FSL_ID_T_PFMT, stashId);
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) return rc;
  rc = fsl_cx_exec_multi(f,
    "DELETE FROM {{dbname.ckout}}.stash WHERE stashid=%" FSL_ID_T_PFMT ";"
    "DELETE FROM {{dbname.ckout}}.stashfile WHERE stashid=%" FSL_ID_T_PFMT ";",
    stashId, stashId);
  {
    int const rc2 = fsl_cx_txn_end(f, !!rc);
    if(!rc) rc = rc2;
  }
  return rc;
}

int fsl_stash_rename(fsl_cx * const f, fsl_id_t stashId,
                     char const * zComment){
  fsl_db * const db = fsl_needs_ckout(f);
  int rc;
  if(!db) return FSL_RC_NOT_A_CKOUT;
  if(stashId<=0){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "No such stash: %" FSL_ID_T_PFMT, stashId);
  }
  rc = fsl__stash_tables(f, db);
  if(!rc) rc = fsl__stash_resolve(f, db, &stashId);
  return rc ? rc : fsl_cx_exec(f,
    "UPDATE {{dbname.ckout}}.stash SET comment=%Q WHERE stashid=%" FSL_ID_T_PFMT,
    zComment, stashId);
}

int fsl_stash_latest(fsl_cx * const f, fsl_id_t * stashId){
  fsl_db * const db = fsl_needs_ckout(f);
  int rc;
  if(!db) return FSL_RC_NOT_A_CKOUT;
  rc = fsl__stash_tables(f, db);
  if(!rc) *stashId = fsl_db_g_id(db, 0, "SELECT max(stashid) FROM {{dbname.ckout}}.stash");
  return rc;
}

int fsl_stash_content(fsl_cx * const f, fsl_id_t stashId,
                      char const * zName, fsl_b * const tgt,
                      fsl_b * const baseline){
  fsl_db * const db = fsl_needs_ckout(f);
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  if(!db) return FSL_RC_NOT_A_CKOUT;
  fsl_b_reuse(tgt);
  if(baseline) fsl_b_reuse(baseline);
  rc = fsl__stash_tables(f, db);
  if(!rc) rc = fsl__stash_resolve(f, db, &stashId);
  if(!rc) rc = fsl_cx_prepare(f, &q,
    "SELECT coalesce((SELECT rid FROM {{dbname.repo}}.blob WHERE uuid=stashfile.hash),0),"
    " isRemoved, delta, hash IS NULL FROM {{dbname.ckout}}.stashfile"
    " AS stashfile WHERE stashid=%" FSL_ID_T_PFMT " AND newname=%Q",
    stashId, zName);
  if(rc) goto end;
  rc = fsl_stmt_step(&q);
  if(FSL_RC_STEP_ROW!=rc){
    rc = FSL_RC_STEP_DONE==rc
      ? fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "File not in stash %"
                       FSL_ID_T_PFMT ": %s", stashId, zName)
      : fsl_cx_uplift_db_error2(f, db, rc);
    goto end;
  }
  rc = 0;
  {
    fsl_id_t const rid = fsl_stmt_g_id(&q, 0);
    void const * pDelta = NULL;
    fsl_size_t nDelta = 0;
    fsl_b delta = fsl_b_empty;
    fsl_b a = fsl_b_empty;
    if(fsl_stmt_g_int32(&q, 1)){
      rc = fsl_cx_err_set(f, FSL_RC_TYPE, "File was removed in stash %"
                          FSL_ID_T_PFMT ": %s", stashId, zName);
      goto end;
    }
    fsl_stmt_get_blob(&q, 2, &pDelta, &nDelta);
    fsl_b_external(&delta, pDelta, (fsl_int_t)nDelta);
    if(fsl_stmt_g_int32(&q, 3)){
      /* An added file: the delta column holds the whole content. */
      rc = delta.used ? fsl_b_append(tgt, delta.mem, delta.used) : 0;
    }else if(0==rid){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "The baseline of %s in "
                          "stash %" FSL_ID_T_PFMT " is not in the "
                          "repository.", zName, stashId);
    }else{
      rc = fsl_content_get(f, rid, &a);
      if(!rc) rc = fsl_b_delta_apply(&a, &delta, tgt);
      if(!rc && baseline) fsl_b_swap(&a, baseline);
      fsl_b_clear(&a);
    }
  }
  end:
  fsl_stmt_finalize(&q);
  return rc;
}

int fsl_stash_save(fsl_cx * const f,
                   fsl_stash_save_opt const * opt,
                   fsl_id_t * stashId){
  /* As in fossil(1), the revert which a save runs is not undoable. */
  bool undoOwner = false;
  int rc = fsl__undo_begin(f, NULL, &undoOwner);
  if(!rc) rc = fsl__stash_save_impl(f, opt, stashId);
  return fsl__undo_end(f, rc, undoOwner);
}

int fsl_stash_apply(fsl_cx * const f,
                    fsl_stash_apply_opt const * opt,
                    unsigned * nConflicts){
  fsl_stash_apply_opt o = *opt;
  bool undoOwner = false;
  int rc = 0;
  if(o.stashId<=0) rc = fsl_stash_latest(f, &o.stashId);
  if(!rc) rc = fsl__undo_begin(f, o.gotoBaseline ? "stash goto"
                               : (o.pop ? "stash pop" : "stash apply"),
                               &undoOwner);
  if(!rc && o.pop && o.stashId>0) rc = fsl__undo_keep_stash(f, o.stashId);
  if(!rc) rc = fsl__stash_apply_impl(f, &o, nConflicts);
  return fsl__undo_end(f, rc, undoOwner);
}

int fsl_stash_drop(fsl_cx * const f, fsl_id_t stashId){
  bool undoOwner = false;
  int rc = fsl__undo_begin(f, "stash drop", &undoOwner);
  if(!rc && stashId) rc = fsl__undo_keep_stash(f, stashId);
  if(!rc) rc = fsl__stash_drop_impl(f, stashId);
  return fsl__undo_end(f, rc, undoOwner);
}
/* end of file src/stash.c */
/* start of file src/undo.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**
   One level of undo and redo (see undo.h), built on the stash.

   An undo record has two slots: 'cur', the record undo or redo
   uses, and 'new', which an operation in progress fills and which
   replaces 'cur' when the operation succeeds. Each slot holds the
   checkout version before the operation (preRid), the version and a
   fingerprint of the local state after it (postRid, fprint), a stash
   snapshot of the local changes before it, copies of vfile and
   vmerge before it, and the stashes it removed or added, to put back
   or take away.

   The TEMP table fx_undo_active marks an operation in progress on
   this connection. Operations which run inside another one, e.g. the
   update which (stash goto) runs, or the revert which a stash save
   runs, find it and record nothing of their own. A NULL label in it
   means recording is suppressed altogether.
*/
#include <assert.h>
#include <string.h>

/* The tables are qualified with the checkout schema's name, "ckout",
   so that they land in the checkout db even when the main db is a host
   application's (fsl_cx_host_db()), or are that db's prefixed tables
   (fsl_repo_open_ckout_opt::hostTablePrefix). */
static char const * const fsl__undo_schema =
  "CREATE TABLE IF NOT EXISTS {{dbname.ckout}}.fsl_undo("
  "  slot TEXT PRIMARY KEY, label TEXT, isRedo INTEGER,"
  "  preRid INTEGER, postRid INTEGER, fprint TEXT, ctime TIMESTAMP);"
  "CREATE TABLE IF NOT EXISTS {{dbname.ckout}}.fsl_undo_vmerge("
  "  slot TEXT, id INTEGER, merge INTEGER, mhash TEXT);"
  "CREATE TABLE IF NOT EXISTS {{dbname.ckout}}.fsl_undo_vfile("
  "  slot TEXT, id INTEGER, vid INTEGER, chnged INT, deleted BOOLEAN,"
  "  isexe BOOLEAN, islink BOOLEAN, rid INTEGER, mrid INTEGER,"
  "  mtime INTEGER, pathname TEXT, origname TEXT, mhash TEXT);"
  "CREATE TABLE IF NOT EXISTS {{dbname.ckout}}.fsl_undo_stash("
  "  slot TEXT PRIMARY KEY, vid INTEGER, hash TEXT, comment TEXT,"
  "  ctime TIMESTAMP);"
  "CREATE TABLE IF NOT EXISTS {{dbname.ckout}}.fsl_undo_stashfile("
  "  slot TEXT, isAdded BOOLEAN, isRemoved BOOLEAN, isExec BOOLEAN,"
  "  isLink BOOLEAN, rid INTEGER, hash TEXT, origname TEXT,"
  "  newname TEXT, delta BLOB);"
  /* Stashes to put back (act='restore') or take away (act='drop'). */
  "CREATE TABLE IF NOT EXISTS {{dbname.ckout}}.fsl_undo_keepstash("
  "  slot TEXT, act TEXT, stashid INTEGER, vid INTEGER, hash TEXT,"
  "  comment TEXT, ctime TIMESTAMP);"
  "CREATE TABLE IF NOT EXISTS {{dbname.ckout}}.fsl_undo_keepstashfile("
  "  slot TEXT, stashid INTEGER, isAdded BOOLEAN, isRemoved BOOLEAN,"
  "  isExec BOOLEAN, isLink BOOLEAN, rid INTEGER, hash TEXT,"
  "  origname TEXT, newname TEXT, delta BLOB);"
  /* Unmanaged files to write back (see fsl__undo_save_extras()). */
  "CREATE TABLE IF NOT EXISTS {{dbname.ckout}}.fsl_undo_extra("
  "  slot TEXT, pathname TEXT, isExec BOOLEAN, content BLOB);"
  "CREATE TEMP TABLE IF NOT EXISTS {{temp.fx_undo_active}}(label TEXT);";

static char const * const fsl__undo_tables_list[] = {
  "fsl_undo", "fsl_undo_vmerge", "fsl_undo_vfile",
  "fsl_undo_stash", "fsl_undo_stashfile",
  "fsl_undo_keepstash", "fsl_undo_keepstashfile", "fsl_undo_extra", NULL
};

static int fsl__undo_tables(fsl_cx * const f){
  fsl_id_t dummy = 0;
  /* fsl_stash_latest() creates the stash tables, which undo uses. */
  int rc = fsl_stash_latest(f, &dummy);
  return rc ? rc : fsl_cx_exec_multi(f, fsl__undo_schema);
}

/**
   Runs zFmt, an UPDATE or DELETE whose "%b" is the qualified name of
   each undo table in turn and whose "%Q" is zSlot, for each of them.
*/
static int fsl__undo_tables_each(fsl_cx * const f, char const * zFmt,
                                 char const * zSlot){
  fsl_b * const name = fsl__cx_scratchpad(f);
  int rc = 0;
  for(int i = 0; !rc && fsl__undo_tables_list[i]; ++i){
    fsl_b_reuse(name);
    rc = fsl__db_table_name(f->dbMain, FSL_DBROLE_CKOUT,
                            fsl__undo_tables_list[i], true, name);
    if(rc) rc = fsl_cx_err_set(f, rc, NULL);
    else rc = fsl_cx_exec(f, zFmt, name, zSlot);
  }
  fsl__cx_scratchpad_yield(f, name);
  return rc;
}

static int fsl__undo_slot_clear(fsl_cx * const f, char const * zSlot){
  return fsl__undo_tables_each(f, "DELETE FROM %b WHERE slot=%Q", zSlot);
}

/** Replaces slot 'cur' with slot 'new'. */
static int fsl__undo_promote(fsl_cx * const f){
  int rc = fsl__undo_slot_clear(f, "cur");
  return rc ? rc : fsl__undo_tables_each(f, "UPDATE %b SET slot=%Q"
                                         " WHERE slot='new'", "cur");
}

/**
   Computes a fingerprint of the checkout's local state into tgt: its
   version, the managed files which differ from it with their on-disk
   hashes, and the merge state. Anything which changes it after an
   operation would be lost by undoing that operation.
*/
static int fsl__undo_fprint(fsl_cx * const f, fsl_b * const tgt){
  fsl_b * const acc = fsl_cx_b_borrow(f);
  fsl_b * const h = fsl_cx_b_borrow(f);
  fsl_b * const path = fsl_cx_b_borrow(f);
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  if( !acc || !h || !path ){
    rc = f->error.code;
    goto end;
  }
  rc = fsl_vfile_changes_scan(f, 0, 0);
  if(!rc) rc = fsl_b_appendf(acc, "rid=%" FSL_ID_T_PFMT "\n",
                             f->db.ckout.rid);
  if(!rc) rc = fsl_cx_prepare(f, &q,
    "SELECT pathname, deleted, coalesce(origname,''), rid, chnged"
    " FROM {{dbname.ckout}}.vfile WHERE vid=%" FSL_ID_T_PFMT
    " AND (chnged OR deleted OR origname NOT NULL OR rid==0)"
    " ORDER BY pathname", f->db.ckout.rid);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    char const * const zName = fsl_stmt_g_text(&q, 0, NULL);
    bool const deleted = !!fsl_stmt_g_int32(&q, 1);
    fsl_b_reuse(h);
    if(!deleted){
      fsl_b_reuse(path);
      rc = fsl_b_appendf(path, "%s%s", f->db.ckout.dir, zName);
      if(!rc){
        int const rcHash = fsl__cfs_sha3sum(f, fsl_b_cstr(path), h);
        /* A missing file hashes as nothing. */
        if(rcHash && FSL_RC_NOT_FOUND!=rcHash) rc = rcHash;
        if(rcHash) fsl_b_reuse(h);
      }
    }
    if(!rc) rc = fsl_b_appendf(acc, "%s %d %s %d %d %b\n", zName,
                               (int)deleted, fsl_stmt_g_text(&q, 2, NULL),
                               (int)fsl_stmt_g_id(&q, 3),
                               fsl_stmt_g_int32(&q, 4), h);
  }
  fsl_stmt_finalize(&q);
  if(!rc) rc = fsl_cx_prepare(f, &q,
    "SELECT id, merge, coalesce(mhash,'') FROM {{dbname.ckout}}.vmerge"
    " ORDER BY id, merge, mhash");
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    rc = fsl_b_appendf(acc, "vmerge %d %d %s\n",
                       (int)fsl_stmt_g_id(&q, 0), (int)fsl_stmt_g_id(&q, 1),
                       fsl_stmt_g_text(&q, 2, NULL));
  }
  fsl_stmt_finalize(&q);
  if(!rc){
    fsl_b_reuse(tgt);
    rc = fsl_sha3sum_buffer(acc, tgt);
  }
  end:
  fsl_cx_b_return(f, acc);
  fsl_cx_b_return(f, h);
  fsl_cx_b_return(f, path);
  return rc;
}

/**
   Completes a snapshot with what a stash leaves out but undo needs:
   each file's actual executable bit, where the stash has vfile's, and
   the content of a file which was removed from management but is
   still on disk, which the stash does not store. Such content goes in
   the delta column, which is otherwise NULL for a removed file.
*/
static int fsl__undo_snapshot_disk(fsl_cx * const f, char const * zSlot){
  fsl_stmt q = fsl_stmt_empty;
  fsl_b * const path = fsl_cx_b_borrow(f);
  fsl_b * const content = fsl_cx_b_borrow(f);
  int rc = (path && content) ? 0 : f->error.code;
  if(!rc) rc = fsl_cx_prepare(f, &q,
    "SELECT rowid, isRemoved, newname FROM {{dbname.ckout}}.fsl_undo_stashfile"
    " WHERE slot=%Q AND NOT isLink", zSlot);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    fsl_int_t const rowid = fsl_stmt_g_int64(&q, 0);
    fsl_b_reuse(path);
    rc = fsl_b_appendf(path, "%s%s", f->db.ckout.dir,
                       fsl_stmt_g_text(&q, 2, NULL));
    if(rc) break;
    if(!fsl_stmt_g_int32(&q, 1)){
      rc = fsl_cx_exec(f, "UPDATE {{dbname.ckout}}.fsl_undo_stashfile SET isExec=%d"
                       " WHERE rowid=%" FSL_INT_T_PFMT,
                       (int)fsl__cfs_isexec(f, fsl_b_cstr(path)), rowid);
    }else if(fsl__cfs_is_file(f, fsl_b_cstr(path))){
      fsl_stmt * up = NULL;
      fsl_b_reuse(content);
      rc = fsl__cfs_read(f, content, fsl_b_cstr(path));
      if(!rc) rc = fsl_cx_prepare_cached(f, &up,
        "UPDATE {{dbname.ckout}}.fsl_undo_stashfile SET delta=?1, isExec=?2"
        " WHERE rowid=?3 /*%s()*/", __func__);
      if(!rc) rc = fsl_stmt_bind_blob(up, 1, content->mem
                                      ? (void*)content->mem : (void*)"",
                                      (int)content->used, false);
      if(!rc) rc = fsl_stmt_bind_int32(up, 2,
                                       fsl__cfs_isexec(f, fsl_b_cstr(path)));
      if(!rc) rc = fsl_stmt_bind_int64(up, 3, rowid);
      if(!rc) rc = fsl_stmt_step(up)==FSL_RC_STEP_DONE
        ? 0 : fsl_cx_uplift_db_error2(f, up->db, FSL_RC_DB);
      if(up) fsl_stmt_cached_yield(up);
    }
  }
  fsl_stmt_finalize(&q);
  fsl_cx_b_return(f, path);
  fsl_cx_b_return(f, content);
  return rc;
}

/**
   Saves the local changes as a stash snapshot in the given slot,
   then takes that stash out of the stash list, so that it does not
   show up there or in (fossil stash list).
*/
static int fsl__undo_snapshot(fsl_cx * const f, char const * zSlot){
  fsl_stash_save_opt opt = fsl_stash_save_opt_empty;
  fsl_id_t sid = 0;
  int rc;
  opt.keepChanges = true;
  opt.comment = "undo snapshot";
  rc = fsl_stash_save(f, &opt, &sid);
  if(FSL_RC_NOOP==rc){
    /* No local changes: an empty snapshot. */
    fsl_cx_err_reset(f);
    return 0;
  }
  if(!rc) rc = fsl_cx_exec_multi(f,
    "INSERT INTO {{dbname.ckout}}.fsl_undo_stash(slot,vid,hash,comment,ctime)"
    " SELECT %Q, vid, hash, comment, ctime FROM {{dbname.ckout}}.stash"
    " WHERE stashid=%" FSL_ID_T_PFMT ";"
    "INSERT INTO {{dbname.ckout}}.fsl_undo_stashfile(slot,isAdded,isRemoved,isExec,isLink,"
    "  rid,hash,origname,newname,delta)"
    " SELECT %Q, isAdded, isRemoved, isExec, isLink, rid, hash, origname,"
    "  newname, delta FROM {{dbname.ckout}}.stashfile WHERE stashid=%" FSL_ID_T_PFMT ";"
    "DELETE FROM {{dbname.ckout}}.stash WHERE stashid=%" FSL_ID_T_PFMT ";"
    "DELETE FROM {{dbname.ckout}}.stashfile WHERE stashid=%" FSL_ID_T_PFMT ";",
    zSlot, sid, zSlot, sid, sid, sid);
  /* Give the stash ID back. */
  if(!rc) rc = fsl_config_set_id(f, FSL_CONFDB_CKOUT, "stash-next", sid);
  if(!rc) rc = fsl__undo_snapshot_disk(f, zSlot);
  return rc;
}

/**
   Records the current state in the given slot, with the given label:
   the checkout version, the merge state and a snapshot of the local
   changes.
*/
static int fsl__undo_capture(fsl_cx * const f, char const * zSlot,
                             char const * zLabel){
  int rc = fsl__undo_slot_clear(f, zSlot);
  if(!rc) rc = fsl_cx_exec(f,
    "INSERT INTO {{dbname.ckout}}.fsl_undo(slot,label,isRedo,preRid,postRid,fprint,ctime)"
    " VALUES(%Q,%Q,0,%" FSL_ID_T_PFMT ",0,NULL,julianday('now'))",
    zSlot, zLabel, f->db.ckout.rid);
  if(!rc) rc = fsl_cx_exec(f,
    "INSERT INTO {{dbname.ckout}}.fsl_undo_vmerge(slot,id,merge,mhash)"
    " SELECT %Q, id, merge, mhash FROM {{dbname.ckout}}.vmerge", zSlot);
  if(!rc) rc = fsl__undo_snapshot(f, zSlot);
  /* The snapshot holds file contents but not the vfile bookkeeping,
     e.g. which files a merge changed, so keep a copy of that, as
     fossil(1)'s undo_vfile does. Taken after the snapshot, whose
     changes scan brings vfile up to date. */
  if(!rc) rc = fsl_cx_exec(f,
    "INSERT INTO {{dbname.ckout}}.fsl_undo_vfile(slot,%s) SELECT %Q,%s FROM {{dbname.ckout}}.vfile",
    "id,vid,chnged,deleted,isexe,islink,rid,mrid,mtime,pathname,origname,mhash", zSlot, "id,vid,chnged,deleted,isexe,islink,rid,mrid,mtime,pathname,origname,mhash");
  return rc;
}

/**
   Copies stash stashId, or all stashes if it is negative, into the
   given slot's list of stashes to act on.
*/
static int fsl__undo_copy_stash(fsl_cx * const f, char const * zSlot,
                                char const * zAct, fsl_id_t stashId){
  return fsl_cx_exec_multi(f,
    "INSERT INTO {{dbname.ckout}}.fsl_undo_keepstash(slot,act,stashid,vid,hash,comment,ctime)"
    " SELECT %Q, %Q, stashid, vid, hash, comment, ctime FROM {{dbname.ckout}}.stash"
    " WHERE (%" FSL_ID_T_PFMT "<0 OR stashid=%" FSL_ID_T_PFMT ")"
    " AND stashid NOT IN (SELECT stashid FROM {{dbname.ckout}}.fsl_undo_keepstash"
    "                     WHERE slot=%Q);"
    "INSERT INTO {{dbname.ckout}}.fsl_undo_keepstashfile(slot,stashid,isAdded,isRemoved,"
    "  isExec,isLink,rid,hash,origname,newname,delta)"
    " SELECT %Q, stashid, isAdded, isRemoved, isExec, isLink, rid, hash,"
    "  origname, newname, delta FROM {{dbname.ckout}}.stashfile"
    " WHERE (%" FSL_ID_T_PFMT "<0 OR stashid=%" FSL_ID_T_PFMT ")"
    " AND stashid NOT IN (SELECT stashid FROM {{dbname.ckout}}.fsl_undo_keepstashfile"
    "                     WHERE slot=%Q);",
    zSlot, zAct, stashId, stashId, zSlot,
    zSlot, stashId, stashId, zSlot);
}

/**
   Returns true if an operation is being recorded on f's connection,
   setting *recording to whether it records (as opposed to having
   suppressed recording).
*/
static bool fsl__undo_active(fsl_cx * const f, bool * recording){
  fsl_db * const db = fsl_cx_db_ckout(f);
  *recording = false;
  if(!db || !fsl_db_exists(db, "SELECT 1 FROM {{temp.fx_undo_active}}")) return false;
  *recording = fsl_db_exists(db, "SELECT 1 FROM {{temp.fx_undo_active}}"
                             " WHERE label IS NOT NULL");
  return true;
}

int fsl__undo_begin(fsl_cx * const f, char const * zLabel,
                    bool * const owner){
  bool recording = false;
  int rc;
  *owner = false;
  if(!fsl_cx_db_ckout(f)) return 0;
  rc = fsl__undo_tables(f);
  if(rc || fsl__undo_active(f, &recording)) return rc;
  rc = fsl_cx_exec(f, "INSERT INTO {{temp.fx_undo_active}}(label) VALUES(%Q)",
                   zLabel);
  if(rc) return rc;
  *owner = true;
  if(zLabel){
    /* One transaction, so that a failure cannot leave the snapshot's
       stash behind in the stash list. */
    rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
    if(!rc){
      rc = fsl__undo_capture(f, "new", zLabel);
      int const rc2 = fsl_cx_txn_end(f, !!rc);
      if(!rc) rc = rc2;
    }
  }
  return rc;
}

int fsl__undo_keep_stash(fsl_cx * const f, fsl_id_t stashId){
  bool recording = false;
  if(!fsl__undo_active(f, &recording) || !recording) return 0;
  return fsl__undo_copy_stash(f, "new", "restore", stashId);
}

int fsl__undo_end(fsl_cx * const f, int rc, bool owner){
  bool recording = false;
  int rc2 = 0;
  if(!owner) return rc;
  fsl__undo_active(f, &recording);
  if(recording){
    if(0==rc){
      fsl_b * const fp = fsl_cx_b_borrow(f);
      rc2 = fp ? fsl__undo_fprint(f, fp) : f->error.code;
      if(!rc2) rc2 = fsl_cx_exec(f,
        "UPDATE {{dbname.ckout}}.fsl_undo SET postRid=%" FSL_ID_T_PFMT ", fprint=%Q"
        " WHERE slot='new'", f->db.ckout.rid, fsl_b_cstr(fp));
      if(!rc2) rc2 = fsl__undo_promote(f);
      fsl_cx_b_return(f, fp);
    }else{
      fsl__undo_slot_clear(f, "new");
    }
  }
  {
    int const rc3 = fsl_cx_exec(f, "DELETE FROM {{temp.fx_undo_active}}");
    if(!rc2) rc2 = rc3;
  }
  return rc ? rc : rc2;
}

int fsl_undo_state(fsl_cx * const f, fsl_undo_e * state, char ** zLabel){
  fsl_db * const db = fsl_needs_ckout(f);
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  if(!db) return FSL_RC_NOT_A_CKOUT;
  *state = FSL_UNDO_NONE;
  if(zLabel) *zLabel = NULL;
  rc = fsl__undo_tables(f);
  if(!rc) rc = fsl_cx_prepare(f, &q, "SELECT isRedo, label FROM {{dbname.ckout}}.fsl_undo"
                              " WHERE slot='cur'");
  if(rc) return rc;
  if(FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
    *state = fsl_stmt_g_int32(&q, 0) ? FSL_UNDO_REDO : FSL_UNDO_UNDO;
    if(zLabel){
      *zLabel = fsl_strdup(fsl_stmt_g_text(&q, 1, NULL));
      if(!*zLabel) rc = FSL_RC_OOM;
    }
  }
  fsl_stmt_finalize(&q);
  return rc;
}

int fsl_undo_reset(fsl_cx * const f){
  fsl_db * const db = fsl_needs_ckout(f);
  int rc;
  if(!db) return FSL_RC_NOT_A_CKOUT;
  rc = fsl__undo_tables(f);
  if(!rc) rc = fsl__undo_slot_clear(f, "cur");
  if(!rc) rc = fsl__undo_slot_clear(f, "new");
  return rc;
}

/**
   Writes back the files of the snapshot in slot 'cur', exactly as
   they were, over a clean checkout of its version: each one's content
   is its baseline plus its stashed delta, or, for an added file, the
   stashed content itself. Then restores the vfile and vmerge
   bookkeeping saved with the snapshot.
*/
static int fsl__undo_restore(fsl_cx * const f){
  fsl_stmt q = fsl_stmt_empty;
  fsl_b * const path = fsl_cx_b_borrow(f);
  fsl_b base = fsl_b_empty;
  fsl_b content = fsl_b_empty;
  bool const allowLinks = fsl_cx_allows_symlinks(f, false);
  int rc = path ? 0 : f->error.code;
  if(!rc) rc = fsl_cx_prepare(f, &q,
    "SELECT isRemoved, isExec, isLink, origname, newname, delta,"
    " (SELECT rid FROM {{dbname.repo}}.blob WHERE uuid=s.hash), s.hash IS NULL,"
    " delta IS NULL FROM {{dbname.ckout}}.fsl_undo_stashfile s WHERE slot='cur'");
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    bool const isRemoved = !!fsl_stmt_g_int32(&q, 0);
    bool const isExec = !!fsl_stmt_g_int32(&q, 1);
    bool const isLink = !!fsl_stmt_g_int32(&q, 2);
    char const * const zOrig = fsl_stmt_g_text(&q, 3, NULL);
    char const * const zNew = fsl_stmt_g_text(&q, 4, NULL);
    fsl_id_t const rid = fsl_stmt_g_id(&q, 6);
    bool const isAdded = !!fsl_stmt_g_int32(&q, 7);
    void const * pDelta = NULL;
    fsl_size_t nDelta = 0;
    fsl_b delta = fsl_b_empty;
    if(fsl_strcmp(zOrig, zNew)){
      fsl_b_reuse(path);
      rc = fsl_b_appendf(path, "%s%s", f->db.ckout.dir, zOrig);
      if(rc) break;
      fsl__cfs_unlink(f, fsl_b_cstr(path));
    }
    fsl_b_reuse(path);
    rc = fsl_b_appendf(path, "%s%s", f->db.ckout.dir, zNew);
    if(rc) break;
    if(isRemoved && fsl_stmt_g_int32(&q, 8)){
      /* Removed, and not on disk. */
      fsl__cfs_unlink(f, fsl_b_cstr(path));
      continue;
    }
    fsl_stmt_get_blob(&q, 5, &pDelta, &nDelta);
    fsl_b_external(&delta, pDelta, (fsl_int_t)nDelta);
    fsl_b_reuse(&content);
    if(isAdded || isRemoved){
      /* The whole content: an added file, or a removed one which was
         still on disk. */
      rc = delta.used ? fsl_b_append(&content, delta.mem, delta.used) : 0;
    }else if(rid<=0){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "The baseline of %s is "
                          "not in the repository.", zNew);
    }else{
      rc = fsl_content_get(f, rid, &base);
      if(!rc) rc = fsl_b_delta_apply(&base, &delta, &content);
    }
    if(rc) break;
    fsl__cfs_unlink(f, fsl_b_cstr(path));
    if(isLink){
      rc = fsl__cfs_symlink_create(f, fsl_b_cstr(&content), fsl_b_cstr(path),
                              allowLinks);
    }else{
      rc = fsl__cfs_mkdir_for_file(f, fsl_b_cstr(path), true);
      if(!rc) rc = fsl__cfs_write(f, &content, fsl_b_cstr(path));
      if(!rc) rc = fsl__cfs_exec_set(f, fsl_b_cstr(path), isExec);
    }
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Error %R writing %s", rc, zNew);
      break;
    }
  }
  fsl_stmt_finalize(&q);
  fsl_b_clear(&base);
  fsl_b_clear(&content);
  fsl_cx_b_return(f, path);
  /* The bookkeeping, with mtime=0 so that the next changes scan looks
     at every file. */
  if(!rc) rc = fsl_cx_exec_multi(f,
    "DELETE FROM {{dbname.ckout}}.vfile;"
    "INSERT INTO {{dbname.ckout}}.vfile(id,vid,chnged,deleted,isexe,islink,rid,mrid,mtime,pathname,origname,mhash)"
    " SELECT id,vid,chnged,deleted,isexe,islink,rid,mrid,mtime,pathname,origname,mhash FROM {{dbname.ckout}}.fsl_undo_vfile WHERE slot='cur';"
    "UPDATE {{dbname.ckout}}.vfile SET mtime=0;"
    "DELETE FROM {{dbname.ckout}}.vmerge;"
    "INSERT INTO {{dbname.ckout}}.vmerge(id,merge,mhash)"
    " SELECT id, merge, mhash FROM {{dbname.ckout}}.fsl_undo_vmerge WHERE slot='cur';");
  return rc;
}

/**
   Called while recording the opposite state ('new') just before
   restoring slot 'cur': saves each unmanaged file which sits at a
   path that 'cur' manages, under its current or original name. The
   restore would overwrite or move it, e.g. a file left behind by an
   update which dropped a rename, and the snapshot holds only managed
   files.
*/
static int fsl__undo_save_extras(fsl_cx * const f){
  fsl_stmt q = fsl_stmt_empty;
  fsl_b * const path = fsl_cx_b_borrow(f);
  fsl_b * const content = fsl_cx_b_borrow(f);
  int rc = (path && content) ? 0 : f->error.code;
  if(!rc) rc = fsl_cx_prepare(f, &q,
    "SELECT DISTINCT p FROM ("
    "  SELECT pathname AS p FROM {{dbname.ckout}}.fsl_undo_vfile WHERE slot='cur'"
    "  UNION SELECT origname FROM {{dbname.ckout}}.fsl_undo_vfile"
    "   WHERE slot='cur' AND origname IS NOT NULL)"
    " WHERE p NOT IN (SELECT pathname FROM {{dbname.ckout}}.vfile)"
    "   AND p NOT IN (SELECT origname FROM {{dbname.ckout}}.vfile WHERE origname IS NOT NULL)");
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    char const * const zName = fsl_stmt_g_text(&q, 0, NULL);
    fsl_b_reuse(path);
    rc = fsl_b_appendf(path, "%s%s", f->db.ckout.dir, zName);
    if(rc || !fsl__cfs_is_file(f, fsl_b_cstr(path))) continue;
    fsl_b_reuse(content);
    rc = fsl__cfs_read(f, content, fsl_b_cstr(path));
    if(!rc){
      fsl_stmt * up = NULL;
      rc = fsl_cx_prepare_cached(f, &up,
        "INSERT INTO {{dbname.ckout}}.fsl_undo_extra(slot,pathname,isExec,content)"
        " VALUES('new',?1,?2,?3) /*%s()*/", __func__);
      if(!rc) rc = fsl_stmt_bind_text(up, 1, zName, -1, false);
      if(!rc) rc = fsl_stmt_bind_int32(up, 2,
                                       fsl__cfs_isexec(f, fsl_b_cstr(path)));
      if(!rc) rc = fsl_stmt_bind_blob(up, 3, content->mem
                                      ? (void*)content->mem : (void*)"",
                                      (int)content->used, false);
      if(!rc) rc = fsl_stmt_step(up)==FSL_RC_STEP_DONE
        ? 0 : fsl_cx_uplift_db_error2(f, up->db, FSL_RC_DB);
      if(up) fsl_stmt_cached_yield(up);
    }
  }
  fsl_stmt_finalize(&q);
  fsl_cx_b_return(f, path);
  fsl_cx_b_return(f, content);
  return rc;
}

/**
   Writes back the unmanaged files saved with slot 'cur'.
*/
static int fsl__undo_restore_extras(fsl_cx * const f){
  fsl_stmt q = fsl_stmt_empty;
  fsl_b * const path = fsl_cx_b_borrow(f);
  int rc = path ? 0 : f->error.code;
  if(!rc) rc = fsl_cx_prepare(f, &q, "SELECT pathname, isExec, content"
                              " FROM {{dbname.ckout}}.fsl_undo_extra WHERE slot='cur'");
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    void const * pC = NULL;
    fsl_size_t nC = 0;
    fsl_b c = fsl_b_empty;
    fsl_b_reuse(path);
    rc = fsl_b_appendf(path, "%s%s", f->db.ckout.dir,
                       fsl_stmt_g_text(&q, 0, NULL));
    if(rc) break;
    fsl_stmt_get_blob(&q, 2, &pC, &nC);
    fsl_b_external(&c, pC, (fsl_int_t)nC);
    rc = fsl__cfs_mkdir_for_file(f, fsl_b_cstr(path), true);
    if(!rc) rc = fsl__cfs_write(f, &c, fsl_b_cstr(path));
    if(!rc) rc = fsl__cfs_exec_set(f, fsl_b_cstr(path),
                                   !!fsl_stmt_g_int32(&q, 1));
    if(rc) rc = fsl_cx_err_set(f, rc, "Error %R writing %b", rc, path);
  }
  fsl_stmt_finalize(&q);
  fsl_cx_b_return(f, path);
  return rc;
}

int fsl_undo(fsl_cx * const f, bool redo, bool force){
  fsl_db * const db = fsl_needs_ckout(f);
  fsl_stmt q = fsl_stmt_empty;
  fsl_b * const fp = fsl_cx_b_borrow(f);
  fsl_id_t preRid = 0, postRid = 0;
  char * zLabel = NULL;
  char * zFprint = NULL;
  bool inTxn = false, active = false;
  int rc;
  if(!db){
    rc = FSL_RC_NOT_A_CKOUT;
    goto end;
  }
  if(!fp){
    rc = f->error.code;
    goto end;
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) goto end;
  inTxn = true;
  rc = fsl__undo_tables(f);
  if(!rc){
    bool recording = false;
    if(fsl__undo_active(f, &recording)){
      rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "Cannot %s while another "
                          "checkout operation is running.",
                          redo ? "redo" : "undo");
      goto end;
    }
  }
  if(!rc) rc = fsl_cx_prepare(f, &q,
    "SELECT label, preRid, postRid, fprint FROM {{dbname.ckout}}.fsl_undo"
    " WHERE slot='cur' AND isRedo=%d", redo ? 1 : 0);
  if(rc) goto end;
  if(FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
    zLabel = fsl_strdup(fsl_stmt_g_text(&q, 0, NULL));
    preRid = fsl_stmt_g_id(&q, 1);
    postRid = fsl_stmt_g_id(&q, 2);
    zFprint = fsl_strdup(fsl_stmt_g_text(&q, 3, NULL));
    if(!zLabel || !zFprint) rc = FSL_RC_OOM;
  }else{
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "Nothing to %s.",
                        redo ? "redo" : "undo");
  }
  fsl_stmt_finalize(&q);
  if(rc) goto end;
  if(postRid!=f->db.ckout.rid){
    rc = fsl_cx_err_set(f, FSL_RC_CONFLICT,
                        "The checkout is no longer on the version which "
                        "%s left it on, so it cannot be %s.",
                        zLabel, redo ? "redone" : "undone");
    goto end;
  }
  rc = fsl__undo_fprint(f, fp);
  if(rc) goto end;
  if(!force && fsl_strcmp(zFprint, fsl_b_cstr(fp))){
    rc = fsl_cx_err_set(f, FSL_RC_CONFLICT,
                        "The checkout changed after %s. %s it would "
                        "discard those changes.", zLabel,
                        redo ? "Redoing" : "Undoing");
    goto end;
  }
  /* From here on, the operations below must not record undo state of
     their own. */
  rc = fsl_cx_exec(f, "INSERT INTO {{temp.fx_undo_active}}(label) VALUES(NULL)");
  if(rc) goto end;
  active = true;
  /* The opposite record: the state now, and the stashes to undo
     this undo's stash changes. */
  rc = fsl__undo_capture(f, "new", zLabel);
  if(!rc) rc = fsl__undo_save_extras(f);
  if(!rc) rc = fsl_cx_exec_multi(f,
    "INSERT INTO {{dbname.ckout}}.fsl_undo_keepstash(slot,act,stashid)"
    " SELECT 'new', 'drop', stashid FROM {{dbname.ckout}}.fsl_undo_keepstash"
    " WHERE slot='cur' AND act='restore';");
  if(!rc){
    rc = fsl_cx_prepare(f, &q, "SELECT stashid FROM {{dbname.ckout}}.fsl_undo_keepstash"
                        " WHERE slot='cur' AND act='drop'");
    while(fsl__cx_stmt_step_each(f, &q, &rc)){
      rc = fsl__undo_copy_stash(f, "new", "restore", fsl_stmt_g_id(&q, 0));
    }
    fsl_stmt_finalize(&q);
  }
  if(rc) goto end;
  /* A revert removes what merges added and unmanages, but keeps, what
     was added by hand, as in fossil(1). The snapshot below rewrites
     any of those which the recorded state has. */
  {
    fsl_ckout_revert_opt ropt = fsl_ckout_revert_opt_empty;
    ropt.relativeToCwd = false;
    rc = fsl_ckout_revert(f, &ropt);
  }
  if(!rc && preRid!=f->db.ckout.rid){
    fsl_ckup_opt uopt = fsl_ckup_opt_empty;
    uopt.checkinRid = preRid;
    rc = fsl_ckout_update(f, &uopt);
  }
  if(!rc) rc = fsl__undo_restore(f);
  if(!rc) rc = fsl__undo_restore_extras(f);
  if(!rc) rc = fsl_cx_exec_multi(f,
    "INSERT OR IGNORE INTO {{dbname.ckout}}.stash(stashid,vid,hash,comment,ctime)"
    " SELECT stashid, vid, hash, comment, ctime FROM {{dbname.ckout}}.fsl_undo_keepstash"
    " WHERE slot='cur' AND act='restore';"
    "INSERT OR IGNORE INTO {{dbname.ckout}}.stashfile(stashid,isAdded,isRemoved,isExec,"
    "  isLink,rid,hash,origname,newname,delta)"
    " SELECT stashid, isAdded, isRemoved, isExec, isLink, rid, hash,"
    "  origname, newname, delta FROM {{dbname.ckout}}.fsl_undo_keepstashfile"
    " WHERE slot='cur' AND stashid IN (SELECT stashid FROM"
    "  {{dbname.ckout}}.fsl_undo_keepstash WHERE slot='cur' AND act='restore');"
    "DELETE FROM {{dbname.ckout}}.stashfile WHERE stashid IN (SELECT stashid FROM"
    "  {{dbname.ckout}}.fsl_undo_keepstash WHERE slot='cur' AND act='drop');"
    "DELETE FROM {{dbname.ckout}}.stash WHERE stashid IN (SELECT stashid FROM"
    "  {{dbname.ckout}}.fsl_undo_keepstash WHERE slot='cur' AND act='drop');");
  if(!rc) rc = fsl__undo_fprint(f, fp);
  if(!rc) rc = fsl_cx_exec(f,
    "UPDATE {{dbname.ckout}}.fsl_undo SET isRedo=%d, postRid=%" FSL_ID_T_PFMT ", fprint=%Q"
    " WHERE slot='new'", redo ? 0 : 1, f->db.ckout.rid, fsl_b_cstr(fp));
  if(!rc) rc = fsl__undo_promote(f);
  end:
  if(active){
    int const rc2 = fsl_cx_exec(f, "DELETE FROM {{temp.fx_undo_active}}");
    if(!rc) rc = rc2;
  }
  fsl_stmt_finalize(&q);
  fsl_free(zLabel);
  fsl_free(zFprint);
  fsl_cx_b_return(f, fp);
  if(inTxn){
    int const rc2 = fsl_cx_txn_end(f, !!rc);
    if(!rc) rc = rc2;
  }
  return rc;
}
/* end of file src/undo.c */
/* start of file src/bisect.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**
   Bisect sessions (see bisect.h). A port of fossil(1) 2.29's
   src/bisect.c, and, for the path between the good and bad
   check-ins, of its src/path.c path_shortest() and src/pqueue.c.
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>

const fsl_bisect_state_t fsl_bisect_state_t_empty = {0,0,0,0,0,false};

/** The bisect options, with fossil(1)'s defaults. */
static struct {
  char const * zName;
  char const * zDefault;
} const fsl__bisect_options[] = {
  {"auto-next", "on"},
  {"direct-only", "on"},
  {"display", "chart"},
  {"linear", "off"}
};
#define fsl__bisect_option_count \
  (sizeof(fsl__bisect_options)/sizeof(fsl__bisect_options[0]))

/** fossil(1)'s is_truth(). */
static bool fsl__bisect_is_truth(char const * z){
  static char const * const azOn[] = {"on", "yes", "true"};
  for(unsigned i = 0; i < sizeof(azOn)/sizeof(azOn[0]); ++i){
    if(0==fsl_stricmp(z, azOn[i])) return true;
  }
  return 0!=atoi(z);
}

/** fossil(1)'s is_false(). */
static bool fsl__bisect_is_false(char const * z){
  static char const * const azOff[] = {"off", "no", "false", "0"};
  for(unsigned i = 0; i < sizeof(azOff)/sizeof(azOff[0]); ++i){
    if(0==fsl_stricmp(z, azOff[i])) return true;
  }
  return false;
}

/** Reads vvar entry zName, or returns NULL. Caller frees. */
static char * fsl__bisect_vvar(fsl_cx * const f, char const * zName){
  return fsl_db_g_text(fsl_cx_db_ckout(f), NULL,
                       "SELECT value FROM {{dbname.ckout}}.vvar WHERE name=%Q", zName);
}

static fsl_id_t fsl__bisect_vvar_id(fsl_cx * const f, char const * zName){
  return fsl_db_g_id(fsl_cx_db_ckout(f), 0,
                     "SELECT value FROM {{dbname.ckout}}.vvar WHERE name=%Q", zName);
}

static int fsl__bisect_vvar_set_id(fsl_cx * const f, char const * zName,
                                   fsl_id_t v){
  return fsl_cx_exec(f, "REPLACE INTO {{dbname.ckout}}.vvar(name,value) VALUES(%Q,"
                     "%" FSL_ID_T_PFMT ")", zName, v);
}

int fsl_bisect_option(fsl_cx * const f, char const * zName,
                      char const * zNewValue, char ** zValue){
  char * zKey;
  char * z;
  unsigned i;
  int rc = 0;
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  for(i = 0; i < fsl__bisect_option_count; ++i){
    if(0==fsl_strcmp(zName, fsl__bisect_options[i].zName)) break;
  }
  if(i==fsl__bisect_option_count){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "No such bisect option: %s",
                          zName);
  }
  zKey = fsl_mprintf("bisect-%s", zName);
  if(!zKey) return FSL_RC_OOM;
  if(zNewValue){
    rc = fsl_cx_exec(f, "REPLACE INTO {{dbname.ckout}}.vvar(name,value) VALUES(%Q,%Q)",
                     zKey, zNewValue);
  }
  if(!rc && zValue){
    z = fsl__bisect_vvar(f, zKey);
    *zValue = z ? z : fsl_strdup(fsl__bisect_options[i].zDefault);
    if(!*zValue) rc = FSL_RC_OOM;
  }
  fsl_free(zKey);
  return rc;
}

bool fsl_bisect_option_is_on(fsl_cx * const f, char const * zName){
  char * z = NULL;
  char const * zDflt = "off";
  bool on;
  for(unsigned i = 0; i < fsl__bisect_option_count; ++i){
    if(0==fsl_strcmp(zName, fsl__bisect_options[i].zName)){
      zDflt = fsl__bisect_options[i].zDefault;
      break;
    }
  }
  if(!fsl_cx_db_ckout(f) || fsl_bisect_option(f, zName, NULL, &z)){
    fsl_cx_err_reset(f);
    return fsl__bisect_is_truth(zDflt);
  }
  if(fsl__bisect_is_truth(z)) on = true;
  else if(fsl__bisect_is_false(z)) on = false;
  else on = fsl__bisect_is_truth(zDflt);
  fsl_free(z);
  return on;
}

int fsl_bisect_mark(fsl_cx * const f, fsl_bisect_e verdict, fsl_id_t rid){
  int rc;
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  if(rid<=0) rid = f->db.ckout.rid;
  if(rid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE, "No check-in to mark.");
  }
  switch(verdict){
    case FSL_BISECT_GOOD:
    case FSL_BISECT_BAD: {
      char const * zKey = FSL_BISECT_GOOD==verdict ? "bisect-good"
        : "bisect-bad";
      /* The log holds good check-ins as positive RIDs, bad ones as
         negative. */
      fsl_id_t const logged = FSL_BISECT_GOOD==verdict ? rid : -rid;
      if(fsl__bisect_vvar_id(f, zKey)==rid) return 0;
      rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
      if(rc) return rc;
      rc = fsl__bisect_vvar_set_id(f, zKey, rid);
      if(!rc) rc = fsl_cx_exec(f,
        "REPLACE INTO {{dbname.ckout}}.vvar(name,value) VALUES('bisect-log',"
        "COALESCE((SELECT value||' ' FROM {{dbname.ckout}}.vvar WHERE name='bisect-log'),'')"
        " || '%" FSL_ID_T_PFMT "')", logged);
      {
        int const rc2 = fsl_cx_txn_end(f, !!rc);
        if(!rc) rc = rc2;
      }
      return rc;
    }
    case FSL_BISECT_SKIP:
      /* As in fossil(1), this appends only to an existing log. */
      return fsl_cx_exec(f, "UPDATE {{dbname.ckout}}.vvar SET value=value||' s%"
                         FSL_ID_T_PFMT "' WHERE name='bisect-log'", rid);
    default:
      return fsl_cx_err_set(f, FSL_RC_RANGE, "Invalid bisect verdict: %d",
                            (int)verdict);
  }
}

int fsl_bisect_undo(fsl_cx * const f){
  char * zLog;
  char const * z;
  fsl_id_t good = 0, bad = 0;
  fsl_size_t keep = 0;
  int cnt = 0, rc;
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  zLog = fsl__bisect_vvar(f, "bisect-log");
  for(z = zLog ? zLog : ""; *z; ){
    while(*z==' ') ++z;
    if(*z){ ++cnt; while(*z && *z!=' ') ++z; }
  }
  if(0==cnt){
    fsl_free(zLog);
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "No previous bisect steps to undo.");
  }
  /* Replay all but the last entry for the good and bad check-ins, and
     keep the log up to the end of the second-to-last one. Skip entries
     are passed over. (fossil(1) 2.29 parses a skip entry as RID 0 and
     takes it as the good check-in, so its undo forgets the good one
     whenever a skip follows it.) */
  z = zLog;
  for(int i = 0; i < cnt-1; ++i){
    fsl_id_t rid;
    while(*z==' ') ++z;
    rid = (fsl_id_t)strtoll(z, NULL, 10);
    if(rid<0) bad = -rid;
    else if(rid>0) good = rid;
    while(*z && *z!=' ') ++z;
  }
  keep = (fsl_size_t)(z - zLog);
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(!rc){
    rc = fsl_cx_exec(f, "UPDATE {{dbname.ckout}}.vvar SET value=substr(value,1,%d)"
                     " WHERE name='bisect-log'", (int)keep);
    if(!rc) rc = fsl__bisect_vvar_set_id(f, "bisect-bad", bad);
    if(!rc) rc = fsl__bisect_vvar_set_id(f, "bisect-good", good);
    int const rc2 = fsl_cx_txn_end(f, !!rc);
    if(!rc) rc = rc2;
  }
  fsl_free(zLog);
  return rc;
}

int fsl_bisect_reset(fsl_cx * const f){
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  return fsl_cx_exec(f, "DELETE FROM {{dbname.ckout}}.vvar WHERE name IN"
                     " ('bisect-good','bisect-bad','bisect-log',"
                     "  'bisect-complete','bisect-linear')");
}

int fsl_bisect_state(fsl_cx * const f, fsl_bisect_state_t * st){
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  *st = fsl_bisect_state_t_empty;
  st->good = fsl__bisect_vvar_id(f, "bisect-good");
  st->bad = fsl__bisect_vvar_id(f, "bisect-bad");
  st->complete = 0!=fsl__bisect_vvar_id(f, "bisect-complete");
  return 0;
}

/*
  The path search: fossil(1) 2.29's path_shortest() with no branch
  cost and both directions allowed, which is how bisect calls it. Its
  pending nodes are kept in a binary heap, ported from pqueue.c,
  because the order in which the heap returns equal-cost nodes picks
  between equally short paths, and so the midpoint.
*/
typedef struct {
  fsl_vpath_node * node;
  double value;
} fsl__bisect_qe;

typedef struct {
  fsl__bisect_qe * a;
  int cnt;
  int sz;
} fsl__bisect_pq;

static int fsl__bisect_pq_insert(fsl__bisect_pq * const p,
                                 fsl_vpath_node * node, double v){
  int i, j;
  if(p->cnt+1 > p->sz){
    int const n = p->cnt+7;
    fsl__bisect_qe * const a = fsl_realloc(p->a, sizeof(*a)*n);
    if(!a) return FSL_RC_OOM;
    p->a = a;
    p->sz = n;
  }
  p->a[p->cnt].node = node;
  p->a[p->cnt].value = v;
  i = p->cnt++;
  while((j = (i-1)/2)>=0 && p->a[j].value > p->a[i].value){
    fsl__bisect_qe const t = p->a[j];
    p->a[j] = p->a[i];
    p->a[i] = t;
    i = j;
  }
  return 0;
}

static fsl_vpath_node * fsl__bisect_pq_extract(fsl__bisect_pq * const p,
                                               double * v){
  fsl_vpath_node * node;
  int i, j;
  if(0==p->cnt) return NULL;
  node = p->a[0].node;
  *v = p->a[0].value;
  i = 0;
  p->a[0] = p->a[p->cnt-1];
  p->cnt--;
  while((j = i*2+1) < p->cnt){
    if(j+1 < p->cnt && p->a[j].value > p->a[j+1].value) j++;
    if(p->a[i].value < p->a[j].value) break;
    fsl__bisect_qe const t = p->a[i];
    p->a[i] = p->a[j];
    p->a[j] = t;
    i = j;
  }
  return node;
}

/** Adds a node to path's list of all nodes, which fsl_vpath_clear()
    frees. */
static fsl_vpath_node * fsl__bisect_new_node(fsl_vpath * const path,
                                             fsl_id_t rid,
                                             fsl_vpath_node * pFrom,
                                             bool isParent,
                                             fsl_id_bag const * hidden){
  fsl_vpath_node * const p = fsl_malloc(sizeof(*p));
  if(!p) return NULL;
  memset(p, 0, sizeof(*p));
  p->rid = rid;
  p->fromIsParent = isParent;
  p->pFrom = pFrom;
  p->isHidden = hidden && fsl_id_bag_contains(hidden, rid);
  p->pAll = path->pAll;
  path->pAll = p;
  return p;
}

static int fsl__bisect_shortest(fsl_cx * const f, fsl_vpath * const path,
                                fsl_id_t iFrom, fsl_id_t iTo,
                                bool directOnly,
                                fsl_id_bag const * hidden){
  fsl__bisect_pq pq = {NULL, 0, 0};
  fsl_stmt s = fsl_stmt_empty;
  fsl_vpath_node * p;
  double cost = 0;
  int rc;
  fsl_vpath_clear(path);
  path->pStart = fsl__bisect_new_node(path, iFrom, NULL, false, NULL);
  if(!path->pStart) return FSL_RC_OOM;
  if(iTo==iFrom){
    path->pEnd = path->pStart;
    path->pEnd->u.pTo = NULL;
    return 0;
  }
  rc = fsl__bisect_pq_insert(&pq, path->pStart, 1.0);
  if(!rc) rc = fsl_cx_prepare(f, &s, directOnly
    ? "SELECT cid, 1 FROM {{dbname.repo}}.plink WHERE pid=?1 AND isprim"
      " UNION ALL"
      " SELECT pid, 0 FROM {{dbname.repo}}.plink WHERE ?2 AND cid=?1 AND isprim"
    : "SELECT cid, 1 FROM {{dbname.repo}}.plink WHERE pid=?1"
      " UNION ALL"
      " SELECT pid, 0 FROM {{dbname.repo}}.plink WHERE ?2 AND cid=?1");
  while(!rc && (p = fsl__bisect_pq_extract(&pq, &cost))){
    if(p->rid==iTo){
      fsl_vpath_node * q;
      path->pEnd = p;
      for(q = path->pEnd; q && q->pFrom; q = q->pFrom){
        q->pFrom->u.pTo = q;
        ++path->nStep;
      }
      path->pEnd->u.pTo = NULL;
      goto end;
    }
    if(fsl_id_bag_contains(&path->seen, p->rid)) continue;
    rc = fsl_id_bag_insert(&path->seen, p->rid);
    if( !rc ){
      rc = fsl_stmt_bind_fmt(&s, "Ri", p->rid,
                             (int)(p->fromIsParent ? 0 : 1))
        /* Only go back to a parent if this node was not reached from
           its parent: no zig-zags. */;
      if( rc ){
        rc = fsl_cx_uplift_db_error2(f, s.db, rc);
      }
    }
    while(!rc && fsl__cx_stmt_step_each(f, &s, &rc)){
      fsl_id_t const cid = fsl_stmt_g_id(&s, 0);
      fsl_vpath_node * pNew;
      if(fsl_id_bag_contains(&path->seen, cid)) continue;
      pNew = fsl__bisect_new_node(path, cid, p, !!fsl_stmt_g_int32(&s, 1),
                                  hidden);
      rc = pNew ? fsl__bisect_pq_insert(&pq, pNew, cost + 1.0)
        : FSL_RC_OOM;
    }
    fsl_stmt_reset(&s);
  }
  if(!rc) rc = FSL_RC_NOT_FOUND;
  end:
  fsl_stmt_finalize(&s);
  fsl_free(pq.a);
  if(rc) fsl_vpath_clear(path);
  return rc;
}

/** The number of non-hidden steps in path, as path.nNotHidden. */
static int fsl__bisect_not_hidden(fsl_vpath * const path){
  int n = 0;
  if(path->pStart && path->pStart!=path->pEnd){
    for(fsl_vpath_node * p = path->pStart->u.pTo; p; p = p->u.pTo){
      if(!p->isHidden) ++n;
    }
  }
  return n;
}

/** fossil(1)'s path_midpoint(). */
static fsl_vpath_node * fsl__bisect_midpoint(fsl_vpath * const path){
  int const nNotHidden = fsl__bisect_not_hidden(path);
  fsl_vpath_node * p;
  int i;
  if(nNotHidden<2) return NULL;
  for(p = path->pEnd, i = 0; p && (p->isHidden || i<nNotHidden/2);
      p = p->pFrom){
    if(!p->isHidden) ++i;
  }
  return p;
}

int fsl_bisect_path(fsl_cx * const f, fsl_vpath * const path){
  fsl_bisect_state_t st = fsl_bisect_state_t_empty;
  fsl_id_bag skip = fsl_id_bag_empty;
  char * zLog;
  int rc = fsl_bisect_state(f, &st);
  if(rc) return rc;
  if(st.good>0 && st.bad<=0){
    return fsl__bisect_shortest(f, path, st.good, st.good, false, NULL);
  }else if(st.bad>0 && st.good<=0){
    return fsl__bisect_shortest(f, path, st.bad, st.bad, false, NULL);
  }else if(st.good<=0 && st.bad<=0){
    return fsl_cx_err_set(f, FSL_RC_MISUSE, "Neither \"good\" nor \"bad\" "
                          "versions have been identified.");
  }
  zLog = fsl__bisect_vvar(f, "bisect-log");
  for(char const * z = zLog ? zLog : ""; !rc && *z; ){
    while(*z==' ') ++z;
    if(*z=='s'){
      fsl_id_t const rid = (fsl_id_t)strtoll(z+1, NULL, 10);
      if(rid>0) rc = fsl_id_bag_insert(&skip, rid);
    }
    while(*z && *z!=' ') ++z;
  }
  fsl_free(zLog);
  if(!rc){
    rc = fsl__bisect_shortest(f, path, st.good, st.bad,
                              fsl_bisect_option_is_on(f, "direct-only"),
                              &skip);
    if(FSL_RC_NOT_FOUND==rc){
      rc = fsl_cx_err_set(f, rc, "No path from good (%" FSL_ID_T_PFMT
                          ") to bad (%" FSL_ID_T_PFMT ") or back.",
                          st.good, st.bad);
    }
  }
  fsl_id_bag_clear(&skip);
  return rc;
}

int fsl_bisect_next(fsl_cx * const f, fsl_ckup_opt const * uOpt,
                    fsl_bisect_state_t * st){
  fsl_vpath path = fsl_vpath_empty;
  fsl_bisect_state_t s = fsl_bisect_state_t_empty;
  fsl_vpath_node * pMid;
  int rc = fsl_bisect_path(f, &path);
  if(rc) return rc;
  fsl_bisect_state(f, &s);
  if(fsl_bisect_option_is_on(f, "linear")){
    /* fossil(1)'s path_next(), unless that is where the checkout is. */
    pMid = path.pStart ? path.pStart->u.pTo : NULL;
    if(pMid && pMid->rid==f->db.ckout.rid) pMid = NULL;
  }else{
    pMid = fsl__bisect_midpoint(&path);
  }
  s.span = fsl__bisect_not_hidden(&path);
  for(int j = 1; j < s.span; j += j) ++s.stepsLeft;
  /* bisect-complete stays set once set, as in fossil(1) (e.g. after
     an undo of the last verdict), but this step reports its own
     result. */
  s.complete = !pMid;
  if(!pMid){
    rc = fsl__bisect_vvar_set_id(f, "bisect-complete", 1);
  }else{
    s.next = pMid->rid;
    if(uOpt){
      fsl_ckup_opt o = *uOpt;
      o.checkinRid = pMid->rid;
      rc = fsl_ckout_update(f, &o);
    }
  }
  fsl_vpath_clear(&path);
  if(!rc && st) *st = s;
  return rc;
}
/* end of file src/bisect.c */
/* start of file src/patch.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**
   fossil(1)-compatible binary patches (see patch.h). This is a port
   of fossil(1)'s src/patch.c.

   A patch is held in its own in-memory fsl_db, separate from f's
   databases: create builds it there and serializes it, and open
   deserializes a copy of the patch into it. That keeps an untrusted
   patch away from f's connection and leaves no journal files next to
   a patch file.
*/
#include <assert.h>
#include <string.h>

const fsl_patch_create_opt fsl_patch_create_opt_empty =
  fsl_patch_create_opt_empty_m;
const fsl_patch_apply_opt fsl_patch_apply_opt_empty =
  fsl_patch_apply_opt_empty_m;

/**
   fossil(1)'s patch schema, from its patch_create(). The page size is
   that of fossil(1)'s patches, the smallest SQLite allows, which keeps
   small patches small.
*/
static char const * const fsl__patch_schema =
  "PRAGMA page_size=512;"
  "CREATE TABLE chng("
  "  pathname TEXT,"
  "  origname TEXT,"
  "  hash TEXT,"
  "  isexe BOOL,"
  "  islink BOOL,"
  "  delta BLOB"
  ");"
  "CREATE TABLE cfg("
  "  key TEXT,"
  "  value ANY"
  ");";

/** Indexes into fsl_patch::aStr, one per string in fsl_patch_info. */
enum fsl__patch_str_e {
  FSL__PATCH_BASELINE = 0,
  FSL__PATCH_PCODE,
  FSL__PATCH_PNAME,
  FSL__PATCH_USER,
  FSL__PATCH_HOST,
  FSL__PATCH_CKOUT,
  FSL__PATCH_REPO,
  FSL__PATCH_STR_COUNT
};

/** The cfg keys for the fsl__patch_str_e entries, in the same order. */
static char const * const fsl__patch_cfg_keys[FSL__PATCH_STR_COUNT] = {
  "baseline", "project-code", "project-name", "user", "hostname",
  "ckout", "repo"
};

struct fsl_patch {
  /** The context the patch was opened with, for error reporting. */
  fsl_cx * f;
  /** The patch's db, deserialized into memory. */
  fsl_db db;
  /** True if the patch has a patchmerge table. */
  bool hasMerges;
  /** Owned strings which this->info points to. */
  char * aStr[FSL__PATCH_STR_COUNT];
  fsl_patch_info info;
};

static const fsl_patch fsl__patch_empty = {
  NULL/*f*/, fsl_db_empty_m/*db*/, false/*hasMerges*/,
  {NULL}/*aStr*/,
  {NULL,NULL,NULL,NULL,NULL,NULL,NULL,0.0}/*info*/
};

/**
   Reads a checkout file as fossil(1)'s patch_create() does, via
   blob_read_from_file(...,RepoFILE): with the allow-symlinks setting
   on, a symlink's content is its target name, else the symlink is
   followed. Unlike fsl_stash_save(), a missing file is an error, as
   it is in fossil(1).
*/
static int fsl__patch_read_file(fsl_cx * const f, char const * zPath,
                                fsl_b * const tgt){
  int const rc = fsl__cfs_read_repofile(f, tgt, zPath, NULL);
  return rc ? fsl_cx_err_set(f, rc, "Error %R reading file: %s",
                             rc, zPath) : 0;
}

/**
   Inserts (zKey,zVal) into pdb's cfg table, unless zVal is NULL, in
   which case fossil(1) would not have a value for it either.
*/
static int fsl__patch_cfg_set(fsl_cx * const f, fsl_db * const pdb,
                              char const * zKey, char const * zVal){
  int rc = 0;
  if(zVal){
    rc = fsl_db_exec(pdb, "INSERT INTO cfg(key,value) VALUES(%Q,%Q)",
                     zKey, zVal);
    if(rc) rc = fsl_cx_uplift_db_error2(f, pdb, rc);
  }
  return rc;
}

/**
   Fills pdb's cfg table, as fossil(1)'s patch_create() does. fossil(1)
   also records a "fossil-date", the build date of the fossil(1)
   binary, which has no libfossil equivalent, so it is left out.
*/
static int fsl__patch_create_cfg(fsl_cx * const f, fsl_db * const pdb,
                                 fsl_patch_create_opt const * opt){
  int rc;
  fsl_uuid_cstr zBaseline = NULL;
  char * zUser = NULL;
  char * zPCode = NULL;
  char * zPName = NULL;
  fsl_b * const ckDir = fsl_cx_b_borrow(f);
  if(!ckDir) return f->error.code;

  fsl_ckout_version_info(f, NULL, &zBaseline);
  rc = fsl_b_append(ckDir, fsl_cx_ckout_dir_name(f, NULL), -1);
  if(rc) goto end;
  fsl_b_strip_slashes(ckDir);
  zUser = fsl_cx_user_get(f)
    ? fsl_strdup(fsl_cx_user_get(f))
    : fsl_user_name_guess();
  zPCode = fsl_config_get_text(f, FSL_CONFDB_REPO, "project-code", NULL);
  zPName = fsl_config_get_text(f, FSL_CONFDB_REPO, "project-name", NULL);
  rc = fsl__patch_cfg_set(f, pdb, "baseline", zBaseline);
  if(!rc) rc = fsl__patch_cfg_set(f, pdb, "ckout", fsl_b_cstr(ckDir));
  if(!rc) rc = fsl__patch_cfg_set(f, pdb, "repo",
                                  fsl_cx_db_file_repo(f, NULL));
  if(!rc) rc = fsl__patch_cfg_set(f, pdb, "user", zUser);
  if(!rc){
    rc = fsl_db_exec(pdb, "INSERT INTO cfg(key,value)"
                     " VALUES('date',julianday('now'))");
    if(rc) rc = fsl_cx_uplift_db_error2(f, pdb, rc);
  }
  if(!rc) rc = fsl__patch_cfg_set(f, pdb, "project-code", zPCode);
  if(!rc) rc = fsl__patch_cfg_set(f, pdb, "project-name", zPName);
  if(!rc) rc = fsl__patch_cfg_set(f, pdb, "hostname", opt->hostname);
  end:
  fsl_cx_b_return(f, ckDir);
  fsl_free(zUser);
  fsl_free(zPCode);
  fsl_free(zPName);
  return rc;
}

/**
   Fills pdb's chng table from the checkout's vfile table, as the
   "New files", "Deleted files" and "Changed files" queries in
   fossil(1)'s patch_create() do. The checkout must have been scanned
   for changes.
*/
static int fsl__patch_create_chng(fsl_cx * const f, fsl_db * const pdb){
  fsl_id_t vid = 0;
  fsl_stmt q = fsl_stmt_empty;
  fsl_stmt ins = fsl_stmt_empty;
  fsl_b orig = fsl_b_empty;
  fsl_b delta = fsl_b_empty;
  fsl_b * const disk = fsl_cx_b_borrow(f);
  fsl_b * const absPath = fsl_cx_b_borrow(f);
  fsl_b * const zipped = fsl_cx_b_borrow(f);
  int rc;
  if(!disk || !absPath || !zipped){
    rc = f->error.code;
    assert(rc);
    goto end;
  }
  fsl_ckout_version_info(f, &vid, NULL);
  /* Column 0 is the kind of change: 1=new, 2=deleted, 3=changed. */
  rc = fsl_cx_prepare(f, &q,
    "SELECT 1, pathname, NULL, NULL, isexe, islink, 0"
    "  FROM {{dbname.ckout}}.vfile"
    " WHERE vid=%" FSL_ID_T_PFMT " AND rid==0"
    " UNION ALL"
    " SELECT 2, pathname, NULL, NULL, 0, 0, 0"
    "  FROM {{dbname.ckout}}.vfile"
    " WHERE vid=%" FSL_ID_T_PFMT " AND deleted"
    " UNION ALL"
    " SELECT 3, pathname, nullif(origname,pathname), b.uuid,"
    "        isexe, islink, v.rid"
    "  FROM {{dbname.ckout}}.vfile v, {{dbname.repo}}.blob b"
    " WHERE v.vid=%" FSL_ID_T_PFMT " AND b.rid=v.rid"
    "   AND NOT deleted AND (chnged OR origname<>pathname)",
    vid, vid, vid);
  if(!rc){
    rc = fsl_db_prepare(pdb, &ins,
      "INSERT INTO chng(pathname,origname,hash,isexe,islink,delta)"
      " VALUES(?1,?2,?3,?4,?5,?6)");
    if(rc) rc = fsl_cx_uplift_db_error2(f, pdb, rc);
  }
  if(rc) goto end;
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    int const kind = fsl_stmt_g_int32(&q, 0);
    char const * const zName = fsl_stmt_g_text(&q, 1, NULL);
    fsl_id_t const rid = fsl_stmt_g_id(&q, 6);
    int isExe = 0;
    int isLink = 0;
    fsl_b_reuse(absPath);
    rc = fsl_b_appendf(absPath, "%s%s", f->db.ckout.dir, zName);
    if(rc) break;
    if(2!=kind){
      /* Unlike fossil(1), which copies vfile.isexe and vfile.islink,
         take these from the file: a changes scan records a change of
         either only in vfile.chnged, so the vfile columns still hold
         the baseline's state, and fossil(1)'s patches lose such
         changes. */
      isLink = fsl_cx_allows_symlinks(f, false)
        && fsl__cfs_is_symlink(f, fsl_b_cstr(absPath));
      isExe = !isLink && fsl__cfs_isexec(f, fsl_b_cstr(absPath));
    }
    switch(kind){
      case 1:
        /* A new file: its whole content, compressed. */
        rc = fsl__patch_read_file(f, fsl_b_cstr(absPath), disk);
        if(!rc) rc = fsl_b_compress(disk, zipped);
        if(!rc) rc = fsl_stmt_bind_blob(&ins, 6, zipped->mem,
                                        zipped->used, false);
        break;
      case 2:
        rc = fsl_stmt_bind_null(&ins, 6);
        break;
      default:
        /* A changed file: a compressed delta from its baseline
           version, or an empty blob if only its name or permissions
           changed, as fossil(1)'s mkdelta() makes it. */
        rc = fsl__patch_read_file(f, fsl_b_cstr(absPath), disk);
        if(!rc) rc = fsl_content_get(f, rid, &orig);
        if(rc) break;
        if(orig.used==disk->used
           && (0==orig.used || 0==memcmp(orig.mem, disk->mem, orig.used))){
          rc = fsl_stmt_bind_blob(&ins, 6, "", 0, false);
        }else{
          rc = fsl_b_delta_create(&orig, disk, &delta);
          if(!rc) rc = fsl_b_compress(&delta, zipped);
          if(!rc) rc = fsl_stmt_bind_blob(&ins, 6, zipped->mem,
                                          zipped->used, false);
        }
        break;
    }
    if(!rc) rc = fsl_stmt_bind_text(&ins, 1, zName, -1, false);
    if(!rc) rc = fsl_stmt_bind_text(&ins, 2,
                                    fsl_stmt_g_text(&q, 2, NULL), -1, false);
    if(!rc) rc = fsl_stmt_bind_text(&ins, 3,
                                    fsl_stmt_g_text(&q, 3, NULL), -1, false);
    if(!rc) rc = fsl_stmt_bind_int32(&ins, 4, isExe);
    if(!rc) rc = fsl_stmt_bind_int32(&ins, 5, isLink);
    if(!rc) rc = fsl_stmt_step(&ins)==FSL_RC_STEP_DONE
      ? 0 : fsl_cx_uplift_db_error2(f, pdb, FSL_RC_DB);
    fsl_stmt_reset(&ins);
  }
  end:
  fsl_stmt_finalize(&q);
  fsl_stmt_finalize(&ins);
  fsl_b_clear(&orig);
  fsl_b_clear(&delta);
  fsl_cx_b_return(f, disk);
  fsl_cx_b_return(f, absPath);
  fsl_cx_b_return(f, zipped);
  return rc;
}

/**
   Copies the checkout's pending merges into a patchmerge table in
   pdb, creating that table only if there are any, as fossil(1)'s
   patch_create() does.
*/
static int fsl__patch_create_merges(fsl_cx * const f, fsl_db * const pdb){
  fsl_stmt q = fsl_stmt_empty;
  fsl_stmt ins = fsl_stmt_empty;
  int rc = fsl_cx_prepare(f, &q,
    "SELECT CASE id WHEN 0 THEN 'merge' WHEN -1 THEN 'cherrypick'"
    "  WHEN -2 THEN 'backout' WHEN -4 THEN 'integrate' END, mhash"
    "  FROM {{dbname.ckout}}.vmerge WHERE id IN (0,-1,-2,-4)");
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    if(!ins.stmt){
      rc = fsl_db_exec(pdb, "CREATE TABLE patchmerge(type TEXT,mhash TEXT)");
      if(!rc) rc = fsl_db_prepare(pdb, &ins,
        "INSERT INTO patchmerge(type,mhash) VALUES(?1,?2)");
      if(rc){
        rc = fsl_cx_uplift_db_error2(f, pdb, rc);
        break;
      }
    }
    rc = fsl_stmt_bind_text(&ins, 1, fsl_stmt_g_text(&q, 0, NULL), -1, false);
    if(!rc) rc = fsl_stmt_bind_text(&ins, 2, fsl_stmt_g_text(&q, 1, NULL),
                                    -1, false);
    if(!rc) rc = fsl_stmt_step(&ins)==FSL_RC_STEP_DONE
      ? 0 : fsl_cx_uplift_db_error2(f, pdb, FSL_RC_DB);
    fsl_stmt_reset(&ins);
  }
  fsl_stmt_finalize(&q);
  fsl_stmt_finalize(&ins);
  return rc;
}

/**
   Writes the n bytes at src to opt->filename or opt->out.
*/
static int fsl__patch_write(fsl_cx * const f,
                            fsl_patch_create_opt const * opt,
                            void const * src, fsl_size_t n){
  int rc = 0;
  if(opt->filename){
    FILE * const fp = fsl_fopen(opt->filename, "wb");
    if(!fp){
      return fsl_cx_err_set(f, FSL_RC_IO, "Cannot open for writing: %s",
                            opt->filename);
    }
    if(n!=fwrite(src, 1, (size_t)n, fp)) rc = FSL_RC_IO;
    if(0!=fflush(fp)) rc = FSL_RC_IO;
    fsl_fclose(fp);
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Error writing patch file: %s",
                          opt->filename);
    }
  }else{
    rc = opt->out(opt->outState, src, n);
    if(rc && !f->error.code){
      rc = fsl_cx_err_set(f, rc, "Error %R writing patch.", rc);
    }
  }
  return rc;
}

int fsl_patch_create(fsl_cx * const f, fsl_patch_create_opt const * opt){
  fsl_db pdb = fsl_db_empty;
  bool inTxn = false;
  unsigned char * pData = NULL;
  sqlite3_int64 nData = 0;
  int rc;
  if(!opt->filename && !opt->out){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "A patch needs a file name or an output channel.");
  }
  if(!fsl_needs_ckout(f)) return f->error.code;
  if(opt->filename){
    int const dc = fsl_dir_check(opt->filename);
    if(dc>0){
      return fsl_cx_err_set(f, FSL_RC_TYPE, "Patch file is a directory: %s",
                            opt->filename);
    }else if(dc<0 && !opt->overwrite){
      return fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                            "Patch file already exists: %s", opt->filename);
    }
  }
  rc = fsl_cx_txn_begin(f);
  if(rc) goto end;
  inTxn = true;
  rc = fsl_ckout_changes_scan(f);
  if(rc) goto end;
  rc = fsl_db_open(&pdb, ":memory:", FSL_DB_OPEN_RWC);
  if(!rc) rc = fsl_db_exec_multi(&pdb, "%s", fsl__patch_schema);
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, &pdb, rc);
    goto end;
  }
  rc = fsl__patch_create_cfg(f, &pdb, opt);
  if(!rc) rc = fsl__patch_create_chng(f, &pdb);
  if(!rc) rc = fsl__patch_create_merges(f, &pdb);
  if(rc) goto end;
  /* The checkout db side is done: commit the changes scan. */
  inTxn = false;
  rc = fsl_cx_txn_end(f, false);
  if(rc) goto end;
  pData = sqlite3_serialize(pdb.dbh, "main", &nData, 0);
  if(!pData){
    rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
    goto end;
  }
  rc = fsl__patch_write(f, opt, pData, (fsl_size_t)nData);
  end:
  sqlite3_free(pData);
  fsl_db_close(&pdb);
  if(inTxn) fsl_cx_txn_end(f, true);
  return rc;
}

/**
   Returns true if pdb has a table named zTable with the given
   comma-separated columns.
*/
static bool fsl__patch_has_table(fsl_db * const pdb, char const * zTable,
                                 char const * zCols){
  fsl_stmt q = fsl_stmt_empty;
  bool ok = fsl_db_exists(pdb, "SELECT 1 FROM sqlite_schema"
                          " WHERE type='table' AND name=%Q", zTable);
  if(ok){
    ok = 0==fsl_db_prepare(pdb, &q, "SELECT %s FROM %s LIMIT 0",
                           zCols, zTable);
    fsl_stmt_finalize(&q);
    fsl_db_err_reset(pdb);
  }
  return ok;
}

/**
   Validates p's db as a patch and reads its cfg table into p->info.
   Returns 0 or FSL_RC_SYNTAX, with p->f's error state set, if p is
   not a well-formed patch.
*/
static int fsl__patch_load(fsl_patch * const p, char const * zLabel){
  fsl_cx * const f = p->f;
  fsl_stmt q = fsl_stmt_empty;
  int rc = fsl_db_prepare(&p->db, &q, "PRAGMA quick_check");
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    if(0!=fsl_strcmp("ok", fsl_stmt_g_text(&q, 0, NULL))){
      rc = FSL_RC_SYNTAX;
    }
  }
  fsl_stmt_finalize(&q);
  if(rc
     || !fsl__patch_has_table(&p->db, "chng",
                              "pathname,origname,hash,isexe,islink,delta")
     || !fsl__patch_has_table(&p->db, "cfg", "key,value")){
    fsl_db_err_reset(&p->db);
    return fsl_cx_err_set(f, FSL_RC_SYNTAX,
                          "Not a well-formed fossil patch: %s", zLabel);
  }
  p->hasMerges = fsl__patch_has_table(&p->db, "patchmerge", "type,mhash");
  rc = fsl_db_prepare(&p->db, &q, "SELECT key, value FROM cfg");
  if(rc) return fsl_cx_uplift_db_error2(f, &p->db, rc);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    char const * const zKey = fsl_stmt_g_text(&q, 0, NULL);
    if(0==fsl_strcmp("date", zKey)){
      p->info.date = fsl_stmt_g_double(&q, 1);
      continue;
    }
    for(int i = 0; i < FSL__PATCH_STR_COUNT; ++i){
      if(0==fsl_strcmp(fsl__patch_cfg_keys[i], zKey)){
        char const * const zVal = fsl_stmt_g_text(&q, 1, NULL);
        fsl_free(p->aStr[i]);
        p->aStr[i] = zVal ? fsl_strdup(zVal) : NULL;
        if(zVal && !p->aStr[i]) rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
        break;
      }
    }
  }
  fsl_stmt_finalize(&q);
  if(rc) return rc;
  p->info.baseline = p->aStr[FSL__PATCH_BASELINE];
  p->info.projectCode = p->aStr[FSL__PATCH_PCODE];
  p->info.projectName = p->aStr[FSL__PATCH_PNAME];
  p->info.user = p->aStr[FSL__PATCH_USER];
  p->info.hostname = p->aStr[FSL__PATCH_HOST];
  p->info.ckoutDir = p->aStr[FSL__PATCH_CKOUT];
  p->info.repoDb = p->aStr[FSL__PATCH_REPO];
  return 0;
}

/**
   The guts of fsl_patch_open_mem(). zLabel names the patch in error
   messages.
*/
static int fsl__patch_open(fsl_cx * const f, void const * src,
                           fsl_size_t n, char const * zLabel,
                           fsl_patch ** pOut){
  fsl_patch * p = NULL;
  unsigned char * pCopy = NULL;
  int rc;
  if(n<512){
    /* The smallest page size, so the smallest possible db. */
    return fsl_cx_err_set(f, FSL_RC_SYNTAX,
                          "Too small to be a fossil patch: %s", zLabel);
  }
  p = fsl_malloc(sizeof(fsl_patch));
  if(!p) return fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  *p = fsl__patch_empty;
  p->f = f;
  rc = fsl_db_open(&p->db, ":memory:", FSL_DB_OPEN_RWC);
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, &p->db, rc);
    goto end;
  }
  /* A patch is untrusted input: forbid writes to its schema and the
     use of functions with side effects from its views or triggers. */
  sqlite3_db_config(p->db.dbh, SQLITE_DBCONFIG_DEFENSIVE, 1, NULL);
  sqlite3_db_config(p->db.dbh, SQLITE_DBCONFIG_TRUSTED_SCHEMA, 0, NULL);
  pCopy = sqlite3_malloc64((sqlite3_uint64)n);
  if(!pCopy){
    rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
    goto end;
  }
  memcpy(pCopy, src, (size_t)n);
  /* sqlite3_deserialize() takes ownership of pCopy, even on error. */
  if(SQLITE_OK!=sqlite3_deserialize(p->db.dbh, "main", pCopy,
                                    (sqlite3_int64)n, (sqlite3_int64)n,
                                    SQLITE_DESERIALIZE_FREEONCLOSE
                                    | SQLITE_DESERIALIZE_READONLY)){
    rc = fsl_cx_err_set(f, FSL_RC_SYNTAX, "Cannot open patch %s: %s",
                        zLabel, sqlite3_errmsg(p->db.dbh));
    goto end;
  }
  rc = fsl__patch_load(p, zLabel);
  end:
  if(rc){
    fsl_patch_close(p);
  }else{
    *pOut = p;
  }
  return rc;
}

int fsl_patch_open_mem(fsl_cx * const f, void const * src,
                       fsl_size_t n, fsl_patch ** pOut){
  return fsl__patch_open(f, src, n, "<memory>", pOut);
}

int fsl_patch_open_file(fsl_cx * const f, char const * zFile,
                        fsl_patch ** pOut){
  fsl_b content = fsl_b_empty;
  int rc;
  if(!fsl_is_file(zFile)){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "No such file: %s", zFile);
  }
  /* The file is read into memory, rather than opened as a db, so that
     SQLite never writes beside it or holds it open. */
  rc = fsl_b_fill_from_filename(&content, zFile);
  if(rc){
    rc = fsl_cx_err_set(f, rc, "Error %R reading patch file: %s", rc, zFile);
  }else{
    rc = fsl__patch_open(f, content.mem, content.used, zFile, pOut);
  }
  fsl_b_clear(&content);
  return rc;
}

void fsl_patch_close(fsl_patch * p){
  if(p){
    fsl_db_close(&p->db);
    for(int i = 0; i < FSL__PATCH_STR_COUNT; ++i) fsl_free(p->aStr[i]);
    *p = fsl__patch_empty;
    fsl_free(p);
  }
}

fsl_patch_info const * fsl_patch_info_get(fsl_patch const * p){
  return &p->info;
}

int fsl_patch_each(fsl_patch * const p, fsl_patch_each_f cb, void * state){
  fsl_cx * const f = p->f;
  fsl_stmt q = fsl_stmt_empty;
  /* Classified as fossil(1)'s patch_view() does. An empty origname is
     treated as no rename, as patch_view() does. */
  int rc = fsl_db_prepare(&p->db, &q,
    "SELECT pathname, nullif(nullif(origname,''),pathname), hash,"
    "       isexe, islink, delta IS NULL, length(delta)>0"
    "  FROM chng ORDER BY pathname");
  if(rc) return fsl_cx_uplift_db_error2(f, &p->db, rc);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    fsl_patch_entry e = {NULL, NULL, NULL, false, false, false, false, false};
    e.name = fsl_stmt_g_text(&q, 0, NULL);
    if(!e.name || !*e.name){
      rc = fsl_cx_err_set(f, FSL_RC_SYNTAX,
                          "Patch has a file entry with no name.");
      break;
    }
    e.origName = fsl_stmt_g_text(&q, 1, NULL);
    e.baselineHash = fsl_stmt_g_text(&q, 2, NULL);
    e.isExe = !!fsl_stmt_g_int32(&q, 3);
    e.isLink = !!fsl_stmt_g_int32(&q, 4);
    e.isDeleted = !!fsl_stmt_g_int32(&q, 5);
    e.isNew = !e.baselineHash && !e.isDeleted;
    e.isModified = !e.isNew && !e.isDeleted && !!fsl_stmt_g_int32(&q, 6);
    rc = cb(&e, state);
  }
  fsl_stmt_finalize(&q);
  return FSL_RC_BREAK==rc ? 0 : rc;
}

int fsl_patch_each_merge(fsl_patch * const p, fsl_patch_merge_f cb,
                         void * state){
  fsl_cx * const f = p->f;
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  if(!p->hasMerges) return 0;
  /* The same filter as in fossil(1)'s patch_apply(). */
  rc = fsl_db_prepare(&p->db, &q,
    "SELECT CASE type WHEN 'merge' THEN %d WHEN 'cherrypick' THEN %d"
    "  WHEN 'backout' THEN %d WHEN 'integrate' THEN %d END, mhash"
    "  FROM patchmerge"
    " WHERE type IN ('merge','cherrypick','backout','integrate')"
    "   AND length(mhash)>0 AND mhash NOT GLOB '*[^a-fA-F0-9]*'"
    " ORDER BY rowid",
    (int)FSL_MERGE_TYPE_NORMAL, (int)FSL_MERGE_TYPE_CHERRYPICK,
    (int)FSL_MERGE_TYPE_BACKOUT, (int)FSL_MERGE_TYPE_INTEGRATE);
  if(rc) return fsl_cx_uplift_db_error2(f, &p->db, rc);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    rc = cb((fsl_merge_type_e)fsl_stmt_g_int32(&q, 0),
            fsl_stmt_g_text(&q, 1, NULL), state);
  }
  fsl_stmt_finalize(&q);
  return FSL_RC_BREAK==rc ? 0 : rc;
}

/**
   Returns 0 if zName is safe to use as a checkout-relative file name
   from a patch, else sets f's error state and returns FSL_RC_RANGE.
*/
static int fsl__patch_name_check(fsl_cx * const f, char const * zName){
  if(!zName || !*zName || !fsl_is_simple_pathname(zName, true)){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Patch has an unsafe file name: %s",
                          zName ? zName : "<NULL>");
  }else if(fsl_is_reserved_fn(zName, -1)){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Patch has a reserved file name: %s", zName);
  }
  return 0;
}

/**
   Resolves zHash, which must be a full artifact hash, to its RID in
   f's repository. zWhat describes the artifact in error messages.
*/
static int fsl__patch_rid(fsl_cx * const f, char const * zHash,
                          char const * zWhat, fsl_id_t * const rid){
  if(!zHash || !fsl_is_uuid(zHash)){
    return fsl_cx_err_set(f, FSL_RC_SYNTAX, "Patch has a malformed "
                          "hash for %s: %s", zWhat, zHash ? zHash : "<NULL>");
  }
  *rid = fsl_uuid_to_rid(f, zHash);
  if(*rid<=0){
    return f->error.code ? f->error.code
      : fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "The %s (%.16s) is not in "
                       "this repository. It may need to be synced first.",
                       zWhat, zHash);
  }
  return 0;
}

/**
   Checks everything in p which can be checked before the checkout is
   changed: file names, the project code, and that the baseline and
   every file's baseline version are in the repository. Writes the
   baseline's RID to *baseRid.
*/
static int fsl__patch_apply_check(fsl_cx * const f, fsl_patch * const p,
                                  fsl_id_t * const baseRid){
  fsl_stmt q = fsl_stmt_empty;
  char * zPCode = NULL;
  int rc = 0;
  if(p->info.projectCode){
    zPCode = fsl_config_get_text(f, FSL_CONFDB_REPO, "project-code", NULL);
    if(zPCode && fsl_strcmp(zPCode, p->info.projectCode)){
      rc = fsl_cx_err_set(f, FSL_RC_REPO_MISMATCH, "The patch is for a "
                          "different project (project code %.16s).",
                          p->info.projectCode);
    }
    fsl_free(zPCode);
    if(rc) return rc;
  }
  rc = fsl__patch_rid(f, p->info.baseline, "patch's baseline", baseRid);
  if(rc) return rc;
  rc = fsl_db_prepare(&p->db, &q, "SELECT pathname, origname, hash"
                      " FROM chng");
  if(rc) return fsl_cx_uplift_db_error2(f, &p->db, rc);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    char const * const zName = fsl_stmt_g_text(&q, 0, NULL);
    char const * const zOrig = fsl_stmt_g_text(&q, 1, NULL);
    char const * const zHash = fsl_stmt_g_text(&q, 2, NULL);
    fsl_id_t rid = 0;
    rc = fsl__patch_name_check(f, zName);
    if(!rc && zOrig) rc = fsl__patch_name_check(f, zOrig);
    if(!rc && zHash) rc = fsl__patch_rid(f, zHash, "baseline version "
                                         "of a patched file", &rid);
  }
  fsl_stmt_finalize(&q);
  return rc;
}

/** State for fsl__patch_revert_f(). */
struct fsl__patch_revert_state {
  fsl_patch_apply_opt const * opt;
  fsl_patch_apply_e step;
};

/** fsl_ckout_revert_f() which reports each reverted file to the
    fsl_patch_apply() callback. */
static int fsl__patch_revert_f(char const *zFilename,
                               fsl_ckout_revert_e changeType,
                               void * state){
  struct fsl__patch_revert_state const * const st = state;
  (void)changeType;
  return st->opt->callback
    ? st->opt->callback(st->step, zFilename, NULL,
                        st->opt->callbackState)
    : 0;
}

/** Calls opt->callback, if set. */
static int fsl__patch_report(fsl_patch_apply_opt const * opt,
                             fsl_patch_apply_e step, char const * zName,
                             char const * zOrigName){
  return opt->callback
    ? opt->callback(step, zName, zOrigName, opt->callbackState)
    : 0;
}

/**
   Reverts every change in the checkout, for fsl_patch_apply_opt::force,
   or in a dry run reports what would be reverted.
*/
static int fsl__patch_apply_revert(fsl_cx * const f,
                                   fsl_patch_apply_opt const * opt){
  struct fsl__patch_revert_state st = {opt, FSL_PATCH_APPLY_REVERT};
  fsl_ckout_revert_opt ropt = fsl_ckout_revert_opt_empty;
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  if(!opt->dryRun){
    ropt.scanForChanges = false;
    ropt.callback = fsl__patch_revert_f;
    ropt.callbackState = &st;
    return fsl_ckout_revert(f, &ropt);
  }
  rc = fsl_cx_prepare(f, &q,
    "SELECT pathname FROM {{dbname.ckout}}.vfile"
    " WHERE vid=%" FSL_ID_T_PFMT
    " AND (chnged OR deleted OR rid=0 OR coalesce(origname<>pathname,0))"
    " ORDER BY pathname", f->db.ckout.rid);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    rc = fsl__patch_report(opt, FSL_PATCH_APPLY_REVERT,
                           fsl_stmt_g_text(&q, 0, NULL), NULL);
  }
  fsl_stmt_finalize(&q);
  return rc;
}

/** State for fsl__patch_merge_f(). */
struct fsl__patch_merge_state {
  fsl_cx * f;
  fsl_patch_apply_opt const * opt;
  unsigned nMerge;
};

/** fsl_patch_merge_f() which re-does one of a patch's merges. */
static int fsl__patch_merge_f(fsl_merge_type_e type, char const * zHash,
                              void * state){
  struct fsl__patch_merge_state * const st = state;
  fsl_merge_opt mopt = fsl_merge_opt_empty;
  int rc = fsl__patch_rid(st->f, zHash, "merged version",
                          &mopt.mergeRid);
  if(rc) return rc;
  ++st->nMerge;
  if(!st->opt->dryRun){
    mopt.mergeType = type;
    rc = fsl_ckout_merge(st->f, &mopt);
  }
  return rc ? rc
    : fsl__patch_report(st->opt, FSL_PATCH_APPLY_MERGE, zHash, NULL);
}

/**
   After the merges are re-done, reverts each file which they changed
   but which p does not mention, as fossil(1)'s patch_apply() does
   since 2024-12-16 (https://fossil-scm.org/forum/forumpost/51a37054):
   such changes were not in the checkout the patch was made from.
*/
static int fsl__patch_apply_unmerge(fsl_cx * const f, fsl_patch * const p,
                                    fsl_patch_apply_opt const * opt){
  struct fsl__patch_revert_state st = {opt, FSL_PATCH_APPLY_UNMERGE};
  fsl_id_bag ids = fsl_id_bag_empty;
  fsl_stmt q = fsl_stmt_empty;
  int rc = fsl_cx_prepare(f, &q,
    "SELECT id, pathname FROM {{dbname.ckout}}.vfile"
    " WHERE vid=%" FSL_ID_T_PFMT " AND chnged", f->db.ckout.rid);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    if(!fsl_db_exists(&p->db, "SELECT 1 FROM chng WHERE pathname=%Q",
                      fsl_stmt_g_text(&q, 1, NULL))){
      rc = fsl_id_bag_insert(&ids, fsl_stmt_g_id(&q, 0));
    }
  }
  fsl_stmt_finalize(&q);
  if(!rc && fsl_id_bag_count(&ids)){
    fsl_ckout_revert_opt ropt = fsl_ckout_revert_opt_empty;
    ropt.vfileIds = &ids;
    ropt.scanForChanges = false;
    ropt.callback = fsl__patch_revert_f;
    ropt.callbackState = &st;
    rc = fsl_ckout_revert(f, &ropt);
  }
  fsl_id_bag_clear(&ids);
  return rc;
}

/**
   Checks, with fsl__ckout_safe_file_check(), every path which the
   rest of fsl_patch_apply() will write, remove or rename, so that a
   path through a symlink or a non-directory fails the apply before
   any file is touched. It has to wait until the update and merges are
   done, as they can change what is on disk. The paths are checked
   again as they are used.
*/
static int fsl__patch_apply_safe(fsl_cx * const f, fsl_patch * const p){
  fsl_stmt q = fsl_stmt_empty;
  fsl_b * const absPath = fsl_cx_b_borrow(f);
  int rc;
  if(!absPath) return f->error.code;
  rc = fsl_db_prepare(&p->db, &q, "SELECT pathname FROM chng UNION"
                      " SELECT origname FROM chng WHERE origname IS NOT NULL");
  if(rc) rc = fsl_cx_uplift_db_error2(f, &p->db, rc);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    fsl_b_reuse(absPath);
    rc = fsl_b_appendf(absPath, "%s%s", f->db.ckout.dir,
                       fsl_stmt_g_text(&q, 0, NULL));
    if(!rc) rc = fsl__ckout_safe_file_check(f, fsl_b_cstr(absPath));
  }
  fsl_stmt_finalize(&q);
  fsl_cx_b_return(f, absPath);
  return rc;
}

/**
   Removes the patch's removed files from the checkout and the disk,
   as fossil(1)'s patch_apply() does with (fossil rm --hard).
*/
static int fsl__patch_apply_deletes(fsl_cx * const f, fsl_patch * const p,
                                    fsl_patch_apply_opt const * opt){
  fsl_stmt q = fsl_stmt_empty;
  fsl_b * const absPath = fsl_cx_b_borrow(f);
  int rc;
  if(!absPath) return f->error.code;
  rc = fsl_db_prepare(&p->db, &q, "SELECT pathname FROM chng"
                      " WHERE origname IS NULL AND delta IS NULL"
                      " ORDER BY pathname");
  if(rc) rc = fsl_cx_uplift_db_error2(f, &p->db, rc);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    char const * const zName = fsl_stmt_g_text(&q, 0, NULL);
    if(!opt->dryRun){
      fsl_ckout_unmanage_opt uopt = fsl_ckout_unmanage_opt_empty;
      fsl_b_reuse(absPath);
      rc = fsl_b_appendf(absPath, "%s%s", f->db.ckout.dir, zName);
      if(!rc) rc = fsl__ckout_safe_file_check(f, fsl_b_cstr(absPath));
      if(rc) break;
      uopt.filename = zName;
      uopt.relativeToCwd = false;
      uopt.scanForChanges = false;
      rc = fsl_ckout_unmanage(f, &uopt);
      if(!rc && fsl__cfs_is_file_or_link(f, fsl_b_cstr(absPath))){
        rc = fsl__cfs_unlink(f, fsl_b_cstr(absPath));
        if(rc) rc = fsl_cx_err_set(f, rc, "Error %R removing file: %b",
                                   rc, absPath);
      }
    }
    if(!rc) rc = fsl__patch_report(opt, FSL_PATCH_APPLY_DELETE, zName, NULL);
  }
  fsl_stmt_finalize(&q);
  fsl_cx_b_return(f, absPath);
  return rc;
}

/**
   Renames the patch's renamed files in the checkout and on disk, as
   fossil(1)'s patch_apply() does with (fossil mv --hard).
*/
static int fsl__patch_apply_renames(fsl_cx * const f, fsl_patch * const p,
                                    fsl_patch_apply_opt const * opt){
  fsl_stmt q = fsl_stmt_empty;
  int rc = fsl_db_prepare(&p->db, &q, "SELECT origname, pathname FROM chng"
                          " WHERE origname IS NOT NULL"
                          " AND origname<>pathname ORDER BY pathname");
  if(rc) rc = fsl_cx_uplift_db_error2(f, &p->db, rc);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    char const * const zOrig = fsl_stmt_g_text(&q, 0, NULL);
    char const * const zName = fsl_stmt_g_text(&q, 1, NULL);
    if(!opt->dryRun){
      fsl_ckout_rename_opt ropt = fsl_ckout_rename_opt_empty;
      fsl_list src = fsl_list_empty;
      rc = fsl_list_append(&src, (void*)zOrig);
      if(rc){
        rc = fsl_cx_err_set(f, rc, NULL);
        break;
      }
      ropt.src = &src;
      ropt.dest = zName;
      ropt.relativeToCwd = false;
      ropt.doFsMv = true;
      rc = fsl_ckout_rename(f, &ropt);
      fsl_list_reserve(&src, 0);
    }
    if(!rc) rc = fsl__patch_report(opt, FSL_PATCH_APPLY_RENAME, zName,
                                   zOrig);
  }
  fsl_stmt_finalize(&q);
  return rc;
}

/**
   Uncompresses column iCol of q, a patch's chng.delta, into tgt.
   A zero-length blob is left as an empty tgt.
*/
static int fsl__patch_blob(fsl_cx * const f, fsl_stmt * const q, int iCol,
                           char const * zName, fsl_b * const tgt){
  void const * pMem = NULL;
  fsl_size_t n = 0;
  int rc;
  fsl_b_reuse(tgt);
  rc = fsl_stmt_get_blob(q, iCol, &pMem, &n);
  if(rc) return fsl_cx_uplift_db_error2(f, q->db, rc);
  if(0==n) return 0;
  if(!fsl_data_is_compressed((unsigned char const *)pMem, n)){
    return fsl_cx_err_set(f, FSL_RC_SYNTAX, "Patch data for %s is not "
                          "compressed.", zName);
  }else{
    fsl_b in = fsl_b_empty;
    fsl_b_external(&in, pMem, (fsl_int_t)n);
    rc = fsl_b_uncompress(&in, tgt);
    return rc ? fsl_cx_err_set(f, rc, "Error %R uncompressing patch data "
                               "for %s.", rc, zName) : 0;
  }
}

/**
   Writes content to zPath as a regular file, or as a symlink to the
   name in content if isLink is true, and sets its executable bit, as
   fossil(1)'s patch_apply() does. Without the allow-symlinks setting,
   a symlink is written as a regular file containing its target's
   name, as fossil(1) does.
*/
static int fsl__patch_write_file(fsl_cx * const f, char const * zPath,
                                 fsl_b const * content, bool isLink,
                                 bool isExe){
  int rc = fsl__cfs_mkdir_for_file(f, zPath, true);
  if(!rc && (isLink || fsl__cfs_is_symlink(f, zPath))){
    /* Replace, rather than write through, any symlink in the way. */
    fsl__cfs_unlink(f, zPath);
  }
  if(rc){
    /* Reported below. */
  }else if(isLink){
    rc = fsl__cfs_symlink_create(f, fsl_b_cstr(content), zPath,
                                 fsl_cx_allows_symlinks(f, false));
  }else{
    rc = fsl__cfs_write(f, content, zPath);
    if(!rc) rc = fsl__cfs_exec_set(f, zPath, isExe);
  }
  return rc ? fsl_cx_err_set(f, rc, "Error %R writing file: %s",
                             rc, zPath) : 0;
}

/**
   Writes the patch's new and changed files, queueing the new ones for
   adding, as fossil(1)'s patch_apply() does, except that, unlike
   fossil(1), an empty new file is added and a change to only a file's
   permissions is applied.
*/
static int fsl__patch_apply_edits(fsl_cx * const f, fsl_patch * const p,
                                  fsl_patch_apply_opt const * opt){
  fsl_stmt q = fsl_stmt_empty;
  fsl_b data = fsl_b_empty;
  fsl_b base = fsl_b_empty;
  fsl_b content = fsl_b_empty;
  fsl_b * const absPath = fsl_cx_b_borrow(f);
  bool const allowLinks = fsl_cx_allows_symlinks(f, false);
  int rc;
  if(!absPath) return f->error.code;
  rc = fsl_db_prepare(&p->db, &q, "SELECT pathname, hash, isexe, islink,"
                      " delta FROM chng WHERE delta IS NOT NULL"
                      " ORDER BY pathname");
  if(rc) rc = fsl_cx_uplift_db_error2(f, &p->db, rc);
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    char const * const zName = fsl_stmt_g_text(&q, 0, NULL);
    char const * const zHash = fsl_stmt_g_text(&q, 1, NULL);
    bool const isExe = !!fsl_stmt_g_int32(&q, 2);
    bool const isLink = !!fsl_stmt_g_int32(&q, 3);
    fsl_patch_apply_e step = zHash
      ? FSL_PATCH_APPLY_EDIT : FSL_PATCH_APPLY_NEW;
    fsl_b_reuse(absPath);
    rc = fsl_b_appendf(absPath, "%s%s", f->db.ckout.dir, zName);
    if(!rc) rc = fsl__patch_blob(f, &q, 4, zName, &data);
    if(rc) break;
    char const * const zPath = fsl_b_cstr(absPath);
    if(zHash){
      fsl_id_t rid = 0;
      rc = fsl__patch_rid(f, zHash, "baseline version of a patched file",
                          &rid);
      if(!rc) rc = fsl_content_get(f, rid, &base);
      if(rc) break;
      if(data.used){
        fsl_error err = fsl_error_empty;
        rc = fsl_b_delta_apply2(&base, &data, &content, &err);
        if(rc){
          rc = fsl_cx_err_set(f, rc, "Error %R applying the patch's delta "
                              "for %s: %b", rc, zName, &err.msg);
        }
        fsl_error_clear(&err);
        if(rc) break;
      }else{
        /* Unchanged content: a rename, which has already happened, or
           a change of permissions, which fossil(1) does not apply. */
        bool const diskLink = fsl__cfs_is_symlink(f, zPath);
        if(diskLink==(isLink && allowLinks)
           && (diskLink || isExe==fsl__cfs_isexec(f, zPath))){
          continue;
        }
        fsl_b_swap(&base, &content);
      }
    }else{
      fsl_b_swap(&data, &content);
    }
    if(!opt->dryRun){
      rc = fsl__ckout_safe_file_check(f, zPath);
      if(!rc) rc = fsl__patch_write_file(f, zPath, &content, isLink, isExe);
      if(!rc && !zHash){
        fsl_ckout_manage_opt mopt = fsl_ckout_manage_opt_empty;
        mopt.filename = zName;
        mopt.relativeToCwd = false;
        mopt.checkIgnoreGlobs = false;
        rc = fsl_ckout_manage(f, &mopt);
      }
      if(!rc){
        /* Make the next changes scan look at the file: one written in
           the same second as its recorded mtime would otherwise look
           unchanged, as in fsl_stash_apply(). */
        rc = fsl_cx_exec(f, "UPDATE {{dbname.ckout}}.vfile SET mtime=0"
                         " WHERE vid=%" FSL_ID_T_PFMT " AND pathname=%Q %s",
                         f->db.ckout.rid, zName,
                         fsl_cx_filename_collation(f));
      }
    }
    if(!rc) rc = fsl__patch_report(opt, step, zName, NULL);
  }
  fsl_stmt_finalize(&q);
  fsl_b_clear(&data);
  fsl_b_clear(&base);
  fsl_b_clear(&content);
  fsl_cx_b_return(f, absPath);
  return rc;
}

int fsl_patch_apply(fsl_cx * const f, fsl_patch * const p,
                    fsl_patch_apply_opt const * opt){
  fsl_id_t baseRid = 0;
  struct fsl__patch_merge_state mst = {f, opt, 0};
  int rc;
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  rc = fsl__patch_apply_check(f, p, &baseRid);
  if(rc) return rc;
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) return rc;
  rc = fsl_ckout_changes_scan(f);
  if(!rc && fsl_ckout_has_changes(f)){
    rc = opt->force
      ? fsl__patch_apply_revert(f, opt)
      : fsl_cx_err_set(f, FSL_RC_CONFLICT, "Cannot apply the patch: the "
                       "checkout has uncommitted changes.");
  }
  if(!rc && f->db.ckout.rid!=baseRid){
    /* Unlike fossil(1), which always runs the update, this only does
       so if the checkout is not at the baseline. */
    if(!opt->dryRun){
      fsl_ckup_opt uopt = fsl_ckup_opt_empty;
      uopt.checkinRid = baseRid;
      uopt.scanForChanges = true;
      rc = fsl_ckout_update(f, &uopt);
    }
    if(!rc) rc = fsl__patch_report(opt, FSL_PATCH_APPLY_BASELINE,
                                   p->info.baseline, NULL);
  }
  if(!rc) rc = fsl_patch_each_merge(p, fsl__patch_merge_f, &mst);
  if(!rc && mst.nMerge && !opt->dryRun){
    rc = fsl__patch_apply_unmerge(f, p, opt);
  }
  if(!rc) rc = fsl__patch_apply_safe(f, p);
  if(!rc) rc = fsl__patch_apply_deletes(f, p, opt);
  if(!rc) rc = fsl__patch_apply_renames(f, p, opt);
  if(!rc) rc = fsl__patch_apply_edits(f, p, opt);
  {
    int const rc2 = fsl_cx_txn_end(f, !!rc || opt->dryRun);
    if(!rc) rc = rc2;
  }
  return rc;
}

/**
   Writes to tgt the content of zName in check-in baseRid, for a file
   which a patch removes: fossil(1)'s patches record no hash for
   those.
*/
static int fsl__patch_removed_base(fsl_cx * const f, fsl_id_t baseRid,
                                   char const * zName, fsl_b * const tgt){
  fsl_deck d = fsl_deck_empty;
  fsl_card_F const * fc = NULL;
  fsl_id_t rid = 0;
  int rc = fsl_deck_load_rid(f, &d, baseRid, FSL_SATYPE_CHECKIN);
  if(!rc) rc = fsl_deck_F_search2(&d, zName, &fc);
  if(!rc && (!fc || !fc->uuid)){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "The patch removes %s, "
                        "which is not in its baseline.", zName);
  }
  if(!rc) rc = fsl__patch_rid(f, fc->uuid, "baseline version of a "
                              "removed file", &rid);
  if(!rc) rc = fsl_content_get(f, rid, tgt);
  fsl_deck_finalize(&d);
  return rc;
}

int fsl_patch_content(fsl_patch * const p, char const * zName,
                      fsl_b * const tgt, fsl_b * const baseline){
  fsl_cx * const f = p->f;
  fsl_stmt q = fsl_stmt_empty;
  fsl_b base = fsl_b_empty;
  fsl_b data = fsl_b_empty;
  int rc;
  if(!fsl_needs_repo(f)) return f->error.code;
  if(tgt) fsl_b_reuse(tgt);
  if(baseline) fsl_b_reuse(baseline);
  rc = fsl_db_prepare(&p->db, &q, "SELECT hash, delta IS NULL, delta"
                      " FROM chng WHERE pathname=%Q", zName);
  if(rc) return fsl_cx_uplift_db_error2(f, &p->db, rc);
  rc = fsl_stmt_step(&q);
  if(FSL_RC_STEP_ROW!=rc){
    rc = FSL_RC_STEP_DONE==rc
      ? fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "The patch has no file "
                       "named %s.", zName)
      : fsl_cx_uplift_db_error2(f, &p->db, rc);
    goto end;
  }
  rc = 0;
  {
    char const * const zHash = fsl_stmt_g_text(&q, 0, NULL);
    bool const isDeleted = !!fsl_stmt_g_int32(&q, 1);
    if(zHash){
      fsl_id_t rid = 0;
      rc = fsl__patch_rid(f, zHash, "baseline version of a patched file",
                          &rid);
      if(!rc) rc = fsl_content_get(f, rid, &base);
    }else if(isDeleted && baseline){
      fsl_id_t baseRid = 0;
      rc = fsl__patch_rid(f, p->info.baseline, "patch's baseline", &baseRid);
      if(!rc) rc = fsl__patch_removed_base(f, baseRid, zName, &base);
    }
    if(!rc && !isDeleted) rc = fsl__patch_blob(f, &q, 2, zName, &data);
    if(rc) goto end;
    if(tgt && !isDeleted){
      if(!zHash){
        fsl_b_swap(&data, tgt);
      }else if(data.used){
        fsl_error err = fsl_error_empty;
        rc = fsl_b_delta_apply2(&base, &data, tgt, &err);
        if(rc){
          rc = fsl_cx_err_set(f, rc, "Error %R applying the patch's delta "
                              "for %s: %b", rc, zName, &err.msg);
        }
        fsl_error_clear(&err);
      }else{
        rc = fsl_b_copy(tgt, &base);
      }
    }
    if(!rc && baseline) fsl_b_swap(&base, baseline);
  }
  end:
  fsl_stmt_finalize(&q);
  fsl_b_clear(&base);
  fsl_b_clear(&data);
  return rc;
}
/* end of file src/patch.c */
/* start of file src/cli.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
#include <errno.h>
#include <math.h>
#include <string.h> /* for strchr() */
#if !defined(FSL_AMALGAMATION_BUILD)
/* When not in the amalgamation build, force assert() to always work... */
#  if defined(NDEBUG)
#    undef NDEBUG
#    undef DEBUG
#    define DEBUG 1
#  endif
#endif
#include <assert.h> /* for the benefit of test apps */

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


/** Convenience form of FCLI_VN for level-3 verbosity. */
#define FCLI_V3(pfexp) FCLI_VN(3,pfexp)

static struct {
  /**
     Info needed for decrypting SEE-encrypted repositories.
  */
  struct {
    /**
       Key passed to the --see-key CLI flag.
    */
    const char * key;
    /** Key len. */
    unsigned int nKey;
    /**
       Key type. Derived from --see-key's value.
    */
    enum fsl_see_keytype_e type;
  } see;
} fcliPrivate = {
  .see = { .key = NULL, .nKey = 0, .type = FSL_SEE_KEYTYPE_PLAIN }
};

#define FCLI__REPORT_SYNC_METRICS 0 /* default for --sync-metrics */
#define fcli_empty_m {  \
  .f = NULL,            \
  .argv = NULL,         \
  .argc = 0,            \
  .appName = NULL,      \
  .config = {           \
    .appHelp = NULL,      \
    .cliFlags = NULL,     \
    .checkoutDir = ".",      \
    .verbose = 0,                    \
    .traceSql = -1,                  \
    .outputer = fsl_outputer_empty_m,  \
    .listener = {.callback=fsl_msg_f_fcli, .state=0}  \
  },                         \
  .globalFlags = {             \
    .repoDbArg = NULL,         \
    .userArg = NULL,         \
    .helpRequested = 0,       \
    .versionRequested = false, \
    .reportSyncMetrics = FCLI__REPORT_SYNC_METRICS, \
    .reportCacheMetrics = false,                    \
    .libEvents = true \
  },                                         \
  .err = fsl_error_empty_m                   \
}

const fcli_t fcli_empty = fcli_empty_m;
fcli_t fcli = fcli_empty_m;
const fcli_cliflag fcli_cliflag_empty = fcli_cliflag_empty_m;
static fsl_timer fcliTimer = fsl_timer_empty_m;

/**
   fcli global private state. Platforms which do not allow writable
   static structs simply won't work here.
*/
static struct {
  bool isSyncing;
  char const * flagPW /* --pw/--sync-password */;
  char const * flagPWFile /* --pwf/--sync-password-file */;
} FcliGPS = {
  .isSyncing = false,
  .flagPW = 0,
  .flagPWFile = 0
};

void fcli_printf(char const * fmt, ...){
  va_list args;
  va_start(args,fmt);
  if(fcli.f){
    fsl_outputfv(fcli.f, fmt, args);
  }else{
    fsl_fprintfv(stdout, fmt, args);
  }
  va_end(args);
}

/**
   Outputs app-level help. How it does this depends on the state of
   the fcli object, namely fcli.config.cliFlags and the verbosity
   level. Normally this is triggered automatically by the CLI flag
   handling in fcli_setup().
*/
static void fcli_help(void);

unsigned short fcli_is_verbose(void){
  return fcli.config.verbose;
}

fsl_cx * fcli_cx(void){
  return fcli.f;
}

static int fcli_open(void){
  int rc = 0;
  fsl_cx * f = fcli.f;
  assert(f);
  if(fcli.globalFlags.repoDbArg){
    FCLI_V3(("Trying to open repo db file [%s]...\n", fcli.globalFlags.repoDbArg));
    rc = fsl_repo_open( f, fcli.globalFlags.repoDbArg );
  }
  else if(fcli.config.checkoutDir){
    char const * dirName = fcli.config.checkoutDir;
    FCLI_V3(("Trying to open checkout from [%s]...\n",
             dirName));
    rc = fsl_ckout_open_dir(f, dirName, true);
    FCLI_V3(("checkout open rc=%s\n", fsl_rc_cstr(rc)));

    /* if(FSL_RC_NOT_FOUND==rc) rc = FSL_RC_NOT_A_CKOUT; */
    if(rc){
      if(!fsl_cx_err_get(f,NULL,NULL)){
        rc = fsl_cx_err_set(f, rc, "Opening of checkout under "
                            "[%s] failed with code %d (%s).",
                            dirName, rc, fsl_rc_cstr(rc));
      }
    }
    if(rc) return rc;
  }
  if(!rc){
    if(fcli.config.verbose>1){
      fsl_db * dbC = fsl_cx_db_ckout(f);
      fsl_db * dbR = fsl_cx_db_repo(f);
      if(dbC){
        FCLI_V3(("Checkout DB name: %s\n", f->db.ckout.db.filename));
      }
      if(dbR){
        FCLI_V3(("Opened repo db: %s\n", f->db.repo.db.filename));
        FCLI_V3(("Repo user name: %s\n", f->db.repo.user));
      }
    }
#if 0
    /*
      Only(?) here for testing purposes.

       We don't really need/want to update the repo db on each
       open of the checkout db, do we? Or do we?
     */
    fsl__repo_record_filename(f) /* ignore rc - not critical */;
#endif
  }
  return rc;
}


#define fcli__error (fcli.f ? &fcli.f->error : &fcli.err)
fsl_error * fcli_error(void){
  return fcli__error;
}

void fcli_err_reset(void){
  fsl_error_reset(fcli__error);
}


static struct TempFlags {
  bool traceSql;
  bool doTimer;
  int isTty;
} TempFlags = {
  .traceSql = false,
  .doTimer = false,
  .isTty   = -1 /* <0 = undetermined */
};

static struct {
  fsl_list list;
}  FCliFree = {
fsl_list_empty_m
};

static void fcli_shutdown(void){
  fsl_cx * const f = fcli.f;
  int rc = 0;

  fsl_error_clear(&fcli.err);
  fsl_free(fcli.argv)/*contents are in the FCliFree list*/;

  if(f){
    while(fsl_cx_txn_level(f)){
      MARKER(("WARNING: open db transaction at shutdown-time. "
              "Rolling back.\n"));
      fsl_cx_txn_end(f, true);
    }
    if(1 &&
       fsl_cx_db_ckout(f)){
      /* For testing/demo only: this is implicit
         when we call fsl_cx_finalize().
      */
      rc = fsl_close_scm_dbs(f);
      FCLI_V3(("Closed checkout/repo db(s). rc=%s\n", fsl_rc_cstr(rc)));
      //assert(0==rc);
    }
  }
  fsl_list_visit_free(&FCliFree.list, true);
  if(f){
    FCLI_V3(("Finalizing fsl_cx @%p\n", (void const *)f));
    fsl_cx_finalize( f );
  }
  fcli = fcli_empty;
  if(TempFlags.doTimer){
    fsl_timer_stop(&fcliTimer);
    f_out("Total fcli run time: %.3lf seconds of CPU time\n",
          (double)(fcliTimer.system + fcliTimer.user)/1000.0);
  }
}

static struct {
  fcli_cliflag const * flags;
} FCliHelpState = {
NULL
};


static int fcli_flag_f_nocheckoutDir(fcli_cliflag const *f){
  (void)f;
  fcli.config.checkoutDir = 0;
  return 0;
}
static int fcli_flag_f_verbose(fcli_cliflag const *f){
  (void)f;
  ++fcli.config.verbose;
  return FCLI_RC_FLAG_AGAIN;
}
static int fcli_flag_f_help(fcli_cliflag const *f){
  (void)f;
  ++fcli.globalFlags.helpRequested;
  return FCLI_RC_FLAG_AGAIN;
}
static int fcli_flag_f_seekey(fcli_cliflag const *f){
  static int counter = 0;
  assert( fcliPrivate.see.key );
  if( ++counter != 1 ){
    return fcli_err_set(FSL_RC_MISUSE, "Only one of --see-key, --see-textkey, "
                        "and --see-hexkey may be used.");
  }
  fcliPrivate.see.nKey = fsl_strlen(fcliPrivate.see.key);
  if( strstr(f->flagLong, "textkey") ){
    fcliPrivate.see.type = FSL_SEE_KEYTYPE_TEXTKEY;
  }else if( strstr(f->flagLong, "hex") ){
    fcliPrivate.see.type = FSL_SEE_KEYTYPE_HEXKEY;
    if( fcliPrivate.see.nKey % 2 ){
      return fcli_err_set(FSL_RC_RANGE,"--%s must have an even number of digits.",
                          f->flagLong);
    }
  }else{
    fcliPrivate.see.type = FSL_SEE_KEYTYPE_PLAIN;
  }
  /**
    TODO (2026-10-28): --see-key-binary=FILE for
    FSL_SEE_KEYTYPE_BINARY.
  */
  return 0;
}

static const fcli_cliflag FCliFlagsGlobal[] = {
  FCLI_FLAG_BOOL_X("?","help",NULL,
                   fcli_flag_f_help,
                   "Show app help. Also triggered if the first non-flag is \"help\"."),
  FCLI_FLAG_BOOL(0,"lib-version", &fcli.globalFlags.versionRequested,
                 "Show libfossil version number."),
  FCLI_FLAG("R","repo","REPO-FILE",&fcli.globalFlags.repoDbArg,
            "Selects a specific repository database, ignoring the one "
            "used by the current directory's checkout (if any)."),
  FCLI_FLAG(NULL,"user","username",&fcli.globalFlags.userArg,
            "Sets the name of the fossil user name for this session."),
  FCLI_FLAG_BOOL_X(NULL, "no-checkout",NULL,fcli_flag_f_nocheckoutDir,
                   "Disable automatic attempt to open checkout."),
  FCLI_FLAG(NULL,"checkout-dir","DIRECTORY", &fcli.config.checkoutDir,
            "Open the given directory as a checkout, instead of the current dir."),
  FCLI_FLAG_BOOL_X("V","verbose",NULL,fcli_flag_f_verbose,
              "Increases the verbosity level by 1. May be used multiple times."),
  FCLI_FLAG_BOOL_TOGGLE("CM", "cache-metrics",
                        &fcli.globalFlags.reportCacheMetrics,
                        "Dump various cache metrics at the end of the app."),
  FCLI_FLAG_CSTR("pw", "sync-password", "password",
                 &FcliGPS.flagPW,
                 "Sync password, for apps which sync. "
                 "Optionally environment variable FOSSIL_SYNC_PASSWORD."),
  FCLI_FLAG_CSTR("pw-file", "sync-password-file", "filename",
                 &FcliGPS.flagPWFile,
                 "Read sync password from this file with one trailing "
                 "newline removed. Optionally environment variable "
                 "FOSSIL_SYNC_PASSWORD_FILE."),
#if FCLI__REPORT_SYNC_METRICS
#  define smhelp "Do not show sync metrics after fcli_sync()."
#else
#  define smhelp "Show sync metrics after fcli_sync()."
#endif
  FCLI_FLAG_BOOL_TOGGLE("SM", "sync-metrics",
                        &fcli.globalFlags.reportSyncMetrics,
                        smhelp),
#undef smhelp
  FCLI_FLAG_BOOL(NULL,"trace-sql",&TempFlags.traceSql,
                 "Enable SQL tracing."),
  FCLI_FLAG_BOOL_INVERT(NULL, "no-lib-events",
                        &fcli.globalFlags.libEvents,
                        "Disable library-generated progress output."),
  FCLI_FLAG_BOOL(NULL,"timer",&TempFlags.doTimer,
                 "At the end of successful app execution, output how long it took "
                 "from the call to fcli_setup() until the end of main()."),
  FCLI_FLAG_X(NULL,"see-key","ENCRYPTION-KEY", &fcliPrivate.see.key, fcli_flag_f_seekey,
              "The SEE encryption key to use when opening the repo and checkout databases."),
  FCLI_FLAG_X(NULL,"see-hexkey","HEX-ENCODED-ENCRYPTION-KEY", &fcliPrivate.see.key, fcli_flag_f_seekey,
              "The hex-encoded SEE encryption key to use when opening the repo and checkout databases."),
  FCLI_FLAG_X(NULL,"see-textkey","ENCRYPTION-KEY", &fcliPrivate.see.key, fcli_flag_f_seekey,
              "The SEE encryption key to use when opening the repo and checkout databases."),
  fcli_cliflag_empty_m
};

void fcli_cliflag_help(fcli_cliflag const *defs){
  fcli_cliflag const * f;
  const char * tab = "  ";
  for( f = defs; f->flagShort || f->flagLong; ++f ){
    const char * s = f->flagShort;
    const char * l = f->flagLong;
    const char * fvl = f->flagValueLabel;
    const char * valLbl = 0;
    switch(f->flagType){
      case FCLI_FLAG_TYPE_BOOL:
      case FCLI_FLAG_TYPE_BOOL_TOGGLE:
      case FCLI_FLAG_TYPE_BOOL_INVERT: break;
      case FCLI_FLAG_TYPE_INT32: valLbl = fvl ? fvl : "int32"; break;
      case FCLI_FLAG_TYPE_INT64: valLbl = fvl ? fvl : "int64"; break;
      case FCLI_FLAG_TYPE_ID: valLbl = fvl ? fvl : "db-record-id"; break;
      case FCLI_FLAG_TYPE_DOUBLE: valLbl = fvl ? fvl : "double"; break;
      case FCLI_FLAG_TYPE_CSTR: valLbl = fvl ? fvl : "string"; break;
      default:
        break;
    }
    f_out("%s%s%s%s%s%s%s%s",
          tab,
          s?"-":"", s?s:"", (s&&l)?"|":"",
          l?"--":"",l?l:"",
          valLbl ? "=" : "", valLbl);
    if(f->helpText){
      f_out("\n%s%s%s", tab, tab, f->helpText);
    }
    f_out("\n\n");
  }
}

void fcli_help(void){
  if(fcli.config.appHelp){
    if(fcli.config.appHelp->briefUsage){
      f_out("Usage: %s [options] %s\n", fcli.appName, fcli.config.appHelp->briefUsage);
    }
    if(fcli.config.appHelp->briefDescription){
      f_out("\n%s\n", fcli.config.appHelp->briefDescription);
    }
  }else{
    f_out("Help for %s:\n", fcli.appName);
  }
  const int helpCount = fcli.globalFlags.helpRequested
    + fcli.config.verbose;
  bool const showGlobal = helpCount>1;
  bool const showApp = (2!=helpCount);
  if(showGlobal){
    f_out("\nFCli global flags:\n\n");
    fcli_cliflag_help(FCliFlagsGlobal);
  }else{
    f_out("\n");
  }
  if(showApp){
    if(FCliHelpState.flags
       && (FCliHelpState.flags[0].flagShort || FCliHelpState.flags[0].flagLong)){
      f_out("App-specific flags:\n\n");
      fcli_cliflag_help(FCliHelpState.flags);
      //f_out("\n");
    }
    if(fcli.config.appHelp && fcli.config.appHelp->callback){
      fcli.config.appHelp->callback();
      f_out("\n");
    }
  }
  if(showGlobal){
    if(!showApp){
      f_out("Invoke --help three times (or --help -V -V) to list "
            "both the framework- and app-level options.\n");
    }else{
      f_out("Invoke --help once to list only the "
            "app-level flags.\n");
    }
  }else{
    f_out("Invoke --help twice (or --help -V) to list the "
          "framework-level options. Use --help three times "
          "to list both framework- and app-level options.\n");
  }
  f_out("\nFlags which require values may be passed as "
        "--flag=value or --flag value.\n\n");
}

/**
   Parses v, an optionally signed base-10 integer, into *pOut. Returns
   false if v has no digits, contains anything other than digits after
   the sign, or is outside [lo,hi].
*/
static bool fcli__flag_int(char const *v, int64_t lo, int64_t hi,
                           int64_t *pOut){
  uint64_t n = 0;
  bool const neg = '-'==*v;
  if( neg || '+'==*v ) ++v;
  if( !*v ) return false;
  for( ; *v; ++v ){
    if( *v<'0' || *v>'9' ) return false;
    if( n > (UINT64_MAX - (uint64_t)(*v - '0'))/10 ) return false;
    n = n*10 + (uint64_t)(*v - '0');
  }
  if( neg ){
    if( n > (uint64_t)INT64_MAX + 1 ) return false;
    *pOut = (n == (uint64_t)INT64_MAX + 1) ? INT64_MIN : -(int64_t)n;
  }else{
    if( n > (uint64_t)INT64_MAX ) return false;
    *pOut = (int64_t)n;
  }
  return *pOut>=lo && *pOut<=hi;
}

int fcli_process_flags( fcli_cliflag const * defs ) {
  fcli_cliflag const * f;
  int rc = 0;
  int64_t iVal = 0;
  char const * v = NULL;
  /**
     TODO/FIXME/NICE-TO-HAVE: we "really should" process the CLI flags
     in the order they are provided on the CLI, as opposed to the
     order they're defined in the defs array. The current approach is
     much simpler to process but keeps us from being able to support
     certain useful flag-handling options, e.g.:

     f-tag -a artifact-id-1 --tag x=y --tag y=z -a artifact-id-2 --tag a=b...

     The current approach consumes the -a flags first, leaving us
     unable to match the --tag flags to their corresponding
     (left-hand) -a flag.

     Processing them the other way around, however, requires that we
     keep track of which flags we've already seen so that we can
     reject, where appropriate, duplicate invocations.

     We could, instead of looping on the defs array, loop over the
     head of fcli.argv. If it's a non-flag, move it out of the way
     temporarily (into a new list), else look over the defs array
     looking for a flag match. We don't know, until finding such a
     match, whether the current flag requires a value. If it does, we
     then have to check the current fcli.argv entry to see if it has a
     value (--x=y) or whether the next argv entry is its value (--x
     y). If the current tip has no matching defs entry, we have no
     choice but to skip over it in the hopes that the user can use
     fcli_flag() and friends to consume it, but we cannot know, from
     here, whether such a stray flag requires a value, which means we
     cannot know, for sure, how to process the _next_ argument. The
     best we could do is have a heuristic like "if it starts with a
     dash, assume it's a flag, otherwise assume it's a value for the
     previous flag and skip over it," but whether or not that's sane
     enough for daily use is as yet undetermined.

     If we change the CLI interface to require --flag=value for all
     flags, as opposed to optionally allowing (--flag value), the
     above becomes simpler, but CLI usage suffers. Hmmm. e.g.:

     f-ci -m="message" ...

     simply doesn't fit the age-old muscle memory of:

     svn ci -m ...
     cvs ci -m ...
     fossil ci -m ...
     f-ci -m ...
  */
  for( f = defs; f->flagShort || f->flagLong; ++f ){
    if(!f->flagValue && !f->callback){
      /* We accept these for purposes of generating the --help text,
         but we can't otherwise do anything sensible with them and
         assume the app will handle such flags downstream or ignore
         them altogether.*/
      continue;
    }
    v = NULL;
    const char ** passV = f->flagValue ? &v : NULL;
    switch(f->flagType){
      case FCLI_FLAG_TYPE_BOOL:
      case FCLI_FLAG_TYPE_BOOL_INVERT:
      case FCLI_FLAG_TYPE_BOOL_TOGGLE:
        passV = NULL;
        break;
      default: break;
    };
    bool const gotIt = fcli_flag2(f->flagShort, f->flagLong, passV);
    if(fcli__error->code){
      /**
         Corner case. Consider:

         FCLI_FLAG("x","y","xy", &foo, "blah");

         And: my-app -x

         That will cause fcli_flag2() to return false, but it will
         also populate fcli__error for us.
      */
      rc = fcli__error->code;
      break;
    }
    //MARKER(("Got?=%d flag: %s/%s %s\n",gotIt, f->flagShort, f->flagLong, v ? v : ""));
    if(!gotIt){
      continue;
    }
    if(f->flagValue) switch(f->flagType){
      case FCLI_FLAG_TYPE_BOOL:
        *((bool*)f->flagValue) = true;
        break;
      case FCLI_FLAG_TYPE_BOOL_INVERT:
        *((bool*)f->flagValue) = false;
        break;
      case FCLI_FLAG_TYPE_BOOL_TOGGLE:
        *((bool*)f->flagValue) = !*((bool*)f->flagValue);
        break;
      case FCLI_FLAG_TYPE_CSTR:
        if(!v) goto missing_val;
        *((char const **)f->flagValue) = v;
        break;
      case FCLI_FLAG_TYPE_INT32:
        if(!v) goto missing_val;
        if(!fcli__flag_int(v, INT32_MIN, INT32_MAX, &iVal)) goto bad_val;
        *((int32_t*)f->flagValue) = (int32_t)iVal;
        break;
      case FCLI_FLAG_TYPE_INT64:
        if(!v) goto missing_val;
        if(!fcli__flag_int(v, INT64_MIN, INT64_MAX, &iVal)) goto bad_val;
        *((int64_t*)f->flagValue) = iVal;
        break;
      case FCLI_FLAG_TYPE_ID:
        if(!v) goto missing_val;
        if(!fcli__flag_int(v, 0, sizeof(fsl_id_t)>4 ? INT64_MAX : INT32_MAX,
                           &iVal)) goto bad_val;
        *((fsl_id_t*)f->flagValue) = (fsl_id_t)iVal;
        break;
      case FCLI_FLAG_TYPE_DOUBLE:{
        char * zEnd = NULL;
        if(!v) goto missing_val;
        errno = 0;
        *((double*)f->flagValue) = strtod(v, &zEnd);
        if(zEnd==v || *zEnd || ERANGE==errno
           || !isfinite(*((double*)f->flagValue))) goto bad_val;
        break;
      }
      default:
        rc = fcli_err_set(FSL_RC_MISUSE,
                          "Unhandled type %d for flag %s%s%s%s%s.",
                          (int)f->flagType,
                          f->flagShort ? "-" : "",
                          f->flagShort ? f->flagShort : "",
                          (f->flagShort && f->flagLong) ? "|" : "",
                          f->flagLong ? "--" : "",
                          f->flagLong ? f->flagLong : "");
        break;
    }
    if(rc) break;
    else if(f->callback){
      rc = f->callback(f);
      if(rc==FCLI_RC_FLAG_AGAIN){
        rc = 0;
        --f;
      }else if(rc){
        break;
      }
    }
  }
  //MARKER(("fcli__error->code==%s\n", fsl_rc_cstr(fcli__error->code)));
  return rc;
  missing_val:
  rc = fcli_err_set(FSL_RC_MISUSE,"Missing value for flag %s%s%s%s%s.",
                    f->flagShort ? "-" : "",
                    f->flagShort ? f->flagShort : "",
                    (f->flagShort && f->flagLong) ? "|" : "",
                    f->flagLong ? "--" : "",
                    f->flagLong ? f->flagLong : "");
  return rc;
  bad_val:
  rc = fcli_err_set(FSL_RC_RANGE,"Invalid %s value for flag %s%s%s%s%s: %s",
                    FCLI_FLAG_TYPE_DOUBLE==f->flagType
                    ? "numeric" : "integer",
                    f->flagShort ? "-" : "",
                    f->flagShort ? f->flagShort : "",
                    (f->flagShort && f->flagLong) ? "|" : "",
                    f->flagLong ? "--" : "",
                    f->flagLong ? f->flagLong : "", v);
  return rc;
}

/**
   oldMode must be true if fcli.config.cliFlags is NULL, else false.
*/
static int fcli_process_argv( bool oldMode, int argc, char const * const * argv ){
  int i;
  int rc = 0;
  char * cp;
  if( !fcli.appName ){
    fcli.appName = argv[0];
  }
  fcli.argc = 0;
  fcli.argv = (char **)fsl_malloc( (argc + 1) * sizeof(char*));
  fcli.argv[argc] = NULL;
  for( i = 1; i < argc; ++i ){
    char const * arg = argv[i];
    if('-'==*arg){
      char const * flag = arg+1;
      while('-'==*flag) ++flag;
#define FLAG(F) if(0==fsl_strcmp(F,flag))
      if(oldMode){
        FLAG("help") {
          ++fcli.globalFlags.helpRequested;
          continue;
        }
        FLAG("?") {
          ++fcli.globalFlags.helpRequested;
          continue;
        }
        FLAG("V") {
          fcli.config.verbose += 1;
          continue;
        }
        FLAG("verbose") {
          fcli.config.verbose += 1;
          continue;
        }
      }
#undef FLAG
      /* else fall through */
    }
    cp = fsl_strdup(arg);
    if(!cp) return FSL_RC_OOM;
    fcli.argv[fcli.argc++] = cp;
    fcli_fax(cp);
  }
  if(!rc && !oldMode){
    rc = fcli_process_flags(FCliFlagsGlobal);
  }
  return rc;
}

bool fcli_flag(char const * opt, const char ** value){
  int i = 0;
  int remove = 0 /* number of items to remove from argv */;
  bool rc = false /* true if found, else 0 */;
  fsl_size_t optLen = fsl_strlen(opt);
  for( ; i < fcli.argc; ++i ){
    char const * arg = fcli.argv[i];
    char const * x;
    char const * vp = NULL;
    if(!arg || ('-' != *arg)) continue;
    rc = false;
    x = arg+1;
    if('-' == *x) { ++x;}
    if(0 != fsl_strncmp(x, opt, optLen)) continue;
    if(!value){
      if(x[optLen]) continue /* not exact match */;
      /* Treat this as a boolean. */
      rc = true;
      ++remove;
      break;
    }else{
      /* -FLAG VALUE or -FLAG=VALUE */
      if(x[optLen] == '='){
        rc = true;
        vp = x+optLen+1;
        ++remove;
      }
      else if(x[optLen]) continue /* not an exact match */;
      else if(i<(fcli.argc-1)){ /* -FLAG VALUE */
        vp = fcli.argv[i+1];
        if('-'==*vp && vp[1]/*allow "-" by itself!*/){
          // VALUE looks like a flag.
          fcli_err_set(FSL_RC_MISUSE, "Missing value for flag %s: "
                       "the next argument, %s, looks like a flag. "
                       "Use %s=VALUE for a value starting with '-'.",
                       arg, vp, arg);
          rc = false;
          assert(!remove);
          break;
        }
        rc = true;
        remove += 2;
      }
      else{
        /*
          --FLAG is expecting VALUE but we're at end of argv.  Leave
          --FLAG in the args and report this as "not found."
        */
        rc = false;
        assert(!remove);
        fcli_err_set(FSL_RC_MISUSE,
                     "Missing value for flag %s.",
                     arg);
        assert(fcli__error->code);
        //MARKER(("Missing flag value for [%s]\n",opt));
        break;
      }
      if(rc){
        *value = vp;
      }
      break;
    }
  }
  if(remove>0){
    int x;
    for( x = 0; x < remove; ++x ){
      fcli.argv[i+x] = NULL/*memory ownership==>FCliFree*/;
    }
    for( ; i < fcli.argc; ++i ){
      fcli.argv[i] = fcli.argv[i+remove];
    }
    fcli.argc -= remove;
    fcli.argv[i] = NULL;
  }
  //MARKER(("flag %s check rc=%s\n",opt,fsl_rc_cstr(fcli__error->code)));
  return rc;
}

bool fcli_flag2(char const * shortOpt,
                char const * longOpt,
                const char ** value){
  bool rc = 0;
  if(shortOpt) rc = fcli_flag(shortOpt, value);
  if(!rc && longOpt && !fcli__error->code) rc = fcli_flag(longOpt, value);
  //MARKER(("flag %s check rc=%s\n",shortOpt,fsl_rc_cstr(fcli__error->code)));
  return rc;
}

bool fcli_flag_or_arg(char const * shortOpt,
                      char const * longOpt,
                      const char ** value){
  bool rc = fcli_flag(shortOpt, value);
  if(!rc && !fcli__error->code){
    rc = fcli_flag(longOpt, value);
    if(!rc && value){
      const char * arg = fcli_next_arg(1);
      if(arg){
        rc = true;
        *value = arg;
      }
    }
  }
  return rc;
}


/**
    We copy fsl_lib_configurable.allocator as a base allocator.
 */
static fsl_allocator fslAllocOrig;

/**
    Proxies fslAllocOrig.f() and abort()s on OOM conditions.
*/
static void * fsl_realloc_f_failing(void * state,
                                    void * mem, fsl_size_t n){
  void * rv = fslAllocOrig.f(fslAllocOrig.state, mem, n);
  (void)state;
  if(n && !rv){
    fsl__fatal(FSL_RC_OOM, NULL)/*does not return*/;
  }
  return rv;
}

static void fcli__die_before_init(char const *zFunc){
  if( !fcli.f ){
    fsl__fatal(FSL_RC_MISUSE, "Do not call %s() before initializing fcli\n",
               zFunc);
  }
}

/**
    Replacement for fsl_memory_allocator() which abort()s on OOM.
    Why? Because fossil(1) has shown how much that can simplify error
    checking in an allocates-often API.
 */
static const fsl_allocator fcli_allocator = {
fsl_realloc_f_failing,
NULL/*state*/
};

#if !defined(FCLI_USE_SIGACTION)
#  if (defined(_POSIX_C_SOURCE) || defined(sa_sigaction/*BSD*/)) \
  && defined(HAVE_SIGACTION)
/* ^^^ on Linux, sigaction() is only available in <signal.h>
   if _POSIX_C_SOURCE is set */
#    define FCLI_USE_SIGACTION HAVE_SIGACTION
#  else
#    define FCLI_USE_SIGACTION 0
#  endif
#endif

#if FCLI_USE_SIGACTION
#include <signal.h> /* sigaction(), if our feature macros are set right */
/**
   SIGINT handler which calls fsl_cx_interrupt().
*/
static void fcli__sigc_handler(int s){
  static fsl_cx * f = 0;
  if(f) return/*disable concurrent interruption*/;
  f = fcli_cx();
  if(f && !fsl_cx_interrupted(f)){
    //f_out("^C\n"); // no - this would interfere with curses apps
    fsl_cx_interrupt(f, FSL_RC_INTERRUPTED,
                     "Interrupted by signal #%d.", s);
    f = NULL;
  }
}
#endif
/* ^^^ FCLI_USE_SIGACTION */

/** fsl_cx_config::dbOnOpen::callback. */
static int fcli_db_on_open_f(fsl_db * db, void * pState){
  if( !fcliPrivate.see.nKey ) return 0;
  int rc = 0;
  (void)pState;
  switch( fcliPrivate.see.type ){
    case FSL_SEE_KEYTYPE_TEXTKEY:
    case FSL_SEE_KEYTYPE_PLAIN:
      rc = fsl_db_exec(db, "PRAGMA %s=%Q",
                       (FSL_SEE_KEYTYPE_TEXTKEY==fcliPrivate.see.type
                        ? "textkey" : "key"),
                       fcliPrivate.see.key);
      break;
    case FSL_SEE_KEYTYPE_HEXKEY:
      rc = fsl_db_exec(db, "PRAGMA hexkey=%Q",
                       fcliPrivate.see.key);;
      break;
    case FSL_SEE_KEYTYPE_BINARY:{
      fsl_b buf = fsl_b_empty;
      rc = fsl_b_append_hex(&buf, fcliPrivate.see.key,
                            fcliPrivate.see.nKey, false);
      if( 0==rc ){
        rc = fsl_db_exec(db, "PRAGMA hexkey=%B", buf);
      }else{
        assert( buf.errCode );
        rc = db->error.code = buf.errCode /* OOM */;
      }
      if( buf.capacity ){
        memset(buf.mem, 0, buf.capacity);
      }
      fsl_b_clear(&buf);
      break;
    }
    default:
      rc = fsl_error_set(&db->error,
                         FSL_RC_UNSUPPORTED,
                         "Invalid or unsupported value (%d) for "
                         "SEE key type.",
                         fcliPrivate.see.type);
      break;
  }
  return rc;
}


void fcli_pre_setup(void){
  static int run = 0;
  if(run++) return;
  TempFlags.isTty = fsl_isatty(1);
  fslAllocOrig = fsl_lib_configurable.allocator;
  fsl_lib_configurable.allocator = fcli_allocator
    /* This MUST be done BEFORE the fsl API allocates
       ANY memory! */;
  atexit(fcli_shutdown);
#if FCLI_USE_SIGACTION
  struct sigaction sigIntHandler;
  sigIntHandler.sa_handler = fcli__sigc_handler;
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;
  sigaction(SIGINT, &sigIntHandler, NULL);
#endif
}

/**
   oldMode must be true if fcli.config.cliFlags is NULL, else false.
*/
static int fcli_setup_common1(bool oldMode, int argc, char const * const *argv){
  static char once = 0;
  int rc = 0;
  fsl_timer_start(&fcliTimer);
  if( once++ ){
    return fcli_err_set(FSL_RC_MISUSE, "fcli_setup() must "
                        "not be called more than once.");
  }
  fcli_pre_setup();
  rc = fcli_process_argv(oldMode, argc, argv);
  if(!rc && fcli.argc && 0==fsl_strcmp("help",fcli.argv[0])){
    fcli_next_arg(1) /* strip argument */;
    ++fcli.globalFlags.helpRequested;
  }
  return rc;
}

static int fcli_setup_common2(void){
  int rc = 0;
  fsl_cx_config fcfg = fsl_cx_config_empty;
  fsl_cx * f = 0;

  fcfg.sqlPrint = 1;
  if( fcli.globalFlags.libEvents ){
    fcfg.listener = fcli.config.listener;
  }
  fcfg.dbOnOpen.callback = fcli_db_on_open_f;
  if(fcli.config.outputer.out){
    fcfg.output = fcli.config.outputer;
    fcli.config.outputer = fsl_outputer_empty
      /* To avoid any confusion about ownership */;
  }else{
    fcfg.output = fsl_outputer_FILE;
    fcfg.output.state = stdout;
  }
  if(fcli.config.traceSql>0 || TempFlags.traceSql){
    fcfg.traceSql = fcli.config.traceSql;
  }

  rc = fsl_cx_init( &f, &fcfg );
  fcli.f = f;
#if 0
  /* Just for testing cache size effects... */
  f->cache.arty.szLimit = 1024 * 1024 * 20;
  f->cache.arty.usedLimit = 300;
#endif
  fsl_error_clear(&fcli.err);
  FCLI_V3(("Initialized fsl_cx @0x%p. rc=%s\n",
           (void const *)f, fsl_rc_cstr(rc)));
  if(!rc){
#if 0
    if(fcli.globalFlags.gmtTime){
      fsl_cx_flag_set(f, FSL_CX_F_LOCALTIME_GMT, 1);
    }
#endif
    if(fcli.config.checkoutDir || fcli.globalFlags.repoDbArg){
      rc = fcli_open();
      FCLI_V3(("fcli_open() rc=%s\n", fsl_rc_cstr(rc)));
      if(!fcli.globalFlags.repoDbArg && fcli.config.checkoutDir
         && (FSL_RC_NOT_FOUND == rc)){
        /* If [it looks like] we tried an implicit checkout-open but
           didn't find one, suppress the error. */
        rc = 0;
        fcli_err_reset();
      }
    }
  }
  if(!rc){
    char const * userName = fcli.globalFlags.userArg;
    if(userName){
      fsl_cx_user_set(f, userName);
    }else{
      fsl_cx_user_guess(f);
    }
  }
  return rc;
}

static int check_help_invoked(void){
  int rc = 0;
  if(fcli.globalFlags.helpRequested){
    /* Do this last so that we can get the default user name and such
       for display in the help text. */
    fcli_help();
    rc = FCLI_RC_HELP;
  }else if(fcli.globalFlags.versionRequested){
    f_out("libfossil version: %s\nCheckin: %s\nCheckin timestamp: %s\n",
          fsl_library_version(),
          fsl_buildinfo(FSL_BUILDINFO_VERSION_HASH),
          fsl_buildinfo(FSL_BUILDINFO_VERSION_TIMESTAMP));
    rc = FCLI_RC_HELP;
  }
  return rc;
}

static int fcli_setup2(int argc, char const * const * argv,
                       const fcli_cliflag * flags){
  int rc;
  FCliHelpState.flags = flags;
  rc = fcli_setup_common1(false, argc, argv);
  if(rc) return rc;
  assert(!fcli__error->code);
  rc = check_help_invoked();
  if(!rc){
    rc = fcli_process_flags(flags);
    if(rc) assert(fcli__error->msg.used);
    if(!rc){
      rc = fcli_setup_common2();
    }
  }
  return rc;
}

int fcli_setup_v2(int argc, char const * const * argv,
                  fcli_cliflag const * const cliFlags,
                  fcli_help_info const * const helpInfo ){
  if(NULL!=cliFlags) fcli.config.cliFlags = cliFlags;
  if(NULL!=helpInfo) fcli.config.appHelp = helpInfo;
  if(cliFlags || fcli.config.cliFlags){
    return fcli_setup2(argc, argv, cliFlags ? cliFlags : fcli.config.cliFlags);
  }
  /* Else do "old mode" setup... */
  int rc = fcli_setup_common1(true, argc, argv);
  if(!rc){
    rc = check_help_invoked();
    if(!rc){
      if( fcli_flag2(NULL, "no-checkout", NULL) ){
        fcli.config.checkoutDir = NULL;
      }
      fcli_flag2(NULL,"user", &fcli.globalFlags.userArg);
      fcli.config.traceSql =  fcli_flag2(NULL,"trace-sql", NULL);
      fcli_flag2("R", "repo", &fcli.globalFlags.repoDbArg);
      //--see-key and friends: do not support in "old mode"
      rc = fcli_setup_common2();
    }
  }
  return rc;
}

int fcli_setup(int argc, char const * const * argv ){
  return fcli_setup_v2(argc, argv, fcli.config.cliFlags, fcli.config.appHelp);
}

/**
   Returns the name of rc, including the fcli_rc_e codes, or "?" if
   it has none.
*/
static char const * fcli__rc_cstr(int rc){
  switch(rc){
    case FCLI_RC_FLAG_AGAIN: return "FCLI_RC_FLAG_AGAIN";
    case FCLI_RC_NO_CMD: return "FCLI_RC_NO_CMD";
    case FCLI_RC_HELP: return "FCLI_RC_HELP";
    default: {
      char const * const z = fsl_rc_cstr(rc);
      return z ? z : "?";
    }
  }
}

int fcli_err_report2(bool clear, char const * file, int line){
  int errRc = 0;
  char const * msg = NULL;
  errRc = fsl_error_get( fcli__error, &msg, NULL );
  if(FCLI_RC_HELP==errRc){
    errRc = 0;
  }else if( !errRc && fcli.f ){
    if( fcli.f->interrupted ){
      errRc = fcli.f->interrupted;
      msg = "Interrupted.";
    }else{
      fsl_db * const db = fsl_cx_db(fcli.f);
      if( db && db->error.code ){
        fsl_cx_uplift_db_error(fcli.f, db);
        errRc = fsl_error_get( &fcli.f->error, &msg, NULL);
      }
    }
  }
  if(errRc || msg){
    if(!msg) msg = "(no error message)";
    if(fcli.config.verbose>0){
      fcli_printf("%s %s:%d: ERROR #%d (%s): %s\n",
                  fcli.appName,
                  file, line, errRc, fcli__rc_cstr(errRc), msg);
    }else{
      fcli_printf("%s: ERROR #%d (%s): %s\n",
                  fcli.appName, errRc, fcli__rc_cstr(errRc), msg);
    }
  }
  if(clear){
    fcli_err_reset();
    if(fcli.f) fsl_cx_interrupt(fcli.f, 0, NULL);
  }
  return errRc;
}


const char * fcli_next_arg(bool remove){
  const char * rc = fcli.argc ? fcli.argv[0] : NULL;
  if(fcli.argc && remove){
    int i;
    --fcli.argc;
    for(i = 0; i < fcli.argc; ++i){
      fcli.argv[i] = fcli.argv[i+1];
    }
    fcli.argv[fcli.argc] = NULL/*owned by FCliFree*/;
  }
  return rc;
}

int fcli_has_unused_args(bool outputError){
  int rc = 0;
  if(fcli.argc){
    rc = fcli_err_set(FSL_RC_MISUSE,
                      "Unhandled extra argument: %s",
                      fcli.argv[0]);
    if(outputError){
      fcli_err_report(false);
    }
  }
  return rc;
}

int fcli_has_unused_flags(bool outputError){
  int i;
  for( i = 0; i < fcli.argc; ++i ){
    char const * arg = fcli.argv[i];
    if('-'==*arg && arg[1]/* "-" by itself conventionally means
                             stdin or stdout, not a flag */){
      int rc = fcli_err_set(FSL_RC_MISUSE,
                            "Unhandled/unknown flag or missing value: %s",
                            arg);
      if(outputError){
        fcli_err_report(false);
      }
      return rc;
    }
  }
  return 0;
}

int fcli_err_set(int code, char const * fmt, ...){
  int rc;
  va_list va;
  va_start(va, fmt);
  rc = fsl_error_setv(fcli__error, code, fmt, va);
  va_end(va);
  return rc;
}

int fcli_end_of_main(int mainRc){
  if(FCLI_RC_HELP==mainRc){
    mainRc = 0;
  }
  if( fcli.globalFlags.reportCacheMetrics ){
    fcli_dump_cache_metrics();
  }
  if(fcli_err_report(true)){
    return EXIT_FAILURE;
  }else if(mainRc){
    fsl_b args = fsl_b_empty;
    for(int i = 0; i < fcli.argc; ++i){
      fsl_b_appendf(&args, " %s", fcli.argv[i]);
    }
    fcli_err_set(mainRc,"Ending with unadorned end-of-app "
                 "error code %d/%s.%s%b",
                 mainRc, fcli__rc_cstr(mainRc),
                 args.used ? " Unconsumed argument(s):" : "",
                 &args);
    fsl_b_clear(&args);
    fcli_err_report(true);
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}

int fcli_dispatch_commands( fcli_command const * cmd,
                            bool reportErrors){
  int rc = 0;
  const char * arg = fcli_next_arg(0);
  fcli_command const * orig = cmd;
  fcli_command const * helpPos = 0;
  int helpState = 0;
  if(!arg){
    return fcli_err_set(FSL_RC_MISUSE,
                        "Missing command argument. Try --help.");
  }
  assert(fcli.f);
  for(; arg && cmd->name; ++cmd ){
    if(cmd==orig && 0==fsl_strcmp(arg,"help")){
      /* Accept either (help command) or (command help) as help. */
      /* Except that it turns out that fcli_setup() will trump the
         former and doesn't have the fcli_command state, so can't do
         this. Maybe we can change that somehow. */
      helpState = 1;
      helpPos = orig;
      arg = fcli_next_arg(1); // consume it
    }else if(0==fsl_strcmp(arg,cmd->name) || 0==fcli_cmd_aliascmp(cmd,arg)){
      if(!cmd->f){
        rc = fcli_err_set(FSL_RC_NYI,
                               "Command [%s] has no "
                               "callback function.",
                               cmd->name);
      }else{
        fcli_next_arg(1)/*consume it*/;
        if(helpState){
          assert(1==helpState);
          helpState = 2;
          helpPos = cmd;
          break;
        }
        const char * helpCheck = fcli_next_arg(false);
        if(helpCheck && 0==fsl_strcmp("help",helpCheck)){
          helpState = 3;
          helpPos = cmd;
          break;
        }else{
          rc = cmd->f(cmd);
        }
      }
      break;
    }
  }
  if(helpState){
    f_out("\n");
    fcli_command_help(helpPos, true, helpState>1);
    fcli.globalFlags.helpRequested++;
  }else if(!cmd->name){
    fsl_b * const msg = fsl_cx_b_borrow(fcli.f);
    int rc2;
    if( !msg ){
      rc = rc2 = fcli_err_set(FSL_RC_OOM, 0);
    }else if(!arg){
      rc2 = FSL_RC_MISUSE;
      fsl_b_appendf(msg, "No command provided.");
    }else{
      rc2 = FCLI_RC_NO_CMD;
      fsl_b_appendf(msg, "Command not found: %s.",arg);
    }
    if( msg ){
      fsl_b_appendf(msg, " Available commands: ");
      cmd = orig;
      for( ; cmd && cmd->name; ++cmd ){
        fsl_b_appendf( msg, "%s%s",
                            (cmd==orig) ? "" : ", ",
                            cmd->name);
      }
      rc = fcli_err_set(rc2, "%b", msg);
    }
    fsl_cx_b_return(fcli.f, msg);
  }
  if(rc && reportErrors){
    fcli_err_report(0);
  }
  return rc;
}

int fcli_cmd_aliascmp(fcli_command const * cmd, char const * arg){
  char const * alias = cmd->aliases;
  while ( alias && *alias!=0 ){
    if( 0==fsl_strcmp(alias, arg) ){
      return 0;
    }
    alias = strchr(alias, 0) + 1;
  }
  return 1;
}

void fcli_command_help(fcli_command const * cmd, bool showUsage, bool onlyOne){
  fcli_command const * c = cmd;
  for( ; c->name; ++c ){
    f_out("[%s] command:\n\n", c->name);
    if(c->briefDescription){
      f_out("  %s\n", c->briefDescription);
    }
    if(c->aliases){
      fcli_help_show_aliases(c->aliases);
    }else{
      f_out("\n");
    }
    if(c->flags){
      f_out("\n");
      fcli_cliflag_help(c->flags);
    }
    if(showUsage && c->usage){
      c->usage();
    }
    if(onlyOne) break;
  }
}

void fcli_help_show_aliases(char const * aliases){
  char const * alias = aliases;
  f_out("  (aliases: ");
  while ( *alias!=0 ){
    f_out("%s%s", alias, *(strchr(alias, 0) + 1) ? ", " : ")\n");
    alias = strchr(alias, 0) + 1;
  }
}

void * fcli_fax(void * mem){
  if(mem){
    fsl_list_append( &FCliFree.list, mem );
  }
  return mem;
}

int fcli_ckout_show_info(bool useUtc){
  fsl_cx * const f = fcli_cx();
  int rc = 0;
  fsl_stmt st = fsl_stmt_empty;
  fsl_db * const dbR = fsl_cx_db_repo(f);
  fsl_db * const dbC = fsl_cx_db_ckout(f);
  int lblWidth = -20;
  if(!fsl_needs_ckout(f)){
    return FSL_RC_NOT_A_CKOUT;
  }
  assert(dbR);
  assert(dbC);

  fsl_id_t rid = 0;
  fsl_uuid_cstr uuid = NULL;
  fsl_ckout_version_info(f, &rid, &uuid);
  assert((uuid && (rid>0)) || (!uuid && (0==rid)));

  f_out("%*s %s\n", lblWidth, "repository-db:",
        fsl_cx_db_file_repo(f, NULL));
  f_out("%*s %s\n", lblWidth, "checkout-root:",
        fsl_cx_ckout_dir_name(f, NULL));

  rc = fsl_cx_prepare(f, &st, "SELECT "
                      /*0*/"datetime(event.mtime%s) AS timestampString, "
                      /*1*/"coalesce(euser, user) AS user, "
                      /*2*/"(SELECT group_concat(substr(tagname,5), ', ') FROM {{dbname.repo}}.tag AS tag, {{dbname.repo}}.tagxref AS tagxref "
                      "WHERE tagname GLOB 'sym-*' AND tag.tagid=tagxref.tagid "
                      "AND tagxref.rid=blob.rid AND tagxref.tagtype>0) as tags, "
                      /*3*/"coalesce(ecomment, comment) AS comment, "
                      /*4*/"uuid AS uuid "
                      "FROM {{dbname.repo}}.event AS event JOIN {{dbname.repo}}.blob AS blob "
                      "WHERE "
                      "event.type='ci' "
                      "AND blob.rid=%"FSL_ID_T_PFMT" "
                      "AND blob.rid=event.objid "
                      "ORDER BY event.mtime DESC",
                      useUtc ? "" : ", 'localtime'",
                      rid);
  if(rc) goto end;
  if( FSL_RC_STEP_ROW != fsl_stmt_step(&st)){
    /* fcli_err_set(FSL_RC_ERROR, "Event data for checkout not found."); */
    f_out("\nNo 'event' data found. This is only normal for an empty repo.\n");
    goto end;
  }

  f_out("%*s %s %s %s (RID %"FSL_ID_T_PFMT")\n",
        lblWidth, "checkout-version:",
        fsl_stmt_g_text(&st, 4, NULL),
        fsl_stmt_g_text(&st, 0, NULL),
        useUtc ? "UTC" : "local",
        rid );

  {
    /* list parent(s) */
    fsl_stmt stP = fsl_stmt_empty;
    rc = fsl_cx_prepare(f, &stP, "SELECT "
                        "uuid, pid, isprim, "
                        "datetime(event.mtime%s) "
                        "FROM {{dbname.repo}}.plink, {{dbname.repo}}.blob, {{dbname.repo}}.event AS event "
                        "WHERE cid=%"FSL_ID_T_PFMT" "
                        "AND rid=pid "
                        "AND rid=event.objid "
                        "ORDER BY isprim DESC, event.mtime DESC /*sort*/",
                        useUtc ? "" : ", 'localtime'",
                        rid);
    if(rc) goto end;
    while( fsl__cx_stmt_step_each(f, &stP, &rc) ){
      char const * zLabel = fsl_stmt_g_int32(&stP,2)
        ? "parent:" : "merged-from:";
      f_out("%*s %s %s %s (RID %" FSL_ID_T_PFMT")\n", lblWidth, zLabel,
            fsl_stmt_g_text(&stP, 0, NULL),
            fsl_stmt_g_text(&stP, 3, NULL),
            useUtc ? "UTC" : "local",
            fsl_stmt_g_id(&stP, 1)
      );
    }
    fsl_stmt_finalize(&stP);
    if(rc) goto end;
  }
  {
    /* list merge parent(s) */
    fsl_stmt stP = fsl_stmt_empty;
    rc = fsl_cx_prepare(f, &stP, "SELECT "
                        "mhash, id FROm {{dbname.ckout}}.vmerge WHERE id<=0");
    if(rc) goto end;
    while( fsl__cx_stmt_step_each(f, &stP, &rc) ){
      char const * zClass;
      int32_t const id = fsl_stmt_g_int32(&stP,1);
      switch(id){
        case FSL_MERGE_TYPE_INTEGRATE: zClass = "integrate-merge:"; break;
        case FSL_MERGE_TYPE_BACKOUT: zClass = "backout-merge:"; break;
        case FSL_MERGE_TYPE_CHERRYPICK: zClass = "cherrypick-merge:"; break;
        case FSL_MERGE_TYPE_NORMAL: zClass = "merged-with:"; break;
        default:
          fsl__fatal(FSL_RC_RANGE,
                     "Unexpected value %"PRIi32" in vmerge.id",id);
          break;
      }
      f_out("%*s %s\n", lblWidth, zClass,
            fsl_stmt_g_text(&stP, 0, NULL));
    }
    fsl_stmt_finalize(&stP);
    if(rc) goto end;
  }
  {
    /* list children */
    fsl_stmt stC = fsl_stmt_empty;
    rc = fsl_cx_prepare(f, &stC, "SELECT "
                        "uuid, cid, isprim "
                        "FROM {{dbname.repo}}.plink JOIN {{dbname.repo}}.blob ON cid=rid "
                        "WHERE pid=%"FSL_ID_T_PFMT" "
                        "ORDER BY isprim DESC, mtime DESC /*sort*/",
                        rid);
    if(rc) goto end;
    while( fsl__cx_stmt_step_each(f, &stC, &rc) ){
      char const * zLabel = fsl_stmt_g_int32(&stC,2)
        ? "child:" : "merged-into:";
      f_out("%*s %s\n", lblWidth, zLabel,
            fsl_stmt_g_text(&stC, 0, NULL));
    }
    fsl_stmt_finalize(&stC);
    if(rc) goto end;
  }

  f_out("%*s %s\n", lblWidth, "user:",
        fsl_stmt_g_text(&st, 1, NULL));

  f_out("%*s %s\n", lblWidth, "tags:",
        fsl_stmt_g_text(&st, 2, NULL));

  f_out("%*s %s\n", lblWidth, "comment:",
        fsl_stmt_g_text(&st, 3, NULL));

  end:
  fsl_stmt_finalize(&st);

  return rc;
}

static int fsl_stmt_each_f_ambiguous( fsl_stmt * stmt, void * state ){
  int rc;
  if(1==stmt->rowCount) stmt->rowCount=0
                          /* HORRIBLE KLUDGE to elide header. */;
  rc = fsl_stmt_each_f_dump(stmt, state);
  if(0==stmt->rowCount) stmt->rowCount = 1;
  return rc;
}

void fcli_list_ambiguous_artifacts(char const * label,
                                   char const *prefix){
  fsl_db * const db = fsl_cx_db_repo(fcli.f);
  assert(db);
  if(!label){
    f_out("Artifacts matching ambiguous prefix: %s\n",prefix);
  }else if(*label){
    f_out("%s\n", label);
  }
  /* Possible fixme? Do we only want to list checkins
     here? */
  int rc = fsl_db_each(db, fsl_stmt_each_f_ambiguous, fcli.f,
              "SELECT uuid, CASE "
              "WHEN type='ci' THEN 'Checkin' "
              "WHEN type='w'  THEN 'Wiki' "
              "WHEN type='g'  THEN 'Control' "
              "WHEN type='e'  THEN 'Technote' "
              "WHEN type='t'  THEN 'Ticket' "
              "WHEN type='f'  THEN 'Forum' "
              "ELSE '?'||'?'||'?' END " /* '???' ==> trigraph! */
              "FROM {{dbname.repo}}.blob b, {{dbname.repo}}.event e WHERE uuid LIKE %Q||'%%' "
              "AND b.rid=e.objid "
              "ORDER BY uuid",
              prefix);
  if(rc){
    fsl_cx_uplift_db_error(fcli.f, db);
    fcli_err_report(false);
  }
}

fsl_db * fcli_db_ckout(void){
  return fcli.f ? fsl_cx_db_ckout(fcli.f) : NULL;
}

fsl_db * fcli_db_repo(void){
  return fcli.f ? fsl_cx_db_repo(fcli.f) : NULL;
}

fsl_db * fcli_needs_ckout(void){
  if(fcli.f) return fsl_needs_ckout(fcli.f);
  fcli_err_set(FSL_RC_NOT_A_CKOUT,
               "No checkout db is opened.");
  return NULL;
}

fsl_db * fcli_needs_repo(void){
  if(fcli.f) return fsl_needs_repo(fcli.f);
  fcli_err_set(FSL_RC_NOT_A_REPO,
               "No repository db is opened.");
  return NULL;
}

int fcli_args_to_vfile_ids(fsl_id_bag * const tgt,
                           fsl_id_t vid,
                           bool relativeToCwd,
                           bool changedFilesOnly){
  if(!fcli.argc){
    return fcli_err_set(FSL_RC_MISUSE,
                        "No file/dir name arguments provided.");
  }
  int rc = 0;
  char const * zName;
  while( !rc && (zName = fcli_next_arg(true))){
    FCLI_V3(("Collecting vfile ID(s) for: %s\n", zName));
    rc = fsl_ckout_vfile_ids(fcli.f, vid, tgt, zName,
                             relativeToCwd, changedFilesOnly);
  }
  return rc;
}

int fcli_fingerprint_check(bool reportImmediately){
  int rc = fsl_ckout_fingerprint_check(fcli.f);
  if(rc && reportImmediately){
    f_out("ERROR: repo/checkout fingerprint mismatch detected. "
          "To recover from this, (fossil close) the current checkout, "
          "then re-open it. Be sure to store any modified files somewhere "
          "safe and restore them after re-opening the repository.\n");
  }
  return rc;
}

char const * fcli_progname(void){
  if(!fcli.appName || !*fcli.appName) return NULL;
  char const * z = fcli.appName;
  char const * zEnd = z + fsl_strlen(z) - 1;
  for( ; zEnd > z; --zEnd ){
    switch((int)*zEnd){
      case (int)'/':
      case (int)'\\':
        return zEnd+1;
      default: break;
    }
  }
  return zEnd;
}

void fcli_diff_colors(fsl_dibu_opt * const tgt, fcli_diff_colors_e theme){
  char const * zIns = 0;
  char const * zEdit = 0;
  char const * zDel = 0;
  char const * zReset = 0;
  switch(theme){
    case FCLI_DIFF_COLORS_RG:
          zIns = "\x1b[32m";
          zEdit = "\x1b[36m";
          zDel = "\x1b[31m";
          zReset = "\x1b[0m";
          break;
    case FCLI_DIFF_COLORS_NONE:
    default: break;
  }
  tgt->ansiColor.insertion = zIns;
  tgt->ansiColor.edit = zEdit;
  tgt->ansiColor.deletion = zDel;
  tgt->ansiColor.reset = zReset;
}

void fcli_dump_stmt_cache(bool forceVerbose){
  int i = 0;
  fsl_stmt * st;
  fsl_db * const db = fsl_cx_db(fcli_cx());
  assert(db);
  for( st = db->impl.stCache.head; st; st = st->impl.next ) ++i;
  f_out("%s(): Cached fsl_stmt count: %d\n", __func__, i);
  if(i>0 && (forceVerbose || fcli_is_verbose()>1)){
    for( i = 1, st = db->impl.stCache.head; st; ++i, st = st->impl.next ){
      f_out("CACHED fsl_stmt #%d (%d hit(s)): %b\n", i,
            (int)st->impl.cachedHits, &st->sql);
    }
  }
}

void fcli_dump_cache_metrics(void){
  fsl_cx * const f = fcli.f;
  if(!f) return;
  f_out("fsl_cx::cache::mcache hits = %u misses = %u\n",
        f->cache.mcache.hits,
        f->cache.mcache.misses);
  f_out("fsl_cx::cache::blobContent hits = %u misses = %u. "
        "Entry count=%u totaling %u byte(s).\n",
        f->cache.blobContent.metrics.hits,
        f->cache.blobContent.metrics.misses,
        f->cache.blobContent.used,
        f->cache.blobContent.szTotal);

#define DBN(MEMBER) \
  f_out("fsl_cx::db::" # MEMBER " = %-10d\n", (int)f->db.MEMBER)
  DBN(peakTxnLevel);
  DBN(nBegin);
  DBN(nCommit);
  DBN(nRollback);
#undef DBN

  if( f->metrics.content.nCached ){
    f_out("fsl_cx::cache::fileContent buffer reused %"
          FSL_SIZE_T_PFMT " times " "with a total of %"
          FSL_SIZE_T_PFMT " bytes reported used at "
          "buffer-relinquish time. Peak content buffer size=%"
          FSL_SIZE_T_PFMT "\n",
          f->metrics.content.nCached, f->metrics.content.nTotalUsed,
          f->metrics.content.nPeakBufSize);
    if( f->metrics.content.nCappedMaxSize ){
      f_out("fsl_cx::cache::fileContent was trimmed %" FSL_SIZE_T_PFMT
            " time(s)\n", f->metrics.content.nCappedMaxSize );
    }
  }

#define fcb f->cache.buf
  if( fcb.list.capacity ){
    f_out("fsl_cx::cache::buf:\n"
          "\tborrowed %" PRIu64 " times\n"
          "\t%" FSL_SIZE_T_PFMT " buffer(s) "
          "in %" FSL_SIZE_T_PFMT " slot(s)\n"
          "\ttotaling %" PRIu64 " bytes of capacity.\n",
          fcb.nBorrowed,
          fcb.list.used, fcb.list.capacity,
          fcb.currentCapacity);
    f_out("\ttotal running borrowed/returned "
          "capacity: %" PRIu64 ", %" PRIu64 "\n",
          fcb.nBytesBorrowed,
          fcb.nBytesReturned);
    f_out("\tpeaks: %" PRIu64 " buffers with %" PRIu64 " bytes\n",
          fcb.peakBorrowed, fcb.peakCapacity);
  }else{
    f_out("fsl_cx::cache::buf went unused\n");
  }
#undef fcb
}

static bool fcli__has_pw_flag(void){
  return !!FcliGPS.flagPW
    || !!FcliGPS.flagPWFile
    || !!getenv("FOSSIL_SYNC_PASSWORD_FILE")
    || !!getenv("FOSSIL_SYNC_PASSWORD");
}

static int fcli__pw_f(fsl_cx * f, char const * zUrl,
                      fsl_b * bOut, void * state){
  (void)f; (void)state;
  /**
     Handle --sync-password-file, --sync-password,
     FOSSIL_SYNC_PASSWORD_FILE and FOSSIL_SYNC_PASSWORD,
     in that order.
  */
  char const * z = FcliGPS.flagPWFile;
  if( z ){
    int rc;
  do_file:
    rc = fsl_b_fill_from_filename(bOut, z);
    if( rc ){
      rc = fsl_cx_err_set(f, rc,
                          "Error %R reading password from file [%s].",
                          rc, z);
    }else{
      fsl_b_chomp(bOut);
    }
    return rc;
  }
  if( FcliGPS.flagPW ){
    return fsl_b_append(bOut, FcliGPS.flagPW, -1);
  }
  z = getenv("FOSSIL_SYNC_PASSWORD_FILE");
  if( z ) goto do_file;
  z = getenv("FOSSIL_SYNC_PASSWORD");
  if( z ) return fsl_b_append(bOut, z, -1);
  return 0;
}

int fcli_sync( int ops ){
  fcli__die_before_init(__func__);
  int rc = 0;
  if( FcliGPS.isSyncing ){
    return fcli_err_set(FSL_RC_MISUSE, "Cannot sync recursively.");
  }
  fsl_db * const dbR = fsl_needs_repo(fcli.f);
  if(!dbR){
    return FSL_RC_NOT_A_REPO;
  }else if(!fsl_db_exists(dbR, "select 1 from {{dbname.repo}}.config "
                          "where name='last-sync-url' or "
                          "name like 'syncwith:%%'" )){
    /* No remote, so nothing to do (and any attempt would fail). */
    return 0;
  }
  fsl_xfer_config xc = fsl_xfer_config_empty;
  if( fcli__has_pw_flag() ){
    /* The flag's password must trump a saved one. */
    ops |= FSL_SYNC_NO_SAVED_PASSWORD;
  }
  ops = fsl_xfer_config_from_flags( fcli.f, &xc, ops );
  if( -1==ops ){
    rc = fsl_cx_err_code(fcli.f);
    goto end;
  }
  if( !xc.op.pull && !xc.op.push ) goto end;
  FcliGPS.isSyncing = true;
    /* Reminder: the allocator dies on OOM */;
  rc = fsl_cx_last_sync_url(fcli.f, &xc.url);
  if( rc ) goto end;
  if( 0 == (ops & FSL_SYNC_NO_OUTPUT) ){
    xc.listener.callback = fsl_msg_f_fcli;
    if( fcli.globalFlags.reportSyncMetrics ){
      xc.metrics.callback = fsl_xfer_metrics_f_outputer;
      xc.metrics.state = &fcli.f->cxConfig.output;
    }else{
      assert( 0==xc.metrics.callback );
    }
  }
  if( fcli__has_pw_flag() ){
    xc.password.callback = fcli__pw_f;
    xc.password.state = &xc;
  }
  rc = fsl_sync_client(fcli.f, &xc, 0);
end:
  fsl_xfer_config_cleanup(&xc);
  FcliGPS.isSyncing = false;
  if(rc){
    fsl__cx_caches_reset(fcli.f, true);
  }
  return rc;
}


int fsl_msg_f_fcli(fsl_msg const *msg, void *state){
  char const * z = 0;
  fsl_size_t n = 0;
  char const *zType = 0;
  static enum fsl_msg_e prevType = FSL_MSG_INVALID;
  static bool pendingNL = false /* true after a \r-terminated XFER line */;
  switch(msg->type){
#define E(N,V,P) case FSL_MSG_ ## N:  zType = "fsl_msg " # N; break;
      fsl_msg_map(E)
#undef E
  }

  /* Without this output is not usually flushed and we don't
     see it until a \n is emitted. In most contexts this this
     would be an ugly hack in that we technically don't know
     if a given fsl_cx's output channel _is_ stdout, but in
     fcli we know that because we set it up that way. */
#define flushOut if( TempFlags.isTty>0 ) fflush(stdout);

  switch(msg->type){
    default: break;
    case FSL_MSG_RCV_BLOB:
    case FSL_MSG_RCV_CONFIG:
      /* We can get many thousands of these during sync */
      goto end;
    case FSL_MSG_TXN_BEGIN:
    case FSL_MSG_TXN_COMMIT:
    case FSL_MSG_TXN_ROLLBACK:
      if( fcli.config.verbose<=2 ) return 0;
      break;
    case FSL_MSG_VERBOSE:
      if( !fcli.config.verbose ) return 0;
      break;
    case FSL_MSG_CONNECT:
      if( !fcli.config.verbose ) goto end;
      break;
    case FSL_MSG_XFER:{
      /* Like fossil(1): one \r-overwritten line on a tty, else only the
         final count, then "X done". */
      fsl_msg_xfer const * const x = msg->payload;
      fsl_xfer_metrics const * const m = x->metrics;
      if( x->zDone || fsl_isatty(1) ){
        f_out("Round-trips: %" FSL_SIZE_T_PFMT
              "   Artifacts sent: %" FSL_SIZE_T_PFMT
              "  received: %" FSL_SIZE_T_PFMT "\r",
              x->trips,
              m->cardsTx[fsl_xfcard_e_file] + m->cardsTx[fsl_xfcard_e_cfile]
              + m->cardsTx[fsl_xfcard_e_uvfile],
              m->cardsRx[fsl_xfcard_e_file] + m->cardsRx[fsl_xfcard_e_cfile]
              + m->cardsRx[fsl_xfcard_e_uvfile]
              + m->cardsRx[fsl_xfcard_e_config]);
        flushOut;
        pendingNL = true;
      }
      if( x->zDone ){
        /* fossil(1) says "wire bytes" but these exclude HTTP headers */
        f_out("\n%s done, bytes sent: %" FSL_SIZE_T_PFMT
              "  received: %" FSL_SIZE_T_PFMT "  remote: %s\n",
              x->zDone, m->bytesWritten,
              m->bytesReadWire,
              x->zRemote ? x->zRemote : "");
        pendingNL = false;
      }
      goto end;
    }
  }
  if( pendingNL ){
    f_out("\n");
    pendingNL = false;
  }

  switch(msg->type){
    default: break;
    case FSL_MSG_REBUILD:{
      fsl_msg_rebuild const * const step = msg->payload;
      if( step->errCode ){
        f_out("\nRebuild failed with code %R\n", step->errCode);
      }else if( 0==step->stepNumber ){
        f_out("\rRebuild 100%% complete.%20c\n",
              ' '/*erase trailing REBUILD_STEP parts*/);
      }else if( 0==step->stepNumber % 10 ){
        f_out("%sRebuild %.2f%% of %" FSL_SIZE_T_PFMT " steps",
              (FSL_MSG_REBUILD==prevType) ? "\r" : "",
              (double)step->stepNumber / step->artifactCount * 100,
              step->artifactCount);
        flushOut;
      }
      goto end;
    }
    case FSL_MSG_VERIFY:{
      fsl_size_t const nLeft = *((fsl_size_t const *)msg->payload);
      if( 0==nLeft ){
        f_out("\rVerify complete.%30c\n", ' ');
      }else{
        f_out("%sVerifying: %" FSL_SIZE_T_PFMT " artifacts left",
              (FSL_MSG_VERIFY==prevType) ? "\r" : "", nLeft);
        flushOut;
      }
      goto end;
    }
    case FSL_MSG_TXN_BEGIN:
    case FSL_MSG_TXN_COMMIT:
    case FSL_MSG_TXN_ROLLBACK:
      if( fcli.config.verbose>2 ){
        f_out("%s%s level %" FSL_SIZE_T_PFMT "\n",
              (FSL_MSG_REBUILD==prevType)
            ? "\n" : "",
              zType,
              *((fsl_size_t const *)msg->payload));
      }
      return 0 /* don't record these in prevType or rebuild messages
                  get out of whack */;
  }

  switch(FSL_MSG_mask_type & msg->type){
    case FSL_MSG_type_string:
      z = (char const *)msg->payload;
      n = fsl_strlen(z);
      break;
    case FSL_MSG_type_buffer:
      z = fsl_b_cstr2(msg->payload, &n);
      break;
    case FSL_MSG_type_blob:{
      fsl_msg_blob const * const f = msg->payload;
      z = f->hash;
      n = fsl_strlen(z);
      break;
    }
    default:
      switch(FSL_MSG_mask_type & msg->type){
#define E(N,V,P) case FSL_MSG_ ## N:    \
        z = "unhandled message type: " # N; \
        n = fsl_strlen(z); \
        break;
      fsl_msg_map(E)
#undef E
      }
      break;
  }

  switch(FSL_MSG_mask_type & msg->type){
    case FSL_MSG_type_string:
      if( FSL_MSG_VERBOSE==msg->type ){
        if( !fcli.config.verbose ){
          return 0;
        }
      }
      FSL_SWITCH_FALL_THROUGH;
    case FSL_MSG_type_buffer:
    case FSL_MSG_type_blob:
      f_out("%s: %.*s\n", zType, (int)n, z);
      break;
    default:
      switch( msg->type ){
        case FSL_MSG_CONNECT:
          f_out("%s: starting trip #%" PRIi64 "\n",
                zType, *((fsl_size_t*)msg->payload));
          break;
        case FSL_MSG_ERROR:
          f_out("%s: %.*s\n", zType, (int)n, z);
          break;
        default:
          f_out("MSG: UNHANDLED TYPE %s\n", zType);
      }
      break;
  }
  end:
  prevType = msg->type;
  (void)state;
  return 0;
#undef flushOut
}

#undef FCLI_V3
#undef fcli_empty_m
#undef fcli__error
#undef MARKER
#undef FCLI_USE_SIGACTION
#undef FCLI__REPORT_SYNC_METRICS
/* end of file src/cli.c */
/* start of file src/content.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2025 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**************************************************************************
  This file houses the code for the fsl_content_xxx() APIS.
*/
#include <assert.h>
#include <memory.h> /* memcmp() */

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

fsl_int_t fsl_content_size( fsl_cx * const f, fsl_id_t blobRid ){
  if(blobRid<=0) return -3;
  else if(!fsl_needs_repo(f)) return -4;
  else{
    int rc = 0;
    fsl_int_t rv = -2;
    fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_contentSize);
    if( q ){
      rc = fsl_stmt_bind_step_v2(q, "R", blobRid);
      if(FSL_RC_STEP_ROW==rc){
        rv = (fsl_int_t)fsl_stmt_g_int64(q, 0);
      }
      fsl__cx_stmt_yield(f, q);
    }else{
       rv = -6;
    }
    return rv;
  }
}

int fsl_content_size_v2(fsl_cx * const f, fsl_id_t rid, fsl_int_t *pOut){
  int rc;
  fsl_db * const db = fsl_needs_repo(f);
  fsl_stmt * const q = db ? fsl__cx_stmt(f, fsl__cx_stmt_e_contentSize) : 0;
  if( !q ) return f->error.code;
  rc = fsl_stmt_bind_step_v2(q, "R", rid);
  switch( rc ){
    case FSL_RC_STEP_ROW:
      *pOut = fsl_stmt_g_int32(q, 0);
      rc = 0;
      break;
    case FSL_RC_STEP_DONE:
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "No such blob.rid: %"FSL_ID_T_PFMT,
                          rid);
      break;
    default:
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      break;
  }
  fsl__cx_stmt_yield(f, q);
  return rc;
}

#undef fsl__content_size_sql


bool fsl__content_is_available(fsl_cx * const f, fsl_id_t rid){
  fsl_id_t srcid = 0;
  int rc = 0, depth = 0 /* Limit delta recursion depth */;
  while( depth++ < 100000 ){
    if( fsl__cx_ptl_has(f, fsl__ptl_e_missing, rid) ){
      return false;
    }else if( fsl__cx_ptl_has(f, fsl__ptl_e_available, rid) ){
      return true;
    }else if( fsl_content_size(f, rid)<0 ){
      fsl__cx_ptl_insert(f, fsl__ptl_e_missing, rid)
        /* ignore possible OOM error - not fatal */;
      f->cache.ptl.rc = 0;
      return false;
    }
    rc = fsl_delta_r2s(f, rid, &srcid);
    if(rc) break;
    else if( 0==srcid ){
      fsl__cx_ptl_insert(f, fsl__ptl_e_available, rid)
        /* ignore possible OOM error - not fatal */;
      f->cache.ptl.rc = 0;
      return true;
    }
    rid = srcid;
  }
  if(0==rc){
    /* This "cannot happen" (never has historically, and would be
       indicative of what amounts to corruption in the repo). */
    fsl_cx_err_set(f, FSL_RC_CONSISTENCY, "delta-loop in repository");
  }
  return false;
}


int fsl_content_raw( fsl_cx * const f, fsl_id_t blobRid, fsl_b * const tgt ){
  if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  else if(blobRid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid RID for %s().", __func__);
  }
  int rc = 0;
  fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_contentBlob);
  if(!q) return f->error.code;
  rc = fsl_stmt_bind_step_v2(q, "R", blobRid);
  fsl_check_oom_rc(rc);
  if( FSL_RC_STEP_ROW==rc ){
    void const * mem = NULL;
    fsl_size_t memLen = 0;
    int64_t const sz = fsl_stmt_g_int64(q, 1);
    if(sz<0){
      rc = fsl_cx_err_set(f, FSL_RC_PHANTOM,
                          "Cannot fetch content for phantom "
                          "blob #%"FSL_ID_T_PFMT".",
                          blobRid);
    }else if(sz){
      rc = fsl_stmt_get_blob(q, 0, &mem, &memLen);
      fsl_check_oom_rc(rc);
      if(rc){
        rc = fsl_cx_err_set(f, rc,
                            "Error %R fetching blob content for "
                            "blob #%"FSL_ID_T_PFMT".", rc, blobRid);
      }else{
        fsl_b bb = fsl_b_empty;
        assert(memLen>0);
        fsl_b_external(&bb, mem, memLen);
        rc = fsl_b_uncompress(&bb, tgt);
        fsl_check_oom_rc(rc);
        if(rc && FSL_RC_OOM!=rc){
          rc = fsl_cx_err_set(f, rc,
                              "Error %R decompressing content of "
                              "blob #%"FSL_ID_T_PFMT".", rc, blobRid);
        }
      }
    }else{
      rc = 0;
      fsl_b_reuse(tgt);
    }
  }else if( FSL_RC_STEP_DONE==rc ){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "No blob found for rid %"FSL_ID_T_PFMT".",
                        blobRid);
  }else{
    fsl_check_oom_rc(rc);
    rc = fsl_cx_uplift_db_error2(f, q->db, rc);
  }
  fsl__cx_stmt_yield(f, q);
  return rc;
}

bool fsl_content_is_private(fsl_cx * const f, fsl_id_t rid){
  fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_ridIsPrivate);
  bool rv = false;
  if( q ){
    rv = FSL_RC_STEP_ROW==fsl_stmt_bind_step(q, "R", rid);
    fsl__cx_stmt_yield(f, q);
  }
  return rv;
}

/**
   Helper for f->cache.stmt members in the form of an INSERT
   or DELETE taking a ringle RID-type argument.

   MUST only be passed q values which come from fsl__cx_stmt(), and
   this functions passes it to fsl__cx_stmt_yield(). If q is NULL (as
   can happen in some error cases), it is a no-op.

   A fsl_cx transaction MUST be active when this is called
   (assert()ed).

   Returns f's current error code.
*/
static int fsl__rid_q1arg(fsl_cx * const f, fsl_id_t rid, fsl_stmt * const q){
  assert( fsl_cx_txn_level(f) );
  int rc;
  if( q ){
    assert( q->stmt );
    rc = fsl_stmt_bind_step(q, "R", rid);
    if( rc ) rc = fsl_cx_uplift_db_error2(f, q->db, rc);
    fsl__cx_stmt_yield(f, q);
  }else{
    rc = f->error.code;
    assert( rc && "Expecting that we're in an error state." );
  }
  return rc;
}

int fsl__private_rid_add(fsl_cx * const f, fsl_id_t rid){
  return fsl__rid_q1arg(
    f, rid, fsl__cx_stmt(f, fsl__cx_stmt_e_insertPrivateRid)
  );
}

int fsl__unclustered_rid_add(fsl_cx * const f, fsl_id_t rid){
  return fsl__rid_q1arg(
    f, rid, fsl__cx_stmt(f, fsl__cx_stmt_e_insertUnclusteredRid)
  );
}

int fsl__phantom_rid_add(fsl_cx * const f, fsl_id_t rid){
  return fsl__rid_q1arg(
    f, rid, fsl__cx_stmt(f, fsl__cx_stmt_e_insertPhantomRid)
  );
}

int fsl__unsent_rid_add(fsl_cx * const f, fsl_id_t rid){
  return fsl__rid_q1arg(
    f, rid, fsl__cx_stmt(f, fsl__cx_stmt_e_insertUnsentRid)
  );
}

int fsl__delta_delete(fsl_cx * const f, fsl_id_t rid){
  return fsl__rid_q1arg(
    f, rid, fsl__cx_stmt(f, fsl__cx_stmt_e_ridDelDelta)
  );
}

int fsl__private_rid_delete(fsl_cx * const f, fsl_id_t rid){
  return fsl__rid_q1arg(
    f, rid, fsl__cx_stmt(f, fsl__cx_stmt_e_ridDelPrivate)
  );
}

static int fsl__phantom_rid_delete(fsl_cx * const f, fsl_id_t rid){
  return fsl__rid_q1arg(
    f, rid, fsl__cx_stmt(f, fsl__cx_stmt_e_ridDelPhantom)
  );
}


int fsl_content_get( fsl_cx * const f, fsl_id_t rid,
                     fsl_b * const tgt ){
  fsl_db * const db = fsl_cx_db_repo(f);
  if( !tgt ) return FSL_RC_MISUSE;
  else if( rid<=0 ){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "RID %"FSL_ID_T_PFMT" is out of range.",
                          rid);
  }else if( !db ){
    return fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                          "Fossil has no repo opened.");
  }
  else{
    int rc;
    bool gotIt = false;
    bool ownTxn = false;
    fsl_id_t nextRid;
    fsl__bccache * const ac = &f->cache.blobContent;
    if( fsl__cx_ptl_has(f, fsl__ptl_e_missing, rid) ){
      /* Early out if we know the content is not available */
      return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Content of rid %" FSL_ID_T_PFMT
                            " is not available.", rid);
    }
    /* Look for the artifact in the cache first */
    if(0!=(FSL_CX_F_BLOB_CACHE & f->flags)
       && fsl_id_bag_contains(&ac->inCache, rid) ){
      fsl_size_t i;
      for(i=0; i<ac->used; ++i){
        fsl__bccache_line * const line = &ac->list[i];
        if( line->rid==rid ){
          ++ac->metrics.hits;
          rc = fsl_b_copy(tgt, &line->content);
          fsl_check_oom_rc(rc);
          line->age = ac->nextAge++;
          return rc;
        }
      }
    }
    fsl_b_reuse(tgt);
    ++ac->metrics.misses;
    if( 0==fsl_cx_txn_level(f) && !fsl__db_in_statement_or_txn(f->dbMain) ){
      /* The chain is read in several statements, and another
         connection may change it between them. Not when a running
         statement or an open transaction already prevents that, as
         when called from a host's SQL function. */
      rc = fsl_cx_txn_begin(f);
      if(rc) return rc;
      ownTxn = true;
    }
    nextRid = 0;
    rc = fsl_delta_r2s(f, rid, &nextRid);
    if(rc){
      //MARKER(("rc=%s, rid=%"FSL_ID_T_PFMT"\n", fsl_rc_cstr(rc), rid));
      fsl_check_oom_rc(rc);
      goto end;
    }
    if( nextRid == 0 ){
      /* This is not a delta, so get its raw content. */
      rc = fsl_content_raw(f, rid, tgt);
      fsl_check_oom_rc(rc);
      /*if( rc ){
        MARKER(("rc=%s, rid=%"FSL_ID_T_PFMT"\n", fsl_rc_cstr(rc), rid));
        }*/
      gotIt = 0==rc;
    }else{
      /* Looks like a delta, so let's expand it... */
      fsl_int_t n           /* number of used entries in 'a' */;
      fsl_int_t mx;
      fsl_b * const delta = &f->cache.deltaContent;
      fsl_id_t * a = NULL;
      fsl_b * const bMem =
        /* Underlying memory for `a` */
        fsl_cx_b_borrow(f);
      fsl_b * const bNext =
        /* delta-applied content */
        bMem ? fsl_cx_b_borrow(f) : 0;
      assert(nextRid>0);
      unsigned int nAlloc = 64;
      unsigned szAlloc = sizeof(fsl_id_t) * nAlloc;
      if( !bNext ){
        rc = FSL_RC_OOM;
        goto end_delta;
      }
      rc = fsl_b_reserve(bMem, szAlloc);
      if( rc ) goto end_delta;
      a = (fsl_id_t*)bMem->mem;
      a[0] = rid;
      a[1] = nextRid;
      n = 1;
      bMem->used = szAlloc;
      while( !fsl_id_bag_contains(&ac->inCache, nextRid)
             && 0==(rc=fsl_delta_r2s(f, nextRid, &nextRid))
             && (nextRid>0)){
        /* Figure out how big n needs to be... */
        ++n;
        if( n >= (fsl_int_t)nAlloc ){
          /* Expand 'a' */
          assert( rid==a[0] );
          if( n > fsl_db_g_int64(db, 0,
                                "SELECT max(rid) FROM {{dbname.repo}}.blob")){
            rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                                "Infinite loop in delta table "
                                "for rid %" FSL_ID_T_PFMT ".", rid);
            goto end_delta;
          }
          unsigned int const nAlloc2 = n * 2;
          szAlloc = nAlloc2 * sizeof(fsl_id_t);
          assert( szAlloc > bMem->used && "Else int overflow" );
          if( szAlloc < bMem->used ){
            rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                                "Overflow while calculating delta "
                                "chain length.");
            goto end_delta;
          }
          if( (rc = fsl_b_reserve(bMem, szAlloc)) ){
            goto end_delta;
          }
          /*MARKER(("deltaIds allocated = %u\n", nAlloc2));*/
          bMem->used = szAlloc;
          a = (fsl_id_t*)bMem->mem;
          assert( rid==a[0] );
          nAlloc = nAlloc2;
        }
        a[n] = nextRid;
      }
      if( rc ) goto end_delta;
      /**
         Recursively expand deltas to get the content...
      */
      mx = n;
      rc = fsl_content_get( f, a[n], tgt );
      /* MARKER(("Getting content for rid #%"FSL_ID_T_PFMT", rc=%d\n", a[n], rc)); */
      --n;
      for( ; !rc && (n>=0); --n){
        rc = fsl_content_raw(f, a[n], delta);
        /* MARKER(("Getting/applying delta rid #%"FSL_ID_T_PFMT", rc=%d\n", a[n], rc)); */
        if(rc) break;
        if(!delta->used){
          continue;
        }
        rc = fsl_b_delta_apply2(tgt, delta, bNext, &f->error);
        //assert(FSL_RC_RANGE!=rc);
        if(rc){
          if(FSL_RC_OOM!=rc){
            /* Say which link of the delta chain failed. */
            fsl_b msg = fsl_b_empty;
            fsl_b_appendf(&msg, "Cannot apply delta rid %"
                          FSL_ID_T_PFMT " to rid %" FSL_ID_T_PFMT
                          ": %s", a[n], a[n+1],
                          f->error.msg.used
                          ? fsl_b_cstr(&f->error.msg)
                          : fsl_rc_cstr(rc));
            if(!msg.errCode){
              f->error.code = rc;
              fsl_b_swap(&msg, &f->error.msg);
            }else if(!f->error.code){
              f->error.code = rc;
            }
            fsl_b_clear(&msg);
          }
          break;
        }
#if 1
        /*
           2021-03-24: in a debug build, running:

           f-parseparty -t c -c -q

           (i.e.: parse and crosslink all checkin artifacts)

           on the libfossil repo with 2003 checkins takes:

           10.5s without this cache
           5.2s with this cache

           We shave another 0.5s if we always cache instead of using
           this mysterious (mx-n)%8 heuristic.

           Later testing with f-rebuild gives much different results:
           the (mx-n)%8 heuristic provides the best results of the
           variations tested, including always caching.
        */
        //MARKER(("mx=%d, n=%d, (mx-n)%%8=%d\n",
        //(int)mx, (int)n, (int)(mx-n)%8));
        //MARKER(("nAlloc=%d\n", (int)nAlloc));
        if( (mx-n)%8==0 ){
          //MARKER(("Caching artifact %d\n", (int)a[n+1]));
          rc = fsl__bccache_insert( ac, a[n+1], tgt );
          assert(!tgt->mem && "Passed to artifact cache (even on failure).");
          if( rc ) break;
        }else{
          fsl_b_clear(tgt);
        }
#else
        if(mx){/*unused var*/}
        fsl_b_clear(tgt);
#endif
        fsl_b_swap(tgt, bNext);
        fsl_b_reuse(bNext);
      }/*for 0..n*/
      end_delta:
      fsl_cx_b_return(f, bMem);
      fsl_cx_b_return(f, bNext);
      fsl_b_reuse(delta);
      gotIt = 0==rc;
    }

    if(!rc){
      rc = fsl__cx_ptl_insert(f, gotIt
                              ? fsl__ptl_e_available
                              : fsl__ptl_e_missing,
                              rid);
    }
    end:
    if( ownTxn ){
      if( rc ) fsl_cx_txn_end(f, true);
      else rc = fsl_cx_txn_end(f, false);
    }
    return rc;
  }
}

int fsl_content_get_sym( fsl_cx * const f, char const * sym,
                         fsl_b * const tgt ){
  int rc;
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  fsl_id_t rid = 0;
  if(!f || !sym || !tgt) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  rc = fsl_sym_to_rid(f, sym, FSL_SATYPE_ANY, &rid);
  return rc ? rc : fsl_content_get(f, rid, tgt);
}

/**
    Mark artifact rid as being available now. Update f's cache to show
    that everything that was formerly unavailable because rid was
    missing is now available. Returns 0 on success. f must have an
    opened repo and rid must be valid. On error (allocation failure)
    the state of the cache is not well-defined.
*/
static int fsl__content_mark_available(fsl_cx * const f, fsl_id_t rid){
  assert(f);
  assert(rid>0);
  if( fsl__cx_ptl_has(f, fsl__ptl_e_available, rid) ) return 0;
  /* Walk the transitive closure of artifacts which are delta-encoded
     against rid (directly or indirectly) and mark them all available.

     A single artifact may be the delta source for MANY others, so we
     must enumerate every row of "delta WHERE srcid=rid" per node, not
     just the first one. The earlier implementations used
     fsl_delta_s2r(), which returns only one such child, so siblings
     stay flagged as missing and later trip FSL_RC_NOT_FOUND in
     fsl_content_get() during verify-at-commit (e.g. mid-clone). This
     mirrors fossil(1)'s content_mark_available(). */
  fsl_id_bag * const pending = fsl_id_bag_reuse(&f->cache.markAvailableCache);
  fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_deltaS2R);
  int rc = fsl_id_bag_insert(pending, rid);
  while( 0==rc && (rid = fsl_id_bag_first(pending))!=0 ){
    fsl_id_bag_remove(pending, rid);
    rc = fsl__cx_ptl_insert(f, fsl__ptl_e_available, rid);
    if( !rc ){
      fsl__cx_ptl_remove(f, fsl__ptl_e_missing, rid);
      rc = fsl_stmt_bind_id(q, 1, rid);
      if(rc) rc = fsl_cx_uplift_db_error2(f, q->db, rc);
      while( 0==rc && fsl__cx_stmt_step_each(f, q, &rc) ){
        fsl_id_t const child = fsl_stmt_g_id(q, 0);
        if( child>0 && !fsl__cx_ptl_has(f, fsl__ptl_e_available, child) ){
          rc = fsl_id_bag_insert(pending, child);
          if( 0==rc && f->cache.ptl.level>0 ){
            /* child could not be verified while rid was missing. If
               it was stored in an earlier transaction, e.g. an
               earlier sync round, its verification was skipped and
               nothing else queues it again. */
            rc = fsl__repo_verify_before_commit(f, child);
          }
        }
      }
      fsl_stmt_reset(q);
    }
  }
  fsl__cx_stmt_yield(f, q);
  return rc;
}

/**
   Attempt to parse the given RID as a deck and crosslink it. If the RID
   is not a deck, set *isDeck=false and return 0.
*/
static int fsl__attempt_crosslink(fsl_cx *f, fsl_id_t rid, bool *isADeck){
  fsl_b * const b = fsl__cx_content_buffer(f);
  int rc = fsl_content_get(f, rid, b);
  fsl_check_oom_rc(rc);
  if( 0==rc ){
    if( 36 > b->used ){
      /* Definitely not an artifact. See deck.c:fsl_might_be_artifact() */
      *isADeck = false;
      fsl__cx_content_buffer_yield(f);
      return 0;
    }
    fsl_deck deck = fsl_deck_empty;
    fsl_deck_init(f, &deck, FSL_SATYPE_ANY);
    rc = fsl_deck_parse2(&deck, b, rid);
    fsl_check_oom_rc(rc);
    assert( FSL_RC_NOT_FOUND!=rc );
    if( 0==rc ){
      *isADeck = true;
      rc = fsl__deck_crosslink(&deck);
      fsl_check_oom_rc(rc);
      assert( FSL_RC_NOT_FOUND!=rc );
    }else if( FSL_RC_SYNTAX==rc || FSL_RC_CONSISTENCY==rc ){
      /* This can't be a manifest. The rule is "if it doesn't parse
         as a manifest, it's not one," and we specifically want to
         ignore any it's-not-a-manifest parsing errors here. That
         includes FSL_RC_CONSISTENCY, which fsl_deck_parse2() returns
         for a Z-card checksum mismatch: a file whose text looks like
         an artifact but has a bad Z card is just a file. fossil(1)
         does the same by crosslinking received content with
         MC_NO_ERRORS. */
      *isADeck = false;
      rc = 0;
      //assert( !f->dbMain->doRollback );
      fsl_cx_err_reset(f);
    }
    fsl_deck_finalize(&deck);
  }
  fsl__cx_content_buffer_yield(f);
  return rc;
}

int fsl__after_dephantomize(fsl_cx * f, fsl_id_t rid, bool tryCrosslink){
  int rc = 0;
  unsigned nChildAlloc = 0;
  fsl_id_t * aChild = 0;
  fsl_b bufChild = fsl_b_empty;
  fsl_db * const db = fsl_cx_db_repo(f);
  fsl_stmt * q = NULL;

/*  MARKER(("rid %d tryCrosslink=%d\n", (int)rid, (int)tryCrosslink));  */
  bool ownXlink = false;
  assert( db );
  assert( fsl_cx_txn_level(f)>0 );
  if(f->cache.ignoreDephantomizations) return 0;
  if( !f->cache.isCrosslinking ){
    /* Crosslinking needs the state fsl__crosslink_begin() sets up
       (e.g. time_fudge) and the work fsl__crosslink_end() does.
       fossil(1) runs after_dephantomize() inside that during a sync
       or rebuild. This function also runs from verify-at-commit,
       after the caller's crosslink has ended, so start one here. */
    rc = fsl__crosslink_begin(f);
    if(rc) return rc;
    ownXlink = true;
  }
  while(rid){
    unsigned nChildUsed = 0;
    unsigned i = 0;

    /* See if we can parse it as a manifest */
    if( tryCrosslink ) {
      rc = fsl__attempt_crosslink(f, rid, &tryCrosslink);
      assert( FSL_RC_NOT_FOUND!=rc );
      if( rc ){
#if 1
        if( FSL_RC_PHANTOM==rc ){
          MARKER(("We need(?) to delay this step until the end of "
                  "sync due to phantoms\n"));
        }
#endif
        fsl__bprc(rc);
        break;
      }
    }

    {
      /* Parse all delta-manifests that depend on baseline-manifest
         rid. fsl_deck_baseline_fetch() records those in the orphan
         table when it finds the baseline missing. This must happen
         even when rid itself is not to be crosslinked (tryCrosslink
         is false), e.g. when fsl__content_put_ex() dephantomizes a
         baseline which its caller crosslinks on its own, or else the
         waiting delta-manifests are never crosslinked. fossil(1)'s
         after_dephantomize() likewise does this unconditionally. */
      q = fsl__cx_stmt(f, fsl__cx_stmt_e_afterDephantomizeOrphans);
      rc = q ? fsl_stmt_bind_id(q, 1, rid) : f->error.code;
      if(rc) break;
      while(fsl__cx_stmt_step_each(f, q, &rc)){
        fsl_id_t const child = fsl_stmt_g_id(q, 0);
        if(nChildUsed>=nChildAlloc){
          nChildAlloc = nChildAlloc*2 + 10;
          /* fsl_b_reserve() zeroes everything past bufChild.used, so
             mark the entries filled so far as used or they are lost. */
          bufChild.used = sizeof(fsl_id_t)*nChildUsed;
          rc = fsl_b_reserve(&bufChild, sizeof(fsl_id_t)*nChildAlloc);
          if(rc) goto end;
          aChild = (fsl_id_t*)bufChild.mem;
        }
        aChild[nChildUsed++] = child;
      }
      fsl__cx_stmt_yield(f, q);
      q = NULL;
      if(rc) break;
      for(i=0; i<nChildUsed; ++i){
        fsl_deck deck = fsl_deck_empty;
        rc = fsl_deck_load_rid(f, &deck, aChild[i], FSL_SATYPE_CHECKIN);
        if(!rc){
          assert(aChild[i]==deck.rid);
          rc = fsl__deck_crosslink(&deck);
        }
        fsl_deck_finalize(&deck);
        if(rc){
          fsl__bprc(rc);
          goto end;
        }
      }
      if( nChildUsed ){
        rc = fsl_cx_exec_multi(f,
                               "DELETE FROM {{dbname.repo}}.orphan "
                               "WHERE baseline=%" FSL_ID_T_PFMT "/*%s()*/",
                               rid, __func__);
        if(rc) break;
        /* Go on to the delta children of rid, as fossil(1) does. */
      }
      nChildUsed = 0;
    }

    /* Recursively dephantomize all artifacts that are derived by
    ** delta from artifact rid and which have not already been
    ** cross-linked.
    */
    q = fsl__cx_stmt(f, fsl__cx_stmt_e_afterDephantomizeDeltas);
    rc = q ? fsl_stmt_bind_id(q, 1, rid) : f->error.code;
    if(rc) break;
    while( fsl__cx_stmt_step_each(f, q, &rc) ){
      fsl_id_t const child = fsl_stmt_g_id(q, 0);
      if(nChildUsed>=nChildAlloc){
        nChildAlloc = nChildAlloc*2 + 10;
        /* See the note on the same step above. */
        bufChild.used = sizeof(fsl_id_t)*nChildUsed;
        rc = fsl_b_reserve(&bufChild, sizeof(fsl_id_t)*nChildAlloc);
        if(rc) goto end;
        aChild = (fsl_id_t*)bufChild.mem;
      }
      aChild[nChildUsed++] = child;
    }
    fsl__cx_stmt_yield(f, q);
    q = NULL;
    for(i=1; 0==rc && i<nChildUsed; ++i){
      rc = fsl__after_dephantomize(f, aChild[i], true);
    }
    if(rc) break;
    rid = nChildUsed>0 ? aChild[0] : 0;
    tryCrosslink = true;
  }
  end:
  fsl__cx_stmt_yield(f, q);
  fsl_b_clear(&bufChild);
  if( ownXlink ) rc = fsl__crosslink_end(f, rc);
  return rc;
}

int fsl__content_put_ex( fsl_cx * const f,
                         fsl_b const * pBlob,
                         fsl_uuid_cstr zUuid,
                         fsl_id_t srcId,
                         fsl_size_t uncompSize,
                         bool isPrivate,
                         fsl_id_t * outRid){
  fsl_b cmpr = fsl_b_empty;
  fsl_b hash = fsl_b_empty;
  bool markAsUnclustered = false;
  bool markAsUnsent = true;
  bool isDephantomize = false;
  bool inTrans = false;
  int const zUuidLen = zUuid ? fsl_is_uuid(zUuid) : 0;
  int rc = 0;
  fsl_size_t size = 0;
  fsl_id_t rid = 0;
  assert(f);
  assert(pBlob);
  assert(srcId==0 || zUuid!=NULL);
  assert(!zUuid || zUuidLen);
  assert( fsl_cx_txn_level(f)>0 );
  assert( f->cache.ptl.level>0 );
  if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  static const fsl_size_t MaxSize = 0x70000000
    /* Do we want FSL_BLOB_MAX_SIZE here instead? */;
  if(pBlob->used>=MaxSize || uncompSize>=MaxSize){
    /* fossil(1) uses int for all blob sizes, and therefore has a
       hard-coded limit of 2GB max size per blob. That property of the
       API is well-entrenched, and correcting it properly, including
       all algorithms which access blobs using integer indexes, would
       require a large coding effort with a non-trivial risk of
       lingering, difficult-to-trace bugs.

       Even if we could exceed that limit, SQLite would stop us, as
       it's a limit there, too.

       For compatibility, we limit ourselves to 2GB, but to ensure a
       bit of leeway, we set our limit slightly less than 2GB.
    */
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "For compatibility with fossil(1), "
                          "blobs may not exceed %d bytes in size.",
                          (int)MaxSize);
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if(rc){
    fsl__bprc(rc);
    goto end;
  }
  inTrans = true;
  if(!zUuid){
    assert(0==uncompSize);
    /* "auxiliary hash" bits from:
       https://fossil-scm.org/fossil/file?ci=c965636958eb58aa&name=src%2Fcontent.c&ln=527-537
    */
    /* First check the auxiliary hash to see if there is already an artifact
    ** that uses the auxiliary hash name */
    /* 2021-04-13: we can now use fsl_repo_blob_lookup() to do this,
       but the following code is known to work, so touching it is a
       low priority. */
    rc = fsl_cx_hash_buffer(f, true, pBlob, &hash);
    if(rc){
      if(FSL_RC_UNSUPPORTED==rc) rc = 0;
      else goto end;
    }
    assert(hash.used==0 || hash.used>=FSL_STRLEN_SHA1);
    rid = hash.used ? fsl_uuid_to_rid(f, fsl_b_cstr(&hash)) : 0;
    assert(rid>=0 && "Cannot have malformed/ambiguous UUID at this point.");
    if(!rid){
      /* No existing artifact with the auxiliary hash name.  Therefore, use
      ** the primary hash name. */
      hash.used = 0;
      rc = fsl_cx_hash_buffer(f, false, pBlob, &hash);
      if(rc) goto end;
      assert(hash.used>=FSL_STRLEN_SHA1);
    }else if(rid<0){
      assert( f->error.code );
      rc = f->error.code;
    }
  }else{
    assert( zUuidLen );
    fsl_b_external(&hash, zUuid, (fsl_int_t)zUuidLen);
  }
  assert(!rc);

  if( f->cxConfig.hashPolicy==FSL_HPOLICY_AUTO && hash.used>FSL_STRLEN_SHA1 ){
    fsl_cx_err_reset(f);
    fsl_cx_hash_policy_set(f, FSL_HPOLICY_SHA3);
    if((rc = f->error.code)) goto end;
  }

  if( uncompSize ){
    /* pBlob is compressed and uncompSize is its decompressed size.
    ** Whether content is compressed is decided only by what the
    ** caller says, never by sniffing the bytes: ordinary content can
    ** begin with a 4-byte size and a valid zlib header. The one
    ** compressed payload with a 0 decompressed size, a cfile for the
    ** empty artifact, is turned into empty raw content by the caller
    ** (fsl__rcv_file()). */
    size = uncompSize;
  }else{
    size = pBlob->used;
    if(srcId>0){
      rc = fsl_delta_applied_size(pBlob->mem, pBlob->used, &size);
      if(rc){
        /* draft-fossil-delta-format-00 (zit 477fc5f186) section
           4.1: the size query fails on an empty delta or one whose
           header integer is not followed by a newline. */
        rc = fsl_cx_err_set(f, rc, "Malformed delta header for "
                            "artifact %b (delta source rid %"
                            FSL_ID_T_PFMT "): %R",
                            &hash, srcId, rc);
        goto end;
      }
    }
  }

  {
    /* Check to see if the entry already exists and if it does whether
       or not the entry is a phantom. */
    fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_blobRidSize);
    if( !q ){
      rc = f->error.code;
      assert( rc );
      fsl__bprc(rc);
      goto end;
    }
    rc = fsl_stmt_bind_step(q, "b", &hash);
    switch(rc){
      case FSL_RC_STEP_ROW:
        rc = 0;
        rid = fsl_stmt_g_id(q, 0);
        if( fsl_stmt_g_int64(q, 1)>=0 ){
          /* The entry is not a phantom. There is nothing for us to do
             other than return the RID. */
          /*
            Reminder: the do-nothing-for-empty-phantom behaviour is
            arguable (but historical). There may(?) be(?) a corner
            case there involving an empty file. So far, so good,
            though. After all...  all empty files have the same hash.
          */
          assert(inTrans);
          fsl__cx_stmt_yield(f, q);
          fsl_cx_txn_end_v2(f,true,false);
          if(outRid) *outRid = rid;
          fsl_b_clear(&hash);
          return 0;
        }
        break;
      case 0:
        /* No entry with the same UUID currently exists */
        rid = 0;
        markAsUnclustered = true;
        break;
      default:
        fsl_cx_uplift_db_error(f, NULL);
        break;
    }
    fsl__cx_stmt_yield(f, q);
    if( rc ){
      fsl__bprc(rc);
      goto end;
    }
  }/*blob-exists check*/

#if 0
  /* Requires app-level data. We might need a client hook mechanism or
     other metadata here.
  */
  /* Construct a received-from ID if we do not already have one */
  if( f->cache.rcvId <= 0 ){
    /* FIXME: use cached statement. */
    rc = fsl_db_exec(dbR,
       "INSERT INTO {{dbname.repo}}.rcvfrom(uid, mtime, nonce, ipaddr)"
       "VALUES(%d, julianday('now'), %Q, %Q)",
       g.userUid, g.zNonce, g.zIpAddr
    );
    f->cache.rcvId = fsl_db_last_insert_id(dbR);
  }
#endif

  if( uncompSize ){
    /* Payload arrived already in fossil's on-disk compressed framing
    ** (4-byte big-endian uncompressed-size prefix + zlib stream); store
    ** verbatim. */
    fsl_b_external(&cmpr, pBlob->mem, (fsl_int_t)pBlob->used);
  }else{
    rc = fsl_b_compress(pBlob, &cmpr);
    if(rc){
      fsl__bprc(rc);
      if(FSL_RC_OOM!=rc){
        rc = fsl_cx_err_set(f, rc, "Error %R compressing content "
                            "of artifact %b.", rc, &hash);
      }
      goto end;
    }
  }

  if( rid>0 && srcId==rid ){
    /* Filling the phantom zUuid with a delta against zUuid itself
       would leave content which can never be expanded. */
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "Artifact %b cannot be "
                        "stored as a delta of itself.", &hash);
    goto end;
  }
  bool const srcIdIsZeroOrAvailable =
    (srcId==0 || 0==fsl__bccache_check_available(f, srcId));
  if( rid>0 ){
    /* We are just adding data to a phantom */
    fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_phantomPopulate);
    if( !q ){
      rc = f->error.code;
      assert( rc );
      fsl__bprc(rc);
      goto end;
    }
    rc = fsl_stmt_bind_step_v2(q, "RIBR", f->cache.rcvId, (int64_t)size,
                               &cmpr, rid);
    if( FSL_RC_STEP_DONE==rc ){
      rc = fsl__phantom_rid_delete(f, rid);
      if( !rc && srcIdIsZeroOrAvailable ){
        isDephantomize = true;
        rc = fsl__content_mark_available(f, rid);
        fsl__bprc(rc);
      }
    }else{
      assert( FSL_RC_STEP_ROW!=rc );
      fsl_cx_uplift_db_error2(f, q->db, rc);
    }
    fsl__cx_stmt_yield(f, q);
    if(rc) goto end;
  }else{
    /* We are creating a new entry */
    fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_blobInsertFull);
    if( !q ){
      rc = f->error.code;
      assert( rc );
      fsl__bprc(rc);
      goto end;
    }
    rc = fsl_stmt_bind_step_v2(q, "RIbB", f->cache.rcvId, (int64_t)size,
                               &hash, &cmpr);
    if( FSL_RC_STEP_ROW==rc ){
      rc = 0;
      rid = fsl_stmt_g_id(q, 0);
      fsl_stmt_reset(q);
      assert( rid>0 );
      if(!pBlob){
        assert(!"This cannot happen");
        fsl__fatal(FSL_RC_CANNOT_HAPPEN,"This cannot happen.");
        //rc = fsl__phantom_rid_add(f, rid);
        //markAsUnsent = false;
      }
    }else{
      assert( FSL_RC_STEP_DONE!=rc );
      fsl_cx_uplift_db_error2(f, q->db, rc);
    }
    fsl__cx_stmt_yield(f, q);
    if(rc){
      fsl__bprc(rc);
      goto end;
    }
  }
  if( f->cache.markPrivate || isPrivate ){
    /* A filled phantom is marked private as a new row is, as in
       fossil(1)'s content_put_ex(). */
    rc = fsl__private_rid_add(f, rid);
    markAsUnclustered = false;
    if(rc){
      fsl__bprc(rc);
      goto end;
    }
  }

  /* If the srcId is specified, then the data we just added is
     really a delta. Record this fact in the delta table.
  */
  if( srcId ){
    rc = fsl__delta_replace(f, rid, srcId);
    fsl__bprc(rc);
  }
  if( 0==rc
      && !isDephantomize
      && fsl__cx_ptl_has(f, fsl__ptl_e_missing, rid)
      && srcIdIsZeroOrAvailable ){
    /*
      TODO: document what this is for.
      TODO: figure out what that is.
    */
    rc = fsl__content_mark_available(f, rid);
    fsl__bprc(rc);
  }
  if( 0==rc && isDephantomize ){
#if 1
    /* 2025-08-18: This approach (delaying d14n until
       content-validation time) surives much further, but still
       eventually chokes on a not-found blob in one of the major test
       repos. It's presumably a SHUNned blob, but xfer.c doesn't yet
       read the SHUN list, so we cannot yet differentiate between
       shunned and does-not-exist. We need to side-track and add that
       support before continuing here. */
    rc = fsl__cx_ptl_insert(f, fsl__ptl_e_dephantomize, rid);
#else
    rc = fsl__after_dephantomize(f, rid, false);
#endif
    fsl__bprc(rc);
  }
  /* Add the element to the unclustered table if has never been
     previously seen.
  */
  if( 0==rc && markAsUnclustered ){
    rc = fsl__unclustered_rid_add(f, rid);
    fsl__bprc(rc);
  }
#if 0
  /* Why did we ever do this? fossil(1) does not */
  if( 0==rc && markAsUnsent ){
    rc = fsl__unsent_rid_add(f, rid);
    fsl__bprc(rc);
  }
#else
  (void)markAsUnsent;
#endif
  if( 0==rc ){
    /* Trivia: fossil(1) does this _after_ committing
       the current transaction level. */
    rc = fsl__repo_verify_before_commit(f, rid);
    fsl__bprc(rc);
  }
  if( 0==rc ){
    assert( inTrans );
    if( f->cache.ptl.validateRidLevel < 0 ){
      assert( f->cache.ptl.level>0 );
      f->cache.ptl.validateRidLevel = f->cache.ptl.level - 1
        /* This is a bit of a hack which delays RID content validation
           until after the COMMIT below.  That validation requires
           having complete content and we may have just injected delta
           content deriving from a parent we don't yet have, so
           running content validation in response to _this_ COMMIT is
           doomed to fail during sync (when we get lots of deltas). If
           validateRidLevel>=0 then another transaction level has
           already set it.

           This has to be set before txn_end is called below or else
           we'll end up validating the content as a side-effect of
           this txn_end call.
        */;
    }
    rc = fsl_cx_txn_end_v2(f, true, false);
    fsl__bprc(rc);
    inTrans = false;
    if( 0==rc && outRid ) *outRid = rid;
  }

end:
  assert( FSL_RC_STEP_DONE!=rc );
  if(inTrans){
    assert( rc );
    fsl_cx_txn_end_v2(f,false, false);
  }
  fsl_b_clear(&hash);
  fsl_b_clear(&cmpr);
  return rc;
}

int fsl__content_put( fsl_cx * const f, fsl_b const * pBlob,
                      fsl_id_t * newRid){
  return fsl__content_put_ex(f, pBlob, NULL, 0, 0, 0, newRid);
}

bool fsl_is_shunned_uuid(fsl_cx * const f, fsl_uuid_cstr zUuid){
  fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_uuidIsShunned);
  fsl_size_t nUuid;
  if( !q || zUuid==0 || zUuid[0]==0 ) return false;
  else if(FSL_STRLEN_SHA1==(nUuid=fsl_is_uuid(zUuid))
          && FSL_HPOLICY_SHUN_SHA1==f->cxConfig.hashPolicy){
    return true;
  }
  bool rv = false;
  switch( fsl_stmt_bind_step_v2(q, "s", zUuid) ){
    case FSL_RC_STEP_DONE: break;
    case FSL_RC_STEP_ROW:
      rv = true;
      break;
    default:
      fsl_cx_uplift_db_error(f, q->db);
      break;
  }
  fsl__cx_stmt_yield(f, q);
  return rv;
}

int fsl__phantom_new( fsl_cx * const f, fsl_uuid_cstr uuid,
                      bool isPrivate, fsl_id_t * const newId ){
  fsl_id_t rid = 0;
  int rc;
  int const uuidLen = uuid ? fsl_is_uuid(uuid) : 0;
  fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_contentNew);
#if FSL_API_ARMOR
  if(!uuid) return FSL_RC_MISUSE;
#endif
  assert(f);
  assert(uuid);
  assert(uuidLen);
  assert( fsl_cx_txn_level(f)>0 );
  if( !q ) return f->error.code;
  if( !uuidLen ){
    fsl__cx_stmt_yield(f, q);
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Cannot create a phantom for an invalid "
                          "artifact hash: %s", uuid);
  }
  if( fsl_is_shunned_uuid(f, uuid) ){
    /* Check this before opening a transaction: raising the error from
    ** inside one rolls back a txn that was never needed, and that
    ** rollback aborts whatever cursor the caller is stepping (e.g.
    ** fsl_repo_rebuild()'s blob scan). fossil(1)'s content_new() does
    ** likewise: nothing to do for a shunned uuid, so no transaction. */
    fsl__cx_stmt_yield(f, q);
    return fsl_cx_err_set(f, FSL_RC_SHUNNED,
                          "UUID is shunned: %s", uuid);
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if(rc){
    fsl__cx_stmt_yield(f, q);
    return rc;
  }
  rc = fsl_stmt_bind_step_v2(q, "s", uuid);
  if( FSL_RC_STEP_ROW==rc ){
    rid = fsl_stmt_g_id(q, 0);
    assert( rid>0 );
    rc = 0;
  }else{
    assert( FSL_RC_STEP_DONE!=rc );
    assert( 0!=rc );
    fsl_cx_uplift_db_error2(f, q->db, rc);
    goto end;
  }

  rc = fsl__phantom_rid_add(f, rid);
  if( 0==rc ){
    rc = (isPrivate || f->cache.markPrivate)
      ? fsl__private_rid_add(f, rid)
      : fsl__unclustered_rid_add(f, rid);
  }

  if(!rc){
    rc = fsl__cx_ptl_insert(f, fsl__ptl_e_missing, rid);
  }

  end:
  fsl__cx_stmt_yield(f, q);
  if( rc ){
    if( !f->error.code ){
      fsl_cx_err_set(f, rc, NULL);
    }
    fsl_cx_txn_end_v2(f, false, false);
  }else{
    rc = fsl_cx_txn_end_v2(f, true, false);
    if( 0==rc && newId ) *newId = rid;
  }
  return rc;
}

int fsl__content_undeltify(fsl_cx * const f, fsl_id_t rid){
  int rc;
  fsl_id_t srcid = 0;
  fsl_b x = fsl_b_empty;
  fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_contentUndeltify);
  if(!q) return f->error.code;
  if(rid<=0){
    fsl__cx_stmt_yield(f, q);
    return fsl_cx_err_set(f, FSL_RC_RANGE, "Cannot undeltify "
                          "invalid rid %" FSL_ID_T_PFMT ".", rid);
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if(rc){
    fsl__cx_stmt_yield(f, q);
    return rc;
  }
  /* Reminder: the original impl does not do this in a
     transaction, _possibly_ because it's only done from places
     where a transaction is active (that's unconfirmed).
     Nested transactions are very cheap, though. */
  rc = fsl_delta_r2s( f, rid, &srcid );
  if(rc || srcid<=0) goto end;
  rc = fsl_content_get(f, rid, &x);
  if( rc || !x.used ) goto end;
  {
    /* The blob.size column records the *uncompressed* content size.
    ** fsl_b_compress() below rewrites x in place, after which
    ** x.used is the compressed length; capture the true (uncompressed)
    ** size first. Binding x.used post-compression (the previous
    ** behavior) stored the compressed length as blob.size, leaving it
    ** inconsistent with the content and failing test-integrity
    ** (got>wanted) for any artifact undeltified during clone. */
    int64_t const uncompressedSize = (int64_t)x.used;
    rc = fsl_b_compress(&x, &x);
    if( 0==rc ){
      rc = fsl_stmt_bind_step_v2(q, "BIR", &x, uncompressedSize, rid);
      if(FSL_RC_STEP_DONE==rc){
        rc = fsl__delta_delete(f, rid);
      }else{
        assert( rc );
        goto dberr;
      }
    }else if(FSL_RC_OOM!=rc){
      rc = fsl_cx_err_set(f, rc, "Error %R compressing undeltified "
                          "content of rid %" FSL_ID_T_PFMT ".", rc, rid);
    }
  }
#if 0
  /*
    fossil does not do this, but that seems like an inconsistency.

    On that topic Richard says:

    "When you undelta an artifact, however, it is then stored as
    plain text.  (Actually, as zlib compressed plain text.)  There
    is no possibility of delta loops or bugs in the delta encoder or
    missing source artifacts.  And so there is much less of a chance
    of losing content.  Hence, I didn't see the need to verify the
    content of artifacts that are undelta-ed."

    Potential TODO: f->flags FSL_CX_F_PEDANTIC_VERIFICATION, which
    enables the R-card and this check, and any similarly
    possibly-superfluous ones.
  */
  if(!rc) fsl__repo_verify_before_commit(f, rid);
#endif
end:
  fsl__cx_stmt_yield(f, q);
  fsl_b_clear(&x);
  if(rc) fsl_cx_txn_end(f, true);
  else rc = fsl_cx_txn_end(f, false);
  return rc;
dberr:
  assert(rc);
  rc = fsl_cx_uplift_db_error2(f, NULL, rc);
  goto end;
}

int fsl__content_deltify(fsl_cx * f, fsl_id_t rid,
                        fsl_id_t srcid, bool force){
  fsl_id_t s;
  fsl_b data = fsl_b_empty;
  fsl_b src = fsl_b_empty;
  fsl_b * delta = 0;
  int rc = 0;
  enum { MinSizeThreshold = 50 };
#if FSL_API_ARMOR
  if(rid<=0 || srcid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Cannot deltify rid %" FSL_ID_T_PFMT
                          " against rid %" FSL_ID_T_PFMT
                          ": both must be positive.", rid, srcid);
  }
  else if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  else if( srcid==rid ) return 0;
#else
  assert( rid>0 );
  assert( srcid>0 );
  assert( srcid!=rid );
  assert( fsl_needs_repo(f) );
#endif
  if(!fsl__content_is_available(f, rid)
     || !fsl__content_is_available(f, srcid)){
    /* Deltification is only a storage optimization. fossil(1) skips a
       source it cannot read (content_get() yields an empty blob, which
       its size check discards), and a sync can crosslink a check-in
       before all of its files have arrived. */
    return 0;
  }
  //TODO (2025-08-06): assert( fsl_cx_txn_level(f)>0 );
  if(!force){
    fsl_id_t tmpRid = 0;
    rc = fsl_delta_r2s(f, rid, &tmpRid);
    if( tmpRid>0 || 0!=rc ){
      /* if 0==rc then we already have a delta, it seems. Nothing left
         to do :-D. Should we return FSL_RC_ALREADY_EXISTS here? (Much
         later: no, as that would only complicate where this is used.)
      */
      return rc;
    }
  }

  if( fsl_content_is_private(f, srcid)
      && !fsl_content_is_private(f, rid) ){
    /*
      See API doc comments about crossing the private/public
      boundaries. Do we want to report okay here or FSL_RC_ACCESS?
      Since delitifying is an internal optimization/implementation
      detail, it seems best to return 0 for this case.
    */
    return 0;
  }
  /* Compute all ancestors of srcid and make sure rid is not one of them.
  ** If rid is an ancestor of srcid, then making rid a decendent of srcid
  ** would create a delta loop. */
  s = srcid;
  while( (0==(rc=fsl_delta_r2s(f, s, &s)))
         && (s>0) ){
    if( s==rid ){
      rc = fsl__content_undeltify(f, srcid);
      break;
    }
  }
  if( rc || 0!=s ){
    return rc;
  }

  /******************************************************************
   ** As of here, don't return on error. Use (goto end) instead
   ** because buffers might need cleaning.
   ******************************************************************/
  rc = fsl_content_get(f, srcid, &src);
  if(rc || (src.used < MinSizeThreshold)
     /* See API doc comments about minimum size to delta/undelta. */
  ){
    goto end;
  }

  rc = fsl_content_get(f, rid, &data);
  if(rc || (data.used < MinSizeThreshold)) goto end;
  delta = fsl_b_reuse(&f->cache.deltaContent)
    /* reminder: this buffer is used by fsl_content_get() and this
       routine may recurse into fsl_content_get() before this line. */;
  rc = fsl_b_delta_create(&src, &data, delta);
  if( !rc && (delta->used <= (data.used * 3 / 4 /* 75% */))){
    fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_blobUpdateContent);
    if( q ){
      rc = fsl_b_compress(delta, &data);
      if( !rc ){
        rc = fsl_stmt_bind_step_v2(q, "BR", &data, rid);
        if( FSL_RC_STEP_DONE==rc ){
          rc = fsl__delta_replace(f, rid, srcid);
        }else{
          fsl_cx_uplift_db_error2(f, q->db, rc);
        }
      }
      if(!rc) fsl__repo_verify_before_commit(f, rid);
      fsl__cx_stmt_yield(f, q);
    }else{
      rc = f->error.code;
    }
  }

end:
  fsl_b_clear(&src);
  fsl_b_clear(&data);
  if( delta ) fsl_b_reuse(delta);
  if( rc && FSL_RC_OOM!=rc && !f->error.code ){
    /* fsl_b_delta_create() and fsl_b_compress() have no error
       object. */
    rc = fsl_cx_err_set(f, rc, "Error %R deltifying rid %"
                        FSL_ID_T_PFMT " against rid %" FSL_ID_T_PFMT ".",
                        rc, rid, srcid);
  }
  return rc;
}

/**
   Removes all entries from the repo's blob table which are listed in
   the shun table.
*/
int fsl__repo_shun_artifacts(fsl_cx * const f){
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  if(!f) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if(rc) return fsl_cx_uplift_db_error2(f, db, rc);
  rc = fsl_db_exec_multi(db,
                         "CREATE TEMP TABLE IF NOT EXISTS "
                         "{{temp.toshun}}(rid INTEGER PRIMARY KEY); "
                         "DELETE FROM {{temp.toshun}}; "
                         "INSERT INTO {{temp.toshun}} SELECT rid FROM {{dbname.repo}}.blob AS blob, {{dbname.repo}}.shun AS shun "
                         "WHERE blob.uuid=shun.uuid;"
  );
  if(rc) goto end;
  /* Ensure that deltas generated from the to-be-shunned data
     are unpacked into non-delta form...
  */
  rc = fsl_db_prepare(db, &q,
                      "SELECT rid FROM {{dbname.repo}}.delta WHERE srcid IN {{temp.toshun}}"
                      );
  if(rc) goto end;
  while( !rc && (fsl__cx_stmt_step_each(f, &q, &rc)) ){
    fsl_id_t const srcid = fsl_stmt_g_id(&q, 0);
    rc = fsl__content_undeltify(f, srcid);
  }
  fsl_stmt_finalize(&q);
  if(!rc){
    rc = fsl_db_exec_multi(db,
            "DELETE FROM {{dbname.repo}}.delta WHERE rid IN {{temp.toshun}};"
            "DELETE FROM {{dbname.repo}}.blob WHERE rid IN {{temp.toshun}};"
            "DELETE FROM {{temp.toshun}};"
            "DELETE FROM {{dbname.repo}}.private AS private "
            "WHERE NOT EXISTS "
            "(SELECT 1 FROM {{dbname.repo}}.blob WHERE rid=private.rid);"
    );
  }
  end:
  if(!rc) rc = fsl_db_txn_commit(db);
  else fsl_db_txn_rollback(db);
  if(rc && db->error.code && !f->error.code){
    rc = fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}

int fsl_content_make_public(fsl_cx * const f, fsl_id_t rid){
#if FSL_API_ARMOR
  if(!f) return FSL_RC_MISUSE;
  else if(!fsl_cx_db_repo(f)) return FSL_RC_NOT_A_REPO;
#else
  assert( f );
  assert( fsl_cx_db_repo(f) );
#endif
  int rc;
  if( !fsl_content_is_private(f, rid) ) return 0;
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if( rc ) return rc;
  /* As fossil(1)'s publish command does: the artifact goes into
     unsent and unclustered so that the next sync offers it to
     peers. */
  rc = fsl__private_rid_delete(f, rid);
  if( 0==rc ) rc = fsl__unsent_rid_add(f, rid);
  if( 0==rc ) rc = fsl__unclustered_rid_add(f, rid);
  if( 0==rc ) rc = fsl_cx_txn_end(f, false);
  else fsl_cx_txn_end(f, true);
  return rc;
}

/**
    Load the record ID rid and up to N-1 closest ancestors into
    the "fsl_computed_ancestors" table.
*/
static int fsl__compute_ancestors( fsl_db * const db, fsl_id_t rid,
                                   int N, bool directOnly ){
  fsl_stmt st = fsl_stmt_empty;
  int rc = fsl_db_prepare(db, &st,
    "WITH RECURSIVE "
    "  ancestor(rid, mtime) AS ("
    "    SELECT ?1, mtime "
    "      FROM {{dbname.repo}}.event AS event WHERE objid=?2 "
    "    UNION "
    "    SELECT plink.pid, event.mtime"
    "      FROM ancestor, {{dbname.repo}}.plink AS plink, {{dbname.repo}}.event AS event"
    "     WHERE plink.cid=ancestor.rid"
    "       AND event.objid=plink.pid %s"
    "     ORDER BY mtime DESC LIMIT ?3"
    "  )"
    "INSERT INTO {{temp.fsl_computed_ancestors}}"
    "  SELECT rid FROM ancestor;",
    directOnly ? "AND plink.isPrim" : ""
  );
  if(!rc){
    rc = fsl_stmt_bind_step(&st, "RRi", rid, rid, (int32_t)N);
  }
  fsl_stmt_finalize(&st);
  return rc;
}

int fsl_mtime_of_F_card(fsl_cx * const f, fsl_id_t vid,
                        fsl_card_F const * const fc,
                        fsl_time_t * const pMTime){
  if(!f || !fc) return FSL_RC_MISUSE;
  else if(vid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid check-in rid %" FSL_ID_T_PFMT
                          " for file %s.", vid, fc->name);
  }else if(!fc->uuid){
    if(pMTime) *pMTime = 0;
    return 0;
  }else{
    fsl_id_t const fid = fsl_uuid_to_rid(f, fc->uuid);
    if(fid<0){
      assert(f->error.code);
      return f->error.code;
    }else if(0==fid){
      return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "File %s [%s] is not in the repository.",
                            fc->name, fc->uuid);
    }else{
      return fsl_mtime_of_manifest_file(f, vid, fid, pMTime);
    }
  }
}

int fsl_mtime_of_manifest_file(fsl_cx * const f, fsl_id_t vid, fsl_id_t fid,
                               fsl_time_t * const pMTime){
  fsl_db * const db = fsl_needs_repo(f);
  fsl_stmt * q = NULL;
  int rc = 0;
  if(!db) return FSL_RC_NOT_A_REPO;

  if(fid<=0){
    /* Only fetch the manifest's time... */
    int64_t i = -1;
    rc = fsl_db_get_int64(db, &i,
                          "SELECT fsl_j2u(mtime) "
                          "FROM {{dbname.repo}}.event WHERE objid=%" FSL_ID_T_PFMT,
                          (fsl_id_t)vid);
    if(!rc){
      if(i<0){
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Artifact rid %" FSL_ID_T_PFMT
                            " has no timeline entry.", vid);
      }
      else if(pMTime) *pMTime = (fsl_time_t)i;
    }else{
      rc = fsl_cx_uplift_db_error2(f, db, rc);
    }
    return rc;
  }

  if( f->cache.mtimeManifest != vid ){
    /*
      Computing (and keeping) ancestors is relatively costly, so we
      keep only the copy associated with f->cache.mtimeManifest
      around. For the general case, we will be feeding this function
      files from the same manifest.
    */
    f->cache.mtimeManifest = vid;
    rc = fsl_db_exec_multi(db, "CREATE TEMP TABLE IF NOT EXISTS "
                           "{{temp.fsl_computed_ancestors}}"
                           "(x INTEGER PRIMARY KEY); "
                           "DELETE FROM {{temp.fsl_computed_ancestors}};");
    if(!rc){
      rc = fsl__compute_ancestors(db, vid, 1000000, 1);
    }
    if(rc){
      /* The ancestors table is incomplete, so do not reuse it. */
      f->cache.mtimeManifest = 0;
      return fsl_cx_uplift_db_error2(f, db, rc);
    }
  }
  rc = fsl_db_prepare_cached(db, &q,
    "SELECT fsl_j2u(max(event.mtime)) FROM {{dbname.repo}}.mlink AS mlink, {{dbname.repo}}.event AS event"
    " WHERE mlink.mid=event.objid"
    "   AND mlink.fid=?"
    "   AND +mlink.mid IN {{temp.fsl_computed_ancestors}}"
  );
  if(!rc){
    fsl_stmt_bind_id(q, 1, fid);
    rc = fsl_stmt_step(q);
    if( FSL_RC_STEP_ROW==rc ){
      rc = 0;
      if(pMTime) *pMTime = (fsl_time_t)fsl_stmt_g_int64(q, 0);
    }else{
      assert(rc);
      if(FSL_RC_STEP_DONE==rc) rc = FSL_RC_NOT_FOUND;
      else rc = fsl_cx_uplift_db_error2(f, db, rc);
    }
    fsl_stmt_cached_yield(q);
    /* Reminder: DO NOT clean up fsl_computed ancestors here. Doing so
       is not only costly later on but also breaks test code. */
  }else{
    rc = fsl_cx_uplift_db_error2(f, db, rc);
  }
  return rc;
}

int fsl_card_F_content( fsl_cx * f, fsl_card_F const * fc,
                        fsl_b * const dest ){
  if(!f || !fc || !dest) return FSL_RC_MISUSE;
  else if(!fc->uuid){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Cannot fetch content of deleted file %s "
                          "because it has no UUID.", fc->name);
  }
  else if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  else{
    fsl_id_t const rid = fsl_uuid_to_rid(f, fc->uuid);
    if(!rid) return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                                   "File %s [%s] is not in the "
                                   "repository.",
                                   fc->name, fc->uuid);
    else if(rid<0){
      assert(f->error.code);
      return f->error.code;
    }else{
      return fsl_content_get(f, rid, dest);
    }
  }
}

fsl_hash_types_e fsl_validate_hash(const char *zHash, fsl_size_t nHash){
  /* fossil(1) counterpart: hname_validate() */
  fsl_hash_types_e rc;
  switch(nHash){
    case FSL_STRLEN_SHA1: rc = FSL_HTYPE_SHA1; break;
    case FSL_STRLEN_K256: rc = FSL_HTYPE_K256; break;
    default: return FSL_HTYPE_ERROR;
  }
  return fsl_validate16(zHash, nHash) ? rc : FSL_HTYPE_ERROR;
}

const char * fsl_hash_type_name(fsl_hash_types_e h, const char *zUnknown){
  /* fossil(1) counterpart: hname_alg() */
  switch(h){
    case FSL_HTYPE_SHA1: return "SHA1";
    case FSL_HTYPE_K256: return "SHA3-256";
    default: return zUnknown;
  }
}

fsl_hash_types_e fsl_verify_blob_hash(fsl_b const * pIn,
                                      const char *zHash, int nHash){
  fsl_hash_types_e id = FSL_HTYPE_ERROR;
  switch(nHash){
    case FSL_STRLEN_SHA1:{
      fsl_sha1_cx cx;
      char hex[FSL_STRLEN_SHA1+1] = {0};
      fsl_sha1_init(&cx);
      fsl_sha1_update(&cx, pIn->mem, (unsigned)pIn->used);
      fsl_sha1_final_hex(&cx, hex);
      if(0==memcmp(hex, zHash, FSL_STRLEN_SHA1)){
        id = FSL_HTYPE_SHA1;
      }
      break;
    }
    case FSL_STRLEN_K256:{
      fsl_sha3_cx cx;
      unsigned char const * hex;
      fsl_sha3_init(&cx);
      fsl_sha3_update(&cx, pIn->mem, (unsigned)pIn->used);
      hex = fsl_sha3_end(&cx);
      if(0==memcmp(hex, zHash, FSL_STRLEN_K256)){
        id = FSL_HTYPE_K256;
      }
      break;
    }
    default:
      break;
  }
  return id;
}


int fsl__shunned_remove(fsl_cx * const f){
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  assert(fsl_cx_db_repo(f));
  rc = fsl_cx_exec_multi(f,
     "CREATE TEMP TABLE IF NOT EXISTS {{temp.toshun}}(rid INTEGER PRIMARY KEY);"
     "DELETE FROM {{temp.toshun}};"
     "INSERT INTO {{temp.toshun}} SELECT rid FROM {{dbname.repo}}.blob AS blob, {{dbname.repo}}.shun AS shun WHERE blob.uuid=shun.uuid;"
  );
  if(rc) goto end;
  rc = fsl_cx_prepare(f, &q,
     "SELECT rid FROM {{dbname.repo}}.delta WHERE srcid IN {{temp.toshun}}"
  );
  while( 0==rc && fsl__cx_stmt_step_each(f, &q, &rc) ){
    rc = fsl__content_undeltify(f, fsl_stmt_g_id(&q, 0));
  }
  fsl_stmt_finalize(&q);
  if(rc) goto end;
  rc = fsl_cx_exec_multi(f,
     "DELETE FROM {{dbname.repo}}.delta WHERE rid IN {{temp.toshun}};"
     "DELETE FROM {{dbname.repo}}.blob WHERE rid IN {{temp.toshun}};"
     "DELETE FROM {{temp.toshun}};"
     "DELETE FROM {{dbname.repo}}.private AS private "
     " WHERE NOT EXISTS (SELECT 1 FROM {{dbname.repo}}.blob WHERE rid=private.rid);"
  );
  end:
  fsl_stmt_finalize(&q);
  return rc;
}

#undef MARKER
/* end of file src/content.c */
/* start of file src/config.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**************************************************************************
  This file implements (most of) the fsl_xxx APIs related to handling
  configuration data from the db(s).
*/
#include <assert.h>
#include <stdlib.h> /* bsearch() */
#include <string.h> /* memcpy() */
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

/**
   File-local macro used to ensure that all cached statements used by
   the fsl_config_get_xxx() APIs use an equivalent string (so that
   they use the same underlying cache fsl_stmt handle).  The first %s
   represents one of the config table names (config, vvfar,
   global_config). Normally we wouldn't use %s in a cached statement,
   but we're only expecting 3 values for table here and each one will
   only be cached once. The last %s must be __FILE__.
*/
#define SELECT_FROM_CONFIG "SELECT value FROM %s%s%s%s WHERE name=?/*%s*/"

/**
   The four arguments for a "%s%s%s%s" naming config table TABLE (from
   fsl_config_table_for_role()) of config db MODE on context F: the
   repository's and checkout's tables with their schema names, so that
   no other schema's table of that name is used, and the global
   config's, on a handle of its own, without. The third is the prefix
   of prefixed checkout or repository tables (fsl__db_ckout_prefix(),
   fsl__db_repo_prefix()), which makes a valid identifier on its own,
   else "".
*/
#define FSL__CONFIG_TABLE_ARGS(F,MODE,TABLE)                    \
  fsl__config_schema(F,MODE), (*fsl__config_schema(F,MODE) ? "." : ""), \
  fsl__config_prefix(F,MODE), (TABLE)

/** The schema name, or "", for FSL__CONFIG_TABLE_ARGS(). */
static char const * fsl__config_schema(fsl_cx * const f, fsl_confdb_e m){
  switch(m){
    case FSL_CONFDB_REPO: return fsl__db_schema(f->dbMain, FSL_DBROLE_REPO);
    case FSL_CONFDB_CKOUT: return fsl__db_schema(f->dbMain, FSL_DBROLE_CKOUT);
    default: return "";
  }
}

/** The table name prefix, or "", for FSL__CONFIG_TABLE_ARGS(). */
static char const * fsl__config_prefix(fsl_cx * const f, fsl_confdb_e m){
  char const * z = NULL;
  switch(m){
    case FSL_CONFDB_REPO: z = fsl__db_repo_prefix(f->dbMain); break;
    case FSL_CONFDB_CKOUT: z = fsl__db_ckout_prefix(f->dbMain); break;
    default: break;
  }
  return z ? z : "";
}

static int fsl__confdb_to_role(fsl_confdb_e m){
  switch(m){
    case FSL_CONFDB_REPO: return FSL_DBROLE_REPO;
    case FSL_CONFDB_CKOUT: return FSL_DBROLE_CKOUT;
    case FSL_CONFDB_GLOBAL: return FSL_DBROLE_CONFIG;
    default: return FSL_DBROLE_NONE;
  }
}

/**
   Returns the name error messages use for the settings of the given
   config database.
*/
static char const * fsl__confdb_label(fsl_confdb_e m){
  switch(m){
    case FSL_CONFDB_REPO: return "repository";
    case FSL_CONFDB_CKOUT: return "checkout";
    case FSL_CONFDB_GLOBAL: return "global";
    case FSL_CONFDB_VERSIONABLE: return "versioned";
    default: return "unknown";
  }
}

/**
   Sets f's error state to report that the config database for mode
   is not opened, prefixed by zWhat, and returns rc.
*/
static int fsl__config_no_db(fsl_cx * const f, int rc, fsl_confdb_e mode,
                             char const * zWhat){
  return fsl_cx_err_set(f, rc, "%s: no %s%s database is opened", zWhat,
                        fsl__confdb_label(mode),
                        FSL_CONFDB_GLOBAL==mode ? " config" : "");
}

/**
   Reports a NULL or empty setting name: sets f's error state, if f is
   not NULL, and returns FSL_RC_MISUSE for a NULL key or FSL_RC_RANGE
   for an empty one.
*/
static int fsl__config_key_err(fsl_cx * const f, char const * key){
  int const rc = key ? FSL_RC_RANGE : FSL_RC_MISUSE;
  return f
    ? fsl_cx_err_set(f, rc, "setting name is %s", key ? "empty" : "NULL")
    : rc;
}

/**
   If rc is not 0 or FSL_RC_OOM and f's error state is not set, this
   sets f's error state to say that the operation zVerb ("set",
   "read", "unset") on the given setting in the config database for
   mode failed, with the database file and the cause: db's error
   message where db has one, else rc. A NULL db means the database is
   not opened. Clears db's error state. Returns rc.
*/
static int fsl__config_err(fsl_cx * const f, fsl_db * const db, int rc,
                           fsl_confdb_e mode, char const * zVerb,
                           char const * key){
  char const * const zDb = fsl__confdb_label(mode);
  if(!rc || FSL_RC_OOM==rc) return rc;
  if(f->error.code){
    if(db && rc==db->error.code) fsl_error_reset(&db->error);
    return rc;
  }
  if(!key) key = "";
  if(!db){
    return fsl_cx_err_set(f, rc, "cannot %s %s setting \"%s\": "
                          "no %s%s database is opened", zVerb, zDb, key,
                          zDb, FSL_CONFDB_GLOBAL==mode ? " config" : "");
  }
  char const * const zFile =
    fsl_cx_db_file_for_role(f, (fsl_dbrole_e)fsl__confdb_to_role(mode),
                            NULL);
  if(rc==db->error.code){
    rc = fsl_cx_err_set(f, rc, "cannot %s %s setting \"%s\" in %s: %b",
                        zVerb, zDb, key, zFile ? zFile : db->filename,
                        &db->error.msg);
    fsl_error_reset(&db->error);
  }else{
    rc = fsl_cx_err_set(f, rc, "cannot %s %s setting \"%s\" in %s: %R",
                        zVerb, zDb, key, zFile ? zFile : db->filename,
                        rc);
  }
  return rc;
}

char const * fsl_config_table_for_role(fsl_confdb_e mode){
  switch(mode){
    case FSL_CONFDB_REPO: return "config";
    case FSL_CONFDB_CKOUT: return "vvar";
    case FSL_CONFDB_GLOBAL: return "global_config";
    case FSL_CONFDB_VERSIONABLE: return NULL;
    default:
      assert(!"Invalid fsl_confdb_e value");
      return NULL;
  }
}

fsl_db * fsl_config_for_role(fsl_cx * const f, fsl_confdb_e mode){
  switch(mode){
    case FSL_CONFDB_REPO: return fsl_cx_db_repo(f);
    case FSL_CONFDB_CKOUT: return fsl_cx_db_ckout(f);
    case FSL_CONFDB_GLOBAL: return fsl_cx_db_config(f);
    case FSL_CONFDB_VERSIONABLE: return fsl_cx_db(f);
    default:
      assert(!"Invalid fsl_confdb_e value");
      return NULL;
  }
}

int fsl_config_versionable_filename(fsl_cx *f, char const * key,
                                    fsl_b *b){
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  else if(!key || !*key || !fsl_is_simple_pathname(key, true)){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "invalid versioned setting name: \"%s\"",
                          key ? key : "");
  }
  fsl_b_reuse(b);
  return fsl_b_appendf(b, "%s.fossil-settings/%s",
                            f->db.ckout.dir, key);
}


int fsl_config_unset( fsl_cx * const f, fsl_confdb_e mode, char const * key ){
  fsl_db * const db = fsl_config_for_role(f, mode);
  if(!key || !*key){
    return fsl_cx_err_set(f, FSL_RC_MISUSE, "setting name is %s",
                          key ? "empty" : "NULL");
  }else if(mode==FSL_CONFDB_VERSIONABLE){
    return fsl_cx_err_set(f, FSL_RC_UNSUPPORTED,
                          "cannot unset versioned setting \"%s\": "
                          "edit or remove .fossil-settings/%s instead",
                          key, key);
  }else if(!db){
    return fsl__config_err(f, NULL, FSL_RC_MISUSE, mode, "unset", key);
  }else{
    char const * table = fsl_config_table_for_role(mode);
    assert(table);
    int const rc = fsl_db_exec(db, "DELETE FROM %s%s%s%s WHERE name=%Q",
                               FSL__CONFIG_TABLE_ARGS(f, mode, table), key);
    return fsl__config_err(f, db, rc, mode, "unset", key);
  }
}

/**
   For the getters which return a default on error: if rc, the result
   of a prepare or step on db, is an error, this clears the error it
   left on db, so that no later uplift reports it.
*/
static void fsl__config_quiet(fsl_db * const db, int rc){
  if(rc && FSL_RC_STEP_ROW!=rc && FSL_RC_STEP_DONE!=rc
     && rc==db->error.code){
    fsl_error_reset(&db->error);
  }
}

int32_t fsl_config_get_int32( fsl_cx * const f, fsl_confdb_e mode,
                              int32_t dflt, char const * key ){
  int32_t rv = dflt;
  switch(mode){
    case FSL_CONFDB_VERSIONABLE:{
      char * const val = fsl_config_get_text(f, mode, key, NULL);
      if(val){
        rv = (int32_t)atoi(val);
        fsl_free(val);
      }
      break;
    }
    default: {
      fsl_db * const db = fsl_config_for_role(f, mode);
      char const * const table = fsl_config_table_for_role(mode);
      assert(table);
      if(db){
        fsl_stmt * st = NULL;
        int rc = fsl_db_prepare_cached(db, &st, SELECT_FROM_CONFIG,
                                       FSL__CONFIG_TABLE_ARGS(f, mode, table),
                                       __FILE__);
        if(st){
          st->role = fsl__confdb_to_role(mode);
          fsl_stmt_bind_text(st, 1, key, -1, 0);
          if(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(st))){
            rv = fsl_stmt_g_int32(st, 0);
          }
          fsl_stmt_cached_yield(st);
        }
        fsl__config_quiet(db, rc);
      }
      break;
    }
  }
  return rv;
}

static int fsl__config_notfound(fsl_cx * const f, int rc,
                                fsl_confdb_e mode, char const *key){
  if( FSL_RC_NOT_FOUND==rc ){
    if( FSL_CONFDB_VERSIONABLE!=mode && !fsl_config_for_role(f, mode) ){
      rc = fsl__config_no_db(f, rc, mode, "setting not found");
    }else{
      rc = fsl_cx_err_set(f, rc, "%s setting not found: %s",
                          fsl__confdb_label(mode), key);
    }
  }
  return rc;
}

int64_t fsl_config_get_int64( fsl_cx * const f, fsl_confdb_e mode,
                              int64_t dflt, char const * key ){
  int64_t rv = dflt;
  switch(mode){
    case FSL_CONFDB_VERSIONABLE:{
      char * const val = fsl_config_get_text(f, mode, key, NULL);
      if(val){
        rv = (int64_t)strtoll(val, NULL, 10);
        fsl_free(val);
      }
      break;
    }
    default: {
      fsl_db * const db = fsl_config_for_role(f, mode);
      char const * const table = fsl_config_table_for_role(mode);
      assert(table);
      if(db){
        fsl_stmt * st = NULL;
        int rc = fsl_db_prepare_cached(db, &st, SELECT_FROM_CONFIG,
                                       FSL__CONFIG_TABLE_ARGS(f, mode, table),
                                       __FILE__);
        if(st){
          st->role = fsl__confdb_to_role(mode);
          fsl_stmt_bind_text(st, 1, key, -1, 0);
          if(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(st))){
            rv = fsl_stmt_g_int64(st, 0);
          }
          fsl_stmt_cached_yield(st);
        }
        fsl__config_quiet(db, rc);
      }
      break;
    }
  }
  return rv;
}

fsl_id_t fsl_config_get_id( fsl_cx * const f, fsl_confdb_e mode,
                            fsl_id_t dflt, char const * key ){
  return (sizeof(fsl_id_t)==sizeof(int32_t))
    ? (fsl_id_t)fsl_config_get_int32(f, mode, dflt, key)
    : (fsl_id_t)fsl_config_get_int64(f, mode, dflt, key);
}

double fsl_config_get_double( fsl_cx * const f, fsl_confdb_e mode,
                              double dflt, char const * key ){
  double rv = dflt;
  switch(mode){
    case FSL_CONFDB_VERSIONABLE:{
      char * const val = fsl_config_get_text(f, mode, key, NULL);
      if(val){
        rv = strtod(val, NULL);
        fsl_free(val);
      }
      break;
    }
    default: {
      fsl_db * const db = fsl_config_for_role(f, mode);
      if(!db) break/*e.g. global config is not opened*/;
      fsl_stmt * st = NULL;
      char const * const table = fsl_config_table_for_role(mode);
      assert(table);
      int rc = fsl_db_prepare_cached(db, &st, SELECT_FROM_CONFIG,
                                     FSL__CONFIG_TABLE_ARGS(f, mode, table),
                                     __FILE__);
      if(st){
        st->role = fsl__confdb_to_role(mode);
        fsl_stmt_bind_text(st, 1, key, -1, 0);
        if(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(st))){
          rv = fsl_stmt_g_double(st, 0);
        }
        fsl_stmt_cached_yield(st);
      }
      fsl__config_quiet(db, rc);
      break;
    }
  }
  return rv;
}

/**
   Calls fsl_config_get_buffer(). If that succeeds, or fails with
   FSL_RC_NOT_FOUND, or fails at all and quietAll is true, f's error
   state is left as it was before the call, so that a lookup neither
   reports a missing setting nor clears an error the caller has yet to
   handle. Returns the result of fsl_config_get_buffer().
*/
static int fsl__config_get_buffer_q(fsl_cx * const f, fsl_confdb_e mode,
                                    char const * key, fsl_b * const b,
                                    bool quietAll){
  fsl_error saved = fsl_error_empty;
  fsl_error_propagate(&f->error, &saved);
  int const rc = fsl_config_get_buffer(f, mode, key, b);
  if(!rc || quietAll || FSL_RC_NOT_FOUND==rc){
    fsl_error_propagate(&saved, &f->error);
  }
  fsl_error_clear(&saved);
  return rc;
}

char * fsl_config_get_text( fsl_cx * const f, fsl_confdb_e mode,
                            char const * key, fsl_size_t * len ){
  char * rv = NULL;
  fsl_b val = fsl_b_empty;
  if(fsl__config_get_buffer_q(f, mode, key, &val, true)){
    if(len) *len = 0;
    fsl_b_clear(&val)/*in case of partial read failure*/;
  }else{
    if(len) *len = val.used;
    rv = fsl_b_take(&val);
  }
  return rv;
}

int fsl_config_get_buffer( fsl_cx * const f, fsl_confdb_e mode,
                           char const * key, fsl_b * const b ){
  int rc = FSL_RC_NOT_FOUND;
  fsl_b_reuse(b);
  switch(mode){
    case FSL_CONFDB_VERSIONABLE:{
      if(!fsl_needs_ckout(f)){
        rc = FSL_RC_NOT_A_CKOUT;
        break;
      }
      fsl_b * const fname = fsl__cx_scratchpad(f);
      rc = fsl_config_versionable_filename(f, key, fname);
      if(!rc){
        char const * const zFile = fsl_b_cstr(fname);
        rc = fsl__cfs_stat(f, zFile, 0, false);
        if(rc){
          if(FSL_RC_NOT_FOUND!=rc && FSL_RC_OOM!=rc){
            rc = fsl_cx_err_set(f, rc, "cannot stat versioned "
                                "setting file %s: %R", zFile, rc);
          }
        }else{
          rc = fsl__cfs_read(f, b, zFile);
          if( 0==rc ){
            fsl_b_strip_hash_comments(b);
            //MARKER(("Stripped hash comments: %s\n",b->mem));
          }else if(FSL_RC_OOM!=rc){
            rc = fsl_cx_err_set(f, rc, "cannot read versioned "
                                "setting file %s: %R", zFile, rc);
          }
        }
      }
      fsl__cx_scratchpad_yield(f,fname);
      break;
    }
    default: {
      char const * const table = fsl_config_table_for_role(mode);
      assert(table);
      fsl_db * const db = fsl_config_for_role(f, mode);
      if(!db) break;
      fsl_stmt * st = NULL;
      rc = fsl_db_prepare_cached(db, &st, SELECT_FROM_CONFIG,
                                 FSL__CONFIG_TABLE_ARGS(f, mode, table),
                                 __FILE__);
      if(rc){
        rc = fsl__config_err(f, db, rc, mode, "read", key);
        break;
      }
      st->role = fsl__confdb_to_role(mode);
      fsl_stmt_bind_text(st, 1, key, -1, 0);
      rc = fsl_stmt_step(st);
      if(FSL_RC_STEP_ROW==rc){
        fsl_size_t len = 0;
        char const * const s = fsl_stmt_g_text(st, 0, &len);
        rc = s ? fsl_b_append(b, s, len) : 0;
      }else if(FSL_RC_STEP_DONE==rc){
        rc = FSL_RC_NOT_FOUND;
      }else{
        rc = fsl__config_err(f, db, rc, mode, "read", key);
      }
      fsl_stmt_cached_yield(st);
      break;
    }
  }
  return fsl__config_notfound(f, rc, mode, key);
}

bool fsl_config_get_bool( fsl_cx * const f, fsl_confdb_e mode,
                          bool dflt, char const * key ){
  bool rv = dflt;
  switch((key && *key) ? mode : 999){
    case 999: break;
    case FSL_CONFDB_VERSIONABLE:{
      char * const val = fsl_config_get_text(f, mode, key, NULL);
      if(val){
        rv = fsl_str_bool(val);
        fsl_free(val);
      }
      break;
    }
    default:{
      int rc;
      fsl_stmt * st = NULL;
      char const * const table = fsl_config_table_for_role(mode);
      fsl_db * db;
      db = fsl_config_for_role(f, mode);
      if(!db) break;
      assert(table);
      rc = fsl_db_prepare_cached(db, &st, SELECT_FROM_CONFIG,
                                 FSL__CONFIG_TABLE_ARGS(f, mode, table),
                                 __FILE__);
      if(!rc){
        st->role = fsl__confdb_to_role(mode);
        fsl_stmt_bind_text(st, 1, key, -1, 0);
        if(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(st))){
          char const * const col = fsl_stmt_g_text(st, 0, NULL);
          rv = col ? fsl_str_bool(col) : dflt /* 0? */;
        }
        fsl_stmt_cached_yield(st);
      }
      fsl__config_quiet(db, rc);
      break;
    }
  }
  return rv;
}

/**
    Sets up a REPLACE statement for the given config db and key. On
    success 0 is returned and *st holds the cached statement. The caller
    must bind() parameter #2 and step() the statement, then
    fsl_stmt_cached_yield() it.

    Returns non-0 on error.
*/
static int fsl__config_set_prepare( fsl_cx * const f, fsl_stmt **st,
                                   fsl_confdb_e mode, char const * key ){
  char const * table = fsl_config_table_for_role(mode);
  fsl_db * const db = fsl_config_for_role(f,mode);
  assert(table);
  if(!db || !key) return FSL_RC_MISUSE;
  else if(!*key) return FSL_RC_RANGE;
  else{
    const char * sql = FSL_CONFDB_REPO==mode
      ? "REPLACE INTO %s%s%s%s(name,value,mtime) VALUES(?,?,fsl_now())/*%s()*/"
      : "REPLACE INTO %s%s%s%s(name,value) VALUES(?,?)/*%s()*/";
    int rc = fsl_db_prepare_cached(db, st, sql,
                                   FSL__CONFIG_TABLE_ARGS(f, mode, table),
                                   __func__);
    if(!rc){
      (*st)->role = fsl__confdb_to_role(mode);
      rc = fsl_stmt_bind_text(*st, 1, key, -1, 1);
    }
    return fsl__config_err(f, db, rc, mode, "set", key);
  }
}

/*
  TODO/FIXME: the fsl_config_set_xxx() routines all use the same basic
  structure, differing only in the concrete bind() op they call. They
  should be consolidated somehow.
*/

/**
   Writes valLen bytes of val to a versioned-setting file. Returns 0
   on success. Requires a checkout db.
*/
static int fsl__config_set_versionable( fsl_cx * const f, char const * key,
                                       char const * val,
                                       fsl_size_t valLen){
  assert(key && *key);
  if(!fsl_needs_ckout(f)){
    return FSL_RC_NOT_A_CKOUT;
  }
  fsl_b * fName = fsl__cx_scratchpad(f);
  int rc = fsl_config_versionable_filename(f, key, fName);
  if(!rc){
    fsl_b fake = fsl_b_empty;
    fake.mem = (void*)val;
    fake.capacity = fake.used = valLen;
    rc = fsl__cfs_write(f, &fake, fsl_b_cstr(fName));
    if(rc && FSL_RC_OOM!=rc){
      rc = fsl_cx_err_set(f, rc, "cannot write versioned setting "
                          "file %b: %R", fName, rc);
    }
  }
  fsl__cx_scratchpad_yield(f, fName);
  return rc;
}

int fsl_config_set_text( fsl_cx * const f, fsl_confdb_e mode,
                         char const * key, char const * val ){
  if(!key || !*key) return fsl__config_key_err(f, key);
  else if(FSL_CONFDB_VERSIONABLE==mode){
    return fsl__config_set_versionable(f, key, val,
                                      val ? fsl_strlen(val) : 0);
  }
  fsl_db * db = fsl_config_for_role(f,mode);
  if(!db) return fsl__config_err(f, NULL, FSL_RC_MISUSE, mode, "set", key);
  fsl_stmt * st = NULL;
  int rc = fsl__config_set_prepare(f, &st, mode, key);
  //MARKER(("config-set mode=%d k=%s v=%s\n",
  //        mode, key, val));
  if(!rc){
    if(val){
      rc = fsl_stmt_bind_text(st, 2, val, -1, 0);
    }else{
      rc = fsl_stmt_bind_null(st, 2);
    }
    if(!rc){
      rc = fsl_stmt_step(st);
    }
    fsl_stmt_cached_yield(st);
    if(FSL_RC_STEP_DONE==rc) rc = 0;
  }
  return fsl__config_err(f, db, rc, mode, "set", key);
}

int fsl_config_set_blob( fsl_cx * const f, fsl_confdb_e mode, char const * key,
                         void const * val, fsl_int_t len ){
  if(!key || !*key) return fsl__config_key_err(f, key);
  else if(FSL_CONFDB_VERSIONABLE==mode){
    return fsl__config_set_versionable(f, key, val,
                                      (val && len<0)
                                      ? fsl_strlen((char const *)val)
                                      : (fsl_size_t)len);
  }
  fsl_db * db = fsl_config_for_role(f,mode);
  if(!db) return fsl__config_err(f, NULL, FSL_RC_MISUSE, mode, "set", key);
  fsl_stmt * st = NULL;
  int rc = fsl__config_set_prepare(f, &st, mode, key);
  if(!rc){
    if(val){
      if(len<0) len = fsl_strlen((char const *)val);
      rc = fsl_stmt_bind_blob(st, 2, val, len, 0);
    }else{
      rc = fsl_stmt_bind_null(st, 2);
    }
    if(!rc){
      rc = fsl_stmt_step(st);
    }
    fsl_stmt_cached_yield(st);
    if(FSL_RC_STEP_DONE==rc) rc = 0;
  }
  return fsl__config_err(f, db, rc, mode, "set", key);
}

int fsl_config_set_int32( fsl_cx * const f, fsl_confdb_e mode,
                          char const * key, int32_t val ){
  if(!key || !*key) return fsl__config_key_err(f, key);
  else if(FSL_CONFDB_VERSIONABLE==mode){
    char buf[64] = {0};
    fsl_snprintf(buf, sizeof(buf), "%" PRIi32 "\n", val);
    return fsl__config_set_versionable(f, key, buf,
                                      fsl_strlen(buf));
  }
  fsl_db * db = fsl_config_for_role(f,mode);
  if(!db) return fsl__config_err(f, NULL, FSL_RC_MISUSE, mode, "set", key);
  fsl_stmt * st = NULL;
  int rc = fsl__config_set_prepare(f, &st, mode, key);
  if(!rc){
    rc = fsl_stmt_bind_int32(st, 2, val);
    if(!rc){
      rc = fsl_stmt_step(st);
    }
    fsl_stmt_cached_yield(st);
    if(FSL_RC_STEP_DONE==rc) rc = 0;
  }
  return fsl__config_err(f, db, rc, mode, "set", key);
}

int fsl_config_set_int64( fsl_cx * const f, fsl_confdb_e mode,
                          char const * key, int64_t val ){
  if(!key || !*key) return fsl__config_key_err(f, key);
  else if(FSL_CONFDB_VERSIONABLE==mode){
    char buf[64] = {0};
    fsl_snprintf(buf, sizeof(buf), "%" PRIi64 "\n", val);
    return fsl__config_set_versionable(f, key, buf,
                                      fsl_strlen(buf));
  }
  fsl_db * db = fsl_config_for_role(f,mode);
  if(!db) return fsl__config_err(f, NULL, FSL_RC_MISUSE, mode, "set", key);
  fsl_stmt * st = NULL;
  int rc = fsl__config_set_prepare(f, &st, mode, key);
  if(!rc){
    rc = fsl_stmt_bind_int64(st, 2, val);
    if(!rc){
      rc = fsl_stmt_step(st);
    }
    fsl_stmt_cached_yield(st);
    if(FSL_RC_STEP_DONE==rc) rc = 0;
  }
  return fsl__config_err(f, db, rc, mode, "set", key);
}

int fsl_config_set_id( fsl_cx * const f, fsl_confdb_e mode,
                          char const * key, fsl_id_t val ){
  if(!key || !*key) return fsl__config_key_err(f, key);
  else if(FSL_CONFDB_VERSIONABLE==mode){
    char buf[64] = {0};
    fsl_snprintf(buf, sizeof(buf), "%" FSL_ID_T_PFMT "\n", val);
    return fsl__config_set_versionable(f, key, buf,
                                      fsl_strlen(buf));
  }
  fsl_db * db = fsl_config_for_role(f,mode);
  if(!db) return fsl__config_err(f, NULL, FSL_RC_MISUSE, mode, "set", key);
  fsl_stmt * st = NULL;
  int rc = fsl__config_set_prepare(f, &st, mode, key);
  if(!rc){
    rc = fsl_stmt_bind_id(st, 2, val);
    if(!rc){
      rc = fsl_stmt_step(st);
    }
    fsl_stmt_cached_yield(st);
    if(FSL_RC_STEP_DONE==rc) rc = 0;
  }
  return fsl__config_err(f, db, rc, mode, "set", key);
}

int fsl_config_set_double( fsl_cx * const f, fsl_confdb_e mode,
                           char const * key, double val ){
  if(!key || !*key) return fsl__config_key_err(f, key);
  else if(FSL_CONFDB_VERSIONABLE==mode){
    char buf[128] = {0};
    fsl_snprintf(buf, sizeof(buf), "%f\n", val);
    return fsl__config_set_versionable(f, key, buf,
                                      fsl_strlen(buf));
  }
  fsl_db * db = fsl_config_for_role(f,mode);
  if(!db) return fsl__config_err(f, NULL, FSL_RC_MISUSE, mode, "set", key);
  fsl_stmt * st = NULL;
  int rc = fsl__config_set_prepare(f, &st, mode, key);
  if(!rc){
    rc = fsl_stmt_bind_double(st, 2, val);
    if(!rc){
        rc = fsl_stmt_step(st);
    }
    fsl_stmt_cached_yield(st);
    if(FSL_RC_STEP_DONE==rc) rc = 0;
  }
  return fsl__config_err(f, db, rc, mode, "set", key);
}

int fsl_config_set_bool( fsl_cx * const f, fsl_confdb_e mode,
                         char const * key, bool val ){
  if(!key || !*key) return fsl__config_key_err(f, key);
  char buf[4] = {'o','n','\n','\n'};
  if(!val){
    buf[1] = buf[2] = 'f';
  }
  if(FSL_CONFDB_VERSIONABLE==mode){
    return fsl__config_set_versionable(f, key, buf,
                                      val ? 3 : 4);
  }
  fsl_db * db = fsl_config_for_role(f,mode);
  if(!db) return fsl__config_err(f, NULL, FSL_RC_MISUSE, mode, "set", key);
  fsl_stmt * st = NULL;
  int rc = fsl__config_set_prepare(f, &st, mode, key);
  if(!rc){
    rc = fsl_stmt_bind_text(st, 2, buf, val ? 2 : 3, false);
    if(!rc){
      rc = fsl_stmt_step(st);
    }
    fsl_stmt_cached_yield(st);
    if(FSL_RC_STEP_DONE==rc) rc = 0;
  }
  return fsl__config_err(f, db, rc, mode, "set", key);
}

int fsl_config_transaction_begin(fsl_cx * const f, fsl_confdb_e mode){
  fsl_db * db = fsl_config_for_role(f,mode);
  if(!db){
    return fsl__config_no_db(f, FSL_RC_MISUSE, mode,
                             "cannot begin config transaction");
  }
  else{
    int const rc = fsl_db_txn_begin(db);
    if(rc) fsl_cx_uplift_db_error(f, db);
    return rc;
  }
}

int fsl_config_transaction_end(fsl_cx * const f, fsl_confdb_e mode, bool rollback){
  fsl_db * db = fsl_config_for_role(f,mode);
  if(!db){
    return fsl__config_no_db(f, FSL_RC_MISUSE, mode,
                             "cannot end config transaction");
  }
  else{
    int const rc = fsl_db_txn_end(db, rollback);
    if(rc) fsl_cx_uplift_db_error(f, db);
    return rc;
  }
}

int fsl_config_globs_load(fsl_cx * const f, fsl_list * const li, char const * key){
  int rc = 0;
  char * val = NULL;
  if(!f || !li || !key || !*key) return FSL_RC_MISUSE;
  else if(fsl_cx_db_ckout(f)){
    /* Try versionable settings... */
    fsl_b buf = fsl_b_empty;
    rc = fsl__config_get_buffer_q(f, FSL_CONFDB_VERSIONABLE, key, &buf,
                                  false);
    if(rc){
      switch(rc){
        case FSL_RC_NOT_FOUND:
          rc = 0;
          break;
        default:
          fsl_b_clear(&buf);
          return rc;
      }
      /* Fall through and try the next option. */
    }else{
      if(buf.mem){
        val = fsl_b_take(&buf);
      }else{
        /* Empty but existing list, so it trumps the
           repo/global settings. */;
        fsl_b_clear(&buf);
      }
      goto gotone;
    }
  }
  if(fsl_cx_db_repo(f)){
    /* See if the repo can serve us... */
    val = fsl_config_get_text(f, FSL_CONFDB_REPO, key, NULL);
    if(val) goto gotone;
    /* Else fall through and try global config... */
  }
  if(fsl_cx_db_config(f)){
    /*FIXME?: we arguably should open the global config for this if it
      is not already opened.*/
    val = fsl_config_get_text(f, FSL_CONFDB_GLOBAL, key, NULL);
    if(val) goto gotone;
  }
  gotone:
  if(val){
      rc = fsl_glob_list_parse( li, val );
      fsl_free(val);
      val = 0;
  }
  return rc;
}

/*
  TODO???: the infrastructure from fossil's configure.c and db.c which
  deals with the config db and the list of known/allowed settings.

  ==================

static const struct {
  const char *zName;   / * Name of the configuration set * /
  int groupMask;       / * Mask for that configuration set * /
  const char *zHelp;   / * What it does * /

} fslConfigGroups[] = {
  { "/email",        FSL_CONFIGSET_ADDR,  "Concealed email addresses in tickets" },
  { "/project",      FSL_CONFIGSET_PROJ,  "Project name and description"         },
  { "/skin",         FSL_CONFIGSET_SKIN | FSL_CONFIGSET_CSS,
                                      "Web interface appearance settings"    },
  { "/css",          FSL_CONFIGSET_CSS,   "Style sheet"                          },
  { "/shun",         FSL_CONFIGSET_SHUN,  "List of shunned artifacts"            },
  { "/ticket",       FSL_CONFIGSET_TKT,   "Ticket setup",                        },
  { "/user",         FSL_CONFIGSET_USER,  "Users and privilege settings"         },
  { "/xfer",         FSL_CONFIGSET_XFER,  "Transfer setup",                      },
  { "/all",          FSL_CONFIGSET_ALL,   "All of the above"                     },
  {NULL, 0, NULL}
};
 */

/*
   The following is a list of settings that we are willing to
   transfer.

   Setting names that begin with an alphabetic characters refer to
   single entries in the CONFIG table.  Setting names that begin with
   "@" are for special processing.
*/
static struct {
  const char *zName;   /* Name of the configuration parameter */
  int groupMask;       /* Which config groups is it part of */
} fslConfigXfer[] = {
  { "css",                    FSL_CONFIGSET_CSS  },

  { "header",                 FSL_CONFIGSET_SKIN },
  { "footer",                 FSL_CONFIGSET_SKIN },
  { "logo-mimetype",          FSL_CONFIGSET_SKIN },
  { "logo-image",             FSL_CONFIGSET_SKIN },
  { "background-mimetype",    FSL_CONFIGSET_SKIN },
  { "background-image",       FSL_CONFIGSET_SKIN },
  { "index-page",             FSL_CONFIGSET_SKIN },
  { "timeline-block-markup",  FSL_CONFIGSET_SKIN },
  { "timeline-max-comment",   FSL_CONFIGSET_SKIN },
  { "timeline-plaintext",     FSL_CONFIGSET_SKIN },
  { "adunit",                 FSL_CONFIGSET_SKIN },
  { "adunit-omit-if-admin",   FSL_CONFIGSET_SKIN },
  { "adunit-omit-if-user",    FSL_CONFIGSET_SKIN },

  { "th1-setup",              FSL_CONFIGSET_ALL },

  { "tcl",                    FSL_CONFIGSET_SKIN|FSL_CONFIGSET_TKT|FSL_CONFIGSET_XFER },
  { "tcl-setup",              FSL_CONFIGSET_SKIN|FSL_CONFIGSET_TKT|FSL_CONFIGSET_XFER },

  { "project-name",           FSL_CONFIGSET_PROJ },
  { "project-description",    FSL_CONFIGSET_PROJ },
  { "manifest",               FSL_CONFIGSET_PROJ },
  { "binary-glob",            FSL_CONFIGSET_PROJ },
  { "clean-glob",             FSL_CONFIGSET_PROJ },
  { "ignore-glob",            FSL_CONFIGSET_PROJ },
  { "keep-glob",              FSL_CONFIGSET_PROJ },
  { "crnl-glob",              FSL_CONFIGSET_PROJ },
  { "encoding-glob",          FSL_CONFIGSET_PROJ },
  { "empty-dirs",             FSL_CONFIGSET_PROJ },

  { "ticket-table",           FSL_CONFIGSET_TKT  },
  { "ticket-common",          FSL_CONFIGSET_TKT  },
  { "ticket-change",          FSL_CONFIGSET_TKT  },
  { "ticket-newpage",         FSL_CONFIGSET_TKT  },
  { "ticket-viewpage",        FSL_CONFIGSET_TKT  },
  { "ticket-editpage",        FSL_CONFIGSET_TKT  },
  { "ticket-reportlist",      FSL_CONFIGSET_TKT  },
  { "ticket-report-template", FSL_CONFIGSET_TKT  },
  { "ticket-key-template",    FSL_CONFIGSET_TKT  },
  { "ticket-title-expr",      FSL_CONFIGSET_TKT  },
  { "ticket-closed-expr",     FSL_CONFIGSET_TKT  },
  { "@reportfmt",             FSL_CONFIGSET_TKT  },

  { "@user",                  FSL_CONFIGSET_USER },

  { "@concealed",             FSL_CONFIGSET_ADDR },

  { "@shun",                  FSL_CONFIGSET_SHUN },

  { "xfer-common-script",     FSL_CONFIGSET_XFER },
  { "xfer-push-script",       FSL_CONFIGSET_XFER },
};

#define ARRAYLEN(X) (sizeof(X)/sizeof(X[0]))
/*
   Return a pointer to a string that contains the RHS of an IN
   operator that will select CONFIG table names that are part of the
   configuration that matches iMatch. The returned string must
   eventually be fsl_free()'d.
*/
char *fsl__config_inop_rhs(int iMask){
  fsl_b x = fsl_b_empty;
  const char *zSep = "";
  const int n = (int)ARRAYLEN(fslConfigXfer);
  int i;
  int rc = fsl_b_append(&x, "(", 1);
  for(i=0; !rc && (i<n); i++){
    if( (fslConfigXfer[i].groupMask & iMask)==0 ) continue;
    if( fslConfigXfer[i].zName[0]=='@' ) continue;
    rc = fsl_b_appendf(&x, "%s%Q", zSep, fslConfigXfer[i].zName);
    zSep = ",";
  }
  if(!rc){
    rc = fsl_b_append(&x, ")", 1);
  }
  if(rc){
    fsl_b_clear(&x);
    assert(!x.mem);
  }else{
    fsl_b_resize(&x, x.used);
  }
  return (char *)x.mem;
}

/**
   Maximum number of payload tokens (12 name/value pairs) accepted from
   a single config card, matching fossil's azToken[24].
*/
#define FSL__CFG_MAX_TOKENS 24

/**
   Returns true if z is a "safe" SQL token: a single-quoted string
   literal (with '' escapes), an x'...' blob literal, an integer
   literal, NULL, or any all-alphanumeric bareword. Anything else is
   rejected, which is what makes it safe to interpolate these tokens
   verbatim into SQL text.

   Port of fossil's safeSql() (src/configure.c).
*/
static bool fsl__cfg_safe_sql(char const * z){
  int i;
  if( !z || !*z ) return false;
  if( ('x'==z[0] || 'X'==z[0]) && '\''==z[1] ) ++z;
  if( '\''==z[0] ){
    for( i = 1; z[i]; ++i ){
      if( '\''==z[i] ){
        ++i;
        if( '\''==z[i] ) continue;
        return 0==z[i];
      }
    }
    return false;
  }
  for( i = 0; z[i]; ++i ){
    if( !fsl_isalnum(z[i]) ) return false;
  }
  return true;
}

/**
   Returns true if z consists of nothing but digits. Port of fossil's
   safeInt().
*/
static bool fsl__cfg_safe_int(char const * z){
  int i;
  if( !z || !*z ) return false;
  for( i = 0; fsl_isdigit(z[i]); ++i ){}
  return 0==z[i];
}

/**
   Extracts one whitespace-delimited bareword from *pz, NUL-terminating
   it in place, and advances *pz past it and any trailing whitespace.
   Returns NULL if only whitespace remains.

   The NUL is written over the token's own trailing separator, or not at
   all when the token already ends at the string's terminator, so this
   never writes outside the payload. Port of fossil's blob_token() +
   blob_terminate().
*/
static char * fsl__cfg_token(char ** pz){
  char * z = *pz;
  char * start;
  while( *z && fsl_isspace((unsigned char)*z) ) ++z;
  if( !*z ){ *pz = z; return NULL; }
  start = z;
  while( *z && !fsl_isspace((unsigned char)*z) ) ++z;
  if( *z ) *z++ = 0;
  while( *z && fsl_isspace((unsigned char)*z) ) ++z;
  *pz = z;
  return start;
}

/**
   Like fsl__cfg_token() but extracts a single SQL token: if the token
   starts with a single quote it runs to the matching close quote
   (skipping '' pairs) or to the end of input, else it is a
   whitespace-delimited bareword. Port of fossil's blob_sqltoken().
*/
static char * fsl__cfg_sqltoken(char ** pz){
  char * z = *pz;
  char * start;
  while( *z && fsl_isspace((unsigned char)*z) ) ++z;
  if( !*z ){ *pz = z; return NULL; }
  start = z;
  if( '\''==*z ){
    ++z;
    while( *z ){
      if( '\''==*z ){
        if( '\''!=*++z ) break;
      }
      ++z;
    }
  }else{
    while( *z && !fsl_isspace((unsigned char)*z) ) ++z;
  }
  if( *z ) *z++ = 0;
  while( *z && fsl_isspace((unsigned char)*z) ) ++z;
  *pz = z;
  return start;
}

/**
   Settings fossil(1) itself refuses to transfer as of its 2024
   hardening pass (fossil-scm.org/forum/forumpost/6179500deadf6ec7),
   even though this build's fslConfigXfer[] above still lists some of
   them under FSL_CONFIGSET_ALL. A pushed th1-setup/tcl-setup/etc from
   a compromised or malicious server would otherwise let it plant
   script config in the local repo, so the receive path denies these
   outright regardless of what fslConfigXfer[] says.
*/
static const char * const fsl__cfgSensitiveDeny[] = {
  "th1-setup", "tcl", "tcl-setup", "th1-hooks",
  "xfer-common-script", "xfer-push-script",
  "xfer-commit-script", "xfer-ticket-script",
  "default-csp", "allow-symlinks"
};

/**
   Returns the FSL_CONFIGSET_* mask fslConfigXfer[] records for the
   given unquoted /config setting name, or 0 if the name is unknown to
   this build or is in fsl__cfgSensitiveDeny. A 0 result means "skip
   this card", the same as an unrecognized wire type or group.
*/
int fsl__config_name_mask(char const * zName){
  int i;
  for( i = 0; i < (int)ARRAYLEN(fsl__cfgSensitiveDeny); ++i ){
    if( 0==fsl_strcmp(fsl__cfgSensitiveDeny[i], zName) ) return 0;
  }
  for( i = 0; i < (int)ARRAYLEN(fslConfigXfer); ++i ){
    if( '@'==fslConfigXfer[i].zName[0] ) continue;
    if( 0==fsl_strcmp(fslConfigXfer[i].zName, zName) ){
      return fslConfigXfer[i].groupMask;
    }
  }
  return 0;
}

/**
   Unquotes, in place, an azToken value which has already passed
   fsl__cfg_safe_sql(): a '...'-quoted SQL string (with '' escapes) is
   shifted left over its own quote bytes and re-terminated; a bareword
   is returned unchanged. Never called on an x'...' blob token (config
   names are never blobs).
*/
static char * fsl__cfg_unquote_inplace(char * z){
  size_t i, j;
  if( '\''!=z[0] ) return z;
  for( i = 1, j = 0; z[i]; ++i ){
    if( '\''==z[i] ){
      if( '\''==z[i+1] ){ z[j++] = '\''; ++i; continue; }
      break;
    }
    z[j++] = z[i];
  }
  z[j] = 0;
  return z;
}

/**
   The table-driven equivalent of fossil's configure_receive() aType[].

   zName's leading character is a marker, never compared: fossil uses
   '@' for table-backed types and '/' for the config table, and matches
   by skipping the first character of both sides. We only carry the
   types this build can apply; unknown wire names are silently skipped,
   exactly as fossil does, so that newer servers cannot break a clone.

   zTable and azField are used verbatim as SQL identifiers. They come
   from this table, never from the wire, so no quoting of remote data is
   involved.

   nameGated is true only for "/config": unlike the table-backed types,
   its exportability mask is a property of the individual setting name
   (azToken[1]), looked up via fsl__config_name_mask(), not a fixed
   groupMask for the whole type.
*/
static const struct fsl__cfg_rcv_type {
  char const * zName;       /* marker-prefixed wire name */
  char const * zTable;      /* target table */
  char const * zPrimKey;    /* primary key column */
  int groupMask;            /* FSL_CONFIGSET_* group; ignored if nameGated */
  bool nameGated;           /* mask is resolved per-name, see above */
  int nField;
  char const * azField[6];  /* accepted field names; others are skipped */
} fsl__cfgRcvTypes[] = {
{ "@shun", "shun", "uuid", FSL_CONFIGSET_SHUN, false, 1, {"scom", 0,0,0,0,0} },
{ "/config", "config", "name", 0, true, 1, {"value", 0,0,0,0,0} },
/* "jx" (a JSON blob of extra fields fossil(1) added later) is
** deliberately absent from both of the next two field lists: this
** build's user/reportfmt tables have no jx column. That's
** protocol-legal, not a bug -- an unwhitelisted field name is simply
** skipped per-pair (see the nToken loop below), so a real server's jx
** pair is silently dropped and every other field still applies. */
{ "@user", "user", "login", FSL_CONFIGSET_USER, false, 4,
  {"pw", "cap", "info", "photo", 0,0} },
{ "@reportfmt", "reportfmt", "title", FSL_CONFIGSET_TKT, false, 3,
  {"owner", "cols", "sqlcode", 0,0,0} },
{ "@concealed", "concealed", "hash", FSL_CONFIGSET_ADDR, false, 1,
  {"content", 0,0,0,0,0} }
};

int fsl__config_receive(fsl_cx * const f, char const * zName,
                        fsl_b * const pContent, int groupMask){
  struct fsl__cfg_rcv_type const * pType = NULL;
  char * azToken[FSL__CFG_MAX_TOKENS];
  int nToken = 0;
  int i, rc = 0;
  char * zPos;
  fsl_b sql = fsl_b_empty;
  fsl_db * const db = fsl_needs_repo(f);

  if( !db ) return FSL_RC_NOT_A_REPO;
  /* Legacy (non-'/'-prefixed) config names are ignored outright, as in
     fossil's configure_receive(). */
  if( !zName || '/'!=zName[0] ) return 0;
  for( i = 0; i < (int)ARRAYLEN(fsl__cfgRcvTypes); ++i ){
    if( 0==fsl_strcmp(fsl__cfgRcvTypes[i].zName+1, zName+1) ){
      pType = &fsl__cfgRcvTypes[i];
      break;
    }
  }
  if( !pType ) return 0 /* unknown/unsupported type: skip, never fail */;
  if( !pType->nameGated && 0==(pType->groupMask & groupMask) ) return 0;

  /* Tokenize in place. pContent is scratch space owned by the caller
     (for the sync path, xf->buf.cardPayload, which is reset per card),
     so in-place NUL termination is safe. Guarantee a terminator first:
     the tokenizers rely on the payload being a C string. */
  if( 0!=(rc = fsl_b_reserve(pContent, pContent->used+1)) ) return rc;
  pContent->mem[pContent->used] = 0;
  zPos = (char *)pContent->mem;

  while( 1 ){
    char * zTok = fsl__cfg_token(&zPos);
    char * zVal;
    if( !zTok ) break;
    zVal = fsl__cfg_sqltoken(&zPos);
    if( !zVal ) break;
    if( !fsl__cfg_safe_sql(zTok) ) return 0;
    if( nToken>0 ){
      /* Field names outside the whitelist are silently skipped, which
         is how the protocol stays forward-compatible with columns we
         do not have (e.g. jx). */
      int jj;
      for( jj = 0; jj < pType->nField; ++jj ){
        if( 0==fsl_strcmp(pType->azField[jj], zTok) ) break;
      }
      if( jj>=pType->nField ) continue;
    }else if( !fsl__cfg_safe_int(zTok) ){
      return 0;
    }
    if( !fsl__cfg_safe_sql(zVal) ) return 0;
    azToken[nToken++] = zTok;
    azToken[nToken++] = zVal;
    if( nToken >= FSL__CFG_MAX_TOKENS-1 ) break;
  }
  if( nToken<2 ) return 0;
  /* azToken[0] is the mtime, azToken[1] the primary key, and each
     subsequent pair is (column name, value). Every one of them has
     passed fsl__cfg_safe_sql()/safe_int(), so appending them verbatim
     is injection-safe by construction - the same contract fossil
     relies on. */
  if( pType->nameGated ){
    /* azToken[1] must survive intact (SQL-quoted) for the INSERT/UPDATE
       built below, so the exportability check runs against a scratch
       copy rather than unquoting in place. */
    char nameBuf[128];
    fsl_size_t const rawLen = fsl_strlen(azToken[1]);
    int settingMask = 0;
    if( rawLen < sizeof(nameBuf) ){
      memcpy(nameBuf, azToken[1], rawLen+1);
      settingMask = fsl__config_name_mask(fsl__cfg_unquote_inplace(nameBuf));
    }
    if( 0==(settingMask & groupMask) ) return 0;
  }

  rc = fsl_b_append(&sql, "INSERT OR IGNORE INTO ", -1);
  if( !rc ) rc = fsl__db_table_name(db, FSL_DBROLE_REPO, pType->zTable,
                                    true, &sql);
  if( !rc ) rc = fsl_b_appendf(&sql, "(\"%s\",mtime", pType->zPrimKey);
  for( i = 2; !rc && i < nToken; i += 2 ){
    rc = fsl_b_appendf(&sql, ",\"%s\"", azToken[i]);
  }
  if( !rc ){
    rc = fsl_b_appendf(&sql, ") VALUES(%s,%s",
                            azToken[1], azToken[0]);
  }
  for( i = 2; !rc && i < nToken; i += 2 ){
    rc = fsl_b_appendf(&sql, ",%s", azToken[i+1]);
  }
  if( !rc ) rc = fsl_b_append(&sql, ")", 1);
  if( !rc ) rc = fsl_db_exec(db, "%b", &sql);
  if( rc ) goto end;

  if( 0==fsl_db_changes_recent(db) ){
    /* The row already exists: overwrite it only if ours is newer.
    ** A NULL stored mtime must count as "older than any real value",
    ** not as "unknown, so don't touch it": SQL's `mtime<$M` evaluates
    ** to NULL (neither true nor false) when mtime IS NULL, which a
    ** WHERE clause treats as no-match, permanently blocking the
    ** overwrite. This is reachable in practice, not just in theory:
    ** fsl_repo_create()'s default-user seeding (src/repo.c) never
    ** sets user.mtime, so the very row a real /user sync card for
    ** that same login would want to update already exists with a
    ** NULL mtime before any sync ever happens. */
    fsl_b_reuse(&sql);
    rc = fsl_b_append(&sql, "UPDATE ", -1);
    if( !rc ) rc = fsl__db_table_name(db, FSL_DBROLE_REPO, pType->zTable,
                                      true, &sql);
    if( !rc ) rc = fsl_b_appendf(&sql, " SET mtime=%s", azToken[0]);
    for( i = 2; !rc && i < nToken; i += 2 ){
      rc = fsl_b_appendf(&sql, ", \"%s\"=%s", azToken[i], azToken[i+1]);
    }
    if( !rc ){
      rc = fsl_b_appendf(&sql, " WHERE \"%s\"=%s AND (mtime IS NULL OR mtime<%s)",
                              pType->zPrimKey, azToken[1], azToken[0]);
    }
    if( !rc && 0==fsl_strcmp(pType->zTable, "user")
        && fsl_cx_user_get(f) ){
      /* The repository's own user, which fsl_repo_create() seeded
      ** with setup capability and a local password, stays as it is.
      ** fossil(1)'s clone keeps it the same way, so a server cannot
      ** set the capabilities or password of the person cloning. */
      rc = fsl_b_appendf(&sql, " AND login<>%Q", fsl_cx_user_get(f));
    }
    if( !rc ) rc = fsl_db_exec(db, "%b", &sql);
  }
  end:
  if( rc && FSL_RC_OOM!=rc && !f->error.code ){
    rc = fsl_cx_err_set(f, rc, "cannot apply received %s card %s: %s",
                        zName, azToken[1], rc==db->error.code
                        ? fsl_b_cstr(&db->error.msg) : fsl_rc_cstr(rc));
    if(rc==db->error.code) fsl_error_reset(&db->error);
  }
  fsl_b_clear(&sql);
  return rc;
}

#undef FSL__CFG_MAX_TOKENS

/**
   Holds metadata for fossil-defined configuration settings.

   As of 2021, this library does NOT intend to maintain 100%
   config-entry parity with fossil, as the vast majority of its config
   settings are application-level preferences. The library will
   maintain compatibility with versionable settings and a handful of
   settings which make sense for a library-level API
   (e.g. 'ignore-glob' and 'manifest'). The majority of fossil's
   settings, however, are specific to that application and will not be
   treated specially by the library.

   @see fsl_config_ctrl_get()
   @see fsl_config_has_versionable()
   @see fsl_config_key_is_versionable()
   @see fsl_config_key_default_value()
*/
struct fsl_config_ctrl {
  /** Name of the setting */
  char const *name;
  /**
     Historical (fossil(1)) internal variable name used by
     db_set(). Not currently used by this impl.
  */
  char const *var;
  /**
     Historical (HTML UI). Width of display.  0 for boolean values.
  */
  int width;
  /**
     Is this setting versionable?
  */
  bool versionable;
  /**
     Default value
  */
  char const *defaultValue;
};
typedef struct fsl_config_ctrl fsl_config_ctrl;

/**
   If key is the name of a fossil-defined config key, this returns
   the fsl_config_ctrl value describing that configuration property,
   else it returns NULL.
*/
FSL_EXPORT fsl_config_ctrl const * fsl_config_ctrl_get(char const * key);

/**
   Returns true if key is the name of a config property
   as defined by fossil(1).
*/
FSL_EXPORT bool fsl_config_key_is_fossil(char const * key);


/**
   Returns true if key is the name of a versionable property, as
   defined by fossil(1). Returning false is NOT a guaranty that fossil
   does NOT define that setting (this library does not track _all_
   settings), but returning true is a a guarantee that it is a
   fossil-defined versionable setting.
*/
FSL_EXPORT bool fsl_config_key_is_versionable(char const * key);

/**
   If key refers to a fossil-defined configuration setting, this
   returns its default value as a NUL-terminated string. Its bytes are
   static and immutable. Returns NULL if key is not a known
   configuration key.
*/
FSL_EXPORT char const * fsl_config_key_default_value(char const * key);

/**
   Returns true if f's current checkout contains the given
   versionable configuration setting, else false.
*/
FSL_EXPORT bool fsl_config_has_versionable( fsl_cx * const f, char const * key );

static fsl_config_ctrl const fslConfigCtrl[] = {
/*
  These MUST stay sorted by name and the .defaultValue field MUST have
  a non-NULL value so that some API guarantees can be made.

  FIXME: bring this up to date wrt post-2014 fossil. Or abandon it
  altogether: it has since been decided that this library will not
  attempt to enforce application-level config constraints for the vast
  majority of fossil's config settings. The main benefit for us in
  keeping this is to be able to quickly look up versionable settings,
  as we really need to keep compatibility with fossil for those.
*/
  { "access-log",    0,                0, 0, "off"                 },
  { "allow-symlinks",0,                0, 0/*as of late 2020*/,
                                             "off"                 },
  { "auto-captcha",  "autocaptcha",    0, 0, "on"                  },
  { "auto-hyperlink",0,                0, 0, "on"                  },
  { "auto-shun",     0,                0, 0, "off"
    /* When auto-shun is on, every pull requests this list.  As of
       2026-11-13 sqlite.org/src sends 500-odd cards on every pull.
       fossil(1) defaults auto-shun to off, help text to the
       contrary (somebody ought to patch that... oh, wait). */
  },
  { "autosync",      0,                0, 0, "on"                  },
  { "binary-glob",   0,               40, 1, ""                    },
  { "clearsign",     0,                0, 0, "off"                 },
#if defined(_WIN32) || defined(__CYGWIN__) || defined(__DARWIN__) || defined(__APPLE__)
  { "case-sensitive",0,                0, 0, "off"                 },
#else
  { "case-sensitive",0,                0, 0, "on"                  },
#endif
  { "clean-glob",    0,               40, 1, ""                    },
  { "crnl-glob",     0,               40, 1, ""                    },
  { "default-perms", 0,               16, 0, "u"                   },
  { "diff-binary",   0,                0, 0, "on"                  },
  { "diff-command",  0,               40, 0, ""                    },
  { "dont-push",     0,                0, 0, "off"                 },
  { "dotfiles",      0,                0, 1, "off"                 },
  { "editor",        0,               32, 0, ""                    },
  { "empty-dirs",    0,               40, 1, ""                    },
  { "encoding-glob",  0,              40, 1, ""                    },
  { "gdiff-command", 0,               40, 0, "gdiff"               },
  { "gmerge-command",0,               40, 0, ""                    },
  { "http-port",     0,               16, 0, "8080"                },
  { "https-login",   0,                0, 0, "off"                 },
  { "ignore-glob",   0,               40, 1, ""                    },
  { "keep-glob",     0,               40, 1, ""                    },
  { "localauth",     0,                0, 0, "off"                 },
  { "main-branch",   0,               40, 0, "trunk"               },
  { "manifest",      0,                0, 1, "off"                 },
  { "max-upload",    0,               25, 0, "250000"              },
  { "mtime-changes", 0,                0, 0, "on"                  },
  { "pgp-command",   0,               40, 0, "gpg --clearsign -o " },
  { "proxy",         0,               32, 0, "off"                 },
  { "relative-paths",0,                0, 0, "on"                  },
  { "repo-cksum",    0,                0, 0, "on"                  },
  { "self-register", 0,                0, 0, "off"                 },
  { "ssh-command",   0,               40, 0, ""                    },
  { "ssl-ca-location",0,              40, 0, ""                    },
  { "ssl-identity",  0,               40, 0, ""                    },
  { "tcl",           0,                0, 0, "off"                 },
  { "tcl-setup",     0,               40, 0, ""                    },
  { "th1-setup",     0,               40, 0, ""                    },
  { "web-browser",   0,               32, 0, ""                    },
  { "white-foreground", 0,             0, 0, "off"                 },
  { 0,0,0,0,0 }
};

char *fsl__db_setting_inop_rhs(void){
  fsl_b x = fsl_b_empty;
  const char *zSep = "";
  fsl_config_ctrl const * ct = &fslConfigCtrl[0];
  int rc = fsl_b_append(&x, "(", 1);
  for( ; !rc && ct && ct->name; ++ct){
    rc = fsl_b_appendf(&x, "%s%Q", zSep, ct->name);
    zSep = ",";
  }
  if(!rc){
    rc = fsl_b_append(&x, ")", 1);
  }
  if(rc){
    fsl_b_clear(&x);
    assert(!x.mem);
  }else{
    fsl_b_resize(&x, x.used);
  }
  return (char *)x.mem;
}

static int fsl_config_ctrl_cmp(const void *lhs, const void *rhs){
  fsl_config_ctrl const * l = (fsl_config_ctrl const *)lhs;
  fsl_config_ctrl const * r = (fsl_config_ctrl const *)rhs;
  if(!l) return r ? -1 : 0;
  else if(!r) return 1;
  else return fsl_strcmp(l->name, r->name);
}

fsl_config_ctrl const * fsl_config_ctrl_get(char const * key){
  fsl_config_ctrl const * fcc;
  fsl_config_ctrl bogo = {0,0,0,0,0};
  bogo.name = key;
  fcc = (fsl_config_ctrl const *)
    bsearch( &bogo, fslConfigCtrl,
             ARRAYLEN(fslConfigCtrl) -1 /* for empty tail entry */,
             sizeof(fsl_config_ctrl),
             fsl_config_ctrl_cmp );
  return (fcc && fcc->name) ? fcc : NULL;
}

bool fsl_config_key_is_fossil(char const * key){
  fsl_config_ctrl const * fcc = fsl_config_ctrl_get(key);
  return (fcc && fcc->name) ? 1 : 0;
}

bool fsl_config_key_is_versionable(char const * key){
  fsl_config_ctrl const * fcc = fsl_config_ctrl_get(key);
  return (fcc && fcc->versionable) ? 1 : 0;
}

char const * fsl_config_key_default_value(char const * key){
  fsl_config_ctrl const * fcc = fsl_config_ctrl_get(key);
  return (fcc && fcc->name) ? fcc->defaultValue : NULL;
}

bool fsl_config_has_versionable( fsl_cx * const f, char const * key ){
  if(!f || !key || !*key || !f->db.ckout.dir) return 0;
  else if(!fsl_config_key_is_fossil(key)) return 0;
  else{
    fsl_b * fn = fsl__cx_scratchpad(f);
    int rc = fsl_config_versionable_filename(f, key, fn);
    if(!rc) rc = fsl__cfs_stat(f, fsl_b_cstr(fn), NULL, 0);
    fsl__cx_scratchpad_yield(f, fn);
    return 0==rc;
  }
}

static fsl_confdb_e fsl__char_to_confdb(char ch){
  fsl_confdb_e rc = FSL_CONFDB_NONE;
  switch(ch){
    case 'c': rc = FSL_CONFDB_CKOUT; break;
    case 'r': rc = FSL_CONFDB_REPO; break;
    case 'g': rc = FSL_CONFDB_GLOBAL; break;
    case 'v': rc = FSL_CONFDB_VERSIONABLE; break;
    default: break;
  }
  return rc;
}

#define fsl__configs_get_v(CONV) {                                      \
  char * val = fsl_config_get_text(f, FSL_CONFDB_VERSIONABLE, key, NULL); \
  if(val){ rv = CONV; fsl_free(val); goto end; } \
  break; }

#define fsl__configs_get_x1 \
  fsl_db * const db = fsl_config_for_role(f, mode); \
  char const * table = fsl_config_table_for_role(mode); \
  assert(table); \
  if(db){ \
    fsl_stmt * st = NULL; \
    int qrc = fsl_db_prepare_cached(db, &st, SELECT_FROM_CONFIG, \
                                    FSL__CONFIG_TABLE_ARGS(f, mode, table), \
                                    __FILE__);                   \
    if(st){                                                             \
      fsl_stmt_bind_text(st, 1, key, -1, 0); \
      if(FSL_RC_STEP_ROW==(qrc = fsl_stmt_step(st))){ (void)0
#define fsl__configs_get_x2 \
        fsl_stmt_cached_yield(st);            \
        goto end;                             \
      }                                       \
      fsl_stmt_cached_yield(st);              \
    }                                         \
    fsl__config_quiet(db, qrc);               \
  } \
  break

int32_t fsl_configs_get_int32(fsl_cx * const f, char const * zCfg, int32_t dflt, char const * key){
  int32_t rv = dflt;
  for( char const * z = zCfg; *z; ++z ){
    fsl_confdb_e const mode = fsl__char_to_confdb(*z);
    switch(mode){
      case FSL_CONFDB_VERSIONABLE: fsl__configs_get_v((int32_t)atoi(val));
      case FSL_CONFDB_CKOUT:
      case FSL_CONFDB_REPO:
      case FSL_CONFDB_GLOBAL: {
        fsl__configs_get_x1;
        rv = fsl_stmt_g_int32(st, 0);
        fsl__configs_get_x2;
      }
      default: continue;
    }
  }
  end:
  return rv;
}

int64_t fsl_configs_get_int64(fsl_cx * const f, char const * zCfg, int64_t dflt, char const * key){
  int64_t rv = dflt;
  for( char const * z = zCfg; *z; ++z ){
    fsl_confdb_e const mode = fsl__char_to_confdb(*z);
    switch(mode){
      case FSL_CONFDB_VERSIONABLE: fsl__configs_get_v((int64_t)strtoll(val, NULL, 10));
      case FSL_CONFDB_CKOUT:
      case FSL_CONFDB_REPO:
      case FSL_CONFDB_GLOBAL: {
        fsl__configs_get_x1;
        rv = fsl_stmt_g_int64(st, 0);
        fsl__configs_get_x2;
      }
      default: continue;
    }
  }
  end:
  return rv;
}

fsl_id_t fsl_configs_get_id(fsl_cx * const f, char const * zCfg, fsl_id_t dflt, char const * key){
  return (sizeof(fsl_id_t)==sizeof(int32_t))
    ? (fsl_id_t)fsl_configs_get_int32(f, zCfg, dflt, key)
    : (fsl_id_t)fsl_configs_get_int64(f, zCfg, dflt, key);
}

bool fsl_configs_get_bool(fsl_cx * const f, char const * zCfg, bool dflt, char const * key){
  bool rv = dflt;
  for( char const * z = zCfg; *z; ++z ){
    fsl_confdb_e const mode = fsl__char_to_confdb(*z);
    switch(mode){
      case FSL_CONFDB_VERSIONABLE: fsl__configs_get_v(fsl_str_bool(val));
      case FSL_CONFDB_CKOUT:
      case FSL_CONFDB_REPO:
      case FSL_CONFDB_GLOBAL: {
        fsl__configs_get_x1;
        char const * col = fsl_stmt_g_text(st, 0, NULL);
        rv = col ? fsl_str_bool(col) : dflt;
        fsl__configs_get_x2;
      }
      default: continue;
    }
  }
  end:
  return rv;
}

double fsl_configs_get_double(fsl_cx * const f, char const * zCfg, double dflt, char const * key){
  double rv = dflt;
  for( char const * z = zCfg; *z; ++z ){
    fsl_confdb_e const mode = fsl__char_to_confdb(*z);
    switch(mode){
      case FSL_CONFDB_VERSIONABLE: fsl__configs_get_v(strtod(val,NULL));
      case FSL_CONFDB_CKOUT:
      case FSL_CONFDB_REPO:
      case FSL_CONFDB_GLOBAL: {
        fsl__configs_get_x1;
        rv = fsl_stmt_g_double(st, 0);
        fsl__configs_get_x2;
      }
      default: continue;
    }
  }
  end:
  return rv;
}

char * fsl_configs_get_text(fsl_cx * const f, char const * zCfg, char const * key,
                            fsl_size_t * len){
  char * rv = NULL;
  fsl_b val = fsl_b_empty;
  if(fsl_configs_get_buffer(f, zCfg, key, &val)){
    if(len) *len = 0;
    fsl_b_clear(&val)/*in case of partial read failure*/;
  }else{
    if(len) *len = val.used;
    rv = fsl_b_take(&val);
  }
  return rv;
}

int fsl_configs_get_buffer(fsl_cx * const f, char const * zCfg, char const * key,
                           fsl_b * const b){
  int rc = FSL_RC_NOT_FOUND;
  fsl_b_reuse(b);
  for( char const * z = zCfg;
       (rc && FSL_RC_OOM!=rc) && *z; ++z ){
    fsl_confdb_e const mode = fsl__char_to_confdb(*z);
    switch(mode){
      case FSL_CONFDB_VERSIONABLE:
        rc = fsl__config_get_buffer_q(f, mode, key, b, true);
        if(rc && FSL_RC_OOM!=rc) rc = FSL_RC_NOT_FOUND;
        break;
      case FSL_CONFDB_CKOUT:
      case FSL_CONFDB_REPO:
      case FSL_CONFDB_GLOBAL: {
        fsl__configs_get_x1;
        fsl_size_t len = 0;
        char const * s = fsl_stmt_g_text(st, 0, &len);
        rc = s ? fsl_b_append(b, s, len) : 0;
        fsl__configs_get_x2;
      }
      default: break;
    }
  }
  end:
  return rc;
}

#undef fsl__configs_get_v
#undef fsl__configs_get_x1
#undef fsl__configs_get_x2
#undef SELECT_FROM_CONFIG
#undef MARKER
#undef ARRAYLEN
/* end of file src/config.c */
/* start of file src/ext_regexp.h */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
** 2012-11-13
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** The code in this file implements a compact but reasonably
** efficient regular-expression matcher for posix extended regular
** expressions against UTF8 text.
**
** This file is an SQLite extension.  It registers a single function
** named "regexp(A,B)" where A is the regular expression and B is the
** string to be matched.  By registering this function, SQLite will also
** then implement the "B regexp A" operator.  Note that with the function
** the regular expression comes first, but with the operator it comes
** second.
**
**  The following regular expression syntax is supported:
**
**     X*      zero or more occurrences of X
**     X+      one or more occurrences of X
**     X?      zero or one occurrences of X
**     X{p,q}  between p and q occurrences of X
**     (X)     match X
**     X|Y     X or Y
**     ^X      X occurring at the beginning of the string
**     X$      X occurring at the end of the string
**     .       Match any single character
**     \c      Character c where c is one of \{}()[]|*+?.
**     \c      C-language escapes for c in afnrtv.  ex: \t or \n
**     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
**     \xXX    Where XX is exactly 2 hex digits, unicode value XX
**     [abc]   Any single character from the set abc
**     [^abc]  Any single character not in the set abc
**     [a-z]   Any single character in the range a-z
**     [^a-z]  Any single character not in the range a-z
**     \b      Word boundary
**     \w      Word character.  [A-Za-z0-9_]
**     \W      Non-word character
**     \d      Digit
**     \D      Non-digit
**     \s      Whitespace character
**     \S      Non-whitespace character
**
** A nondeterministic finite automaton (NFA) is used for matching, so the
** performance is bounded by O(N*M) where N is the size of the regular
** expression and M is the size of the input string.  The matcher never
** exhibits exponential behavior.  Note that the X{p,q} operator expands
** to p copies of X following by q-p copies of X? and that the size of the
** regular expression in the O(N*M) performance bound is computed after
** this expansion.
*/
#if !defined NET_FOSSIL_SCM_REGEXP_H_INCLUDED
#define NET_FOSSIL_SCM_REGEXP_H_INCLUDED


#ifdef __cplusplus
extern "C" {
#endif

struct sqlite3_api_routines;

/*registers the REGEXP extension function into a sqlite3 database instance */
int fsl__regexp_init ( sqlite3* db, char** pzErrMsg,
                       const struct sqlite3_api_routines* pApi );


#ifdef __cplusplus
}
#endif

#else
#endif  /*#ifndef NET_FOSSIL_SCM_REGEXP_H_INCLUDED*/
/* end of file src/ext_regexp.h */
/* start of file src/ext_regexp.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
** 2012-11-13
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** The code in this file implements a compact but reasonably
** efficient regular-expression matcher for posix extended regular
** expressions against UTF8 text.
**
** This file is an SQLite extension.  It registers a single function
** named "regexp(A,B)" where A is the regular expression and B is the
** string to be matched.  By registering this function, SQLite will also
** then implement the "B regexp A" operator.  Note that with the function
** the regular expression comes first, but with the operator it comes
** second.
**
**  The following regular expression syntax is supported:
**
**     X*      zero or more occurrences of X
**     X+      one or more occurrences of X
**     X?      zero or one occurrences of X
**     X{p,q}  between p and q occurrences of X
**     (X)     match X
**     X|Y     X or Y
**     ^X      X occurring at the beginning of the string
**     X$      X occurring at the end of the string
**     .       Match any single character
**     \c      Character c where c is one of \{}()[]|*+?-.
**     \c      C-language escapes for c in afnrtv.  ex: \t or \n
**     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
**     \xXX    Where XX is exactly 2 hex digits, unicode value XX
**     [abc]   Any single character from the set abc
**     [^abc]  Any single character not in the set abc
**     [a-z]   Any single character in the range a-z
**     [^a-z]  Any single character not in the range a-z
**     \b      Word boundary
**     \w      Word character.  [A-Za-z0-9_]
**     \W      Non-word character
**     \d      Digit
**     \D      Non-digit
**     \s      Whitespace character
**     \S      Non-whitespace character
**
** A nondeterministic finite automaton (NFA) is used for matching, so the
** performance is bounded by O(N*M) where N is the size of the regular
** expression and M is the size of the input string.  The matcher never
** exhibits exponential behavior.  Note that the X{p,q} operator expands
** to p copies of X following by q-p copies of X? and that the size of the
** regular expression in the O(N*M) performance bound is computed after
** this expansion.
**
** To help prevent DoS attacks, the maximum size of the NFA is restricted.
*/
#include <string.h>
#include <stdlib.h>

/*
** The following #defines change the names of some functions implemented in
** this file to prevent name collisions with C-library functions of the
** same name.
*/
#define re_match   sqlite3re_match
#define re_compile sqlite3re_compile
#define re_free    sqlite3re_free

/* The end-of-input character */
#define RE_EOF            0    /* End of input */
#define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */

/* The NFA is implemented as sequence of opcodes taken from the following
** set.  Each opcode has a single integer argument.
*/
#define RE_OP_MATCH       1    /* Match the one character in the argument */
#define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
#define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
#define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
#define RE_OP_GOTO        5    /* Jump to opcode at iArg */
#define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
#define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
#define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
#define RE_OP_CC_VALUE    9    /* Single value in a character class */
#define RE_OP_CC_RANGE   10    /* Range of values in a character class */
#define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
#define RE_OP_NOTWORD    12    /* Not a perl word character */
#define RE_OP_DIGIT      13    /* digit:  [0-9] */
#define RE_OP_NOTDIGIT   14    /* Not a digit */
#define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
#define RE_OP_NOTSPACE   16    /* Not a digit */
#define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
#define RE_OP_ATSTART    18    /* Currently at the start of the string */

/* Each opcode is a "state" in the NFA */
typedef unsigned short ReStateNumber;

/* Because this is an NFA and not a DFA, multiple states can be active at
** once.  An instance of the following object records all active states in
** the NFA.  The implementation is optimized for the common case where the
** number of actives states is small.
*/
typedef struct ReStateSet {
  unsigned nState;            /* Number of current states */
  ReStateNumber *aState;      /* Current states */
} ReStateSet;

/* An input string read one character at a time.
*/
typedef struct ReInput ReInput;
struct ReInput {
  const unsigned char *z;  /* All text */
  int i;                   /* Next byte to read */
  int mx;                  /* EOF when i>=mx */
};

/* A compiled NFA (or an NFA that is in the process of being compiled) is
** an instance of the following object.
*/
typedef struct ReCompiled ReCompiled;
struct ReCompiled {
  ReInput sIn;                /* Regular expression text */
  const char *zErr;           /* Error message to return */
  char *aOp;                  /* Operators for the virtual machine */
  int *aArg;                  /* Arguments to each operator */
  unsigned (*xNextChar)(ReInput*);  /* Next character function */
  unsigned char zInit[12];    /* Initial text to match */
  int nInit;                  /* Number of bytes in zInit */
  unsigned nState;            /* Number of entries in aOp[] and aArg[] */
  unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
  unsigned mxAlloc;           /* Complexity limit */
};

/* Add a state to the given state set if it is not already there */
static void re_add_state(ReStateSet *pSet, int newState){
  unsigned i;
  for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
  pSet->aState[pSet->nState++] = (ReStateNumber)newState;
}

/* Extract the next unicode character from *pzIn and return it.  Advance
** *pzIn to the first byte past the end of the character returned.  To
** be clear:  this routine converts utf8 to unicode.  This routine is 
** optimized for the common case where the next character is a single byte.
*/
static unsigned re_next_char(ReInput *p){
  unsigned c;
  if( p->i>=p->mx ) return 0;
  c = p->z[p->i++];
  if( c>=0x80 ){
    if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
      c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
      if( c<0x80 ) c = 0xfffd;
    }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
           && (p->z[p->i+1]&0xc0)==0x80 ){
      c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
      p->i += 2;
      if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
    }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
           && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
      c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
                       | (p->z[p->i+2]&0x3f);
      p->i += 3;
      if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
    }else{
      c = 0xfffd;
    }
  }
  return c;
}
static unsigned re_next_char_nocase(ReInput *p){
  unsigned c = re_next_char(p);
  if( c>='A' && c<='Z' ) c += 'a' - 'A';
  return c;
}

/* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
static int re_word_char(int c){
  return (c>='0' && c<='9') || (c>='a' && c<='z')
      || (c>='A' && c<='Z') || c=='_';
}

/* Return true if c is a "digit" character:  [0-9] */
static int re_digit_char(int c){
  return (c>='0' && c<='9');
}

/* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
static int re_space_char(int c){
  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
}

/* Run a compiled regular expression on the zero-terminated input
** string zIn[].  Return true on a match and false if there is no match.
*/
static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
  ReStateSet aStateSet[2], *pThis, *pNext;
  ReStateNumber aSpace[100];
  ReStateNumber *pToFree;
  unsigned int i = 0;
  unsigned int iSwap = 0;
  int c = RE_START;
  int cPrev = 0;
  int rc = 0;
  ReInput in;

  in.z = zIn;
  in.i = 0;
  in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);

  /* Look for the initial prefix match, if there is one. */
  if( pRe->nInit ){
    unsigned char x = pRe->zInit[0];
    while( in.i+pRe->nInit<=in.mx 
     && (zIn[in.i]!=x ||
         strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
    ){
      in.i++;
    }
    if( in.i+pRe->nInit>in.mx ) return 0;
    c = RE_START-1;
  }

  if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
    pToFree = 0;
    aStateSet[0].aState = aSpace;
  }else{
    pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
    if( pToFree==0 ) return -1;
    aStateSet[0].aState = pToFree;
  }
  aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
  pNext = &aStateSet[1];
  pNext->nState = 0;
  re_add_state(pNext, 0);
  while( c!=RE_EOF && pNext->nState>0 ){
    cPrev = c;
    c = pRe->xNextChar(&in);
    pThis = pNext;
    pNext = &aStateSet[iSwap];
    iSwap = 1 - iSwap;
    pNext->nState = 0;
    for(i=0; i<pThis->nState; i++){
      int x = pThis->aState[i];
      switch( pRe->aOp[x] ){
        case RE_OP_MATCH: {
          if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_ATSTART: {
          if( cPrev==RE_START ) re_add_state(pThis, x+1);
          break;
        }
        case RE_OP_ANY: {
          if( c!=0 ) re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_WORD: {
          if( re_word_char(c) ) re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_NOTWORD: {
          if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_DIGIT: {
          if( re_digit_char(c) ) re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_NOTDIGIT: {
          if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_SPACE: {
          if( re_space_char(c) ) re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_NOTSPACE: {
          if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_BOUNDARY: {
          if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
          break;
        }
        case RE_OP_ANYSTAR: {
          re_add_state(pNext, x);
          re_add_state(pThis, x+1);
          break;
        }
        case RE_OP_FORK: {
          re_add_state(pThis, x+pRe->aArg[x]);
          re_add_state(pThis, x+1);
          break;
        }
        case RE_OP_GOTO: {
          re_add_state(pThis, x+pRe->aArg[x]);
          break;
        }
        case RE_OP_ACCEPT: {
          rc = 1;
          goto re_match_end;
        }
        case RE_OP_CC_EXC: {
          if( c==0 ) break;
          /* fall-through */ goto re_op_cc_inc;
        }
        case RE_OP_CC_INC: re_op_cc_inc: {
          int j = 1;
          int n = pRe->aArg[x];
          int hit = 0;
          for(j=1; j>0 && j<n; j++){
            if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
              if( pRe->aArg[x+j]==c ){
                hit = 1;
                j = -1;
              }
            }else{
              if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
                hit = 1;
                j = -1;
              }else{
                j++;
              }
            }
          }
          if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
          if( hit ) re_add_state(pNext, x+n);
          break;
        }
      }
    }
  }
  for(i=0; i<pNext->nState; i++){
    int x = pNext->aState[i];
    while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
    if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
  }
re_match_end:
  sqlite3_free(pToFree);
  return rc;
}

/* Resize the opcode and argument arrays for an RE under construction.
*/
static int re_resize(ReCompiled *p, unsigned int N){
  char *aOp;
  int *aArg;
  if( N>p->mxAlloc ){ p->zErr = "REGEXP pattern too big"; return 1; }
  aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
  if( aOp==0 ){ p->zErr = "out of memory"; return 1; }
  p->aOp = aOp;
  aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
  if( aArg==0 ){ p->zErr = "out of memory"; return 1; }
  p->aArg = aArg;
  p->nAlloc = N;
  return 0;
}

/* Insert a new opcode and argument into an RE under construction.  The
** insertion point is just prior to existing opcode iBefore.
*/
static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
  int i;
  if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
  for(i=p->nState; i>iBefore; i--){
    p->aOp[i] = p->aOp[i-1];
    p->aArg[i] = p->aArg[i-1];
  }
  p->nState++;
  p->aOp[iBefore] = (char)op;
  p->aArg[iBefore] = arg;
  return iBefore;
}

/* Append a new opcode and argument to the end of the RE under construction.
*/
static int re_append(ReCompiled *p, int op, int arg){
  return re_insert(p, p->nState, op, arg);
}

/* Make a copy of N opcodes starting at iStart onto the end of the RE
** under construction.
*/
static void re_copy(ReCompiled *p, int iStart, unsigned int N){
  if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
  memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
  memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
  p->nState += N;
}

/* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
** c is not a hex digit *pV is unchanged.
*/
static int re_hex(int c, int *pV){
  if( c>='0' && c<='9' ){
    c -= '0';
  }else if( c>='a' && c<='f' ){
    c -= 'a' - 10;
  }else if( c>='A' && c<='F' ){
    c -= 'A' - 10;
  }else{
    return 0;
  }
  *pV = (*pV)*16 + (c & 0xff);
  return 1;
}

/* A backslash character has been seen, read the next character and
** return its interpretation.
*/
static unsigned re_esc_char(ReCompiled *p){
  static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]-";
  static const char zTrans[] = "\a\f\n\r\t\v";
  int i, v = 0;
  char c;
  if( p->sIn.i>=p->sIn.mx ) return 0;
  c = p->sIn.z[p->sIn.i];
  if( c=='u' && p->sIn.i+4<p->sIn.mx ){
    const unsigned char *zIn = p->sIn.z + p->sIn.i;
    if( re_hex(zIn[1],&v)
     && re_hex(zIn[2],&v)
     && re_hex(zIn[3],&v)
     && re_hex(zIn[4],&v)
    ){
      p->sIn.i += 5;
      return v;
    }
  }
  if( c=='x' && p->sIn.i+2<p->sIn.mx ){
    const unsigned char *zIn = p->sIn.z + p->sIn.i;
    if( re_hex(zIn[1],&v)
     && re_hex(zIn[2],&v)
    ){
      p->sIn.i += 3;
      return v;
    }
  }
  for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
  if( zEsc[i] ){
    if( i<6 ) c = zTrans[i];
    p->sIn.i++;
  }else{
    p->zErr = "unknown \\ escape";
  }
  return c;
}

/* Forward declaration */
static const char *re_subcompile_string(ReCompiled*);

/* Peek at the next byte of input */
static unsigned char rePeek(ReCompiled *p){
  return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
}

/* Compile RE text into a sequence of opcodes.  Continue up to the
** first unmatched ")" character, then return.  If an error is found,
** return a pointer to the error message string.
*/
static const char *re_subcompile_re(ReCompiled *p){
  const char *zErr;
  int iStart, iEnd, iGoto;
  iStart = p->nState;
  zErr = re_subcompile_string(p);
  if( zErr ) return zErr;
  while( rePeek(p)=='|' ){
    iEnd = p->nState;
    re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
    iGoto = re_append(p, RE_OP_GOTO, 0);
    p->sIn.i++;
    zErr = re_subcompile_string(p);
    if( zErr ) return zErr;
    p->aArg[iGoto] = p->nState - iGoto;
  }
  return 0;
}

/* Compile an element of regular expression text (anything that can be
** an operand to the "|" operator).  Return NULL on success or a pointer
** to the error message if there is a problem.
*/
static const char *re_subcompile_string(ReCompiled *p){
  int iPrev = -1;
  int iStart;
  unsigned c;
  const char *zErr;
  while( (c = p->xNextChar(&p->sIn))!=0 ){
    iStart = p->nState;
    switch( c ){
      case '|':
      case ')': {
        p->sIn.i--;
        return 0;
      }
      case '(': {
        zErr = re_subcompile_re(p);
        if( zErr ) return zErr;
        if( rePeek(p)!=')' ) return "unmatched '('";
        p->sIn.i++;
        break;
      }
      case '.': {
        if( rePeek(p)=='*' ){
          re_append(p, RE_OP_ANYSTAR, 0);
          p->sIn.i++;
        }else{
          re_append(p, RE_OP_ANY, 0);
        }
        break;
      }
      case '*': {
        if( iPrev<0 ) return "'*' without operand";
        re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
        re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
        break;
      }
      case '+': {
        if( iPrev<0 ) return "'+' without operand";
        re_append(p, RE_OP_FORK, iPrev - p->nState);
        break;
      }
      case '?': {
        if( iPrev<0 ) return "'?' without operand";
        re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
        break;
      }
      case '$': {
        re_append(p, RE_OP_MATCH, RE_EOF);
        break;
      }
      case '^': {
        re_append(p, RE_OP_ATSTART, 0);
        break;
      }
      case '{': {
        unsigned int m = 0, n = 0;
        unsigned int sz, j;
        if( iPrev<0 ) return "'{m,n}' without operand";
        while( (c=rePeek(p))>='0' && c<='9' ){
          m = m*10 + c - '0';
          if( m*2>p->mxAlloc ) return "REGEXP pattern too big";
          p->sIn.i++;
        }
        n = m;
        if( c==',' ){
          p->sIn.i++;
          n = 0;
          while( (c=rePeek(p))>='0' && c<='9' ){
            n = n*10 + c-'0';
            if( n*2>p->mxAlloc ) return "REGEXP pattern too big";
            p->sIn.i++;
          }
        }
        if( c!='}' ) return "unmatched '{'";
        if( n<m ) return "n less than m in '{m,n}'";
        p->sIn.i++;
        sz = p->nState - iPrev;
        if( m==0 ){
          if( n==0 ) return "both m and n are zero in '{m,n}'";
          re_insert(p, iPrev, RE_OP_FORK, sz+1);
          iPrev++;
          n--;
        }else{
          for(j=1; j<m; j++) re_copy(p, iPrev, sz);
        }
        for(j=m; j<n; j++){
          re_append(p, RE_OP_FORK, sz+1);
          re_copy(p, iPrev, sz);
        }
        if( n==0 && m>0 ){
          re_append(p, RE_OP_FORK, -(int)sz);
        }
        break;
      }
      case '[': {
        unsigned int iFirst = p->nState;
        if( rePeek(p)=='^' ){
          re_append(p, RE_OP_CC_EXC, 0);
          p->sIn.i++;
        }else{
          re_append(p, RE_OP_CC_INC, 0);
        }
        while( (c = p->xNextChar(&p->sIn))!=0 ){
          if( c=='[' && rePeek(p)==':' ){
            return "POSIX character classes not supported";
          }
          if( c=='\\' ) c = re_esc_char(p);
          if( rePeek(p)=='-' ){
            re_append(p, RE_OP_CC_RANGE, c);
            p->sIn.i++;
            c = p->xNextChar(&p->sIn);
            if( c=='\\' ) c = re_esc_char(p);
            re_append(p, RE_OP_CC_RANGE, c);
          }else{
            re_append(p, RE_OP_CC_VALUE, c);
          }
          if( rePeek(p)==']' ){ p->sIn.i++; break; }
        }
        if( c==0 ) return "unclosed '['";
        if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst;
        break;
      }
      case '\\': {
        int specialOp = 0;
        switch( rePeek(p) ){
          case 'b': specialOp = RE_OP_BOUNDARY;   break;
          case 'd': specialOp = RE_OP_DIGIT;      break;
          case 'D': specialOp = RE_OP_NOTDIGIT;   break;
          case 's': specialOp = RE_OP_SPACE;      break;
          case 'S': specialOp = RE_OP_NOTSPACE;   break;
          case 'w': specialOp = RE_OP_WORD;       break;
          case 'W': specialOp = RE_OP_NOTWORD;    break;
        }
        if( specialOp ){
          p->sIn.i++;
          re_append(p, specialOp, 0);
        }else{
          c = re_esc_char(p);
          re_append(p, RE_OP_MATCH, c);
        }
        break;
      }
      default: {
        re_append(p, RE_OP_MATCH, c);
        break;
      }
    }
    iPrev = iStart;
  }
  return 0;
}

/* Free and reclaim all the memory used by a previously compiled
** regular expression.  Applications should invoke this routine once
** for every call to re_compile() to avoid memory leaks.
*/
static void re_free(ReCompiled *pRe){
  if( pRe ){
    sqlite3_free(pRe->aOp);
    sqlite3_free(pRe->aArg);
    sqlite3_free(pRe);
  }
}

/*
** Version of re_free() that accepts a pointer of type (void*). Required
** to satisfy sanitizers when the re_free() function is called via a
** function pointer.
*/
static void re_free_voidptr(void *p){
  re_free((ReCompiled*)p);
}

/*
** Compile a textual regular expression in zIn[] into a compiled regular
** expression suitable for us by re_match() and return a pointer to the
** compiled regular expression in *ppRe.  Return NULL on success or an
** error message if something goes wrong.
*/
static const char *re_compile(
  ReCompiled **ppRe,      /* OUT: write compiled NFA here */
  const char *zIn,        /* Input regular expression */
  int mxRe,               /* Complexity limit */
  int noCase              /* True for caseless comparisons */
){
  ReCompiled *pRe;
  const char *zErr;
  int i, j;

  *ppRe = 0;
  pRe = sqlite3_malloc64( sizeof(*pRe) );
  if( pRe==0 ){
    return "out of memory";
  }
  memset(pRe, 0, sizeof(*pRe));
  pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
  pRe->mxAlloc = mxRe;
  if( re_resize(pRe, 30) ){
    zErr = pRe->zErr;
    re_free(pRe);
    return zErr;
  }
  if( zIn[0]=='^' ){
    zIn++;
  }else{
    re_append(pRe, RE_OP_ANYSTAR, 0);
  }
  pRe->sIn.z = (unsigned char*)zIn;
  pRe->sIn.i = 0;
  pRe->sIn.mx = (int)strlen(zIn);
  zErr = re_subcompile_re(pRe);
  if( zErr ){
    re_free(pRe);
    return zErr;
  }
  if( pRe->sIn.i>=pRe->sIn.mx ){
    re_append(pRe, RE_OP_ACCEPT, 0);
    *ppRe = pRe;
  }else{
    re_free(pRe);
    return "unrecognized character";
  }

  /* The following is a performance optimization.  If the regex begins with
  ** ".*" (if the input regex lacks an initial "^") and afterwards there are
  ** one or more matching characters, enter those matching characters into
  ** zInit[].  The re_match() routine can then search ahead in the input 
  ** string looking for the initial match without having to run the whole
  ** regex engine over the string.  Do not worry about trying to match
  ** unicode characters beyond plane 0 - those are very rare and this is
  ** just an optimization. */
  if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
    for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
      unsigned x = pRe->aArg[i];
      if( x<=0x7f ){
        pRe->zInit[j++] = (unsigned char)x;
      }else if( x<=0x7ff ){
        pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
        pRe->zInit[j++] = 0x80 | (x&0x3f);
      }else if( x<=0xffff ){
        pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
        pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
        pRe->zInit[j++] = 0x80 | (x&0x3f);
      }else{
        break;
      }
    }
    if( j>0 && pRe->zInit[j-1]==0 ) j--;
    pRe->nInit = j;
  }
  return pRe->zErr;
}

/*
** The value of LIMIT_MAX_PATTERN_LENGTH.
*/
static int re_maxlen(sqlite3_context *context){
  sqlite3 *db = sqlite3_context_db_handle(context);
  return sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH,-1);
}

/*
** Maximum NFA size given a maximum pattern length.
*/
static int re_maxnfa(int mxlen){
  return 75+mxlen/2;
}

/*
** Implementation of the regexp() SQL function.  This function implements
** the build-in REGEXP operator.  The first argument to the function is the
** pattern and the second argument is the string.  So, the SQL statements:
**
**       A REGEXP B
**
** is implemented as regexp(B,A).
*/
static void re_sql_func(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  ReCompiled *pRe;          /* Compiled regular expression */
  const char *zPattern;     /* The regular expression */
  const unsigned char *zStr;/* String being searched */
  const char *zErr;         /* Compile error message */
  int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */

  (void)argc;  /* Unused */
  pRe = sqlite3_get_auxdata(context, 0);
  if( pRe==0 ){
    int mxLen = re_maxlen(context);
    int nPattern;
    zPattern = (const char*)sqlite3_value_text(argv[0]);
    if( zPattern==0 ) return;
    nPattern = sqlite3_value_bytes(argv[0]);
    if( nPattern>mxLen ){
      zErr = "REGEXP pattern too big";
    }else{
      zErr = re_compile(&pRe, zPattern, re_maxnfa(mxLen),
                        sqlite3_user_data(context)!=0);
    }
    if( zErr ){
      re_free(pRe);
      sqlite3_result_error(context, zErr, -1);
      return;
    }
    if( pRe==0 ){
      sqlite3_result_error_nomem(context);
      return;
    }
    setAux = 1;
  }
  zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
  if( zStr!=0 ){
    sqlite3_result_int(context, re_match(pRe, zStr, -1));
  }
  if( setAux ){
    sqlite3_set_auxdata(context, 0, pRe, re_free_voidptr);
  }
}

#if defined(SQLITE_DEBUG)
/*
** This function is used for testing and debugging only.  It is only available
** if the SQLITE_DEBUG compile-time option is used.
**
** Compile a regular expression and then convert the compiled expression into
** text and return that text.
*/
static void re_bytecode_func(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const char *zPattern;
  const char *zErr;
  ReCompiled *pRe;
  sqlite3_str *pStr;
  int i;
  int n;
  char *z;
  static const char *ReOpName[] = {
    "EOF",
    "MATCH",
    "ANY",
    "ANYSTAR",
    "FORK",
    "GOTO",
    "ACCEPT",
    "CC_INC",
    "CC_EXC",
    "CC_VALUE",
    "CC_RANGE",
    "WORD",
    "NOTWORD",
    "DIGIT",
    "NOTDIGIT",
    "SPACE",
    "NOTSPACE",
    "BOUNDARY",
    "ATSTART",
  };

  (void)argc;
  zPattern = (const char*)sqlite3_value_text(argv[0]);
  if( zPattern==0 ) return;
  zErr = re_compile(&pRe, zPattern, re_maxnfa(re_maxlen(context)),
                    sqlite3_user_data(context)!=0);
  if( zErr ){
    re_free(pRe);
    sqlite3_result_error(context, zErr, -1);
    return;
  }
  if( pRe==0 ){
    sqlite3_result_error_nomem(context);
    return;
  }
  pStr = sqlite3_str_new(0);
  if( pRe->nInit>0 ){
    sqlite3_str_appendf(pStr, "INIT     ");
    for(i=0; i<pRe->nInit; i++){
      sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
    }
    sqlite3_str_appendf(pStr, "\n");
  }
  for(i=0; (unsigned)i<pRe->nState; i++){
    sqlite3_str_appendf(pStr, "%-8s %4d\n",
         ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
  }
  if( sqlite3_str_errcode(pStr)==SQLITE_NOMEM ){
    sqlite3_str_finish(pStr);
    re_free(pRe);
    sqlite3_result_error_nomem(context);
    return;
  }
  n = sqlite3_str_length(pStr);
  z = sqlite3_str_finish(pStr);
  sqlite3_result_text(context, z, n-1, sqlite3_free);
  re_free(pRe);
}

#endif /* SQLITE_DEBUG */


/*
** Invoke this routine to register the regexp() function with the
** SQLite database connection.
*/
int fsl__regexp_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  int rc = SQLITE_OK;
  (void)pApi;
  (void)pzErrMsg;  /* Unused */
  rc = sqlite3_create_function(db, "regexp", 2, 
                            SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
                            0, re_sql_func, 0, 0);
  if( rc==SQLITE_OK ){
    /* The regexpi(PATTERN,STRING) function is a case-insensitive version
    ** of regexp(PATTERN,STRING). */
    rc = sqlite3_create_function(db, "regexpi", 2,
                            SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
                            (void*)db, re_sql_func, 0, 0);
#if defined(SQLITE_DEBUG)
    if( rc==SQLITE_OK ){
      rc = sqlite3_create_function(db, "regexp_bytecode", 1,
                            SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
                            0, re_bytecode_func, 0, 0);
    }
#endif /* SQLITE_DEBUG */
  }
  return rc;
}
/* end of file src/ext_regexp.c */
/* start of file src/cx.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*************************************************************************
  This file houses most of the context-related APIs.
*/
#include <assert.h>

#if defined(_WIN32)
# include <windows.h>
# define F_OK 0
# define W_OK 2
#else
# include <unistd.h> /* F_OK */
#endif

#include <stdlib.h>
#include <string.h>
#include <stdio.h> /* FILE class */
#include <errno.h>

/* Only for debugging */
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

/** Number of fsl_cx::scratchpads buffers. */
#define FSL_CX_NSCRATCH \
  ((int)(sizeof(fsl__cx_empty.scratchpads.buf) \
         /sizeof(fsl__cx_empty.scratchpads.buf[0])))
#if !defined(NDEBUG)
typedef int StaticAssert_scratchpadsCounts[
     (FSL_CX_NSCRATCH==
      ((int)(sizeof(fsl__cx_empty.scratchpads.used)
             /sizeof(fsl__cx_empty.scratchpads.used[0]))))
     ? 1 : -1
];
#endif

const fsl__b_list fsl__b_list_empty = fsl__b_list_empty_m;

const fsl_cx fsl__cx_empty = {
  .dbMain = NULL,
  .allocStamp = NULL,
  .cxConfig = fsl_cx_config_empty_m ,
  .db = {
    .ckout = {
      .db = fsl_db_empty_m ,
      .dir = NULL,  .dirLen = 0,
      .rid = -1, .uuid = NULL, .mtime = 0
    },
    .repo = {
      .db = fsl_db_empty_m,
      .user = 0, .mainBranch = 0
    },
    .gconfig = { .db = fsl_db_empty_m },
    .host = { .dbh = NULL, .closing = false, .noShadowCheck = false,
              .gen = 0 },
    .peakTxnLevel = 0,
    .nBegin = 0,
    .nCommit = 0,
    .nRollback = 0
  },
  .ckin = {
    .selectedIds = fsl_id_bag_empty_m,
    .mf = fsl_deck_empty_m
  },
  .confirmer = fsl_confirmer_empty_m,
  .signer = fsl_signer_empty_m,
  .ckoutFs = fsl_ckout_fs_empty_m,
  .output = fsl_outputer_FILE_m,
  .clientState = fsl_state_empty_m,
  .error = fsl_error_empty_m,
  .scratchpads = {
    .buf = {
      fsl_b_empty_m,fsl_b_empty_m,
      fsl_b_empty_m,fsl_b_empty_m,
      fsl_b_empty_m,fsl_b_empty_m,
      fsl_b_empty_m,fsl_b_empty_m
    },
    .used = {
      false,false,false,false,
      false,false,false,false
    },
    .next = 0,
    .emit = fsl_b_empty_m,
    .format = fsl_b_empty_m
  },
  .flags                     = FSL_CX_F_DEFAULTS,
  .interrupted               = 0,
  .xlinkers                  = fsl_xlinker_list_empty_m,
  .cache = {
    .ignoreDephantomizations = false,
    .markPrivate             = false,
    .isCrosslinking          = false,
    .xlinkClustersOnly       = false,
    .inFinalVerify           = false,
    .isSyncing               = false,
    .caseInsensitive         = -1,
    .allowSymlinks           = -1,
    .seenDeltaManifest       = -1,
    .searchIndexExists       = -1,
    .manifestSetting         = -1,
    .rcvId                   = 0,
    .fileContent             = fsl_b_empty_m,
    .deltaContent            = fsl_b_empty_m,
    .blobContent             = fsl__bccache_empty_m,
    .ptl                     = fsl__ptl_empty_m,
    .markAvailableCache      = fsl_id_bag_empty_m,
    .mtimeManifest           = 0,
    .projectCode             = NULL,
    .fstat                   = fsl_fstat_empty_m,
    .mcache                  = fsl__mcache_empty_m,
    .globs = {
      .ignore                = fsl_list_empty_m,
      .binary                = fsl_list_empty_m,
      .crnl                  = fsl_list_empty_m
    },
    .stmt = {
#define STMT(X,IGNORED) .X = fsl_stmt_empty_m,
      fsl__cx_cache_stmt_map(STMT)
#undef STMT
    },
    .tempDirs                = NULL,
    .buf                     = fsl__b_library_empty_m
  }/*cache*/,
  .ticket = {
    .customFields            = fsl_list_empty_m,
    .hasTicket               = 0,
    .hasCTime                = 0,
    .hasChng                 = 0,
    .hasChngRid              = 0,
    .titleColumn             = NULL,
    .statusColumn            = NULL
  },
  .metrics = {
    .content = {
      .nCached = 0, .nTotalUsed = 0, .nPeakBufSize = 0,
      .nCappedMaxSize = 0
    }
  }
}/*fsl__cx_empty*/;

static void fsl__cxreg_free(void * p){
  fsl__cxreg * const r = p;
  if( r ){
    fsl_free(r->a);
    fsl_free(r->sp);
    fsl_free(r);
  }
}

int fsl__cxreg_join(fsl_cx * const f, fsl_db * const db, bool * pFirst){
  sqlite3 * const dbh = db->dbh;
  fsl__cxreg * r = sqlite3_get_clientdata(dbh, "fsl_cxreg");
  if( !r ){
    r = fsl_malloc(sizeof(*r));
    if( !r ) return FSL_RC_OOM;
    memset(r, 0, sizeof(*r));
    if( sqlite3_set_clientdata(dbh, "fsl_cxreg", r, fsl__cxreg_free) ){
      return FSL_RC_OOM /* SQLite has already freed r */;
    }
  }
  if( r->n==r->cap ){
    unsigned const cap = r->cap ? r->cap * 2 : 4;
    fsl_cx ** const a = fsl_realloc(r->a, cap * sizeof(fsl_cx*));
    if( !a ){
      if( !r->n ) sqlite3_set_clientdata(dbh, "fsl_cxreg", NULL, NULL);
      return FSL_RC_OOM;
    }
    r->a = a;
    r->cap = cap;
  }
  r->a[r->n++] = f;
  db->impl.share.reg = r;
  db->impl.share.cx = f;
  db->impl.share.id = ++r->lastId;
  if( pFirst ) *pFirst = 1==r->n;
  return 0;
}

unsigned fsl__cxreg_leave(fsl_db * const db){
  /* Looked up afresh, not from db->impl.share.reg: while the
     connection closes, SQLite may already have freed it. */
  fsl__cxreg * const r = db->dbh
    ? sqlite3_get_clientdata(db->dbh, "fsl_cxreg") : NULL;
  fsl_cx * const f = db->impl.share.cx;
  unsigned n = 0;
  if( r ){
    for( unsigned i = 0; i < r->n; ++i ){
      if( r->a[i]==f ){
        memmove(&r->a[i], &r->a[i+1], (r->n - i - 1) * sizeof(fsl_cx*));
        --r->n;
        break;
      }
    }
    if( r->cur==f ) r->cur = NULL;
    if( r->dflt==f ) r->dflt = NULL;
    for( unsigned i = 0; i < r->nSp; ){
      if( r->sp[i]==db ){
        memmove(&r->sp[i], &r->sp[i+1], (r->nSp - i - 1) * sizeof(fsl_db*));
        --r->nSp;
      }else ++i;
    }
    n = r->n;
    if( !n && db->dbh ){
      sqlite3_set_clientdata(db->dbh, "fsl_cxreg", NULL, NULL)
        /* frees r */;
    }
  }
  db->impl.share.reg = NULL;
  db->impl.share.cx = NULL;
  return n;
}

fsl_cx * fsl__cx_for_dbh(sqlite3 * dbh){
  fsl__cxreg const * const r = dbh
    ? sqlite3_get_clientdata(dbh, "fsl_cxreg") : NULL;
  if( !r || !r->n ) return NULL;
  return r->cur ? r->cur : (r->dflt ? r->dflt : r->a[0]);
}

void fsl__cxreg_default_set(sqlite3 * dbh, fsl_cx * f){
  fsl__cxreg * const r = dbh
    ? sqlite3_get_clientdata(dbh, "fsl_cxreg") : NULL;
  if( r ){
    /* Only a context still on the connection: leaving it clears the
       default. */
    unsigned i = 0;
    while( f && i < r->n && r->a[i]!=f ) ++i;
    r->dflt = (f && i < r->n) ? f : NULL;
  }
}

/**
   Drops the TEMP tables of db's context, which is leaving a host's
   connection that other contexts may go on using. A context after
   the connection's first has TEMP table names of its own, carrying
   its id (fsl__db_schema_token()), so they are told apart by name;
   the first context's have the plain names, and stay. Errors are
   ignored, as for fsl__db_temp_drop().
*/
static void fsl__cx_host_temp_drop(fsl_db * const db){
  unsigned const id = db->impl.share.id;
  char zPrefix[32];
  char * zList, * z, * zNext;
  if( id<2 ) return;
  fsl_snprintf(zPrefix, sizeof(zPrefix), "fsl%u_", id);
  zList = fsl_db_g_text(db, NULL,
    "SELECT group_concat(substr(name, %d), ' ') FROM temp.sqlite_schema"
    " WHERE type='table' AND name GLOB '%q*'",
    (int)fsl_strlen(zPrefix) + 1, zPrefix);
  for( z = zList; z && *z; z = zNext ){
    zNext = strchr(z, ' ');
    if( zNext ) *zNext++ = 0;
    else zNext = z + fsl_strlen(z);
    fsl__db_temp_drop(db, z);
  }
  fsl_free(zList);
  fsl_db_err_reset(db);
}

int fsl__cx_host_rollback_check(fsl_cx * const f){
  fsl_db * const db = f->dbMain;
  int64_t gen = 0;
  int rc;
  if( !db || !fsl__db_is_borrowed(db) || f->db.host.closing ) return 0;
  rc = fsl_db_get_int64(db, &gen, "SELECT max(gen) FROM temp.fsl_host_gen"
                        " WHERE rowid=%u", db->impl.share.id);
  if( rc ) return fsl_cx_uplift_db_error2(f, db, rc);
  if( gen != f->db.host.gen ){
    fsl__cx_caches_reset(f, false);
    if( f->db.ckout.db.dbh || (db->role & FSL_DBROLE_CKOUT) ){
      fsl__ckout_version_fetch(f);
    }
    f->db.host.gen = gen;
  }
  return 0;
}

/**
   For a context bound to a host db handle: records that f's caches now
   reflect writes which a host ROLLBACK could undo. See
   fsl__cx_host_rollback_check().
*/
static int fsl__cx_host_gen_bump(fsl_cx * const f, fsl_db * const db){
  int rc = fsl_db_exec(db, "REPLACE INTO temp.fsl_host_gen(rowid,gen) "
                       "VALUES(%u,%" PRIi64 ")", db->impl.share.id,
                       f->db.host.gen + 1);
  if( 0==rc ) ++f->db.host.gen;
  return rc;
}

static int fsl__db_event_f_cx(fsl_db_event const *ev){
  fsl_cx * const f = ev->state;
  int rc = 0;
  fsl_size_t nLevel = (fsl_size_t)ev->savepointLevel;
  assert(f);

  //MARKER(("db transaction mode=%d rc=%d: %s\n", (int)mode, theRc, db->filename));
  switch( ev->type ){
    case FSL_DB_EVENT_TRACE_SQL:
    case FSL_DB_EVENT_TRACE_SQLX:{
      fsl_b const * const b = ev->payload;
      assert( b );
      fsl_output(f, b->mem, b->used);
      break;
    }
    case FSL_DB_EVENT_CLOSING:
      fsl__cx_caches_reset(f, false);
      //MARKER(("closing db: %s\n", ev->db->filename));
      if( ev->db == f->dbMain ){
        f->dbMain = NULL;
      }
      break;
    case FSL_DB_EVENT_BEGIN:
      assert(ev->savepointLevel>0);
      ++f->db.nBegin;
      if( 1==ev->savepointLevel ){
        rc = fsl__cx_host_rollback_check(f);
      }
      if( 0==rc ) rc = fsl_cx_emit(f, FSL_MSG_TXN_BEGIN, &nLevel);
      if( 0==rc ){
        rc = fsl__cx_ptl_push(f);
      }
      if( 0==rc && ev->savepointLevel>f->db.peakTxnLevel ){
        f->db.peakTxnLevel = ev->savepointLevel;
      }
      break;
    case FSL_DB_EVENT_ROLLING_BACK:
      break;
    case FSL_DB_EVENT_COMMIT:{
      assert(ev->savepointLevel>0);
      ++f->db.nCommit;
      if( 0==rc && f->cache.ptl.validateRidLevel == ev->savepointLevel ){
        f->cache.ptl.validateRidLevel = -1;
        rc = fsl__repo_verify_at_commit(f)
          /* Funny thing... if we unconditionally validate the current
             level's RIDs, we end up running validation in response to
             every inner transaction of fsl__content_put_ex(), which
             is precisely what we don't want to do (it can't work once
             delta content is involved). That's literally the ONE
             routine which is permitted to add non-phantom blob
             content to the repo (and only one other is allowed to add
             phantoms), but content validation has to be delayed until
             all other content (presumably from the same parent
             transaction(s)) is added so that we can resolve deltas
             during the validation.
          */;
      }
      if( 0==rc && 1==ev->savepointLevel ){
        /* Leaf checks can be scheduled without any new content, e.g.
           by fsl_repo_rebuild() crosslinking what is already in the
           blob table. Those never reach the validateRidLevel commit
           above, so apply them at the outermost commit, as fossil(1)
           does in db_end_transaction(). */
        rc = fsl__leaf_do_pending_checks(f);
        if( 0==rc && fsl__db_is_borrowed(ev->db) && !f->db.host.closing ){
          rc = fsl__cx_host_gen_bump(f, ev->db);
        }
      }
      int const rc2 = fsl__cx_ptl_pop(f, 0==rc);
      if( rc2 && !rc ) rc = rc2;
      if( rc ){
        /* Returning non-0 will transform this pending commit
           to a rollback but the rollback trigger won't be
           called in that case. */
        fsl_cx_emit(f, FSL_MSG_TXN_ROLLBACK, &nLevel);
      }
      else{
        rc = fsl_cx_emit(f, FSL_MSG_TXN_COMMIT, &nLevel);
      }
      break;
    }
    case FSL_DB_EVENT_ROLLED_BACK:
      assert(ev->savepointLevel>0);
      ++f->db.nRollback;
      fsl__repo_verify_cancel(f);
      rc = fsl__cx_ptl_pop(f, false);
      if( f->cache.ptl.validateRidLevel == ev->savepointLevel ){
        f->cache.ptl.validateRidLevel = -1;
      }
      fsl_cx_emit(f, FSL_MSG_TXN_ROLLBACK, &nLevel)
        /* We ignore this particular result code because it could
           hypothetically make it look like a rollback failed,
           when in fact the rollback has already happened by this
           point. */;
      break;
  }
  if( rc && f->error.code ){
    fsl_error_copy( &f->error, &ev->db->error );
  }
  return rc;
}

/**
   Clears (most) dynamic state in f, but does not free f and does
   not free "static" state (that set up by the init process). If
   closeDatabases is true then any databases managed by f are
   closed, else they are kept open.

   Client code will not normally need this - it is intended for a
   particular potential memory optimization case. If (and only if)
   closeDatabases is true then after calling this, f may be legally
   re-used as a target for fsl_cx_init().

   This function does not trigger any finializers set for f's client
   state or output channel.

   Results are undefined if !f or f's memory has not been properly
   initialized.
*/
static void fsl__cx_reset( fsl_cx * const f, bool closeDatabases );

int fsl_cx_init( fsl_cx ** tgt, fsl_cx_config const * cfg ){
  fsl_cx_config paramDefaults = fsl_cx_config_empty_m;
  int rc = 0;
  fsl_cx * f;
#if FSL_API_ARMOR
  if(!tgt) return FSL_RC_MISUSE;
#else
  assert( tgt );
#endif
  if(!cfg){
    paramDefaults.output.out = fsl_output_f_FILE;
    paramDefaults.output.state = stdout;
    cfg = &paramDefaults;
  }
  if(*tgt){
    void const * allocStamp = (*tgt)->allocStamp;
    fsl__cx_reset(*tgt, true) /* just to be safe */;
    f = *tgt;
    *f = fsl__cx_empty;
    f->allocStamp = allocStamp;
  }else{
    f = fsl_cx_malloc();
    if(!f) return FSL_RC_OOM;

    *tgt = f;
  }
  memset(&f->cache.mcache, 0, sizeof(f->cache.mcache));
  f->cxConfig = *cfg;

  if( fsl__ptl_init(&f->cache.ptl, 10) ){
    return f->cache.ptl.rc;
  }

  enum {
    /* Because testing shows a lot of re-allocs via some of the
       lower-level stat()-related bits, we pre-allocate this many
       bytes into f->scratchpads.buf[].  Curiously, there is almost no
       difference in (re)allocation behaviour until this size goes
       above about 200.

       We ignore allocation errors here, as they're not critical (but
       upcoming ops will fail when _they_ run out of memory).
    */
    InitialScratchCapacity = 256
  };
  assert(FSL_CX_NSCRATCH
         == (sizeof(f->scratchpads.used)/sizeof(f->scratchpads.used[0])));
  for(int i = 0; i < FSL_CX_NSCRATCH; ++i){
    f->scratchpads.buf[i] = fsl_b_empty;
    f->scratchpads.used[i] = false;
    fsl_b_reserve(&f->scratchpads.buf[i], InitialScratchCapacity);
  }
  /* We update f->error.msg often, so go ahead and pre-allocate that, too,
     also ignoring any OOM error at this point. */
  fsl_b_reserve(&f->error.msg, InitialScratchCapacity);

  if(!rc) rc = fsl__cx_install_timeline_crosslinkers(f);
  if(!rc){
    f->cache.tempDirs = fsl_temp_dirs_get();
    if(!f->cache.tempDirs) rc = FSL_RC_OOM;
  }
  return rc;
}

void fsl__cx_mcache_clear(fsl_cx * const f){
  static const unsigned cacheLen =
    (unsigned)(sizeof(fsl__mcache_empty.aAge)
               /sizeof(fsl__mcache_empty.aAge[0]));
  for(unsigned i = 0; i < cacheLen; ++i){
    fsl_deck_finalize(&f->cache.mcache.decks[i]);
  }
  f->cache.mcache = fsl__mcache_empty;
}

void fsl__cx_content_caches_clear(fsl_cx * const f){
  fsl__bccache_reuse(&f->cache.blobContent);
  fsl__cx_mcache_clear(f);
}

void fsl__cx_reset_for_txn(fsl_cx * const f, bool isCommit){
  if( !isCommit ){
    fsl_free( f->db.repo.mainBranch );
    f->db.repo.mainBranch = 0;
    f->cache.allowSymlinks =
      f->cache.caseInsensitive =
      f->cache.manifestSetting =
      f->cache.searchIndexExists =
      f->cache.seenDeltaManifest = -1;
    if(0) fsl__cx_ckout_clear(f)
      /* We're doing this way too often. Need to limit this to the
         places where we really can invalidate the cached chkout
         state. Plus... this breaks tests. */;
    fsl__cx_mcache_clear(f)
      /* This is unfortunate but we can't yet cherry-pick removing
         content from that cache */;
    /**
       The IDs stored in f->cache.blobContent are ensured not to be
       come stale via fsl__cx_ptl_pop().
    */
  }else{
    fsl__ckout_version_fetch(f)
      /* i don't like doing this here but much code depends on
         f->ckout.rid being up to date. */;
  }
}

void fsl__cx_caches_reset(fsl_cx * const f, bool isCommit){
  fsl__cx_content_caches_clear(f);
  /**
     Operations which might re-initialize f->cache.stmt entries
     should be skipped if repopSome is false.
  */
  fsl__cx_reset_for_txn(f, isCommit);
}

/** Passes each member of f->cache.stmt to fsl_stmt_finalize(). */
static void fsl__cx_finalize_cached_stmt(fsl_cx * const f){
#define STMT(X,IGNORED) fsl_stmt_finalize(&f->cache.stmt.X);
      fsl__cx_cache_stmt_map(STMT)
#undef STMT
}

/**
   Calls fsl_close_scm_dbs() and closes the global config.  If force
   is false and transactions are active on any db then non-0 is
   returned. If force is true, all transaction levels are forcibly
   rolled back before the db is closed.

   This force is false it will fail if any transactions are
   pending. Any databases which are already closed are silently
   skipped. This will fail if any cached statements are currently
   active for the being-closed db(s). "Active" means that
   fsl_db_prepare_cached() was used without a corresponding call to
   fsl_stmt_cached_yield().
*/
static int fsl__cx_close_dbs(fsl_cx * const f, bool force){
  fsl__cx_finalize_cached_stmt(f);
  if( fsl_cx_txn_level(f)
      || fsl_db_txn_level(&f->db.gconfig.db) ){
    if( !force ){
      /* Is this really necessary? Should we instead
         force rollback(s) and close the dbs? */
      return fsl_cx_err_set(f, FSL_RC_MISUSE,
                            "Cannot close the databases when a "
                            "transaction is pending.");
    }
    while( fsl_db_txn_level(&f->db.gconfig.db)!=0 ){
      fsl_db_txn_end_v2(&f->db.gconfig.db, false, true);
    }
    while( fsl_cx_txn_level(f) !=0 ){
      if( !fsl__db_txn_is_innermost(f->dbMain) ){
        /* Another context sharing a host's connection has a
           transaction inside f's, which ending f's would end too. */
        fsl__db_txn_abandon(f->dbMain);
        break;
      }
      fsl_cx_txn_end_v2(f, false, true);
    }
  }
  fsl_db_close(&f->db.gconfig.db);
  return fsl_close_scm_dbs(f);
}

static void fsl__cx_reset(fsl_cx * const f, bool closeDatabases){
  fsl_checkin_discard(f);
#define SFREE(X) fsl_free(X); X = NULL
  if(closeDatabases){
    fsl__cx_close_dbs(f, true)
      /* Recall that any cached statements can prohibit its
         detachment, so those have to be finalized first. */;
    SFREE(f->db.ckout.dir);
    f->db.ckout.dirLen = 0;
    /* assert(NULL==f->dbMain); */
  }else{
    fsl__cx_finalize_cached_stmt(f);
  }
  SFREE(f->db.repo.user);
  fsl__cx_ckout_clear(f);
  SFREE(f->cache.projectCode);
  SFREE(f->ticket.titleColumn);
  SFREE(f->ticket.statusColumn);
#undef SFREE
  fsl_error_clear(&f->error);
  f->interrupted = 0;
  fsl__card_J_list_free(&f->ticket.customFields, true);
  fsl_b_clear(&f->cache.fileContent);
  fsl_b_clear(&f->cache.deltaContent);
  fsl_b_clear(&f->scratchpads.emit);
  fsl_b_clear(&f->scratchpads.format);
  for(int i = 0; i < FSL_CX_NSCRATCH; ++i){
    fsl_b_clear(&f->scratchpads.buf[i]);
    f->scratchpads.used[i] = false;
  }
  fsl__cx_caches_reset(f, false);
  fsl__bccache_clear(&f->cache.blobContent);
  fsl__ptl_clear( &f->cache.ptl );
  fsl_id_bag_clear(&f->cache.markAvailableCache);
  if(f->xlinkers.list){
    fsl_free(f->xlinkers.list);
    f->xlinkers = fsl_xlinker_list_empty;
  }
  fsl_list_visit_free(&f->cache.globs.ignore, 1);
  fsl_list_visit_free(&f->cache.globs.binary, 1);
  fsl_list_visit_free(&f->cache.globs.crnl, 1);
  fsl__b_list_cleanup(&f->cache.buf.list);
  f->cache = fsl__cx_empty.cache;
}

void fsl_state_finalize(fsl_state * const fst){
  if( fst ){
    if( fst->finalize.f ){
      fst->finalize.f( fst->finalize.state, fst->state );
    }
    *fst = fsl_state_empty;
  }
}

void fsl_cx_finalize( fsl_cx * const f ){
  void const * const allocStamp = f ? f->allocStamp : NULL;
  if(!f) return;
  fsl_state_finalize( &f->clientState );
  assert( !f->clientState.finalize.f );
  fsl_temp_dirs_free(f->cache.tempDirs);
  fsl__cx_reset(f, true);
  *f = fsl__cx_empty;
  if(&fsl__cx_empty == allocStamp){
    fsl_free(f);
  }else{
    f->allocStamp = allocStamp;
  }
}

fsl_error * fsl__cx_error( fsl_cx * const f ){
  return &f->error;
}

void fsl_cx_err_reset(fsl_cx * const f){
  //f->interrupted = 0; // No! ONLY modify this via fsl_cx_interrupt()
  fsl_error_reset(&f->error);
  fsl_db_err_reset(&f->db.repo.db);
  fsl_db_err_reset(&f->db.gconfig.db);
  fsl_db_err_reset(&f->db.ckout.db);
}

int fsl_cx_err_set_e( fsl_cx * const f, fsl_error * const err ){
  if(!err){
    return fsl_cx_err_set(f, 0, NULL);
  }else{
    fsl_error_propagate(err, &f->error);
    fsl_error_clear(err);
    return f->error.code;
  }
}

int fsl_cx_err_setv( fsl_cx * const f, int code, char const * fmt,
                     va_list args ){
  return fsl_error_setv( &f->error, code, fmt, args );
}

int fsl_cx_err_set( fsl_cx * const f, int code, char const * fmt,
                    ... ){
  int rc;
  va_list args;
  va_start(args,fmt);
  rc = fsl_error_setv( &f->error, code, fmt, args );
  va_end(args);
  return rc;
}

int fsl_cx_err_get( fsl_cx * const f, char const ** str, fsl_size_t * len ){
#if 1
  return fsl_error_get( &f->error, str, len );
#else
  /* For the docs:
   If fsl_cx_interrupted() has been called with an error code and the
   context has no other pending error state, that code is returned.
  */
  int const rc = fsl_error_get( &f->error, str, len );
  return rc ? rc : f->interrupted;
#endif
}

int fsl_cx_err_code( fsl_cx const * f ){
  return f->error.code;
}

fsl_id_t fsl_cx_last_insert_id(fsl_cx * const f){
  return (f && f->dbMain && f->dbMain->dbh)
    ? fsl_db_last_insert_id(f->dbMain)
    : -1;
}

fsl_cx * fsl_cx_malloc(void){
  fsl_cx * rc = (fsl_cx *)fsl_malloc(sizeof(fsl_cx));
  if(rc) {
    *rc = fsl__cx_empty;
    rc->allocStamp = &fsl__cx_empty;
  }
  return rc;
}

int fsl_cx_err_report( fsl_cx * const f, bool addNewline ){
#if FSL_API_ARMOR
  if(!f) return FSL_RC_MISUSE;
#else
  assert( f );
#endif
  if(f->error.code){
    char const * msg = f->error.msg.used
      ? (char const *)f->error.msg.mem
      : fsl_rc_cstr(f->error.code)
      ;
    return fsl_outputf(f, "Error #%d: %s%s",
                       f->error.code, msg,
                       addNewline ? "\n" : "");
  }
  else return 0;
}

int fsl_cx_uplift_db_error( fsl_cx * const f, fsl_db * db ){
  assert(f);
  if(!db){
    db = f->dbMain;
    assert(db && "misuse: no DB handle to uplift error from!");
    if(!db) return FSL_RC_MISUSE;
  }
  if( db->error.code ){
    fsl_error_propagate( &db->error, &f->error );
  }
  return f->error.code;
}

int fsl_cx_uplift_db_error2(fsl_cx * const f, fsl_db * db, int rc){
  assert(f);
  if(!f->error.code && rc && rc!=FSL_RC_OOM){
    if(!db) db = f->dbMain;
    assert(db && "misuse: no DB handle to uplift error from!");
    if(db && db->error.code==rc) rc = fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}

fsl_db * fsl_cx_db_config( fsl_cx * const f ){
  return f->db.gconfig.db.dbh ? &f->db.gconfig.db : NULL;
}

fsl_db * fsl_cx_db_repo( fsl_cx * const f ){
  if(f->dbMain && (FSL_DBROLE_REPO & f->dbMain->role)) return f->dbMain;
  else if(f->db.repo.db.dbh) return &f->db.repo.db;
  else return NULL;
}

fsl_db * fsl_cx_db_ckout( fsl_cx * const f ){
  if(f->dbMain && (FSL_DBROLE_CKOUT & f->dbMain->role)) return f->dbMain;
  else if(f->db.ckout.db.dbh) return &f->db.ckout.db;
  else return NULL;
}

fsl_db * fsl_needs_repo(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_repo(f);
  if(!db){
    fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                   "Fossil context has no opened repository db.");
  }
  return db;
}

fsl_db * fsl_needs_ckout(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_ckout(f);
  if(!db){
    fsl_cx_err_set(f, FSL_RC_NOT_A_CKOUT,
                   "Fossil context has no opened checkout db.");
  }
  return db;
}

fsl_db * fsl_cx_db( fsl_cx * const f ){
  return f->dbMain;
}

fsl_db * fsl__cx_db_for_role(fsl_cx * const f, fsl_dbrole_e r){
  switch(r){
    case FSL_DBROLE_CONFIG:
      return &f->db.gconfig.db;
    case FSL_DBROLE_REPO:
      return &f->db.repo.db;
    case FSL_DBROLE_CKOUT:
      return &f->db.ckout.db;
    case FSL_DBROLE_MAIN:
      return f->dbMain;
    case FSL_DBROLE_NONE:
    default:
      return NULL;
  }
}

/**
   Returns the "counterpart" role for the given db role.
*/
static fsl_dbrole_e fsl__dbrole_counterpart(fsl_dbrole_e r){
  switch(r){
    case FSL_DBROLE_REPO: return FSL_DBROLE_CKOUT;
    case FSL_DBROLE_CKOUT: return FSL_DBROLE_REPO;
    default:
      fsl__fatal(FSL_RC_MISUSE,
                 "Serious internal API misuse uncovered by %s().",
                 __func__);
      return FSL_DBROLE_NONE;
  }
}

/**
    Detaches/closes the given db role from f->dbMain and removes the
    role from f->dbMain->role. If r reflects the current primary db
    and a secondary db is attached, the secondary gets detached.  If r
    corresponds to the secondary db, only that db is detached. If
    f->dbMain is the given role then f->dbMain is set to NULL.
*/
static int fsl__cx_detach_role(fsl_cx * const f, fsl_dbrole_e r){
  assert(FSL_DBROLE_CONFIG!=r && "Config db now has its own handle.");
  assert(FSL_DBROLE_REPO==r || FSL_DBROLE_CKOUT==r);
  if(NULL==f->dbMain){
    assert(!"Internal API misuse: don't try to detach when dbMain is NULL.");
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close/detach db: none opened.");
  }else if(!(r & f->dbMain->role)){
    assert(!"Misuse: cannot detach unattached role.");
    return fsl_cx_err_set(f, FSL_DBROLE_CKOUT==r
                          ? FSL_RC_NOT_A_CKOUT
                          : FSL_RC_NOT_A_REPO,
                          "Cannot close/detach unattached role: %s",
                          fsl_db_role_name(r));
  }else{
    fsl_db * const db = fsl__cx_db_for_role(f,r);
    int rc = 0;
    switch(r){
      case FSL_DBROLE_REPO:
      case FSL_DBROLE_CKOUT:
        break;
      default:
        fsl__fatal(FSL_RC_ERROR, "Cannot happen. Really. %s:%d",
                   __FILE__, __LINE__);
    }
    fsl__cx_caches_reset(f, false);
    fsl__cx_finalize_cached_stmt(f);
    assert( !f->cache.stmt.ridToUuid.stmt );
    fsl__db_cached_clear_role(f->dbMain, r)
      /* Make sure that we destroy any cached statements which are
         known to be tied to this db role. */;
    if(db->dbh){
      /* This is our MAIN db. CLOSE it. If we still have a
         secondary/counterpart db open, we'll detach it first. */
      fsl_dbrole_e const counterpart = fsl__dbrole_counterpart(r);
      assert(f->dbMain == db);
      if(db->role & counterpart){
        /* When closing the main db, detach the counterpart db first
           (if it's attached). We'll ignore any result code here, for
           sanity's sake. */
        assert(fsl__cx_db_for_role(f,counterpart)->filename &&
               "Inconsistent internal db handle state.");
        fsl__cx_detach_role(f, counterpart);
      }
      if( fsl__db_is_borrowed(db) && !f->db.host.closing ){
        /* The host's handle stays open, so take back everything we
           added to it, sharing with other contexts what they still
           use. */
        char * const zSchema = fsl_strdup(fsl__db_schema(db, r));
        fsl_db_exec(db, "DELETE FROM temp.fsl_host_gen WHERE rowid=%u",
                    db->impl.share.id);
        fsl__cx_host_temp_drop(db);
        fsl__cx_uninit_db(f, db);
        if( !fsl__cx_for_dbh(db->dbh) ){
          /* Shared by the connection's contexts, so not
             fsl__db_temp_drop(), which names this context's own. */
          fsl_db_exec(db, "DROP TABLE IF EXISTS temp.fsl_host_gen");
        }
        if( FSL_DBROLE_REPO==r && fsl__db_repo_prefix(db) ){
          rc = 0 /* prefixed tables of the host's main db: no ATTACH */;
        }else{
          rc = zSchema ? fsl_db_detach(db, zSchema) : FSL_RC_OOM;
        }
        fsl_free(zSchema);
        if(rc) fsl_cx_uplift_db_error(f, db);
      }else if( fsl__db_is_borrowed(db) ){
        /* The host's handle is closing and may no longer run SQL, but
           it can outlive us (sqlite3_close() fails while the host
           still has statements open), so leave its registry. */
        fsl__cxreg_leave(db);
      }
      fsl_db_close(db);
      f->dbMain = NULL;
    }else{
      /* This is our secondary db. DETACH it, unless it is prefixed
         checkout or repository tables in the host's main db, which
         stays. */
      assert(f->dbMain != db);
      rc = (f->db.host.closing
            || (FSL_DBROLE_CKOUT==r && fsl__db_ckout_prefix(f->dbMain))
            || (FSL_DBROLE_REPO==r && fsl__db_repo_prefix(f->dbMain)))
        ? 0 /* the host's handle may no longer run SQL */
        : fsl_db_detach( f->dbMain, fsl__db_schema(f->dbMain, r) );
      //MARKER(("rc=%s %s %s\n", fsl_rc_cstr(rc), fsl_db_role_name(r),
      //        fsl_b_cstr(&f->dbMain->error.msg)));
      if(rc){
        fsl_cx_uplift_db_error(f, f->dbMain);
      }else{
        f->dbMain->role &= ~r;
        if( FSL_DBROLE_REPO==r ){
          fsl_free(f->dbMain->impl.share.zRepo);
          f->dbMain->impl.share.zRepo = NULL;
          fsl_free(f->dbMain->impl.share.zRepoPrefix);
          f->dbMain->impl.share.zRepoPrefix = NULL;
        }else{
          fsl_free(f->dbMain->impl.share.zCkout);
          f->dbMain->impl.share.zCkout = NULL;
          fsl_free(f->dbMain->impl.share.zCkoutPrefix);
          f->dbMain->impl.share.zCkoutPrefix = NULL;
        }
        fsl__db_clear_strings(db, true);
      }
    }
    return rc;
  }
}

/**
   Sets "PRAGMA cache_size" of schema zSchema of db to
   FSL__DB_CACHE_SIZE. SQLite sets the page cache limit of each
   attached database to SQLITE_DEFAULT_CACHE_SIZE, so each schema
   needs its own call.
*/
static int fsl__cx_db_cache_size(fsl_db * const db, char const *zSchema){
  return fsl_db_exec(db, "PRAGMA %!Q.cache_size=%d",
                     zSchema, (int)FSL__DB_CACHE_SIZE);
}

/**
   Sets db->filename to zDbName's canonical form, as fsl_db_open()
   does, so that the name does not depend on the cwd: a checkout
   records its repository's name, and derives its directory from its
   own db's name. "" and names starting with ':', e.g. ":memory:", are
   copied as they are.
*/
static int fsl__cx_db_filename_set(fsl_cx * const f, fsl_db * const db,
                                   char const * zDbName){
  fsl_b tmp = fsl_b_empty;
  int rc;
  if( !*zDbName || ':'==*zDbName ){
    db->filename = fsl_strdup(zDbName);
    return db->filename ? 0 : FSL_RC_OOM;
  }
  rc = fsl_file_canonical_name(zDbName, &tmp, 0);
  if( rc ){
    fsl_b_clear(&tmp);
    return FSL_RC_OOM==rc ? rc
      : fsl_cx_err_set(f, rc, "Cannot canonicalize db file name "
                       "[%s]: %R", zDbName, rc);
  }
  db->filename = (char *)tmp.mem /* transfer ownership */;
  return 0;
}

/** True if zSchema is a repository or checkout schema of a context,
    other than f, which shares db's connection. */
static bool fsl__cx_host_schema_is_cx(fsl_cx const * const f,
                                      fsl_db const * const db,
                                      char const * zSchema){
  fsl__cxreg const * const r = db->dbh
    ? sqlite3_get_clientdata(db->dbh, "fsl_cxreg") : NULL;
  for( unsigned i = 0; r && i < r->n; ++i ){
    fsl_db const * const o = r->a[i]->dbMain;
    if( r->a[i]==f || !o ) continue;
    if( ((o->role & FSL_DBROLE_REPO) && !fsl__db_repo_prefix(o)
         && 0==fsl_strcmp(zSchema, fsl__db_schema(o, FSL_DBROLE_REPO)))
        || ((o->role & FSL_DBROLE_CKOUT) && !fsl__db_ckout_prefix(o)
            /* Prefixed tables are in the host's main db. */
            && 0==fsl_strcmp(zSchema, fsl__db_schema(o, FSL_DBROLE_CKOUT))) ){
      return true;
    }
  }
  return false;
}

/**
   Checks that no table or view in schema zSchema of f's borrowed
   handle is hidden by one of the same name in a schema SQLite
   searches first. SQLite resolves a name without a schema in temp,
   then main, then attached schemas in the order they were attached,
   so such a table would take the place of zSchema's in the host's
   unqualified SQL. (libfossil's own SQL names its schemas, and the
   bodies of a schema's own views and triggers resolve their names in
   that schema.) The
   schemas of the other contexts sharing the handle are not counted:
   their tables have the same names by design, and the host's
   unqualified names reach the first of them.
*/
static int fsl__cx_host_shadow_check(fsl_cx * const f, fsl_db * const db,
                                     char const * zSchema){
  fsl_stmt q = fsl_stmt_empty;
  if( f->db.host.noShadowCheck ) return 0;
  int rc = fsl_db_prepare(db, &q,
    "SELECT name FROM pragma_database_list"
    " WHERE seq < (SELECT seq FROM pragma_database_list WHERE name=%Q)"
    " ORDER BY seq", zSchema);
  while( fsl__cx_stmt_step_each(f, &q, &rc) ){
    char const * const zOther = fsl_stmt_g_text(&q, 0, NULL);
    if( fsl__cx_host_schema_is_cx(f, db, zOther) ) continue;
    char * const zList = fsl_db_g_text(db, NULL,
      "SELECT group_concat(name, ', ') FROM %!Q.sqlite_schema"
      " WHERE type IN('table','view') AND name NOT LIKE 'sqlite\\_%%'"
      " ESCAPE '\\' AND name IN"
      " (SELECT name FROM %!Q.sqlite_schema"
      "  WHERE type IN('table','view'))", zSchema, zOther);
    if( zList && *zList ){
      rc = fsl_cx_err_set(f, FSL_RC_CONSISTENCY,
                          "Schema %s has tables named like %s tables, "
                          "which would hide them: %s",
                          zOther, zSchema, zList);
    }else if( db->error.code ){
      rc = fsl_cx_uplift_db_error(f, db);
    }
    fsl_free(zList);
  }
  fsl_stmt_finalize(&q);
  if( rc && !f->error.code ) rc = fsl_cx_uplift_db_error2(f, db, rc);
  return rc;
}

/**
   Only true if the main db of f's borrowed handle is a file. A
   check-in writes the repository and the checkout db in a single
   transaction. SQLite can only commit a transaction across attached dbs
   atomically using a super-journal, which cannot contain non-DELETE mode
   databases. Without the super-journal it commits each db in turn, so a
   crash between the two leaves inconsistent checkout and repo databases.
*/
static int fsl__cx_host_main_file_check(fsl_cx * const f,
                                        fsl_db * const db){
  char * zFile = NULL;
  int rc = fsl_db_get_text(db, &zFile, NULL,
                           "SELECT file FROM pragma_database_list"
                           " WHERE seq=0");
  if( rc ){
    rc = fsl_cx_uplift_db_error2(f, db, rc);
  }else if( !zFile || !*zFile ){
    rc = fsl_cx_err_set(f, FSL_RC_UNSUPPORTED,
                        "A repository and a checkout can only be "
                        "opened together on a host db handle whose "
                        "main db is a file. Otherwise SQLite cannot "
                        "commit a check-in atomically.");
  }
  fsl_free(zFile);
  return rc;
}

/**
   Creates zDbName as an empty file if it does not exist and
   createIfNotExists is true. Sets *createdIt to true if it did.
*/
static int fsl__cx_db_file_create(fsl_cx * const f, char const * zDbName,
                                  bool createIfNotExists,
                                  bool * createdIt){
  *createdIt = false;
  if(createIfNotExists
     && 0!=fsl_file_access( zDbName, F_OK )){
    FILE * const cf = fsl_fopen(zDbName, "w");
    if(!cf){
      return fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_IO),
                            "Error creating new db file [%s].",
                            zDbName);
    }
    fsl_fclose(cf);
    *createdIt = true;
  }
  return 0;
}

/**
   For a context on a host's connection, db (f's main db): picks the
   schema name for role r, which is fsl_db_role_name(r) unless another
   context on the connection uses that, else the first free one of
   NAME_2, NAME_3, ... Stores it in db->impl.share and returns it, or
   NULL on error (with f's error state set).
*/
static char const * fsl__cx_host_schema_pick(fsl_cx * const f,
                                             fsl_db * const db,
                                             fsl_dbrole_e r){
  char const * const zBase = fsl_db_role_name(r);
  char ** const pz = FSL_DBROLE_REPO==r
    ? &db->impl.share.zRepo : &db->impl.share.zCkout;
  assert(FSL_DBROLE_REPO==r || FSL_DBROLE_CKOUT==r);
  fsl_free(*pz);
  *pz = NULL;
  for( unsigned i = 1; i < 1000; ++i ){
    int32_t n = 0;
    char * const z = 1==i
      ? fsl_strdup(zBase) : fsl_mprintf("%s_%u", zBase, i);
    int rc;
    if( !z ){
      fsl_cx_err_set(f, FSL_RC_OOM, NULL);
      return NULL;
    }
    rc = fsl_db_get_int32(db, &n, "SELECT count(*) FROM "
                          "pragma_database_list WHERE name=%Q", z);
    if( rc ){
      fsl_free(z);
      fsl_cx_uplift_db_error2(f, db, rc);
      return NULL;
    }
    if( !n ){
      if( 1==i ){
        fsl_free(z) /* fsl__db_schema() falls back to zBase */;
        return zBase;
      }
      *pz = z;
      return z;
    }
    fsl_free(z);
  }
  fsl_cx_err_set(f, FSL_RC_RANGE, "No free schema name for %s.", zBase);
  return NULL;
}

static int fsl__cx_prefixed_names(fsl_cx * const f, fsl_db * const dbM,
                                  fsl_dbrole_e r, char const * zPrefix);

/**
   The fsl__cx_attach_role() counterpart for a context bound to a
   host's handle: ATTACHes zDbName to that handle as dbName instead of
   opening a connection of its own, then sets db up as f->dbMain.

   If zPrefix is not NULL, r must be FSL_DBROLE_REPO, and db becomes
   the repository tables of the host's main db whose names start with
   zPrefix instead (fsl_repo_open_host()): nothing is ATTACHed or
   created, and zDbName and dbName are not used.
*/
static int fsl__cx_attach_host(fsl_cx * const f, fsl_db * const db,
                               char const * zDbName,
                               char const * dbName, fsl_dbrole_e r,
                               bool createIfNotExists,
                               char const * zPrefix){
  sqlite3 * const dbh = f->db.host.dbh;
  bool createdIt = false, attached = false;
  int rc;
  int32_t n = 0;
  assert(!zPrefix || FSL_DBROLE_REPO==r);
  fsl__db_borrow(db, dbh);
  if( zPrefix ){
    rc = fsl__cx_repo_prefix_check(f, db, zPrefix);
    if( 0==rc ) rc = fsl__cx_prefixed_names(f, db, r, zPrefix);
  }else{
    rc = fsl__cx_db_filename_set(f, db, zDbName);
  }
  if(rc) goto end;
  {
    /* Contexts may share a host's connection, not one which libfossil
       opened for a context of its own. */
    fsl__cxreg const * const reg = sqlite3_get_clientdata(dbh, "fsl_cxreg");
    if( reg && reg->n && reg->a[0]->dbMain
        && !fsl__db_is_borrowed(reg->a[0]->dbMain) ){
      rc = fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                          "This db handle is a libfossil context's "
                          "own connection.");
      goto end;
    }
  }
  rc = fsl_db_get_int32(db, &n, "PRAGMA foreign_keys");
  if( 0==rc && n ){
    rc = fsl_cx_err_set(f, FSL_RC_UNSUPPORTED,
                        "libfossil needs PRAGMA foreign_keys=OFF.");
  }
  if( 0==rc && !zPrefix ){
    /* Other contexts may share this connection: take a schema name of
       our own if theirs is taken. */
    dbName = fsl__cx_host_schema_pick(f, db, r);
    if( !dbName ) rc = f->error.code;
    else{
      fsl_free(db->name);
      db->name = fsl_strdup(dbName);
      if( !db->name ) rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
    }
  }
  if( 0==rc && !zPrefix ){
    rc = fsl__cx_db_file_create(f, zDbName, createIfNotExists,
                                &createdIt);
    if( 0==rc ){
      rc = fsl_db_attach(db, zDbName, dbName);
      attached = 0==rc;
    }
    if( 0==rc ) rc = fsl__cx_host_shadow_check(f, db, dbName);
  }
  if( 0==rc ){
    /* As for a connection of our own, minus SQL tracing, which would
       replace the host's sqlite3_trace_v2() callback. */
    fsl_db_event_listener(db, fsl__db_event_f_cx, f,
                          FSL_DB_EVENT_group_txn | FSL_DB_EVENT_CLOSING);
    rc = fsl__cx_init_db(f, db);
  }
  if( 0==rc && !zPrefix ) rc = fsl__cx_db_cache_size(db, dbName);
  if( 0==rc ){
    /* One row per context, keyed by its id in the connection's
       registry. */
    rc = fsl_db_exec(db, "CREATE TEMP TABLE IF NOT EXISTS "
                     "temp.fsl_host_gen(gen INTEGER)");
    f->db.host.gen = 0;
    if( 0==rc ) rc = fsl_db_exec(db, "DELETE FROM temp.fsl_host_gen"
                                 " WHERE rowid=%u", db->impl.share.id);
  }
  end:
  if( rc ){
    if( !f->error.code ) rc = fsl_cx_uplift_db_error2(f, db, rc);
    if( f->dbMain == db ){
      fsl__cx_uninit_db(f, db);
      f->dbMain = NULL;
    }
    if( attached ) fsl_db_detach(db, dbName);
    fsl_db_close(db)/*does not close the host's handle*/;
    if( createdIt ) fsl_file_unlink(zDbName);
  }else{
    db->role |= r;
  }
  return rc;
}

int fsl_cx_host_db(fsl_cx * const f, fsl_db_t * const dbh){
  if( f->dbMain ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot bind a host db handle while a "
                          "repository or checkout is opened.");
  }
  f->db.host.dbh = dbh;
  f->db.host.closing = false;
  return 0;
}

void fsl_cx_host_db_closing(fsl_cx * const f){
  if( f->db.host.dbh ) f->db.host.closing = true;
}

/**
   Change the journal mode of f's checkout db to DELETE if it is WAL, MEMORY or
   OFF. A check-in writes the repository and the checkout db's in one
   transaction, and SQLite can only do atomic commits via a super-journal, and a
   super-journal cannot contain a WAL mode db. A WAL checkout db is therefore not
   allowable, because it commits separately from the repository db, ie non-atomically
   across the dbs, meaning a killed process between these commits leaves a corrupted repo. 

   Returns FSL_RC_LOCKED if SQLite cannot change the mode, e.g. while another
   connection has the checkout db open.
*/
static int fsl__cx_ckout_journal_mode(fsl_cx * const f){
  fsl_db * const db = f->dbMain;
  char const * const zSchema = fsl__db_schema(db, FSL_DBROLE_CKOUT);
  char * zMode = NULL;
  int rc = fsl_db_get_text(db, &zMode, NULL, "PRAGMA %s.journal_mode",
                           zSchema);
  if( 0==rc && zMode
      && (0==fsl_stricmp(zMode, "wal")
          || 0==fsl_stricmp(zMode, "memory")
          || 0==fsl_stricmp(zMode, "off")) ){
    char * zNew = NULL;
    rc = fsl_db_get_text(db, &zNew, NULL,
                         "PRAGMA %s.journal_mode=DELETE", zSchema);
    if( rc || !zNew || fsl_stricmp(zNew, "delete") ){
      rc = fsl_cx_err_set(f, FSL_RC_LOCKED,
                          "Cannot change the checkout db's journal "
                          "mode from %s to DELETE%s%s. Check-in is "
                          "only atomic in a rollback journal mode. "
                          "Risk of data loss.", zMode,
                          rc ? ": " : "",
                          rc ? sqlite3_errmsg(db->dbh) : "");
      fsl_db_err_reset(db);
    }
    fsl_free(zNew);
  }
  if( rc && !f->error.code ) rc = fsl_cx_uplift_db_error2(f, db, rc);
  fsl_free(zMode);
  return rc;
}

/**
   Set synchronous=FULL on f's repository db while a checkout db is
   attached with it. The in-tree SQLite is built with
   SQLITE_DEFAULT_WAL_SYNCHRONOUS=1, so a repository db in WAL mode defaults
   to synchronous=NORMAL. A check-in commits a WAL repository db before the
   checkout db, so a power loss after the checkout db commits can lose the
   check-in from the repository db.

   SQLite cannot change synchronous levels inside a transaction. For a
   repository db in WAL mode, fsl_checkin_commit() will refuse check-ins
   until the checkout db is attached again outside a transaction.
*/
int fsl__cx_repo_sync_full(fsl_cx * const f){
  fsl_db * const db = f->dbMain;
  int rc;
  if( fsl__db_repo_prefix(db) ){
    return 0 /* the host's main db, whose settings are the host's */;
  }
  if( !sqlite3_get_autocommit(db->dbh) ) return 0;
  rc = fsl_db_exec(db, "PRAGMA %s.synchronous=FULL",
                   fsl__db_schema(db, FSL_DBROLE_REPO));
  return rc ? fsl_cx_uplift_db_error2(f, db, rc) : 0;
}

int fsl__cx_attach_role(fsl_cx * const f, const char *zDbName,
                         fsl_dbrole_e r, bool createIfNotExists){
  char const * dbName =
    fsl_db_role_name(r)/* Reminder: these bytes MUST be static for
                          legal use with SQLITE_DBCONFIG_MAINDBNAME.
                          On a host's connection, a context which
                          shares it may use another name, from
                          fsl__cx_host_schema_pick(). */;
  fsl_db * const db = fsl__cx_db_for_role(f, r);
  int rc;
  assert(db);
  assert(!db->dbh && "Internal API misuse: don't call this when db is connected.");
  assert(!db->filename && "Don't re-attach!");
  assert(!db->name && "Don't re-attach!");
  assert(dbName);
  assert(f->dbMain != db && "Don't re-attach the main db!");
  switch(r){
    case FSL_DBROLE_REPO:
    case FSL_DBROLE_CKOUT:
      break;
    case FSL_DBROLE_CONFIG:
    case FSL_DBROLE_MAIN:
    case FSL_DBROLE_NONE:
    default:
      assert(!"cannot happen/not legal");
      fsl__fatal(FSL_RC_RANGE, "Serious internal API misuse via %s().",
                 __func__);
      return FSL_RC_RANGE;
  }
  db->name = fsl_strdup(dbName);
  if(!db->name){
    rc = FSL_RC_OOM;
    goto end;
  }
  if(!f->dbMain && f->db.host.dbh){
    rc = fsl__cx_attach_host(f, db, zDbName, dbName, r,
                             createIfNotExists, NULL);
  }else if(!f->dbMain){
    // This is our first/main db. OPEN it.
    rc = fsl_db_open( db, zDbName, createIfNotExists
                      ? FSL_DB_OPEN_RWC
                      : FSL_DB_OPEN_RW );
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      fsl_db_close(db);
      goto end;
    }
    if( f->cxConfig.dbOnOpen.callback ){
      rc = f->cxConfig.dbOnOpen.callback(
        db, f->cxConfig.dbOnOpen.state
      );
      if( rc ){
        if( db->error.code ){
          fsl_error_propagate(&db->error, &f->error);
        }else{
          int const rc2 = fsl_cx_uplift_db_error2(f, db, rc);
          if( rc2 ) rc = rc2;
          if( !f->error.code ){
            rc = fsl_cx_err_set(f, rc,
                                "fsl_cx_config::dbOnOpen::callback() "
                                "failed with code %R.", rc);
          }
        }
        fsl_db_close(db);
        goto end;
      }
    }/* dbOnOpen */
    int const sqrc = sqlite3_db_config(db->dbh,
                                       SQLITE_DBCONFIG_MAINDBNAME,
                                       dbName);
    if(sqrc){
      rc = fsl__db_errcode(db, sqrc);
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      fsl_db_close(db);
    }else{
      if( 1 ){
        /* Delay setup of tracing until after the SEE init
           specifically to keep those pragmas from being traced. */
        fsl_flag32_t mask = FSL_DB_EVENT_group_txn
          | FSL_DB_EVENT_CLOSING;
        if( f->cxConfig.traceSql ){
          fsl_db_sqltrace_enable(db, NULL, false)
            /*workaround for older tracing API*/;
          assert( !db->impl.event.fpTrace );
          mask |= FSL_DB_EVENT_TRACE_SQLX
            /* TODO: a toggle for FSL_DB_EVENT_TRACE_SQLX
               vs FSL_DB_EVENT_TRACE_SQL. */;
        }
        fsl_db_event_listener(db, fsl__db_event_f_cx, f, mask);
      }
      rc = fsl__cx_init_db(f, db);
      if( 0==rc ){
        rc = fsl__cx_db_cache_size(db, dbName);
        if( rc ) rc = fsl_cx_uplift_db_error2(f, db, rc);
      }
      db->role |= r;
      assert(db == f->dbMain)/*even on failure*/;
      /* Should we fsl__cx_detach_role() here? */
    }
  }else{
    // This is our secondary db. ATTACH it.
    assert(db != f->dbMain);
    rc = fsl__cx_db_filename_set(f, db, zDbName);
    if(0==rc && fsl__db_is_borrowed(f->dbMain)){
      rc = fsl__cx_host_main_file_check(f, f->dbMain);
      if(rc) fsl_db_close(db)/*cleans up strings*/;
    }
    if(0==rc && fsl__db_is_borrowed(f->dbMain)){
      char const * const z = fsl__cx_host_schema_pick(f, f->dbMain, r);
      if( !z ){
        rc = f->error.code;
        fsl_db_close(db);
      }else{
        dbName = z;
        fsl_free(db->name);
        db->name = fsl_strdup(z);
        if( !db->name ){
          rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
          fsl_db_close(db);
        }
      }
    }
    if(0==rc){
      bool createdIt = false;
      rc = fsl__cx_db_file_create(f, zDbName, createIfNotExists,
                                  &createdIt);
      if(rc) goto end;
      rc = fsl_db_attach(f->dbMain, zDbName, dbName);
      if(0==rc && fsl__db_is_borrowed(f->dbMain)){
        rc = fsl__cx_host_shadow_check(f, f->dbMain, dbName);
        if(rc) fsl_db_detach(f->dbMain, dbName);
      }
      if(rc){
        if(!f->error.code) fsl_cx_uplift_db_error(f, f->dbMain);
        fsl_db_close(db)/*cleans up strings*/;
        if(createdIt) fsl_file_unlink(zDbName);
      }else{
        /*MARKER(("Attached %p role %d %s %s\n",
          (void const *)db, r, db->name, db->filename));*/
        f->dbMain->role |= r;
        rc = fsl__cx_db_cache_size(f->dbMain, dbName);
        if( rc ) fsl_cx_uplift_db_error(f, f->dbMain);
      }
    }
  }
  end:
  if( 0==rc && FSL_DBROLE_CKOUT==r ){
    rc = fsl__cx_ckout_journal_mode(f);
    if( rc ) fsl__cx_detach_role(f, r);
  }
  if( 0==rc && fsl_cx_db_repo(f) && fsl_cx_db_ckout(f) ){
    rc = fsl__cx_repo_sync_full(f);
    if( rc ) fsl__cx_detach_role(f, r);
  }
  return rc;
}

/** True if z is a valid fsl_repo_open_ckout_opt::hostTablePrefix. */
static bool fsl__cx_host_prefix_ok(char const * z){
  if( !z || !('_'==*z || fsl_isalpha(*z))
      || 0==fsl_strnicmp(z, "sqlite_", 7) ) return false;
  for( ; *z; ++z ){
    if( !('_'==*z || fsl_isalnum(*z)) ) return false;
  }
  return true;
}

/**
   Refuses zPrefix, a table prefix for role r's tables in the main db
   of dbM's connection, if it and a table prefix of another context on
   that connection, of its repository or its checkout, or f's own
   prefix for the other role, are leading parts of one another,
   ignoring case. Prefixes on one host db must not overlap: checkout
   table names end in others' (fsl_undo_vfile, old_stash), so prefix
   "w_fsl_undo_" would name tables of "w_", and "w_" may not be the
   start of a repository's "w_x_" either.
*/
static int fsl__cx_prefix_overlap_check(fsl_cx * const f,
                                        fsl_db * const dbM,
                                        fsl_dbrole_e r,
                                        char const * zPrefix){
  fsl__cxreg const * const reg =
    sqlite3_get_clientdata(dbM->dbh, "fsl_cxreg");
  fsl_size_t const n = fsl_strlen(zPrefix);
  for( unsigned i = 0; reg && i < reg->n; ++i ){
    fsl_db const * const o = reg->a[i]->dbMain;
    for( int k = 0; o && k < 2; ++k ){
      fsl_dbrole_e const rO = k ? FSL_DBROLE_REPO : FSL_DBROLE_CKOUT;
      char const * const zO =
        k ? fsl__db_repo_prefix(o) : fsl__db_ckout_prefix(o);
      fsl_size_t const nO = fsl_strlen(zO);
      if( zO && (reg->a[i]!=f || rO!=r)
          && 0==fsl_strnicmp(zPrefix, zO, (fsl_int_t)(n<nO ? n : nO)) ){
        return fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                              "%s table prefix %s overlaps %s table "
                              "prefix %s of %s context on this db "
                              "handle.", FSL_DBROLE_REPO==r
                              ? "Repository" : "Checkout", zPrefix,
                              FSL_DBROLE_REPO==rO
                              ? "repository" : "checkout", zO,
                              reg->a[i]==f ? "this" : "another");
      }
    }
  }
  return 0;
}

int fsl__cx_repo_prefix_check(fsl_cx * const f, fsl_db * const dbM,
                              char const * zPrefix){
  static char const * const azExt[] = {
    "fslfiles_", "fslclock_", "fslwc_", NULL
  };
  fsl_size_t const n = fsl_strlen(zPrefix);
  if( !fsl__cx_host_prefix_ok(zPrefix) ){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid repository table prefix: %s",
                          zPrefix ? zPrefix : "NULL");
  }
  for( int i = 0; azExt[i]; ++i ){
    fsl_size_t const nE = fsl_strlen(azExt[i]);
    if( 0==fsl_strnicmp(zPrefix, azExt[i], (fsl_int_t)(n<nE ? n : nE)) ){
      return fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                            "Repository table prefix %s overlaps %s, "
                            "a prefix of the SQLite extension's "
                            "working copies.", zPrefix, azExt[i]);
    }
  }
  return fsl__cx_prefix_overlap_check(f, dbM, FSL_DBROLE_REPO, zPrefix);
}

/**
   Makes role r's fsl_db of f the tables of the main db of dbM's
   connection whose names start with zPrefix: its name and schema name
   (fsl__db_schema()) become "main", its file name the main db's, which
   must be a file (else FSL_RC_UNSUPPORTED), and zPrefix becomes
   fsl__db_repo_prefix() resp. fsl__db_ckout_prefix() of dbM. dbM is
   f's main db, or, if role r is opened first, r's own db, which is
   then to become f's main db. ATTACHes nothing, and changes nothing
   of the main db's settings (e.g. its journal mode). Does not add r to
   dbM->role. On error the caller must fsl_db_close() r's db.
*/
static int fsl__cx_prefixed_names(fsl_cx * const f, fsl_db * const dbM,
                                  fsl_dbrole_e r, char const * zPrefix){
  fsl_db * const db = fsl__cx_db_for_role(f, r);
  bool const isRepo = FSL_DBROLE_REPO==r;
  char ** const pzSchema =
    isRepo ? &dbM->impl.share.zRepo : &dbM->impl.share.zCkout;
  char ** const pzPrefix =
    isRepo ? &dbM->impl.share.zRepoPrefix : &dbM->impl.share.zCkoutPrefix;
  char * zFile = NULL;
  int rc = fsl_db_get_text(dbM, &zFile, NULL, "SELECT file FROM "
                           "pragma_database_list WHERE seq=0");
  if( rc ) return fsl_cx_uplift_db_error2(f, dbM, rc);
  if( !zFile || !*zFile ){
    fsl_free(zFile);
    return fsl_cx_err_set(f, FSL_RC_UNSUPPORTED,
                          "Prefixed %s tables need a host db handle "
                          "whose main db is a file.",
                          isRepo ? "repository" : "checkout");
  }
  fsl_free(db->filename);
  db->filename = zFile;
  fsl_free(db->name);
  db->name = fsl_strdup("main");
  fsl_free(*pzSchema);
  *pzSchema = fsl_strdup("main");
  fsl_free(*pzPrefix);
  *pzPrefix = fsl_strdup(zPrefix);
  if( !db->name || !*pzSchema || !*pzPrefix ){
    fsl_free(*pzSchema);
    *pzSchema = NULL;
    fsl_free(*pzPrefix);
    *pzPrefix = NULL;
    return fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  }
  return 0;
}

int fsl__cx_ckout_prefix_check(fsl_cx * const f, char const * zPrefix){
  fsl_db * const dbM = f->dbMain;
  int rc;
  if( !dbM || !fsl__db_is_borrowed(dbM) || !(dbM->role & FSL_DBROLE_REPO) ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Prefixed checkout tables need a repository "
                          "opened on a host db handle (fsl_cx_host_db()).");
  }else if( !fsl__cx_host_prefix_ok(zPrefix) ){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid checkout table prefix: %s",
                          zPrefix ? zPrefix : "NULL");
  }
  rc = fsl__cx_prefix_overlap_check(f, dbM, FSL_DBROLE_CKOUT, zPrefix);
  return rc ? rc : fsl__cx_host_main_file_check(f, dbM);
}

int fsl__cx_attach_ckout_prefixed(fsl_cx * const f, char const * zPrefix){
  fsl_db * const dbM = f->dbMain;
  fsl_db * const dbC = fsl__cx_db_for_role(f, FSL_DBROLE_CKOUT);
  int rc;
  assert(!dbC->dbh && !dbC->filename && !dbC->name);
  rc = fsl__cx_ckout_prefix_check(f, zPrefix);
  if( 0==rc ) rc = fsl__cx_prefixed_names(f, dbM, FSL_DBROLE_CKOUT,
                                          zPrefix);
  if( rc ){
    fsl_db_close(dbC)/*cleans up strings*/;
  }else{
    dbM->role |= FSL_DBROLE_CKOUT
      /* fsl_repo_open_ckout() sets the repository's synchronous=FULL
         first, as SQLite does not allow that in a transaction. */;
  }
  return rc;
}

int fsl__cx_attach_repo_prefixed(fsl_cx * const f, char const * zPrefix){
  fsl_db * const db = fsl__cx_db_for_role(f, FSL_DBROLE_REPO);
  int rc;
  assert(!db->dbh && !db->filename && !db->name);
  if( !(f->dbMain ? fsl__db_is_borrowed(f->dbMain) : !!f->db.host.dbh) ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Prefixed repository tables need a context "
                          "on a host db handle (fsl_cx_host_db()).");
  }else if( !f->dbMain ){
    return fsl__cx_attach_host(f, db, NULL, NULL, FSL_DBROLE_REPO,
                               false, zPrefix);
  }
  /* A checkout db on the host's handle was opened first. */
  rc = fsl__cx_repo_prefix_check(f, f->dbMain, zPrefix);
  if( 0==rc ) rc = fsl__cx_prefixed_names(f, f->dbMain, FSL_DBROLE_REPO,
                                          zPrefix);
  if( rc ) fsl_db_close(db)/*cleans up strings*/;
  else f->dbMain->role |= FSL_DBROLE_REPO;
  return rc;
}

int fsl_config_close( fsl_cx * const f ){
  if( fsl_db_txn_level(&f->db.gconfig.db) ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close config db with an "
                          "opened transaction.");
  }
  fsl_db_close(&f->db.gconfig.db);
  return 0;
}

int fsl_close_scm_dbs(fsl_cx * const f){
  if(fsl_cx_txn_level(f)){
    /* TODO???: force a full rollback and close it */
    //if(f->db.repo.db.dbh) fsl_db_rollback_force(&f->db.repo.db);
    //if(f->db.ckout.db.dbh) fsl_db_rollback_force(&f->db.ckout.db);
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close repo or checkout with an "
                          "opened transaction.");
  }
  int rc = 0;
  if(!f->dbMain){
    // Make sure that all string resources are cleaned up...
    fsl__cx_finalize_cached_stmt(f);
    fsl_db_close(&f->db.repo.db);
    fsl_db_close(&f->db.ckout.db);
  }else{
    fsl_db * const dbR = &f->db.repo.db;
    rc = fsl__cx_detach_role(f, f->dbMain == dbR
                             ? FSL_DBROLE_REPO
                             : FSL_DBROLE_CKOUT)
      /* Will also close the counterpart db. */;
  }
  fsl_cx_user_set(f, NULL);
  return rc;
}

int fsl_close_dbs(fsl_cx * f){
  int rc = fsl_close_scm_dbs(f);
  return rc ? rc : fsl_config_close(f);
}

int fsl_repo_close( fsl_cx * const f ){
  return fsl_close_scm_dbs(f);
}

int fsl_ckout_close( fsl_cx * const f ){
  return fsl_close_scm_dbs(f);
}

/**
   If zDbName is a valid checkout database file, open it and return 0.
   If it is not a valid local database file, return a non-0 code.
*/
static int fsl__cx_ckout_open_db(fsl_cx * f, const char *zDbName){
  /* char *zVFileDef; */
  int rc;
  fsl_int_t const lsize = fsl_file_size(zDbName);
  if( -1 == lsize  ){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Checkout db [%s] not found or cannot "
                          "be read.", zDbName);
  }
  if(
#if defined(LIBFOSSIL_LUMOSQL)
    fsl_dir_check(zDbName)!=1 &&
#endif
    (lsize%1024!=0 || lsize<4096)
  ){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "File's size is not correct for a "
                          "checkout db: %s",
                          zDbName);
  }
  rc = fsl__cx_attach_role(f, zDbName, FSL_DBROLE_CKOUT, false);
  return rc;
}


int fsl_cx_execv( fsl_cx * const f, char const * sql, va_list args ){
#if FSL_API_ARMOR
  if(!f->dbMain) return FSL_RC_MISUSE;
  if(!sql) return FSL_RC_MISUSE;
#else
  assert( f->dbMain );
  assert( sql );
#endif
  int const rc = fsl_db_execv(f->dbMain, sql, args);
  return rc ? fsl_cx_uplift_db_error2(f, f->dbMain, rc) : 0;
}

int fsl_cx_exec( fsl_cx * const f, char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_cx_execv( f, sql, args );
  va_end(args);
  return rc;
}

int fsl_cx_exec_multiv( fsl_cx * const f, char const * sql, va_list args ){
#if FSL_API_ARMOR
  if(!f->dbMain) return FSL_RC_MISUSE;
  if(!sql) return FSL_RC_MISUSE;
#else
  assert( f->dbMain );
  assert( sql );
#endif
  int const rc = fsl_db_exec_multiv(f->dbMain, sql, args);
  return rc ? fsl_cx_uplift_db_error2(f, f->dbMain, rc) : 0;
}

int fsl_cx_exec_multi( fsl_cx * const f, char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_cx_exec_multiv( f, sql, args );
  va_end(args);
  return rc;
}

int fsl_cx_preparev( fsl_cx * const f, fsl_stmt * const tgt, char const * sql,
                     va_list args ){
#if FSL_API_ARMOR
  if(!f->dbMain) return FSL_RC_MISUSE;
  if(!tgt) return FSL_RC_MISUSE;
#else
  assert( f->dbMain );
  assert( tgt );
#endif
  int const rc = fsl_db_preparev(f->dbMain, tgt, sql, args);
  return rc ? fsl_cx_uplift_db_error2(f, f->dbMain, rc) : 0;
}

int fsl_cx_prepare( fsl_cx * const f, fsl_stmt * const tgt, char const * sql,
                      ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_cx_preparev( f, tgt, sql, args );
  va_end(args);
  return rc;
}

int fsl_cx_preparev_cached( fsl_cx * const f, fsl_stmt ** tgt, char const * sql,
                            va_list args ){
#if FSL_API_ARMOR
  if(!f->dbMain) return FSL_RC_MISUSE;
  if(!tgt) return FSL_RC_MISUSE;
#else
  assert( f->dbMain );
  assert( tgt );
#endif
  int const rc = fsl_db_preparev_cached(f->dbMain, tgt, sql, args);
  return rc ? fsl_cx_uplift_db_error2(f, f->dbMain, rc) : 0;
}

int fsl_cx_prepare_cached( fsl_cx * const f, fsl_stmt ** tgt, char const * sql,
                           ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_cx_preparev_cached( f, tgt, sql, args );
  va_end(args);
  return rc;
}


/**
    Passes the fsl_schema_config() SQL code through a new/truncated
    file named dbName. If the file exists before this call, it is
    unlink()ed and fails if that operation fails.
 */
static int fsl_config_file_reset(fsl_cx * const f, char const * dbName){
  fsl_db DB = fsl_db_empty;
  fsl_db * db = &DB;
  int rc = 0;
  bool isAttached = false;
  const char * zPrefix = fsl_db_role_name(FSL_DBROLE_CONFIG);
  if(-1 != fsl_file_size(dbName)){
    rc = fsl_file_unlink(dbName);
    if(rc){
      return fsl_cx_err_set(f, rc,
                            "Error %s while removing old config file (%s)",
                            fsl_rc_cstr(rc), dbName);
    }
  }
  /**
     Hoop-jumping: because the schema file has a cfg. prefix for the
     table(s), and we cannot assign an arbitrary name to an open()'d
     db, we first open the db (making the the "main" db), then
     ATTACH it to itself to provide the fsl_db_role_name() alias.

     2024-09-16: we can use SQLITE_DBCONFIG_MAINDBNAME for this instead.
  */
  rc = fsl_db_open(db, dbName, FSL_DB_OPEN_RWC);
  if(rc) goto end;
  rc = fsl_db_attach(db, dbName, zPrefix);
  if(rc) goto end;
  isAttached = true;
  rc = fsl_db_exec_multi(db, "%s", fsl_schema_config());
  end:
  if(rc && FSL_RC_OOM!=rc && !f->error.code){
    rc = fsl_cx_err_set(f, rc, "cannot create global config "
                        "database %s: %s", dbName,
                        rc==db->error.code
                        ? fsl_b_cstr(&db->error.msg)
                        : fsl_rc_cstr(rc));
  }
  if(isAttached) fsl_db_detach(db, zPrefix);
  fsl_db_close(db);
  return rc;
}

int fsl_config_global_preferred_name(char ** zOut){
  char * zEnv = 0 /* from fsl_getenv(). Note the special-case free()
                     semantics!!! */;
  char * zRc = 0 /* `*zOut` result, from fsl_mprintf() */;
  int rc = 0;

#if FSL_PLATFORM_IS_WINDOWS
  zEnv = fsl_getenv("FOSSIL_HOME");
  if( zEnv==0 ){
    zEnv = fsl_getenv("LOCALAPPDATA");
    if( zEnv==0 ){
      zEnv = fsl_getenv("APPDATA");
      if( zEnv==0 ){
        zEnv = fsl_getenv("USERPROFILE");
        if( zEnv==0 ){
          char * const zDrive = fsl_getenv("HOMEDRIVE");
          char * const zPath = fsl_getenv("HOMEPATH");
          if( zDrive && zPath ){
            zRc = fsl_mprintf("%s%//_fossil", zDrive, zPath);
          }
          if(zDrive) fsl_os_str_free(zDrive);
          if(zPath) fsl_os_str_free(zPath);
        }
      }
    }
  }
  if(!zRc){
    if(!zEnv) rc = FSL_RC_NOT_FOUND;
    else{
      zRc = fsl_mprintf("%//_fossil", zEnv);
      if(!zRc) rc = FSL_RC_OOM;
    }
  }
#else
  fsl_b buf = fsl_b_empty;
  /* Option 1: $FOSSIL_HOME/.fossil */
  zEnv = fsl_getenv("FOSSIL_HOME");
  if(zEnv){
    zRc = fsl_mprintf("%s/.fossil", zEnv);
    if(!zRc) rc = FSL_RC_OOM;
    goto end;
  }
  /* Option 2: if $HOME/.fossil exists, use that */
  rc = fsl_find_home_dir(&buf, 0);
  if(rc){
    /* fossil(1) uses XDG_CONFIG_HOME when no home directory
       is set. */
    if(FSL_RC_OOM!=rc && (zEnv = fsl_getenv("XDG_CONFIG_HOME"))){
      zRc = fsl_mprintf("%s/fossil.db", zEnv);
      rc = zRc ? 0 : FSL_RC_OOM;
    }
    goto end;
  }
  rc = fsl_b_append(&buf, "/.fossil", 8);
  if(rc) goto end;
  if(fsl_file_size(fsl_b_cstr(&buf))>1024*3){
    zRc = fsl_b_take(&buf);
    goto end;
  }
  /* Option 3: $XDG_CONFIG_HOME/fossil.db */
  fsl_os_str_free(zEnv);
  zEnv = fsl_getenv("XDG_CONFIG_HOME");
  if(zEnv){
    zRc = fsl_mprintf("%s/fossil.db", zEnv);
    if(!zRc) rc = FSL_RC_OOM;
    goto end;
  }
  /* Option 4: If $HOME/.config is a directory,
     use $HOME/.config/fossil.db */
  buf.used -= 8 /* "/.fossil" */;
  buf.mem[buf.used] = 0;
  rc = fsl_b_append(&buf, "/.config", 8);
  if(rc) goto end;
  if(fsl_dir_check(fsl_b_cstr(&buf))>0){
    zRc = fsl_mprintf("%b/fossil.db", &buf);
    if(!zRc) rc = FSL_RC_OOM;
    goto end;
  }
  /* Option 5: fall back to $HOME/.fossil */
  buf.used -= 8 /* "/.config" */;
  buf.mem[buf.used] = 0;
  rc = fsl_b_append(&buf, "/.fossil", 8);
  if(!rc) zRc = fsl_b_take(&buf);
  end:
  fsl_b_clear(&buf);
#endif
  if(zEnv) fsl_os_str_free(zEnv);
  if(!rc){
    if(zRc) *zOut = zRc;
    else rc = FSL_RC_OOM;
  }
  return rc;
}

/**
   Sets f's error state for a failure code from
   fsl_config_global_preferred_name() and returns rc.
*/
static int fsl__config_global_name_err(fsl_cx * const f, int rc){
  if(FSL_RC_NOT_FOUND==rc){
#if FSL_PLATFORM_IS_WINDOWS
    rc = fsl_cx_err_set(f, rc, "cannot locate home directory - please "
                        "set one of the FOSSIL_HOME, LOCALAPPDATA, "
                        "APPDATA, USERPROFILE, or HOMEDRIVE and "
                        "HOMEPATH environment variables");
#else
    rc = fsl_cx_err_set(f, rc, "cannot locate home directory - please "
                        "set one of the FOSSIL_HOME, XDG_CONFIG_HOME, "
                        "or HOME environment variables");
#endif
  }else if(FSL_RC_OOM!=rc){
    fsl_b msg = fsl_b_empty;
    if(fsl_find_home_dir(&msg, false) && msg.used){
      rc = fsl_cx_err_set(f, rc, "cannot locate the global config "
                          "database: %b", &msg);
    }else{
      rc = fsl_cx_err_set(f, rc, "cannot locate the global config "
                          "database: %R", rc);
    }
    fsl_b_clear(&msg);
  }
  return rc;
}

int fsl_config_open( fsl_cx * const f, char const * openDbName ){
  int rc = 0;
  const char * zDbName = 0;
  char * zPrefName = 0;
  if(fsl_cx_db_config(f)){
    if(NULL==openDbName || 0==*openDbName) return 0/*nothing to do*/;
    rc = fsl_config_close(f);
    if(rc) return rc;
    assert(!f->db.gconfig.db.dbh);
  }
  if(openDbName && *openDbName){
    zDbName = openDbName;
  }else{
    rc = fsl_config_global_preferred_name(&zPrefName);
    if(rc){
      rc = fsl__config_global_name_err(f, rc);
      goto end;
    }
    zDbName = zPrefName;
  }
  {
    fsl_int_t const fsize = fsl_file_size(zDbName);
    if( -1==fsize || (fsize<1024*3) ){
      rc = fsl_config_file_reset(f, zDbName);
      if(rc) goto end;
    }
  }
#if defined(_WIN32) || defined(__CYGWIN__)
  /* TODO: Jan made some changes in this area in fossil(1) in
     January(?) 2014, such that only the config file needs to be
     writable, not the directory. Port that in.
  */
  if( fsl_file_access(zDbName, W_OK) ){
    rc = fsl_cx_err_set(f, FSL_RC_ACCESS,
                        "Configuration database [%s] "
                        "must be writeable.", zDbName);
    goto end;
  }
#endif
  assert(NULL==fsl_cx_db_config(f));
  rc = fsl_db_open(&f->db.gconfig.db, zDbName,
                   FSL_DB_OPEN_RW | (f->cxConfig.traceSql
                                    ? FSL_DB_OPEN_TRACE_SQL
                                    : 0));
  if(0==rc){
    int const sqrc = sqlite3_db_config(f->db.gconfig.db.dbh,
                                       SQLITE_DBCONFIG_MAINDBNAME,
                                       fsl_db_role_name(FSL_DBROLE_CONFIG));
    if(sqrc) rc = fsl__db_errcode(&f->db.gconfig.db, sqrc);
    if(0==rc){
      rc = fsl__cx_db_cache_size(&f->db.gconfig.db,
                                 fsl_db_role_name(FSL_DBROLE_CONFIG));
    }
  }
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, &f->db.gconfig.db, rc);
    fsl_db_close(&f->db.gconfig.db);
  }
  end:
  fsl_free(zPrefName);
  return rc;
}

static int fsl_cx_load_glob_lists(fsl_cx * f){
  int rc;
  rc = fsl_config_globs_load(f, &f->cache.globs.ignore, "ignore-glob");
  if(!rc) rc = fsl_config_globs_load(f, &f->cache.globs.binary, "binary-glob");
  if(!rc) rc = fsl_config_globs_load(f, &f->cache.globs.crnl, "crnl-glob");
  return rc;
}

int fsl_cx_glob_list( fsl_cx * const f,
                      fsl_glob_category_e gtype,
                      fsl_list **tgt,
                      bool reload ){
  fsl_list * li = NULL;
  char const * reloadKey = NULL;
  switch(gtype){
    case FSL_GLOBS_IGNORE: li = &f->cache.globs.ignore;
      reloadKey = "ignore-glob"; break;
    case FSL_GLOBS_CRNL: li = &f->cache.globs.crnl;
      reloadKey = "crnl-glob"; break;
    case FSL_GLOBS_BINARY: li = &f->cache.globs.binary;
      reloadKey = "binary-glob"; break;
    default:
      return fsl_cx_err_set(f, FSL_RC_RANGE,
                            "invalid glob category: %d", (int)gtype);
  }
  int rc = 0;
  if(reload){
    assert(reloadKey);
    fsl_glob_list_clear(li);
    rc = fsl_config_globs_load(f, li, reloadKey);
  }
  if(0==rc) *tgt = li;
  return rc;
}

fsl_glob_category_e fsl_glob_name_to_category(char const * str){
  if(str){
#define CHECK(PRE,E) \
    if(*str==PRE[0] &&                          \
       (0==fsl_strcmp(PRE "-glob",str)          \
        || 0==fsl_strcmp(PRE,str))) return E;
    CHECK("ignore", FSL_GLOBS_IGNORE);
    CHECK("binary", FSL_GLOBS_BINARY);
    CHECK("crnl", FSL_GLOBS_CRNL);
#undef CHECK
  }
  return FSL_GLOBS_INVALID;
}


/**
   To be called after a repo or checkout/repo combination has been
   opened. This updates some internal cached info based on the
   checkout and/or repo.
*/
int fsl__cx_detach_ckout(fsl_cx * const f){
  return fsl__cx_detach_role(f, FSL_DBROLE_CKOUT);
}

int fsl__cx_after_open(fsl_cx * const f){
  f->cache.searchIndexExists = -1;
  int rc = fsl__ckout_version_fetch(f);
  if( !rc ) rc = fsl_cx_load_glob_lists(f);
  if( !rc ) fsl_cx_user_guess(f);
  return rc;
}


static void fsl_cx_fetch_hash_policy(fsl_cx * f){
  int const iPol =
    fsl_config_get_int32( f, FSL_CONFDB_REPO,
                          FSL_HPOLICY_AUTO, "hash-policy");
  fsl_hashpolicy_e p;
  switch(iPol){
    case FSL_HPOLICY_SHA3: p = FSL_HPOLICY_SHA3; break;
    case FSL_HPOLICY_SHA3_ONLY: p = FSL_HPOLICY_SHA3_ONLY; break;
    case FSL_HPOLICY_SHA1: p = FSL_HPOLICY_SHA1; break;
    case FSL_HPOLICY_SHUN_SHA1: p = FSL_HPOLICY_SHUN_SHA1; break;
    default: p = FSL_HPOLICY_AUTO; break;
  }
  f->cxConfig.hashPolicy = p;
}

#if 0
/**
    Return true if the schema is out-of-date. db must be an opened
    repo db.
 */
static bool fsl__db_repo_schema_is_outofdate(fsl_db *db){
  return fsl_db_exists(db, "SELECT 1 FROM {{dbname.repo}}.config "
                       "WHERE name='aux-schema' "
                       "AND value<>'%s'",
                       FSL_AUX_SCHEMA);
}

/*
   Returns 0 if db appears to have a current repository schema, 1 if
   it appears to have an out of date schema, and -1 if it appears to
   not be a repository.
*/
int fsl__db_repo_verify_schema(fsl_db * const db){
  if(fsl__db_repo_schema_is_outofdate(db)) return 1;
  else return fsl_db_exists(db,
                            "SELECT 1 FROM {{dbname.repo}}.config "
                            "WHERE name='project-code'")
    ? 0 : -1;
}
int fsl_repo_schema_validate(fsl_cx * const f, fsl_db * const db){
  int rc = 0;
  int const check = fsl__db_repo_verify_schema(db);
  if(0 != check){
    rc = (check<0)
      ? fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                      "DB file [%s] does not appear to be "
                      "a repository.", db->filename)
      : fsl_cx_err_set(f, FSL_RC_REPO_NEEDS_REBUILD,
                      "DB file [%s] appears to be a fossil "
                      "repsitory, but is out-of-date and needs "
                      "a rebuild.",
                      db->filename);
  }
  return rc;
}
#endif

bool fsl__repo_looks_valid(fsl_cx * const f){
  static char const * const azTable[] = {
    "blob", "delta", "rcvfrom", "user", "config", "mlink", "plink", NULL
  };
  fsl_db * const db = fsl_cx_db_repo(f);
  char const * const zPre = fsl__db_repo_prefix(db);
  fsl_b * const list = fsl__cx_scratchpad(f);
  int32_t n = 0;
  int rc = 0;
  for( int i = 0; 0==rc && azTable[i]; ++i ){
    rc = fsl_b_appendf(list, "%s'%q%q'", i ? "," : "", zPre ? zPre : "",
                       azTable[i]);
  }
  if( 0==rc ){
    rc = fsl_db_get_int32(db, &n,
                          "SELECT count(*) FROM %s.sqlite_master"
                          " WHERE name COLLATE nocase IN(%b)",
                          fsl__db_schema(db, FSL_DBROLE_REPO), list);
  }
  fsl__cx_scratchpad_yield(f, list);
  fsl_db_err_reset(db);
  return 0==rc && 7==n;
}

/**
   The rest of fsl_repo_open() resp. fsl_repo_open_host() for f's
   newly opened repository, db file zFile or the tables with prefix
   zPrefix: closes it again and fails with FSL_RC_NOT_A_REPO if it does
   not look like one (fsl__repo_looks_valid()), else loads f's state
   from it.
*/
static int fsl__repo_open_finish(fsl_cx * const f, char const * zFile,
                                 char const * zPrefix){
  int rc = 0;
  if(!fsl__repo_looks_valid(f)){
    fsl__cx_detach_role(f, FSL_DBROLE_REPO);
    return zPrefix
      ? fsl_cx_err_set(f, FSL_RC_NOT_A_REPO, "No repository with table "
                       "prefix %s in the host db.", zPrefix)
      : fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                       "Not a valid repository: %s", zFile);
  }
  if(!(FSL_CX_F_IS_OPENING_CKOUT & f->flags)){
    rc = fsl__cx_after_open(f);
  }
  if(!rc){
    fsl_db * const db = fsl_cx_db_repo(f);
    /* 2024-09-02: why do we force-set allows_symlinks and
       is_case_sensitive here? */
    fsl_cx_allows_symlinks(f, true);
    fsl_cx_is_case_sensitive(f, true);
    f->cache.seenDeltaManifest =
      fsl_config_get_int32(f, FSL_CONFDB_REPO, -1,
                           "seen-delta-manifest");
    fsl_cx_fetch_hash_policy(f);
    if(f->cxConfig.hashPolicy==FSL_HPOLICY_AUTO){
      if(fsl_db_exists(db, "SELECT 1 FROM {{dbname.repo}}.blob WHERE length(uuid)>40")
         || !fsl_db_exists(db, "SELECT 1 FROM {{dbname.repo}}.blob WHERE length(uuid)==40")){
        f->cxConfig.hashPolicy = FSL_HPOLICY_SHA3;
      }
    }
  }
  return rc;
}

int fsl_repo_open( fsl_cx * const f, char const * repoDbFile
                   /* , bool readOnlyCurrentlyIgnored */ ){
  if(fsl_cx_db_repo(f)){
    return fsl_cx_err_set(f, FSL_RC_ACCESS,
                          "Context already has an opened repository.");
  }else{
    int rc;
    if(0!=fsl_file_access( repoDbFile, F_OK )){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Repository db [%s] not found or cannot be read.",
                          repoDbFile);
    }else{
      rc = fsl__cx_attach_role(f, repoDbFile, FSL_DBROLE_REPO, false);
      if(!rc) rc = fsl__repo_open_finish(f, repoDbFile, NULL);
    }
    return rc;
  }
}

int fsl_repo_open_host( fsl_cx * const f, char const * zPrefix ){
  int rc;
  if(fsl_cx_db_repo(f)){
    return fsl_cx_err_set(f, FSL_RC_ACCESS,
                          "Context already has an opened repository.");
  }
  rc = fsl__cx_attach_repo_prefixed(f, zPrefix);
  if(rc) return rc;
  {
    /* SQLite's names ignore case, but GLOB, which picks the
       repository's tables (e.g. for fsl_repo_export()), does not: the
       prefix must be spelled as its tables are. */
    char * const zStored = fsl_db_g_text(f->dbMain, NULL,
      "SELECT substr(name, 1, %d) FROM main.sqlite_schema"
      " WHERE type='table' AND lower(name)=lower(%Q||'blob')",
      (int)fsl_strlen(zPrefix), zPrefix);
    if(zStored && 0!=fsl_strcmp(zStored, zPrefix)){
      rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "The repository with table "
                          "prefix %s is spelled %s in the host db.",
                          zPrefix, zStored);
    }
    fsl_free(zStored);
  }
  if(!rc) rc = fsl__host_prefix_recorded_check(f, f->dbMain,
                                               FSL_DBROLE_REPO, zPrefix);
  if(rc) fsl__cx_detach_role(f, FSL_DBROLE_REPO);
  else rc = fsl__repo_open_finish(f, NULL, zPrefix);
  return rc;
}

char * fsl__cx_repo_ref(fsl_cx * const f){
  char const * const zPre = fsl__db_repo_prefix(f->dbMain);
  char * z;
  assert(f->db.repo.db.filename);
  z = zPre
    ? fsl_mprintf("%s%s", FSL__REPO_HOST_REF, zPre)
    : fsl_strdup(f->db.repo.db.filename);
  if( !z ) fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  return z;
}

/**
    Tries to open the repository from which the current checkout
    derives. Returns 0 on success.
*/
static int fsl__repo_open_for_ckout(fsl_cx * f){
  char * repoDb = NULL;
  int rc;
  fsl_b nameBuf = fsl_b_empty;
  fsl_db * db = fsl_cx_db_ckout(f);
  assert(f);
  assert(f->db.ckout.dir);
  assert(db);
  rc = fsl_db_get_text(db, &repoDb, NULL,
                       "SELECT value FROM {{dbname.ckout}}.vvar "
                       "WHERE name='repository'");
  if(rc){
    rc = fsl_cx_err_set(f, rc, "Cannot read the repository name "
                        "from checkout db [%s]: %b",
                        db->filename, &db->error.msg);
    fsl_db_err_reset(db);
  }else if(repoDb && 0==fsl_strncmp(repoDb, FSL__REPO_HOST_REF,
                                    sizeof(FSL__REPO_HOST_REF)-1)){
    /* Prefixed repository tables of the host's main db, which must be
       the repository whose project-code the checkout recorded, and
       whose rid for the checkout's version has the hash it recorded,
       which a clone (the same project-code, other rids) need not. */
    char const * const zPre = repoDb + sizeof(FSL__REPO_HOST_REF)-1;
    rc = fsl_repo_open_host(f, zPre);
    if(!rc){
      char * const zCode =
        fsl_config_get_text(f, FSL_CONFDB_CKOUT, "project-code", NULL);
      char * const zMine =
        fsl_config_get_text(f, FSL_CONFDB_REPO, "project-code", NULL);
      char * const zHash =
        fsl_config_get_text(f, FSL_CONFDB_CKOUT, "checkout-hash", NULL);
      fsl_id_t const rid =
        fsl_config_get_id(f, FSL_CONFDB_CKOUT, -1, "checkout");
      char * zUuid = rid>0 ? fsl_rid_to_uuid(f, rid) : NULL;
      if(rid>0 && !zUuid) fsl_cx_err_reset(f);
      if(!zCode || !zMine || 0!=fsl_strcmp(zCode, zMine)){
        rc = fsl_cx_err_set(f, FSL_RC_REPO_MISMATCH,
                            "The checkout in [%s] belongs to the "
                            "repository with project-code %s, not to "
                            "the one with table prefix %s (%s).",
                            f->db.ckout.dir, zCode ? zCode : "(none)",
                            zPre, zMine ? zMine : "(none)");
      }else if(rid>0 ? (!zUuid || !zHash || 0!=fsl_strcmp(zUuid, zHash))
               : !!zHash){
        rc = fsl_cx_err_set(f, FSL_RC_REPO_MISMATCH,
                            "The checkout in [%s] has version %s, which "
                            "the repository with table prefix %s does "
                            "not have as rid %" FSL_ID_T_PFMT
                            " (a clone?).", f->db.ckout.dir,
                            zHash ? zHash : "(none)", zPre, rid);
      }
      fsl_free(zCode);
      fsl_free(zMine);
      fsl_free(zHash);
      fsl_free(zUuid);
      if(rc) fsl__cx_detach_role(f, FSL_DBROLE_REPO);
    }
    fsl_free(repoDb);
  }else if(repoDb){
    if(!fsl_is_absolute_path(repoDb)){
      /* Make it relative to the checkout db dir */
      rc = fsl_b_appendf(&nameBuf, "%s/%s", f->db.ckout.dir, repoDb);
      fsl_free(repoDb);
      if(rc) {
        fsl_b_clear(&nameBuf);
        return rc;
      }
      repoDb = (char*)nameBuf.mem /* transfer ownership */;
      nameBuf = fsl_b_empty;
    }
    rc = fsl_file_canonical_name(repoDb, &nameBuf, 0);
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Cannot canonicalize this checkout's "
                          "repository name [%s]: %R", repoDb, rc);
    }
    fsl_free(repoDb);
    if(!rc){
      repoDb = fsl_b_str(&nameBuf) /* transfer ownership */;
      assert(repoDb);
      rc = fsl_repo_open(f, repoDb);
      if(FSL_RC_NOT_FOUND==rc){
        /* Report a code which fsl_ckout_open_dir() does not use for
           "no checkout found", so that callers can tell the two
           apart. */
        rc = fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                            "Repository db [%s] for the checkout in "
                            "[%s] not found or cannot be read.",
                            repoDb, f->db.ckout.dir);
      }
    }
  }else{
    /* This can only happen if we are not using a proper
       checkout db or someone has removed the repo link.
    */
    rc = fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                        "Could not determine the repository db file "
                        "of the checkout in [%s].", f->db.ckout.dir);
  }
  fsl_b_clear(&nameBuf);
  return rc;
}

static void fsl_ckout_mtime_set(fsl_cx * const f){
  f->db.ckout.mtime = f->db.ckout.rid>0
    ? fsl_db_g_double(fsl_cx_db_repo(f), 0.0,
                      "SELECT mtime FROM {{dbname.repo}}.event "
                      "WHERE objid=%" FSL_ID_T_PFMT,
                      f->db.ckout.rid)
    : 0.0;
}

void fsl__cx_ckout_clear( fsl_cx * const f ){
  fsl_free(f->db.ckout.uuid);
  f->db.ckout.rid = -1;
  f->db.ckout.uuid = NULL;
  f->db.ckout.mtime = 0.0;
}

int fsl__ckout_version_fetch( fsl_cx * const f ){
  fsl_id_t rid = 0;
  int rc = 0;
  fsl_db * dbC = fsl_cx_db_ckout(f);
  fsl_db * dbR = dbC ? fsl_needs_repo(f) : NULL;
  fsl__cx_ckout_clear(f);
  if(!dbC) return 0;
  else if(!dbR) return FSL_RC_NOT_A_REPO;
  rid = fsl_config_get_id(f, FSL_CONFDB_CKOUT, -1, "checkout");
  //MARKER(("rc=%s rid=%d\n",fsl_rc_cstr(f->error.code), (int)rid));
  if(rid>0){
    assert( !f->db.ckout.uuid );
    f->db.ckout.uuid = fsl_rid_to_uuid(f, rid);
    if(!f->db.ckout.uuid){
      assert(f->error.code);
      if(!f->error.code){
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Could not load UUID for RID %"FSL_ID_T_PFMT,
                            (fsl_id_t)rid);
      }
    }else{
      assert(fsl_is_uuid(f->db.ckout.uuid));
    }
    f->db.ckout.rid = rid;
    fsl_ckout_mtime_set(f);
  }else if(rid==0){
    /* This is a legal case not possible before libfossil (and only
       afterwards possible in fossil(1)) - an empty repo without an
       active checkin. [Much later:] that capability has since been
       removed from fossil.
    */
    f->db.ckout.rid = 0;
  }else{
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "Cannot determine checkout version.");
  }
  return rc;
}

/** @internal

    Sets f->db.ckout.rid to the given rid (which must be 0 or a valid
    RID) and f->db.ckout.uuid to a copy of the given uuid. If uuid is
    NULL and rid is not 0 then the uuid is fetched using
    fsl_rid_to_uuid(), else if uuid is not NULL then it is assumed to
    be the UUID for the given RID and is copies to f->db.ckout.uuid.

    Returns 0 on success, FSL_RC_OOM if copying uuid fails, or some
    error from fsl_rid_to_uuid() if that fails.

    Does not write the changes to disk. Use fsl__ckout_version_write()
    for that. That routine also calls this one, so there's no need to
    call both.
*/
static int fsl_cx_ckout_version_set(fsl_cx *f, fsl_id_t rid,
                                    fsl_uuid_cstr uuid){
  char * u = 0;
  assert(rid>=0);
  u = uuid
    ? fsl_strdup(uuid)
    : (rid ? fsl_rid_to_uuid(f, rid) : NULL);
  if(rid && !u){
    if(uuid || !f->error.code){
      fsl_report_oom;
      return FSL_RC_OOM;
    }
    return f->error.code /* from fsl_rid_to_uuid() */;
  }
  f->db.ckout.rid = rid;
  fsl_free(f->db.ckout.uuid);
  f->db.ckout.uuid = u;
  fsl_ckout_mtime_set(f);
  return 0;
}

int fsl__ckout_version_write( fsl_cx * const f, fsl_id_t vid,
                             fsl_uuid_cstr hash ){
  int rc = 0;
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  else if(vid<0){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Invalid vid for fsl__ckout_version_write()");
  }
  if(f->db.ckout.rid!=vid){
    rc = fsl_cx_ckout_version_set(f, vid, hash);
  }
  if(!rc){
    rc = fsl_config_set_id(f, FSL_CONFDB_CKOUT,
                           "checkout", f->db.ckout.rid);
    if(!rc){
      rc = fsl_config_set_text(f, FSL_CONFDB_CKOUT,
                               "checkout-hash", f->db.ckout.uuid);
    }
  }
  if(!rc){
    char * zFingerprint = 0;
    rc = fsl__repo_fingerprint_search(f, 0, &zFingerprint);
    if(FSL_RC_NOT_FOUND==rc){
      /* The repo has no rcvfrom entries. fossil(1) records a NULL
         fingerprint in that case, and fsl_ckout_fingerprint_check()
         accepts a NULL fingerprint. */
      rc = 0;
    }
    if(!rc){
      rc = fsl_config_set_text(f, FSL_CONFDB_CKOUT,
                               "fingerprint", zFingerprint);
      fsl_free(zFingerprint);
    }
  }
  if(!rc){
    int const mode = vid ? -1 : 0;
    rc = fsl_ckout_manifest_write(f, mode, mode, mode, 0);
  }
  return rc;
}

void fsl_ckout_version_info(fsl_cx * const f, fsl_id_t * const rid,
                            fsl_uuid_cstr * const uuid ){
  if(uuid) *uuid = f->db.ckout.uuid;
  if(rid) *rid = f->db.ckout.rid>=0 ? f->db.ckout.rid : 0;
}

int fsl_ckout_db_search( char const * dirName, bool checkParentDirs,
                         fsl_b * const pOut ){
  int rc = 0;
  fsl_int_t dLen = 0, i;
  const char aDbName[][10] = { "_FOSSIL_", ".fslckout" };
  fsl_int_t const nDbName = (fsl_int_t)(sizeof(aDbName) / sizeof(aDbName[0]));
  fsl_fstat fst = fsl_fstat_empty;
  fsl_b Buf = fsl_b_empty;
  fsl_b * const buf = &Buf;
  if(dirName){
    dLen = fsl_strlen(dirName);
    if(0==dLen) return FSL_RC_RANGE;
    fsl_b_reserve( buf, (fsl_size_t)(dLen + 10) );
    fsl_b_append( buf, dirName, dLen );
    if(buf->errCode){
      fsl_b_clear(buf);
      return buf->errCode;
    }
  }else{
    char zPwd[4000];
    fsl_size_t pwdLen = 0;
    rc = fsl_getcwd( zPwd, sizeof(zPwd)/sizeof(zPwd[0]), &pwdLen );
    if(rc){
      fsl_b_clear(buf);
#if 0
      return fsl_cx_err_set(f, rc,
                            "Could not determine current directory. "
                            "Error code %d (%s).",
                            rc, fsl_rc_cstr(rc));
#else
      return rc;
#endif
    }
    if(1 == pwdLen && '/'==*zPwd) *zPwd = '.'
      /* When in the root directory (or chroot) then change dir name
         name to something we can use.
      */;
    if(fsl_b_append(buf, zPwd, pwdLen)){
      fsl_b_clear(buf);
      return buf->errCode;
    }
    dLen = (fsl_int_t)pwdLen;
  }
  if(rc){
    fsl_b_clear(buf);
    return rc;
  }
  assert(buf->capacity>=buf->used);
  assert((buf->used == (fsl_size_t)dLen) || (1==buf->used && (int)'.'==(int)buf->mem[0]));
  assert(0==buf->mem[buf->used]);

  while(dLen>0){
    /*
      Loop over the list in aDbName, appending each one to
      the dir name in the search for something we can use.
    */
    fsl_int_t const lenMarker = dLen /* position to re-set to on each
                                        sub-iteration. */ ;
    /* trim trailing slashes on this part, so that we don't end up
       with multiples between the dir and file in the final output. */
    while( dLen && ((int)'/'==(int)buf->mem[dLen-1])) --dLen;
    for( i = 0; i < nDbName; ++i ){
      char const * zName;
      buf->used = (fsl_size_t)lenMarker;
      dLen = lenMarker;
      rc = fsl_b_appendf( buf, "/%s", aDbName[i]);
      if(rc){
        fsl_b_clear(buf);
        return rc;
      }
      zName = fsl_b_cstr(buf);
      if(0==fsl_stat(zName, &fst, false)
         && (0 == (fst.size % 512 /*else cannot be an sqlite db*/))
         && 0==fsl_file_access(zName, 0)
         /* ^^^ fsl_fstat does not store OS-level permissions, only
            fossil-relevant permissions, so we can't check this in
            fsl.perm. Maybe we should add fsl_fstat::osPerm.  Yes,
            there's a race condition here but it's wildly a
            hypothetical problem, not a real one. */){
        if(pOut){
          if( pOut->mem ){
            rc = fsl_b_append( pOut, buf->mem, buf->used );
            fsl_b_clear(buf);
          }else{
            fsl_b_swap( pOut, buf );
          }
        }
        return rc;
      }
      if(i==nDbName-1 && !checkParentDirs){
        dLen = 0;
        break;
      }else{
        /* Traverse up one dir and try again. */
        --dLen;
        while( dLen>0 && (int)buf->mem[dLen]!=(int)'/' ){ --dLen; }
        while( dLen>0 && (int)buf->mem[dLen-1]==(int)'/' ){ --dLen; }
        if(dLen>lenMarker){
          buf->mem[dLen] = 0;
        }
      }
    }
  }
  fsl_b_clear(buf);
  return FSL_RC_NOT_FOUND;
}

int fsl_cx_getcwd(fsl_cx * const f, fsl_b * const pOut){
  char cwd[FILENAME_MAX] = {0};
  fsl_size_t cwdLen = 0;
  int rc = fsl_getcwd(cwd, (fsl_size_t)sizeof(cwd), &cwdLen);
  if(rc){
    return fsl_cx_err_set(f, rc,
                          "Could not get current working directory!");
  }
  rc = fsl_b_append(pOut, cwd, cwdLen);
  return rc
    ? fsl_cx_err_set(f, rc/*must be an OOM*/, NULL)
    : 0;
}

int fsl_ckout_open_dir( fsl_cx * const f, char const * dirName,
                        bool checkParentDirs ){
  int rc;
  fsl_b buf = fsl_b_empty;
  char const * zName;
  fsl_b * const bufD = fsl_cx_b_borrow(f);
  if( !bufD ) return f->error.code;
  if(fsl_cx_db_ckout(f)){
    rc = fsl_cx_err_set( f, FSL_RC_ACCESS,
                         "A checkout is already opened. "
                         "Close it before opening another.");
    goto end;
  }else if(!dirName){
    dirName = ".";
  }
  rc = fsl_file_canonical_name( dirName, bufD, false );
  if(rc){
    rc = fsl_cx_err_set(f, rc, "Cannot canonicalize directory "
                        "name [%s]: %R", dirName, rc);
    goto end;
  }
  dirName = fsl_b_cstr(bufD);
  rc = fsl_ckout_db_search(dirName, checkParentDirs, &buf);
  if(rc){
    if(FSL_RC_NOT_FOUND==rc){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Could not find checkout under [%s].",
                          dirName ? dirName : ".");
    }else{
      rc = fsl_cx_err_set(f, rc, "Searching for a checkout under "
                          "[%s] failed: %R", dirName, rc);
    }
    goto end;
  }
  assert(buf.used>1 /* "/<FILENAME>" */);
  zName = fsl_b_cstr(&buf);
  rc = fsl__cx_ckout_open_db(f, zName);
  if(0==rc){
    /* Checkout db is now opened. Fiddle some internal
       bits...
    */
    unsigned char * end = buf.mem+buf.used-1;
    /* Find dir part */
    while(end>buf.mem && (unsigned char)'/'!=*end) --end;
    assert('/' == (char)*end && "fsl_ckout_db_search() appends '/<DBNAME>'");
    fsl_free(f->db.ckout.dir);
    f->db.ckout.dirLen = end - buf.mem +1 /* for trailing '/' */ ;
    *(end+1) = 0; /* Rather than strdup'ing, we'll just lop off the
                     filename part. Keep the '/' for historical
                     conventions purposes - it simplifies path
                     manipulation later on. */
    f->db.ckout.dir = fsl_b_take(&buf);
    assert(!f->db.ckout.dir[f->db.ckout.dirLen]);
    assert('/' == f->db.ckout.dir[f->db.ckout.dirLen-1]);
    f->flags |= FSL_CX_F_IS_OPENING_CKOUT;
    rc = fsl__repo_open_for_ckout(f);
    f->flags &= ~FSL_CX_F_IS_OPENING_CKOUT;
    if(!rc) rc = fsl__cx_after_open(f);
    if(rc){
      /* Is this sane? Is not doing it sane? */
      fsl_close_scm_dbs(f);
    }
  }
  end:
  fsl_b_clear(&buf);
  fsl_cx_b_return(f, bufD);
  return rc;
}


char const * fsl_cx_db_file_for_role(fsl_cx const * f,
                                     fsl_dbrole_e r,
                                     fsl_size_t * len){
  fsl_db const * db = fsl__cx_db_for_role((fsl_cx*)f, r);
  char const * rc = db ? db->filename : NULL;
  if(len) *len = fsl_strlen(rc);
  return rc;
}

char const * fsl_cx_db_name_for_role(fsl_cx const * f,
                                     fsl_dbrole_e r,
                                     fsl_size_t * len){
  if(FSL_DBROLE_MAIN == r){
    if(f->dbMain){
      if(len) *len=4;
      return "main";
    }else{
      return NULL;
    }
  }else{
    fsl_db const * db = fsl__cx_db_for_role((fsl_cx*)f, r);
    char const * rc = db ? db->name : NULL;
    if(len) *len = rc ? fsl_strlen(rc) : 0;
    return rc;
  }
}

char const * fsl_cx_db_file_config(fsl_cx const * f,
                                   fsl_size_t * len){
  char const * rc = NULL;
  if(f && f->db.gconfig.db.filename){
    rc = f->db.gconfig.db.filename;
    if(len) *len = fsl_strlen(rc);
  }
  return rc;
}

char const * fsl_cx_db_file_repo(fsl_cx const * f,
                                 fsl_size_t * len){
  char const * rc = NULL;
  if(f && f->db.repo.db.filename){
    rc = f->db.repo.db.filename;
    if(len) *len = fsl_strlen(rc);
  }
  return rc;
}

char const * fsl_cx_db_file_ckout(fsl_cx const * f,
                                     fsl_size_t * len){
  char const * rc = NULL;
  if(f && f->db.ckout.db.filename){
    rc = f->db.ckout.db.filename;
    if(len) *len = fsl_strlen(rc);
  }
  return rc;
}

char const * fsl_cx_ckout_dir_name(fsl_cx const * f,
                                      fsl_size_t * len){
  char const * rc = NULL;
  if(f && f->db.ckout.dir){
    rc = f->db.ckout.dir;
    if(len) *len = f->db.ckout.dirLen;
  }
  return rc;
}

fsl_flag32_t fsl_cx_flags_get( fsl_cx const * const f ){
  return f->flags;
}

fsl_flag32_t fsl_cx_flag_set( fsl_cx * const f, fsl_flag32_t flags,
                              bool enable ){
  fsl_flag32_t const oldFlags = f->flags;
  if(enable) f->flags |= flags;
  else f->flags &= ~flags;
  return oldFlags;
}


fsl_xlinker * fsl_xlinker_by_name( fsl_cx * f, char const * name ){

  fsl_xlinker * rv = NULL;
  fsl_size_t i;
  for( i = 0; i < f->xlinkers.used; ++i ){
    rv = f->xlinkers.list + i;
    if(0==fsl_strcmp(rv->name, name)) return rv;
  }
  return NULL;
}

int fsl_xlink_listener( fsl_cx * const f, char const * name,
                        fsl_deck_xlink_f cb, void * cbState ){
  fsl_xlinker * x;
  if(!*name){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Crosslink listener name must not be empty.");
  }
  x = fsl_xlinker_by_name(f, name);
  if(x){
    /* Replace existing entry */
    x->f = cb;
    x->state = cbState;
    return 0;
  }else if(f->xlinkers.used >= f->xlinkers.capacity){
    /* Expand the array */
    fsl_size_t const n = f->xlinkers.used ? f->xlinkers.used * 2 : 5;
    fsl_xlinker * re =
      (fsl_xlinker *)fsl_realloc(f->xlinkers.list,
                                 n * sizeof(fsl_xlinker));
    if(!re) return FSL_RC_OOM;
    f->xlinkers.list = re;
    f->xlinkers.capacity = n;
  }
  x = f->xlinkers.list + f->xlinkers.used++;
  *x = fsl_xlinker_empty;
  x->f = cb;
  x->state = cbState;
  x->name = name;
  return 0;
}

int fsl_cx_user_set( fsl_cx * const f, char const * userName ){
  if(!f) return FSL_RC_MISUSE;
  else if(!userName || !*userName){
    fsl_free(f->db.repo.user);
    f->db.repo.user = NULL;
    return 0;
  }else{
    char * u = fsl_strdup(userName);
    if(!u) return FSL_RC_OOM;
    else{
      fsl_free(f->db.repo.user);
      f->db.repo.user = u;
      return 0;
    }
  }
}

char const * fsl_cx_user_guess(fsl_cx * const f){
  if(!f->db.repo.user){
    char * u = fsl_config_get_text(f, FSL_CONFDB_CKOUT, "default-user", NULL);
    if( !u ){
      fsl_db * const dbR = fsl_cx_db_repo(f);
      u = dbR
        ? fsl_db_g_text(dbR, NULL, "SELECT login FROM {{dbname.repo}}.user WHERE uid=1")
        : NULL;
    }
    if( !u ) u = fsl_user_name_guess();
    if( u ){
      assert( u!=f->db.repo.user );
      fsl_free(f->db.repo.user);
      f->db.repo.user = u;
      // don't use fsl_cx_user_set(f, u), to avoid another strdup()
    }
  }
  return f->db.repo.user;
}

char const * fsl_cx_user_get( fsl_cx const * const f ){
  return f->db.repo.user;
}

int fsl_cx_schema_ticket(fsl_cx * f, fsl_b * pOut){
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  if(!f || !pOut) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  else{
    fsl_size_t const oldUsed = pOut->used;
    int rc = fsl_config_get_buffer(f, FSL_CONFDB_REPO,
                                   "ticket-table", pOut);
    if((FSL_RC_NOT_FOUND==rc)
       || (oldUsed == pOut->used/*found but it was empty*/)
       ){
      fsl_cx_err_reset(f);
      rc = fsl_b_append(pOut, fsl_schema_ticket(), -1);
    }
    return rc;
  }
}


int fsl_cx_stat2( fsl_cx * const f, bool relativeToCwd,
                  char const * zName, fsl_fstat * const tgt,
                  fsl_b * const nameOut, bool fullPath){
  int rc;
  fsl_b * b = 0;
  fsl_b * bufRel = 0;
  fsl_size_t n = 0;
  assert(f);
  if(!zName || !*zName){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Empty file name passed to %s().", __func__);
  }else if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  b = fsl_cx_b_borrow(f);
  bufRel = fsl_cx_b_borrow(f);
  if( !b || !bufRel ){
    rc = f->error.code;
    assert( rc );
    goto end;
  }
#if 1
  rc = fsl_ckout_filename_check(f, relativeToCwd, zName, bufRel);
  if(rc) goto end;
  zName = fsl_b_cstr2( bufRel, &n );
#else
  if(!fsl_is_simple_pathname(zName, 1)){
    rc = fsl_ckout_filename_check(f, relativeToCwd, zName, bufRel);
    if(rc) goto end;
    zName = fsl_b_cstr2( bufRel, &n );
    /* MARKER(("bufRel=%s\n",zName)); */
  }else{
    n = fsl_strlen(zName);
  }
#endif
  assert(n>0 &&
         "Will fail if fsl_ckout_filename_check() changes "
         "to return nothing if zName==checkout root");
  if(!n
     /* i don't like the "." resp "./" result when zName==checkout root */
     || (1==n && '.'==bufRel->mem[0])
     || (2==n && '.'==bufRel->mem[0] && '/'==bufRel->mem[1])){
    rc = fsl_b_appendf(b, "%s%s", f->db.ckout.dir,
                            (2==n) ? "/" : "");
  }else{
    rc = fsl_b_appendf(b, "%s%s", f->db.ckout.dir, zName);
  }
  if(!rc){
    /* As fossil(1)'s fossil_stat() for RepoFILE: look at a symlink
       itself only if allow-symlinks is on. */
    rc = fsl__cfs_stat(f, fsl_b_cstr(b), tgt,
                       !fsl_cx_allows_symlinks(f, false));
    if(rc){
      if(FSL_RC_NOT_FOUND==rc){
        fsl_cx_err_set(f, rc, "File not found: %b", b);
      }else{
        fsl_cx_err_set(f, rc, "Cannot stat file %b: %R", b, rc);
      }
    }else if(nameOut){
      rc = fullPath
        ? fsl_b_append(nameOut, b->mem, b->used)
        : fsl_b_append(nameOut, zName, n);
    }
  }
  end:
  fsl_cx_b_return(f, b);
  fsl_cx_b_return(f, bufRel);
  return rc;
}

int fsl_cx_stat(fsl_cx * const f, bool relativeToCwd,
                char const * zName, fsl_fstat * const tgt){
  return fsl_cx_stat2(f, relativeToCwd, zName, tgt, NULL, false);
}

bool fsl_cx_allows_symlinks(fsl_cx * const f, bool forceRecheck){
  if(forceRecheck || f->cache.allowSymlinks<0){
    f->cache.allowSymlinks = fsl_config_get_bool(f, FSL_CONFDB_REPO,
                                                 false, "allow-symlinks");
  }
  return f->cache.allowSymlinks>0;
}

void fsl_cx_case_sensitive_set(fsl_cx * const f, bool caseSensitive){
  f->cache.caseInsensitive = caseSensitive ? 0 : 1;
}

/*
   The default for the "case-sensitive" setting follows the platform's
   usual filesystem, as fossil(1) does: case-insensitive on Windows,
   Cygwin and macOS, case-sensitive elsewhere.
*/
bool fsl_cx_is_case_sensitive(fsl_cx * const f, bool forceRecheck){
#if defined(_WIN32) || defined(__CYGWIN__) || defined(__APPLE__) \
  || defined(__DARWIN__)
#  define FSL__CASE_SENSITIVE_DEFAULT false
#else
#  define FSL__CASE_SENSITIVE_DEFAULT true
#endif
  if(forceRecheck || f->cache.caseInsensitive<0){
    f->cache.caseInsensitive =
      fsl_config_get_bool(f, FSL_CONFDB_REPO,
                          FSL__CASE_SENSITIVE_DEFAULT,
                          "case-sensitive") ? 0 : 1;
  }
  return f->cache.caseInsensitive <= 0;
#undef FSL__CASE_SENSITIVE_DEFAULT
}

int fsl_cx_filename_cmp(fsl_cx * f, char const * z1, char const * z2){
  return fsl_cx_is_case_sensitive(f, false)
    ? fsl_strcmp(z1, z2)
    : fsl_stricmp(z1, z2);
}

char const * fsl_cx_filename_collation(fsl_cx const * f){
  return f->cache.caseInsensitive>0 ? "COLLATE nocase" : "";
}

fsl_b * fsl__cx_content_buffer(fsl_cx * const f){
  if(f->cache.fileContent.used){
    fsl__fatal(FSL_RC_MISUSE,
               "Called %s() while the content buffer has bytes in use.",
               __func__);
  }
  ++f->metrics.content.nCached;
  return &f->cache.fileContent;
}

void fsl__cx_content_buffer_yield(fsl_cx * const f){
  enum { MaxSize = 1024 * 1024 * 10 };
  fsl_b * const b = &f->cache.fileContent;
  assert(f);
  f->metrics.content.nTotalUsed += b->used;
  if( b->capacity > f->metrics.content.nPeakBufSize ){
    f->metrics.content.nPeakBufSize = b->capacity;
  }
  if(b->capacity>MaxSize){
    ++f->metrics.content.nCappedMaxSize;
    fsl_b_resize(b, MaxSize);
    assert( (b->capacity<=MaxSize+1) || b->errCode);
  }
  fsl_b_reuse(b);
}

fsl_error const * fsl_cx_err_ec(fsl_cx const * f){
  return &f->error;
}
fsl_error * fsl_cx_err_e(fsl_cx * f){
  return &f->error;
}

char const * fsl_cx_glob_matches( fsl_cx * const f, int gtype,
                                  char const * str ){
  int i, count = 0;
  char const * rv = NULL;
  fsl_list const * lists[] = {0,0,0};
  if(!f || !str || !*str) return NULL;
  if(gtype & FSL_GLOBS_IGNORE) lists[count++] = &f->cache.globs.ignore;
  if(gtype & FSL_GLOBS_CRNL) lists[count++] = &f->cache.globs.crnl;
  /*CRNL/BINARY together makes little sense, but why strictly prohibit
    it?*/
  if(gtype & FSL_GLOBS_BINARY) lists[count++] = &f->cache.globs.binary;
  for( i = 0; i < count; ++i ){
    if( (rv = fsl_glob_list_matches( lists[i], str )) ) break;
  }
  return rv;
}

int fsl_output_f_fsl_cx(void * state, void const * src, fsl_size_t n ){
  return (state && src && n)
    ? fsl_output((fsl_cx*)state, src, n)
    : (n ? FSL_RC_MISUSE : 0);
}

int fsl_cx_hash_buffer( fsl_cx const * f, bool useAlternate,
                        fsl_b const * pIn, fsl_b * pOut){
  /* fossil(1) counterpart: hname_hash() */
  if(useAlternate){
    switch(f->cxConfig.hashPolicy){
      case FSL_HPOLICY_AUTO:
      case FSL_HPOLICY_SHA1:
        return fsl_sha3sum_buffer(pIn, pOut);
      case FSL_HPOLICY_SHA3:
        return fsl_sha1sum_buffer(pIn, pOut);
      default: return FSL_RC_UNSUPPORTED;
    }
  }else{
    switch(f->cxConfig.hashPolicy){
      case FSL_HPOLICY_SHA1:
      case FSL_HPOLICY_AUTO:
        return fsl_sha1sum_buffer(pIn, pOut);
      case FSL_HPOLICY_SHA3:
      case FSL_HPOLICY_SHA3_ONLY:
      case FSL_HPOLICY_SHUN_SHA1:
        return fsl_sha3sum_buffer(pIn, pOut);
    }
  }
  assert(!"not reached");
  return FSL_RC_RANGE;
}

int fsl_cx_hash_filename( fsl_cx * f, bool useAlternate,
                          const char * zFilename, fsl_b * pOut){
  /* FIXME: reimplement this to stream the content in bite-sized
     chunks. That requires duplicating most of fsl_b_fill_from()
     and fsl_cx_hash_buffer(). */
  fsl_b * const content = fsl__cx_content_buffer(f);
  int rc;
  rc = fsl__cfs_read(f, content, zFilename);
  if(rc){
    rc = fsl_cx_err_set(f, rc, "Cannot read file [%s] for hashing: %R",
                        zFilename, rc);
  }else{
    rc = fsl_cx_hash_buffer(f, useAlternate, content, pOut);
  }
  fsl__cx_content_buffer_yield(f);
  return rc;
}

char const * fsl_hash_policy_name(fsl_hashpolicy_e p){
  switch(p){
    case FSL_HPOLICY_SHUN_SHA1: return "shun-sha1";
    case FSL_HPOLICY_SHA3: return "sha3";
    case FSL_HPOLICY_SHA3_ONLY: return "sha3-only";
    case FSL_HPOLICY_SHA1: return "sha1";
    case FSL_HPOLICY_AUTO: return "auto";
    default: return NULL;
  }
}

fsl_hashpolicy_e fsl_cx_hash_policy_set(fsl_cx *f, fsl_hashpolicy_e p){
  fsl_hashpolicy_e const old = f->cxConfig.hashPolicy;
  fsl_db * const dbR = fsl_cx_db_repo(f);
  if(dbR){
    /* Write it regardless of whether it's the same as the old policy
       so that we're sure the db knows the policy. */
    if(FSL_HPOLICY_AUTO==p &&
       fsl_db_exists(dbR,"SELECT 1 FROM {{dbname.repo}}.blob WHERE length(uuid)>40")){
      p = FSL_HPOLICY_SHA3;
    }
    fsl_config_set_int32(f, FSL_CONFDB_REPO, "hash-policy", p);
  }
  f->cxConfig.hashPolicy = p;
  return old;
}

fsl_hashpolicy_e fsl_cx_hash_policy_get(fsl_cx const*f){
  return f->cxConfig.hashPolicy;
}

int fsl_cx_txn_level(fsl_cx * const f){
   return f->dbMain
    ? fsl_db_txn_level(f->dbMain)
    : 0;
}

int fsl_cx_txn_begin(fsl_cx * const f){
  if( !f->dbMain ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot begin a transaction: no repository "
                          "or checkout db is opened.");
  }
  int const rc = fsl_db_txn_begin(f->dbMain);
  if( rc ) return fsl_cx_uplift_db_error2(f, f->dbMain, rc);
  return 0;
}

/**
   Takes the write lock on the db with role r unless the transaction
   holds it already. An UPDATE of zTable which matches no rows takes the
   lock without changing the db.
*/
static int fsl__cx_txn_lock(fsl_cx * const f, fsl_dbrole_e r){
  char const * const zSchema = fsl__db_schema(f->dbMain, r);
  if( SQLITE_TXN_WRITE==sqlite3_txn_state(f->dbMain->dbh, zSchema) ){
    return 0;
  }
  /* Through the placeholders, so that a checkout whose tables live in
     the host's main db under a prefix locks its own vvar. */
  return FSL_DBROLE_CKOUT==r
    ? fsl_cx_exec(f, "UPDATE {{dbname.ckout}}.vvar SET name=name WHERE 0")
    : fsl_cx_exec(f, "UPDATE {{dbname.repo}}.config SET name=name WHERE 0");
}

int fsl_cx_txn_begin_write(fsl_cx * const f, int roles){
  int rc = fsl_cx_txn_begin(f);
  if( rc ) return rc;
  if( (roles & FSL_DBROLE_REPO) && fsl_cx_db_repo(f) ){
    rc = fsl__cx_txn_lock(f, FSL_DBROLE_REPO);
  }
  if( 0==rc && (roles & FSL_DBROLE_CKOUT) && fsl_cx_db_ckout(f) ){
    rc = fsl__cx_txn_lock(f, FSL_DBROLE_CKOUT);
  }
  if( rc ) fsl_cx_txn_end_v2(f, false, false);
  return rc;
}

int fsl_cx_txn_end_v2(fsl_cx * f, bool keepSavepoint, bool bubbleRollback){
  assert( f->dbMain );
  assert( f->dbMain->impl.txn.level>0 );
  int const rc = fsl_db_txn_end_v2(f->dbMain, keepSavepoint,
                                   bubbleRollback);
  if( rc ) return fsl_cx_uplift_db_error2(f, f->dbMain, rc);
  return 0;
}

void fsl_cx_confirmer(fsl_cx * f,
                      fsl_confirmer const * newConfirmer,
                      fsl_confirmer * prevConfirmer){
  if(prevConfirmer) *prevConfirmer = f->confirmer;
  f->confirmer = newConfirmer ? *newConfirmer : fsl_confirmer_empty;
}

void fsl_cx_confirmer_get(fsl_cx const * f, fsl_confirmer * dest){
  *dest = f->confirmer;
}

void fsl_cx_signer(fsl_cx * const f, fsl_signer const * newSigner,
                   fsl_signer * prevSigner){
  if(prevSigner) *prevSigner = f->signer;
  if(newSigner) f->signer = *newSigner;
  else f->signer = fsl_signer_empty;
}

void fsl_cx_signer_get(fsl_cx const * const f, fsl_signer * dest){
  *dest = f->signer;
}

int fsl_cx_confirm(fsl_cx * const f, fsl_confirm_detail const * detail,
                   fsl_confirm_response *outAnswer){
  if(f->confirmer.callback){
    return f->confirmer.callback(detail, outAnswer,
                                 f->confirmer.callbackState);
  }
  /* Default answers... */
  switch(detail->eventId){
    case FSL_CEVENT_OVERWRITE_MOD_FILE:
    case FSL_CEVENT_OVERWRITE_UNMGD_FILE:
      outAnswer->response =  FSL_CRESPONSE_NEVER;
      break;
    case FSL_CEVENT_RM_MOD_UNMGD_FILE:
      outAnswer->response = FSL_CRESPONSE_NEVER;
      break;
    case FSL_CEVENT_MULTIPLE_VERSIONS:
      outAnswer->response = FSL_CRESPONSE_CANCEL;
      break;
    default:
      assert(!"Unhandled fsl_confirm_event_e value");
      fsl__fatal(FSL_RC_UNSUPPORTED,
                "Unhandled fsl_confirm_event_e value: %d",
                detail->eventId)/*does not return*/;
  }
  return 0;
}

int fsl__cx_update_seen_delta_deck(fsl_cx * const f){
  int rc = 0;
  fsl_db * const d = fsl_cx_db_repo(f);
  if(d && f->cache.seenDeltaManifest <= 0){
    f->cache.seenDeltaManifest = 1;
    rc = fsl_config_set_bool(f, FSL_CONFDB_REPO,
                             "seen-delta-manifest", 1);
  }
  return rc;
}

int fsl__file_realpath(fsl_b * const b){
#if defined(_WIN32)
  (void)b;
  return 0;
#else
  char * const z = fsl_b_str(b) ? fsl_strdup(fsl_b_cstr(b)) : NULL;
  char * zReal;
  char const * zBase = "";
  int rc = 0;
  if( !z ) return b->used ? FSL_RC_OOM : 0;
  zReal = realpath(z, NULL);
  if( !zReal ){
    char * const zSlash = strrchr(z, '/');
    if( zSlash && zSlash>z ){
      *zSlash = 0;
      zBase = zSlash + 1;
      zReal = realpath(z, NULL);
    }
  }
  if( zReal ){
    fsl_b_reuse(b);
    rc = *zBase ? fsl_b_appendf(b, "%s/%s", zReal, zBase)
      : fsl_b_append(b, zReal, -1);
    free(zReal) /* from realpath() */;
  }
  fsl_free(z);
  return rc;
#endif
}

int fsl_reserved_fn_check(fsl_cx * const f, const char *zPath,
                          fsl_int_t nPath, bool relativeToCwd){
  static const int errRc = FSL_RC_RANGE;
  int rc = 0;
  char const * z1 = 0;
  if(nPath<0) nPath = (fsl_int_t)fsl_strlen(zPath);
  if(fsl_is_reserved_fn(zPath, nPath)){
    return fsl_cx_err_set(f, errRc,
                        "Filename is reserved, not legal "
                        "for adding to a repository: %.*s",
                        (int)nPath, zPath);
  }
  if(!(f->flags & FSL_CX_F_ALLOW_WINDOWS_RESERVED_NAMES)
     && fsl__is_reserved_fn_windows(zPath, nPath)){
    return fsl_cx_err_set(f, errRc,
                          "Filename is a Windows reserved name: %.*s",
                          (int)nPath, zPath);
  }
  /* The repository db, and, for prefixed checkout tables
     (fsl_repo_open_ckout_opt::hostTablePrefix), the host's main db
     and its journal files, which fsl_is_reserved_fn() does not know
     by name. */
  static char const * const azSuffix[] = {"", "-journal", "-wal", "-shm"};
  unsigned const nDb =
    fsl__db_ckout_prefix(f->dbMain) && fsl_cx_db_file_ckout(f, NULL)
    ? 5 : 1;
  for( unsigned iDb = 0; !rc && iDb < nDb; ++iDb ){
    fsl_b * zDbName = NULL;
    z1 = iDb
      ? fsl_cx_db_file_ckout(f, NULL)
      : fsl_cx_db_file_for_role(f, FSL_DBROLE_REPO, NULL);
    if( !z1 ) continue;
    if( iDb ){
      zDbName = fsl_cx_b_borrow(f);
      if( !zDbName ) return f->error.code;
      rc = fsl_b_appendf(zDbName, "%s%s", z1, azSuffix[iDb-1]);
      if( rc ){
        fsl_cx_b_return(f, zDbName);
        return fsl_cx_err_set(f, rc, NULL);
      }
      z1 = fsl_b_cstr(zDbName);
    }
    fsl_b * const c1 = fsl_cx_b_borrow(f);
    fsl_b * const c2 = fsl_cx_b_borrow(f);
    if( !c1 || !c2 ){
      rc = f->error.code;
      assert( rc );
      goto b_yield;
    }
    rc = fsl_file_canonical_name2(relativeToCwd
                                  ? NULL : f->db.ckout.dir/*NULL is okay*/,
                                  z1, c1, false);
    if(!rc) rc = fsl_file_canonical_name2(relativeToCwd
                                          ? NULL : f->db.ckout.dir,
                                          zPath, c2, false);
    if(!rc && iDb){
      /* The host's file may be named through symbolic links. */
      rc = fsl__file_realpath(c1);
      if(!rc) rc = fsl__file_realpath(c2);
    }
    //MARKER(("\nzPath=%s\nc1=%s\nc2=%s\n", zPath,
    //fsl_b_cstr(c1), fsl_b_cstr(c2)));
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Cannot canonicalize file name "
                          "[%.*s]: %R", (int)nPath, zPath, rc);
    }else if(c1->used == c2->used &&
       0==fsl_stricmp(fsl_b_cstr(c1), fsl_b_cstr(c2))){
      rc = fsl_cx_err_set(f, errRc, "File is the %s database%s: %.*s",
                          iDb ? "checkout tables'" : "repository",
                          iDb>1 ? "'s journal" : "",
                          (int)nPath, zPath);
    }
  b_yield:
    fsl_cx_b_return(f, c1);
    fsl_cx_b_return(f, c2);
    if( zDbName ) fsl_cx_b_return(f, zDbName);
    if(rc) return rc;
  }
  assert(!rc);
  /* Check the name against the repo's "manifest" setting and reject
     any filenames which that setting implies. */
  int manifestSetting = 0;
  fsl_ckout_manifest_setting(f, &manifestSetting);
  if(manifestSetting){
    typedef struct {
      short flag;
      char const * fn;
    } MSetting;
    const MSetting M[] = {
    {FSL_MANIFEST_MAIN, "manifest"},
    {FSL_MANIFEST_UUID, "manifest.uuid"},
    {FSL_MANIFEST_TAGS, "manifest.tags"},
    {0,0}
    };
    fsl_b * const c1 = fsl_cx_b_borrow(f);
    if( !c1 ){
      rc = f->error.code;
    }else if( f->db.ckout.dir ){
      rc = fsl_ckout_filename_check(f, relativeToCwd, zPath, c1);
    }else{
      rc = fsl_file_canonical_name2("", zPath, c1, false);
      if(rc){
        rc = fsl_cx_err_set(f, rc, "Cannot canonicalize file name "
                            "[%.*s]: %R", (int)nPath, zPath, rc);
      }
    }
    if(rc) goto yield;
    char const * const z = fsl_b_cstr(c1);
    //MARKER(("Checking file against manifest setting 0x%03x: %s\n",
    //manifestSetting, z));
    for( MSetting const * m = &M[0]; m->fn; ++m ){
      if((m->flag & manifestSetting)
         && 0==fsl_strcmp(z, m->fn)){
        rc = fsl_cx_err_set(f, errRc,
                            "Filename is reserved due to the "
                            "'manifest' setting: %s",
                            m->fn);
        break;
      }
    }
    yield:
    fsl_cx_b_return(f, c1);
  }
  return rc;
}

fsl_b * fsl__cx_scratchpad(fsl_cx * const f){
  fsl_b * rc = 0;
  int i = (f->scratchpads.next<FSL_CX_NSCRATCH)
    ? f->scratchpads.next : 0;
  for(; i < FSL_CX_NSCRATCH; ++i){
    if(!f->scratchpads.used[i]){
      rc = &f->scratchpads.buf[i];
      f->scratchpads.used[i] = true;
      ++f->scratchpads.next;
      //MARKER(("Doling out scratchpad[%d] w/ capacity=%d next=%d\n",
      //        i, (int)rc->capacity, f->scratchpads.next));
      break;
    }
  }
  if(!rc){
    assert(!"Fatal fsl_cx::scratchpads misuse.");
    fsl__fatal(FSL_RC_MISUSE,
              "Fatal internal fsl_cx::scratchpads misuse: "
              "too many unyielded buffer requests.");
  }else if(0!=rc->used){
    assert(!"Fatal fsl_cx::scratchpads misuse.");
    fsl__fatal(FSL_RC_MISUSE,
              "Fatal internal fsl_cx::scratchpads misuse: "
              "used buffer after yielding it.");
  }
  return rc;
}

void fsl__cx_scratchpad_yield(fsl_cx * const f, fsl_b * const b){
  int i;
  assert(b);
  for(i = 0; i < FSL_CX_NSCRATCH; ++i){
    if(b == &f->scratchpads.buf[i]){
      assert(f->scratchpads.next != i);
      assert(f->scratchpads.used[i] && "Scratchpad misuse.");
      f->scratchpads.used[i] = false;
      fsl_b_reuse(b);
      if(f->scratchpads.next>i) f->scratchpads.next = i;
      //MARKER(("Yielded scratchpad[%d] w/ capacity=%d, next=%d\n",
      //        i, (int)b->capacity, f->scratchpads.next));
      return;
    }
  }
  fsl__fatal(FSL_RC_MISUSE,
            "Fatal internal fsl_cx::scratchpads misuse: "
            "passed a non-scratchpad buffer.");
}


/** @internal

   Don't use this. Use fsl__ckout_rm_empty_dirs() instead.

   Attempts to remove empty directories from under a checkout,
   starting with tgtDir and working upwards until it either cannot
   remove one or it reaches the top of the checkout dir.

   The first argument must be the canonicalized absolute path to the
   checkout root. The second is the length of coRoot - if it's
   negative then fsl_strlen() is used to calculate it. The third must
   be the canonicalized absolute path to some directory under the
   checkout root. The contents of the buffer may, for efficiency's
   sake, be modified by this routine as it traverses the directory
   tree. It will never grow the buffer but may mutate its memory's
   contents.

   Returns the number of directories it is able to remove.

   Results are undefined if tgtDir is not an absolute path or does not
   have coRoot as its initial prefix.

   There are any number of valid reasons removal of a directory might
   fail, and this routine stops at the first one which does.
*/
static unsigned fsl__rm_empty_dirs(fsl_cx * const f,
                                   char const * const coRoot,
                                   fsl_int_t rootLen,
                                   fsl_b const * const tgtDir){
  if(rootLen<0) rootLen = (fsl_int_t)fsl_strlen(coRoot);
  char const * zAbs = fsl_b_cstr(tgtDir);
  char const * zCoDirPart = zAbs + rootLen;
  char * zEnd = fsl_b_str(tgtDir) + tgtDir->used - 1;
  unsigned rc = 0;
  assert(coRoot);
  if(0!=memcmp(coRoot, zAbs, (size_t)rootLen)){
    assert(!"Misuse of fsl__rm_empty_dirs()");
    return 0;
  }
  if(fsl__cfs_rmdir(f, zAbs)) return rc;
  ++rc;
  /** Now walk up each dir in the path and try to remove each,
      stopping when removal of one fails or we reach coRoot. */
  while(zEnd>zCoDirPart){
    for( ; zEnd>zCoDirPart && '/'!=*zEnd; --zEnd ){}
    if(zEnd==zCoDirPart) break;
    else if('/'==*zEnd){
      *zEnd = 0;
      assert(zEnd>zCoDirPart);
      if(fsl__cfs_rmdir(f, zAbs)) break;
      ++rc;
    }
  }
  return rc;
}

unsigned int fsl__ckout_rm_empty_dirs(fsl_cx * const f,
                                      fsl_b const * const tgtDir){
  return f->db.ckout.dir
    ? fsl__rm_empty_dirs(f, f->db.ckout.dir, f->db.ckout.dirLen, tgtDir)
    : 0;
}

int fsl__ckout_rm_empty_dirs_for_file(fsl_cx * const f, char const *zAbsPath){
  if(!fsl_is_rooted_in_ckout(f, zAbsPath)){
    assert(!"Internal API misuse!");
    return FSL_RC_MISUSE;
  }else{
    fsl_b * const p = fsl_cx_b_borrow(f);
    fsl_int_t const nAbs = (fsl_int_t)fsl_strlen(zAbsPath);
    int const rc = p
      ? fsl_file_dirpart(zAbsPath, nAbs, p, false)
      : f->error.code;
    if(!rc) fsl__rm_empty_dirs(f, f->db.ckout.dir, f->db.ckout.dirLen, p);
    fsl_cx_b_return(f,p);
    return rc;
  }
}

int fsl_ckout_fingerprint_check(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_ckout(f);
  if(!db
     || !f->db.ckout.rid/*new repo - no fingerprint*/){
    return 0;
  }
  int rc = 0;
  char const * zCkout = 0;
  char * zRepo = 0;
  fsl_id_t rcvCkout = 0;
  fsl_b * const buf = fsl_cx_b_borrow(f);
  rc = buf
    ? fsl_config_get_buffer(f, FSL_CONFDB_CKOUT, "fingerprint", buf)
    : f->error.code;
  if(FSL_RC_NOT_FOUND==rc){
    /* Older checkout with no fingerprint. Assume it's okay. */
    rc = 0;
    fsl_cx_err_reset(f);
    goto end;
  }else if(rc){
    goto end;
  }else if(!buf->used){
    /* NULL fingerprint, recorded when the repo had no rcvfrom
       entries. fossil(1) also assumes it's okay. */
    goto end;
  }
  zCkout = fsl_b_cstr(buf);
#if 0
  /* Inject a bogus byte for testing purposes */
  buf->mem[6] = 'x';
#endif
  (void)sscanf(zCkout, "%"FSL_ID_T_SFMT, &rcvCkout);
  rc = fsl__repo_fingerprint_search(f, rcvCkout, &zRepo);
  switch(rc){
    case FSL_RC_NOT_FOUND: goto mismatch;
    case 0:
      assert(zRepo);
      if(fsl_strcmp(zRepo,zCkout)){
        goto mismatch;
      }
      break;
    default:
      break;
  }
  end:
  fsl_cx_b_return(f, buf);
  fsl_free(zRepo);
  return rc;
  mismatch:
  rc = fsl_cx_err_set(f, FSL_RC_REPO_MISMATCH,
                      "Mismatch found between repo/checkout "
                      "fingerprints: checkout has %s, repository "
                      "has %s.", zCkout,
                      zRepo ? zRepo : "no matching rcvfrom entry");
  goto end;
}

bool fsl_cx_has_ckout(fsl_cx const * const f ){
  return f->db.ckout.dir ? true : false;
}

int fsl_cx_interruptv(fsl_cx * const f, int code, char const * fmt, va_list args){
  f->interrupted = code;
  if(code && NULL!=fmt){
    code = fsl_cx_err_setv(f, code, fmt, args);
  }
  return code;
}

int fsl_cx_interrupt(fsl_cx * const f, int code, char const * fmt, ...){
  int rc;
  va_list args;
  va_start(args,fmt);
  rc = fsl_cx_interruptv(f, code, fmt, args);
  va_end(args);
  return rc;
}

int fsl_cx_interrupted(fsl_cx const * const f){
  return f->interrupted;
}

#if 0
struct tm * fsl_cx_localtime( fsl_cx const * f, const time_t * clock ){
  if(!clock) return NULL;
  else if(!f) return localtime(clock);
  else return (f->flags & FSL_CX_F_LOCALTIME_GMT)
         ? gmtime(clock)
         : localtime(clock)
         ;
}

struct tm * fsl_localtime( const time_t * clock ){
  return fsl_cx_localtime(NULL, clock);
}

time_t fsl_cx_time_adj(fsl_cx const * f, time_t clock){
  struct tm * tm = fsl_cx_localtime(f, &clock);
  return tm ? mktime(tm) : 0;
}
#endif

int fsl_cx_last_sync_url(fsl_cx * const f, fsl_b *tgt){
  int rc;
  if( !fsl_needs_repo(f) ) return f->error.code;
  rc = fsl_config_get_buffer(f, FSL_CONFDB_REPO, "last-sync-url", tgt);
  if( FSL_RC_NOT_FOUND==rc ){
    rc = fsl_cx_err_set(f, rc, "No remote URL: this repository has "
                        "no \"last-sync-url\" setting");
  }
  return rc;
}

#define STMT_YIELD_BIT 0x0200 /* must not colide with db.c:fsl__stmt_flags_e */

fsl_stmt * fsl__cx_stmt( fsl_cx * f, enum fsl__cx_stmt_e which ){
  fsl_stmt * q = 0;
  char const * zSql = 0;
  char const * zName = 0;

#if 0
#define E(NAME,SQL) \
  static int xx_ ## NAME = 0;
    fsl__cx_cache_stmt_map(E)
#undef E
#endif

  assert( f->dbMain->role & FSL_DBROLE_REPO );
  switch(which){
#define CASE(NAME,SQL) \
    case fsl__cx_stmt_e_ ## NAME: \
      q = &f->cache.stmt.NAME; \
      zSql = SQL " /* fsl__cx_stmt(" #NAME ") */"; zName = #NAME; \
      break;
    fsl__cx_cache_stmt_map(CASE)
#undef CASE
  }
  assert( q );
  assert( zSql );
  assert( zName );
#if !defined(NDEBUG)
  if( !*zSql ){
    fsl__fatal(FSL_RC_CANNOT_HAPPEN, "Missing SQL for %s(%d)",
               __func__, (int)which);
  }
#endif
  if( q->stmt ){
    if( STMT_YIELD_BIT & q->impl.flags ){
#if !defined(NDEBUG)
      assert( !(STMT_YIELD_BIT & q->impl.flags) && "Statement is already checked out");
      fsl__fatal(FSL_RC_MISUSE,
                 "Internal API misuse: %s() was used to fetch "
                 "cached statement '%s', but it's already checked out.",
                 __func__, zName) /* does not return */;
#else
      fsl_cx_err_set(f, FSL_RC_MISUSE,
                     "Internal API misuse: %s() was used to fetch "
                     "cached statement '%s', but it's already checked out.",
                     __func__, zName);
      q = 0;
#endif
    }else{
      q->impl.flags |= STMT_YIELD_BIT;
    }
  }else{
#if 0
    switch(which){
#define E(NAME,SQL) \
      case fsl__cx_stmt_e_ ##NAME: assert( ++xx_ ## NAME < 2 );
      fsl__cx_cache_stmt_map(E)
#undef E
    }
#endif
    /* zSql is the format string, not an argument, so that its
       {{dbname.repo}} placeholders are expanded for f. It has no '%'. */
    if( fsl_cx_prepare(f, q, zSql) ){
      q = 0;
    }else{
      q->impl.flags |= STMT_YIELD_BIT;
    }
  }
  return q;
}

void fsl__cx_stmt_yield( fsl_cx * f, fsl_stmt * q ){
  if( q ){
    (void)f;
    assert( STMT_YIELD_BIT & q->impl.flags && "Statement check-out misuse");
    q->impl.flags &= ~STMT_YIELD_BIT;
    fsl_stmt_reset(q);
    fsl_stmt_clear_bindings(q);
  }
}

int fsl__ckout_rid(fsl_cx * const f, fsl_id_t *rid){
  int rc = 0;
  if( (*rid=f->db.ckout.rid) <= 0 ){
    if( 0==(rc = fsl__ckout_version_fetch(f)) ){
      *rid = f->db.ckout.rid;
    }
  }
  return rc;
}

int fsl__array_reserve(fsl_error *err, void **list, fsl_size_t nDesired,
                       fsl_size_t * nAlloc, unsigned sizeOfEntry){
  int rc = err ? err->code : 0;
  if( 0==rc && nDesired > *nAlloc ){
    fsl_size_t const nA = nDesired < 10 ? 10 : nDesired;
    if( nA > (fsl_size_t)SIZE_MAX / sizeOfEntry ){
      return fsl_error_set(err, FSL_RC_OOM, 0);
    }
    void * const p = fsl_realloc(*list, sizeOfEntry * nA);
    if( p ){
      memset((unsigned char *)p +
             (sizeOfEntry * *nAlloc), 0,
             sizeOfEntry * (nA - *nAlloc));
      *list = p;
      *nAlloc = nA;
    }else{
      rc = fsl_error_set(err, FSL_RC_OOM, 0);
    }
  }
  return rc;
}

#if 0
void fsl__b_list_reuse(fsl__b_list *li){
  while( li->used ){
    fsl_b * const b = li->list[--li->used];
    if(b) fsl_b_reuse(b);
  }
}
#endif

void fsl__b_list_cleanup(fsl__b_list *li){
  while( li->capacity ){
    fsl_b * const b = li->list[--li->capacity];
    if(b){
      fsl_b_clear(b);
      fsl_free(b);
    }
  }
  fsl_free(li->list);
  *li = fsl__b_list_empty;
}


static fsl_b * fsl__b_list_push(fsl__b_list *li){
  fsl_b * p = 0;
  assert( li->list ? li->capacity : 0==li->capacity );
  if( 0==fsl__b_list_reserve(
        NULL, li,
        fsl__ListType__reserve1_size(
          li, 8
          /* ^^^ f-rebuild caps out at 6 buffers, f-sanity and
             f-parseparty at 3, and f-clone a measly 1. (FWIW, the
             buffer pool proves its worth with f-sanity.)

             Might want to revisit this with the addition of S-cards,
             as their tree-walking might use more. */
        )
      ) ){
    p = li->list[li->used];
    if( p ){
      fsl_b_reuse(p);
    }else{
      p = fsl_malloc(sizeof(*p));
      if( p ){
        li->list[li->used++] = p;
        *p = fsl_b_empty;
      }else{
        fsl_report_oom;
      }
    }
  }
  return p;
}

/**
   bsearch()/qsort() comparison for (fsl_b**), sorting by size,
   largest first and empty slots last.
*/
static int fsl__buffer__cmp_desc(const void *p1, const void *p2){
  fsl_b const * const eL = *(fsl_b const **)p1;
  fsl_b const * const eR = *(fsl_b const **)p2;
  if( eL==eR ) return 0;
  else if( !eL ) return 1;
  else if (!eR ) return -1;
  return /*largest first*/(eL->capacity > eR->capacity)
    ? -1 : (eL->capacity < eR->capacity);
}

/**
   bsearch()/qsort() comparison for (fsl_b**), sorting by size,
   smallest first and empty slots last.
*/
static int fsl__buffer__cmp_asc(const void *p1, const void *p2){
  fsl_b const * const eL = *(fsl_b const **)p1;
  fsl_b const * const eR = *(fsl_b const **)p2;
  if( eL==eR ) return 0;
  else if( !eL ) return 1;
  else if (!eR ) return -1;
  return /*smallest first*/(eL->capacity < eR->capacity)
    ? -1 : (eL->capacity > eR->capacity);
}

/**
   Sort li's buffer list using the given policy. NULL entries always
   sort last. This is a no-op of how == fsl__b_list_UNSORTED or
   li->used<2.
*/
static void fsl__b_list__sort(fsl__b_list * const li,
                                   enum fsl__b_list_e how){
  switch( li->used<2 ? fsl__b_list_e_UNSORTED : how ){
    case fsl__b_list_e_UNSORTED:
      break;
    case fsl__b_list_e_DESC:
      qsort(li->list, li->used, sizeof(fsl_b*), fsl__buffer__cmp_desc);
      break;
    case fsl__b_list_e_ASC:
      qsort(li->list, li->used, sizeof(fsl_b*), fsl__buffer__cmp_asc);
      break;
  }
}

fsl_b * fsl__cx_buffer_borrow(fsl_cx *f, bool honorErrorState){
  /* TODO: factor this into another level so that we can add buffer
     lists elsewhere. (But where? When we can answer that, this will
     be refactored.) */
  if( honorErrorState && FSL_RC_OOM==f->error.code ) return 0;
  fsl__b_library * const lib = &f->cache.buf;
  fsl__b_list * const li = &lib->list;
  fsl_b * b = 0;
  if( fsl__b_list_e_UNSORTED==lib->sort ){
    lib->sort = fsl__b_list_e_DESC;
    fsl__b_list__sort(li, lib->sort);
    assert( fsl__b_list_e_UNSORTED!=lib->sort
            || lib->list.used<2 );
  }
#define incrBorrowed                                             \
  if( (++lib->nBorrowed - lib->nReturned) > lib->peakBorrowed ){ \
    lib->peakBorrowed = lib->nBorrowed - lib->nReturned;         \
  } (void)0
  for(fsl_size_t i = 0; i < li->capacity; ++i){
    b = li->list[i];
    if( b ){
      assert( li->used );
      assert( !b->used &&
              "Someone wrote to a buffer after giving it back" );
      assert( b->capacity <= lib->currentCapacity
              && "Else we've mismanaged "
              "fsl__b_library::currentCapacity" );
      lib->nBytesBorrowed  += b->capacity;
      lib->currentCapacity -= b->capacity;
      lib->sort = i>1
        ? fsl__b_list_e_UNSORTED
        : fsl__b_list_e_DESC;
      li->list[i] = 0;
      --li->used;
      incrBorrowed;
      return fsl_b_reuse(b);
    }
  }
  /**
     Allocate the list entry now and then remove the buffer from it to
     "borrow" it.
  */
  b = fsl__b_list_push(li);
  if( b ) {
    assert( li->used );
    assert( b==li->list[li->used-1] );
    incrBorrowed;
    li->list[--li->used] = 0;
  }else{
    fsl_report_oom;
    fsl_cx_err_set(f, FSL_RC_OOM, 0);
  }
  return b;
#undef incrBorrowed
}

fsl_b * fsl_cx_b_borrow(fsl_cx *f){
  return fsl__cx_buffer_borrow(f, true);
}

void fsl_cx_b_return(fsl_cx * const f, fsl_b * const b){
  if( !b ) return;
  fsl__b_library * const lib = &f->cache.buf;
  fsl__b_list * const li = &lib->list;
  assert( lib->nBorrowed > lib->nReturned );
  ++lib->nReturned;
  if( !lib->limitCount || (li->used+1>lib->limitCount) ){
    lib->nBytesReturned += b->capacity;
    /* Don't update lib->peakCapacity here */
    fsl_b_clear(b);
    fsl_free(b);
    return;
  }
  if( (lib->limitCapacity
       && (b->capacity + lib->currentCapacity > lib->limitCapacity))
      || (lib->limitSingleCapacity
          && b->capacity>lib->limitSingleCapacity) ){
    /* keep b but not its memory. */
    lib->nBytesReturned += b->capacity;
    fsl_b_clear(b);
  }
  assert( li->used < li->capacity
          && "Else serious buffer mismanagement" );
  for( fsl_size_t i = 0; i < li->capacity; ++i ){
    if( !li->list[i] ){
      li->list[i] = fsl_b_reuse(b);
      lib->sort = (++li->used > 1)
        ? fsl__b_list_e_UNSORTED
        : fsl__b_list_e_DESC;
      lib->nBytesReturned += b->capacity;
      lib->currentCapacity += b->capacity;
      if( lib->currentCapacity > lib->peakCapacity ){
        lib->peakCapacity = lib->currentCapacity;
      }
      return;
    }
  }
  fsl__fatal(FSL_RC_CANNOT_HAPPEN,
             "Serious memory misuse. "
             "This suggests that fsl_cx_b_return() was used "
             "without a corresponding fsl_cx_b_borrow() or "
             "that a given buffer was returned multiple times." );
}

void fsl_cx_b_return_wipe(fsl_cx *f, fsl_b *b){
  if( b && b->capacity ) memset(b->mem, 0, b->capacity);
  fsl_cx_b_return(f, b);
}

fsl__ListType_impl(fsl__b_list,fsl_b*)

#undef MARKER
#undef FSL_CX_NSCRATCH
/* end of file src/cx.c */
/* start of file src/db.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).

  *****************************************************************************
  This file contains the fsl_db_xxx() and fsl_stmt_xxx() parts of the
  API.

  Maintenance reminders:

  When returning dynamically allocated memory to the client, it needs
  to come from fsl_malloc(), as opposed to sqlite3_malloc(), so that
  it is legal to pass to fsl_free().
*/
#include <assert.h>
#include <string.h> /* strchr() */
/* Only for debugging */
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

int fsl__db_errcode(fsl_db * const db, int sqliteCode){
  int rc = 0;
  if(!sqliteCode) sqliteCode = sqlite3_errcode(db->dbh);
  switch(sqliteCode & 0xff){
    case SQLITE_ROW:
    case SQLITE_DONE:
    case SQLITE_OK: rc = 0; break;
    case SQLITE_NOMEM:
      rc = FSL_RC_OOM;
      fsl_check_oom_rc(rc);
      break;
    case SQLITE_INTERRUPT: rc = FSL_RC_INTERRUPTED; break;
    case SQLITE_TOOBIG:
    case SQLITE_FULL:
    case SQLITE_RANGE: rc = FSL_RC_RANGE; break;
    case SQLITE_NOTFOUND: rc = FSL_RC_NOT_FOUND; break;
    case SQLITE_BUSY:
    case SQLITE_LOCKED: rc = FSL_RC_LOCKED; break;
    case SQLITE_PERM:
    case SQLITE_AUTH:
    case SQLITE_READONLY: rc = FSL_RC_ACCESS; break;
    case SQLITE_CORRUPT: rc = FSL_RC_CONSISTENCY; break;
    case SQLITE_CANTOPEN:
    case SQLITE_IOERR: rc = FSL_RC_IO; break;
    case SQLITE_NOLFS: rc = FSL_RC_UNSUPPORTED; break;
    default:
      //MARKER(("sqlite3_errcode()=0x%04x\n", rc));
      rc = FSL_RC_DB; break;
  }
  return rc
    ? fsl_error_set(&db->error, rc,
                    "sqlite3 error #%d: %s",
                    /* use ^^^^ "error" instead of "result code" to
                       match sqlite3's own output. */
                    sqliteCode, sqlite3_errmsg(db->dbh))
    : (fsl_error_reset(&db->error), 0);
}

void fsl__db_clear_strings(fsl_db * const db, bool alsoBuffers){
  fsl_free(db->filename);
  db->filename = NULL;
  fsl_free(db->name);
  db->name = NULL;
  fsl_free(db->impl.share.zRepo);
  db->impl.share.zRepo = NULL;
  fsl_free(db->impl.share.zCkout);
  db->impl.share.zCkout = NULL;
  fsl_free(db->impl.share.zCkoutPrefix);
  db->impl.share.zCkoutPrefix = NULL;
  fsl_free(db->impl.share.zRepoPrefix);
  db->impl.share.zRepoPrefix = NULL;
  if(alsoBuffers){
    fsl_b_clear(&db->impl.buffer);
    fsl_error_clear(&db->error);
  }
}

int fsl_db_err_get( fsl_db const * const db, char const ** msg, fsl_size_t * len ){
  return fsl_error_get(&db->error, msg, len);
}

fsl_db * fsl_stmt_db( fsl_stmt * const stmt ){
  return stmt->db;
}

char const * fsl_stmt_sql( fsl_stmt * const stmt, fsl_size_t * const len ){
  return fsl_b_cstr2(&stmt->sql, len);
}

char const * fsl_db_filename(fsl_db const * db, fsl_size_t * len){
  if(len && db->filename) *len = fsl_strlen(db->filename);
  return db->filename;
}

fsl_id_t fsl_db_last_insert_id(fsl_db * const db){
  return (db && db->dbh)
    ? (fsl_id_t)sqlite3_last_insert_rowid(db->dbh)
    : -1;
}

/**
   Immediately cleans up all cached statements (if any) and returns
   the number of statements cleaned up. It is illegal to call this
   while any of the cached statements are actively being used (have
   not been fsl_stmt_cached_yield()ed), and doing so will lead to
   undefined results if the statement(s) in question are used after
   this function completes.

   @see fsl_db_prepare_cached()
   @see fsl_stmt_cached_yield()
*/
static fsl_size_t fsl_db_stmt_cache_clear(fsl_db * const db){
  fsl_size_t rc = 0;
  if(db && db->impl.stCache.head){
    fsl_stmt * st;
    fsl_stmt * next = 0;
    for( st = db->impl.stCache.head; st; st = next, ++rc ){
      next = st->impl.next;
      st->impl.next = 0;
      fsl_stmt_finalize( st );
    }
    db->impl.stCache.head = 0;
  }
  return rc;
}

static void fsl__db_finalize_sp( fsl_db * const db ){
#define STMT(MEMBER) sqlite3_finalize(db->impl.txn.MEMBER); db->impl.txn.MEMBER=0
  STMT(sSavepoint);
  STMT(sRelease);
  STMT(sRollback);
#undef STMT
}

static void fsl__db_err_dump2(fsl_db * const db, char const *zFile, int line){
  MARKER(( "%s:%d: rc=%s %s\n", zFile, line,
           fsl_rc_cstr(db->error.code),
           fsl_b_cstr(&db->error.msg) ));
}
#define fsl__db_err_dump(DB) fsl__db_err_dump2(DB, __FILE__, __LINE__)

static int fsl__db_fire(fsl_db * const db, fsl_db_event_e mode, void * payload){
  int rc = 0;
  if( db->impl.event.f &&
      (FSL_DB_EVENT_mask_id & db->impl.event.maskIds & mode)
  ){
    int const spLevel = db->impl.txn.level + (FSL_DB_EVENT_BEGIN==mode);
    fsl_db_event const ev = {
      .db = db,
      .state = db->impl.event.state,
      .type = mode,
      .savepointLevel = spLevel,
      .payload = payload
    };
    rc = db->impl.event.f(&ev);
    if( rc && !db->error.code ){
      char const *zMode = 0;
      switch(mode){
#define E(X,V) case X: zMode = # X ; break;
        fsl_db_event_map(E)
#undef E
      }
      rc = fsl_error_set(&db->error, rc,
                         "Transaction hook %s for level %d failed",
                         zMode, spLevel);
      fsl__db_err_dump(db);
    }
  }
  return rc;
}

void fsl_db_close( fsl_db * const db ){
  if(!db) return;
  while(db->impl.txn.level>0){
    /* We do this primarily for the sake of keeping downstream code's
       internals intact. */
    if( !fsl__db_txn_is_innermost(db) ){
      fsl__db_txn_abandon(db);
      break;
    }
    fsl_db_txn_end_v2(db, false, true);
  }
  fsl__db_fire(db, FSL_DB_EVENT_CLOSING, NULL);
  fsl_db_stmt_cache_clear(db);
  if(db->impl.openStatementCount>0){
    assert(db->dbh);
    MARKER(("WARNING: %d open statement(s) left on db [%s].\n",
            (int)db->impl.openStatementCount, db->filename));
    sqlite3_stmt * pq = NULL;
    while( !fsl__db_is_borrowed(db)
           /* A host's statements are not ours to list. */
           && (pq = sqlite3_next_stmt(db->dbh, pq)) ){
      MARKER(("Lingering stmt: %s\n", sqlite3_sql(pq)));
    }
    //assert(!"here");
  }
  fsl__db_finalize_sp(db);
  if(db->dbh && !fsl__db_is_borrowed(db)){
    sqlite3_close_v2(db->dbh);
  }
  fsl__db_clear_strings(db, true);
  void const * const allocStamp = db->impl.allocStamp;
  *db = fsl_db_empty;
  if(&fsl_db_empty == allocStamp){
    fsl_free( db );
  }else{
    db->impl.allocStamp = allocStamp;
  }
  return;
}

void fsl_db_err_reset( fsl_db * const db ){
  if(db && (db->error.code||db->error.msg.used)){
    fsl_error_reset(&db->error);
  }
}

int fsl_db_attach(fsl_db * const db, const char *zDbName,
                  const char *zLabel){
  return (db && db->dbh && zDbName && *zDbName && zLabel && *zLabel)
    ? fsl_db_exec(db, "ATTACH DATABASE %Q AS %!Q /*%s()*/",
                  zDbName, zLabel, __func__)
    : FSL_RC_MISUSE;
}

int fsl_db_detach(fsl_db * const db, const char *zLabel){
  return (db && db->dbh && zLabel && *zLabel)
    ? fsl_db_exec(db, "DETACH DATABASE %!Q /*%s()*/", zLabel, __func__)
    : FSL_RC_MISUSE;
}

char const * fsl_db_name(fsl_db const * const db){
  return db ? db->name : NULL;
}

/**
    Returns the db name for the given role.
 */
const char * fsl_db_role_name(fsl_dbrole_e r){
  switch(r){
    case FSL_DBROLE_CONFIG:
      return "cfg";
    case FSL_DBROLE_REPO:
      return "repo";
    case FSL_DBROLE_CKOUT:
      return "ckout";
    case FSL_DBROLE_MAIN:
      return "main";
    case FSL_DBROLE_TEMP:
      return "temp";
    case FSL_DBROLE_NONE:
    default:
      return NULL;
  }
}

char * fsl_db_julian_to_iso8601( fsl_db * const db, double j,
                                 bool msPrecision,
                                 bool localTime){
  char * s = NULL;
  fsl_stmt * st = NULL;
  if(db && db->dbh && (j>=0.0)){
    char const * sql;
    if(msPrecision){
      sql = localTime
        ? "SELECT strftime('%%Y-%%m-%%dT%%H:%%M:%%f',?, 'localtime')"
        : "SELECT strftime('%%Y-%%m-%%dT%%H:%%M:%%f',?)";
    }else{
      sql = localTime
        ? "SELECT strftime('%%Y-%%m-%%dT%%H:%%M:%%S',?, 'localtime')"
        : "SELECT strftime('%%Y-%%m-%%dT%%H:%%M:%%S',?)";
    }
    fsl_db_prepare_cached(db, &st, sql);
    if(st){
      fsl_stmt_bind_double( st, 1, j );
      if( FSL_RC_STEP_ROW==fsl_stmt_step(st) ){
        s = fsl_strdup(fsl_stmt_g_text(st, 0, NULL));
      }
      fsl_stmt_cached_yield(st);
    }
  }
  return s;
}

char * fsl_db_unix_to_iso8601( fsl_db * const db, fsl_time_t t, bool localTime ){
  char * s = NULL;
  fsl_stmt * st = NULL;
  if(db && db->dbh && (t>=0)){
    char const * sql = localTime
      ? "SELECT datetime(?, 'unixepoch', 'localtime')/*%s()*/"
      : "SELECT datetime(?, 'unixepoch')/*%s()*/"
      ;
    int const rc = fsl_db_prepare_cached(db, &st, sql,__func__);
    if(!rc){
      fsl_stmt_bind_int64(st, 1, t);
      if( FSL_RC_STEP_ROW==fsl_stmt_step(st) ){
        fsl_size_t n = 0;
        char const * v = fsl_stmt_g_text(st, 0, &n);
        s = (v&&n) ? fsl_strndup(v, (fsl_int_t)n) : NULL;
      }
      fsl_stmt_cached_yield(st);
    }
  }
  return s;
}

enum fsl__stmt_flags_e {
  /**
     fsl_stmt::flags bit indicating that fsl_db_preparev_cached() has
     doled out this statement, effectively locking it until
     fsl_stmt_cached_yield() is called to release it.
  */
  FSL__STMT_F_CACHE_HELD = 0x01,

  /**
     Propagates our intent to "statically" prepare a given statement
     through various internal API calls.
  */
  FSL__STMT_F_PREP_CACHE = 0x10
};

/**
   For use with fsl_db::flags.
*/
enum fsl__db_flag_e {
  /**
     For communicating rollback state through the call stack. If this
     is set, the final fsl_db_txn_end() call in a stack will behave
     like a rollback regardless of the arguments to that
     function. i.e. it propagates a rollback through pseudo-nested
     transactions.
  */
  FSL__DB_F_BUBBLING_ROLLBACK = 0x01,
  /**
     Tells fsl__db_verify_begin_was_not_called() that the commit in
     question was triggered by this API instead of random input.
  */
  FSL__DB_F_IN_COMMIT = 0x02,
  /**
     The sqlite3 handle belongs to a host application. See
     fsl__db_borrow().
  */
  FSL__DB_F_BORROWED = 0x04
};

void fsl__db_borrow(fsl_db * const db, sqlite3 * const dbh){
  assert(!db->dbh);
  db->dbh = dbh;
  db->impl.flags |= FSL__DB_F_BORROWED;
}

bool fsl__db_is_borrowed(fsl_db const * const db){
  return !!(db->impl.flags & FSL__DB_F_BORROWED);
}

bool fsl__db_in_statement_or_txn(fsl_db * const db){
  sqlite3_stmt * st = NULL;
  if( !db->dbh ) return false;
  if( !sqlite3_get_autocommit(db->dbh) ) return true;
  while( NULL!=(st = sqlite3_next_stmt(db->dbh, st)) ){
    if( sqlite3_stmt_busy(st) ) return true;
  }
  return false;
}

int fsl__db_temp_drop(fsl_db * const db, char const * zTable){
  /* zTable is the name as written in {{temp.NAME}}: this context's
     own TEMP table of that name. */
  fsl_b tok = fsl_b_empty, name = fsl_b_empty;
  int rc = fsl_b_appendf(&tok, "temp.%s", zTable);
  if( 0==rc ) rc = fsl__db_schema_token(db, fsl_b_cstr(&tok), tok.used,
                                        NULL, NULL, &name);
  if( 0==rc ) rc = fsl_db_exec(db, "DROP TABLE IF EXISTS %b", &name);
  if( rc && FSL_RC_OOM!=rc ){
    /* SQLite cannot drop a table while another statement runs, as it
       does when we are called from a host's SQL function. Empty it
       for reuse instead. */
    fsl_db_err_reset(db);
    rc = fsl_db_exec(db, "DELETE FROM %b", &name);
  }
  fsl_b_clear(&tok);
  fsl_b_clear(&name);
  return rc;
}

char const * fsl__db_schema(fsl_db const * const db, fsl_dbrole_e r){
  if( db ){
    if( FSL_DBROLE_REPO==r && db->impl.share.zRepo ){
      return db->impl.share.zRepo;
    }else if( FSL_DBROLE_CKOUT==r && db->impl.share.zCkout ){
      return db->impl.share.zCkout;
    }
  }
  return fsl_db_role_name(r);
}

int fsl__db_main_write_lock(fsl_db * const db){
  /* Writing a header field opens a write transaction on main alone.
     BEGIN IMMEDIATE would also lock every attached db, and fail if
     one file is attached twice. The write comes first, with no read
     before it, so that SQLite's busy handler waits for another
     connection's lock: upgrading a read transaction fails at once.
     Rolling back to the savepoint undoes the write but keeps the
     lock. */
  int rc = fsl_db_exec(db, "SAVEPOINT fsl__main_write_lock");
  if( 0==rc ){
    fsl_error err = fsl_error_empty;
    int const rc2 = fsl_db_exec(db, "PRAGMA main.user_version=0");
    if( rc2 ) fsl_error_copy(&db->error, &err);
    fsl_db_err_reset(db);
    rc = fsl_db_exec_multi(db, "ROLLBACK TO fsl__main_write_lock;"
                           "RELEASE fsl__main_write_lock");
    if( rc2 ){
      /* Report the lock failure, not the cleanup. */
      fsl_db_err_reset(db);
      fsl_error_copy(&err, &db->error);
      rc = rc2;
    }
    fsl_error_clear(&err);
  }
  return rc;
}

char const * fsl__db_ckout_prefix(fsl_db const * const db){
  return db ? db->impl.share.zCkoutPrefix : NULL;
}

char const * fsl__db_repo_prefix(fsl_db const * const db){
  return db ? db->impl.share.zRepoPrefix : NULL;
}

/** The table name prefix of role r's tables in db, else NULL. */
static char const * fsl__db_role_prefix(fsl_db const * const db,
                                        fsl_dbrole_e r){
  switch(r){
    case FSL_DBROLE_CKOUT: return fsl__db_ckout_prefix(db);
    case FSL_DBROLE_REPO: return fsl__db_repo_prefix(db);
    default: return NULL;
  }
}

/** The length of the [A-Za-z0-9_] identifier at the start of z. */
static fsl_size_t fsl__db_ident_len(char const * z){
  fsl_size_t n = 0;
  for( ; z[n] && ('_'==z[n] || fsl_isalnum(z[n])); ++n ){}
  return n;
}

int fsl__db_table_name(fsl_db const * const db, fsl_dbrole_e r,
                       char const * zTable, bool qualified,
                       fsl_b * const b){
  char const * const zPre = fsl__db_role_prefix(db, r);
  if( zPre ){
    return qualified
      ? fsl_b_appendf(b, "%s.\"%s%s\"", fsl__db_schema(db, r),
                      zPre, zTable)
      : fsl_b_appendf(b, "%s%s", zPre, zTable);
  }
  return qualified
    ? fsl_b_appendf(b, "%s.%s", fsl__db_schema(db, r), zTable)
    : fsl_b_append(b, zTable, -1);
}

int fsl__db_schema_token(fsl_db const * const db, char const * zTok,
                         fsl_size_t n, char const * zTail,
                         fsl_size_t * pnConsumed, fsl_b * const b){
  char const * zName = NULL;
  fsl_dbrole_e r = FSL_DBROLE_NONE;
  fsl_size_t nT = 0 /* length of "bare.ckout." resp. "bare.repo." */;
  if( 11==n && 0==memcmp(zTok, "dbname.repo", 11) ){
    r = FSL_DBROLE_REPO;
  }else if( 12==n && 0==memcmp(zTok, "dbname.ckout", 12) ){
    r = FSL_DBROLE_CKOUT;
  }else if( n>11 && 0==memcmp(zTok, "bare.ckout.", 11) ){
    r = FSL_DBROLE_CKOUT;
    nT = 11;
  }else if( n>10 && 0==memcmp(zTok, "bare.repo.", 10) ){
    r = FSL_DBROLE_REPO;
    nT = 10;
  }
  if( FSL_DBROLE_NONE!=r ){
    char const * const zPre = fsl__db_role_prefix(db, r);
    if( nT ){
      /* As bare.temp.NAME, for a checkout or repository table. */
      if( zPre ){
        return fsl_b_appendf(b, "\"%s%.*s\"", zPre, (int)(n - nT),
                             zTok + nT);
      }
      return fsl_b_append(b, zTok + nT, (fsl_int_t)(n - nT));
    }else if( zPre ){
      /* The role's tables are the host main db's PNAME tables:
         {{dbname.ckout}}.NAME as a whole becomes main."PNAME". */
      fsl_size_t const nId =
        (zTail && '.'==*zTail) ? fsl__db_ident_len(zTail + 1) : 0;
      if( !nId ) return FSL_RC_MISUSE;
      assert( pnConsumed );
      *pnConsumed = 1 + nId;
      return fsl_b_appendf(b, "%s.\"%s%.*s\"", fsl__db_schema(db, r),
                           zPre, (int)nId, zTail + 1);
    }
    zName = fsl__db_schema(db, r);
  }else if( n>5 && 0==memcmp(zTok, "temp.", 5) ){
    /* A TEMP table: the first context on a connection uses its name
       as is, a later one a name of its own, since they share the
       connection's one TEMP schema. */
    if( db && db->impl.share.id>1 ){
      return fsl_b_appendf(b, "temp.fsl%u_%.*s", db->impl.share.id,
                           (int)(n - 5), zTok + 5);
    }
    return fsl_b_append(b, zTok, (fsl_int_t)n);
  }else if( n>10 && 0==memcmp(zTok, "bare.temp.", 10) ){
    /* As temp.NAME, without the schema, for where SQLite wants a bare
       table name, e.g. CREATE INDEX temp.X ON NAME(...). */
    if( db && db->impl.share.id>1 ){
      return fsl_b_appendf(b, "fsl%u_%.*s", db->impl.share.id,
                           (int)(n - 10), zTok + 10);
    }
    return fsl_b_append(b, zTok + 10, (fsl_int_t)(n - 10));
  }
  return zName ? fsl_b_append(b, zName, -1) : FSL_RC_NOT_FOUND;
}

/** fsl__brace_f for fsl__db_appendfv(). */
static int fsl__db_brace_f(void * state, char const * zTok,
                           fsl_size_t n, char const * zTail,
                           fsl_size_t * pnConsumed, fsl_b * const b,
                           bool escPct){
  fsl_db * const db = state;
  int const rc = fsl__db_schema_token(db, zTok, n, zTail, pnConsumed, b);
  (void)escPct /* schema and table names contain no '%' */;
  if( FSL_RC_MISUSE==rc ){
    bool const isRepo = 'r'==zTok[7] /* dbname.repo, not dbname.ckout */;
    fsl_error_set(&db->error, rc, "{{%.*s}} not followed by "
                  "a table name, with the %s's tables prefixed "
                  "with \"%s\": %.*s", (int)n, zTok,
                  isRepo ? "repository" : "checkout",
                  isRepo ? fsl__db_repo_prefix(db)
                  : fsl__db_ckout_prefix(db),
                  (int)fsl_strlen(zTail)>60 ? 60 : (int)fsl_strlen(zTail),
                  zTail);
  }
  return rc;
}

/**
   fsl_b_appendfv(buf, zFmt, args) for the SQL functions, after
   replacing the schema placeholders {{dbname.repo}} and
   {{dbname.ckout}} in zFmt
   (the format string, never the formatted values) with db's schema
   names for those roles.
*/
static int fsl__db_appendfv(fsl_db * const db, fsl_b * const buf,
                            char const * zFmt, va_list args){
  if( !strstr(zFmt, "{{") ) return fsl_b_appendfv(buf, zFmt, args);
  else{
    fsl_b fmt = fsl_b_empty;
    int rc = fsl__brace_expand(&fmt, zFmt, false, fsl__db_brace_f, db);
    if( 0==rc ) rc = fsl_b_appendfv(buf, fsl_b_cstr(&fmt), args);
    fsl_b_clear(&fmt);
    return rc;
  }
}

int fsl__db_appendf(fsl_db * const db, fsl_b * const b,
                    char const * zFmt, ... ){
  int rc;
  va_list args;
  va_start(args, zFmt);
  rc = fsl__db_appendfv(db, b, zFmt, args);
  va_end(args);
  return rc;
}

int fsl_db_preparev( fsl_db  * const db, fsl_stmt * const tgt, char const * sql, va_list args ){
  if(!db || !tgt || !sql) return FSL_RC_MISUSE;
  else if(!db->dbh){
    return fsl_error_set(&db->error, FSL_RC_NOT_FOUND, "Db is not opened.");
  }else if(!*sql){
    return fsl_error_set(&db->error, FSL_RC_RANGE, "SQL is empty.");
  }else if(tgt->stmt){
    return fsl_error_set(&db->error, FSL_RC_ALREADY_EXISTS,
                         "Error: attempt to re-prepare "
                         "active statement.");
  }
  else{
    int rc;
    fsl_b buf = fsl_b_empty;
    fsl_stmt_t * liteStmt = NULL;
    rc = fsl__db_appendfv( db, &buf, sql, args );
    if(!rc){
#if 0
      /* Arguably improves readability of some queries.
         And breaks some caching uses. */
      fsl_simplify_sql_buffer(&buf);
#endif
      sql = fsl_b_cstr(&buf);
      if(!sql || !*sql){
        rc = fsl_error_set(&db->error, FSL_RC_RANGE,
                           "Input SQL is empty.");
      }else{
        /*
          Achtung: if sql==NULL here, or evaluates to a no-op
          (e.g. only comments or spaces), prepare_v2 succeeds but has
          a NULL liteStmt, which is why we handle the empty-SQL case
          specially. We don't want that specific behaviour leaking up
          through the API. Though doing so would arguably more correct
          in a generic API, for this particular API we have no reason
          to be able to handle empty SQL. Where we do let through
          through we'd have to add a flag to fsl_stmt to tell us
          whether it's really prepared or not, since checking of
          st->stmt would no longer be useful.
        */
        rc = sqlite3_prepare_v3(db->dbh, sql, (int)buf.used,
                                (FSL__STMT_F_PREP_CACHE & tgt->impl.flags)
                                ? SQLITE_PREPARE_PERSISTENT
                                : 0,
                                &liteStmt, NULL);
        if(rc){
          rc = fsl_error_set(&db->error, FSL_RC_DB,
                             "Db statement preparation failed. "
                             "Error #%d: %s. SQL: %.*s",
                             rc, sqlite3_errmsg(db->dbh),
                             (int)buf.used, (char const *)buf.mem);
        }else if(!liteStmt){
          /* SQL was empty. In sqlite this is allowed, but this API will
             disallow this because it leads to headaches downstream.
          */
          rc = fsl_error_set(&db->error, FSL_RC_RANGE,
                             "Input SQL is empty.");
        }
      }
    }
    if(!rc){
      assert(liteStmt);
      ++db->impl.openStatementCount;
      tgt->stmt = liteStmt;
      tgt->db = db;
      tgt->sql = buf /*transfer ownership*/;
    }else{
      assert(!liteStmt);
      fsl_b_clear(&buf);
    }
    return rc;
  }
}

int fsl_db_prepare( fsl_db * const db, fsl_stmt * const tgt, char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_preparev( db, tgt, sql, args );
  va_end(args);
  return rc;
}


int fsl_db_preparev_cached( fsl_db * const db, fsl_stmt ** rv,
                            char const * sql, va_list args ){
  int rc = 0;
  fsl_stmt * st = NULL;
  fsl_stmt * cs = NULL;
  if(!db || !rv || !sql) return FSL_RC_MISUSE;
  else if(!*sql){
    return fsl_error_set(&db->error, FSL_RC_RANGE, "SQL is empty.");
  }
  fsl_b * const buf = &db->impl.buffer;
  if(!buf->capacity && fsl_b_reserve(buf, 1024*2)){
    return FSL_RC_OOM;
  }
  fsl_b_reuse(buf);
  rc = fsl__db_appendfv(db, buf, sql, args);
  if(rc) goto end;
  /**
     Hash buf's contents using a very primitive algo and stores the
     hash in buf->cursor. This is a blatant abuse of that member but
     we're otherwise not using it on these buffer instances. We use
     this to slightly speed up lookup of previously-cached entries and
     reduce the otherwise tremendous number of calls to
     fsl_b_compare() libfossil makes.
  */
  for(fsl_size_t i = 0; i < buf->used; ++i){
    //buf->cursor = (buf->cursor<<3) ^ buf->cursor ^ buf->mem[i];
    buf->cursor = 31 * buf->cursor + (buf->mem[i] * 307);
  }
  for( cs = db->impl.stCache.head; cs; cs = cs->impl.next ){
    if(cs->sql.cursor==buf->cursor/*hash value!*/
       && buf->used==cs->sql.used
       && 0==fsl_b_compare(buf, &cs->sql)){
      if(cs->impl.flags & FSL__STMT_F_CACHE_HELD){
        rc = fsl_error_set(&db->error, FSL_RC_ACCESS,
                           "Cached statement is already in use. "
                           "Do not use cached statements if recursion "
                           "involving the statement is possible, and use "
                           "fsl_stmt_cached_yield() to release them "
                           "for further (re)use. SQL: %b",
                           &cs->sql);
        goto end;
      }
      cs->impl.flags |= FSL__STMT_F_CACHE_HELD;
      ++cs->impl.cachedHits;
      *rv = cs;
      goto end;
    }
  }
  st = fsl_stmt_malloc();
  if(!st){
    rc = FSL_RC_OOM;
    goto end;
  }
  st->impl.flags |= FSL__STMT_F_PREP_CACHE;
  rc = fsl_db_prepare( db, st, "%b", buf );
  if(rc){
    fsl_free(st);
    st = 0;
  }else{
    st->sql.cursor = buf->cursor/*hash value!*/;
    st->impl.next = db->impl.stCache.head;
    st->role = db->role
      /* Pessimistic assumption for purposes of invalidating
         fsl__db_cached_clear_role(). */;
    db->impl.stCache.head = st;
    st->impl.flags = FSL__STMT_F_CACHE_HELD;
    *rv = st;
  }
  end:
  return rc;
}

int fsl_db_prepare_cached( fsl_db * const db, fsl_stmt ** st, char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_preparev_cached( db, st, sql, args );
  va_end(args);
  return rc;
}

int fsl_stmt_cached_yield( fsl_stmt * const st ){
  if(!st || !st->db || !st->stmt) return FSL_RC_MISUSE;
  else if(!(st->impl.flags & FSL__STMT_F_CACHE_HELD)) {
    return fsl_error_set(&st->db->error, FSL_RC_MISUSE,
                         "fsl_stmt_cached_yield() was passed a "
                         "statement which is not marked as cached. "
                         "SQL: %b",
                         &st->sql);
  }else{
    fsl_stmt_reset(st);
    fsl_stmt_clear_bindings(st);
    st->impl.flags &= ~FSL__STMT_F_CACHE_HELD;
    return 0;
  }
}

int fsl_stmt_finalize( fsl_stmt * const stmt ){
  if(!stmt) return 0;
  void const * allocStamp = stmt->impl.allocStamp;
  fsl_db * const db = stmt->db;
  int rc = 0;
  if(db){
    if(stmt->sql.mem){
      /* ^^^ b/c that buffer is set at the same time
         that openStatementCount is incremented.
      */
      --stmt->db->impl.openStatementCount;
    }
    if(db->impl.stCache.head){
      /* It _might_ be cached - let's remove it. */
      fsl_stmt * s;
      fsl_stmt * prev = 0;
      for( s = db->impl.stCache.head; s; prev = s, s = s->impl.next ){
        if(s == stmt){
          if(prev){
            assert(prev->impl.next == s);
            prev->impl.next = s->impl.next;
          }else{
            assert(s == db->impl.stCache.head);
            db->impl.stCache.head = s->impl.next;
          }
          s->impl.next = 0;
          break;
        }
      }
    }
  }
  fsl_b_clear(&stmt->sql);
  if(stmt->stmt){
    rc = sqlite3_finalize( stmt->stmt );
    if( rc && !db->error.code ){
      rc = fsl__db_errcode(db, rc);
    }
  }
  *stmt = fsl_stmt_empty;
  if(&fsl_stmt_empty==allocStamp){
    fsl_free(stmt);
  }else{
    stmt->impl.allocStamp = allocStamp;
  }
  return rc;
}

int fsl__db_cached_clear_role(fsl_db * const db, fsl_flag32_t role){
  int rc = 0;
  fsl_stmt * s;
  fsl_stmt * prev = 0;
  fsl_stmt * next = 0;
  for( s = db->impl.stCache.head; s; s = next ){
    next = s->impl.next;
    if(0!=role && 0==(s->role & role)){
      prev = s;
      continue;
    }
    else if(FSL__STMT_F_CACHE_HELD & s->impl.flags){
      rc = fsl_error_set(&db->error, FSL_RC_MISUSE,
                         "Cannot clear cached SQL statement "
                         "for role #%d because it is currently "
                         "being held by a call to "
                         "fsl_db_preparev_cached(). SQL=%B",
                         (int)role, &s->sql);
      break;
    }
    //MARKER(("Closing cached stmt: %s\n", fsl_b_cstr(&s->sql)));
    if(prev){
      prev->impl.next = next;
    }else if(s==db->impl.stCache.head){
      db->impl.stCache.head = next;
    }
    s->impl.next = 0;
    s->impl.flags = 0;
    s->role = FSL_DBROLE_NONE;
    fsl_stmt_finalize(s);
    break;
  }
  return rc;
}

/**
   Steps q, a statement of db's, as the current context of db's
   connection when that is shared (a host's, see fsl__cxreg), so that
   SQL functions running in the step find db's context. The previous
   current context is restored afterwards, unless it has meanwhile
   left the connection.
*/
static int fsl__db_step(fsl_db * const db, sqlite3_stmt * const q){
  fsl__cxreg * const r = (db && fsl__db_is_borrowed(db))
    ? db->impl.share.reg : NULL;
  if( !r ) return sqlite3_step(q);
  else{
    fsl_cx * const prev = r->cur;
    int rc;
    r->cur = db->impl.share.cx;
    rc = sqlite3_step(q);
    r->cur = NULL;
    for( unsigned i = 0; prev && i < r->n; ++i ){
      if( r->a[i]==prev ){
        r->cur = prev;
        break;
      }
    }
    return rc;
  }
}

int fsl_stmt_step( fsl_stmt * const stmt ){
  if(!stmt->stmt) return FSL_RC_MISUSE;
  else{
    int const rc = fsl__db_step(stmt->db, stmt->stmt);
    assert(stmt->db);
    switch( rc ){
      case SQLITE_ROW:
        ++stmt->rowCount;
        return FSL_RC_STEP_ROW;
      case SQLITE_DONE:
        return FSL_RC_STEP_DONE;
      default:
        return fsl__db_errcode(stmt->db, rc);
    }
  }
}

int fsl_db_eachv( fsl_db * const db, fsl_stmt_each_f callback,
                  void * callbackState, char const * sql, va_list args ){
  if(!db->dbh || !callback || !sql) return FSL_RC_MISUSE;
  else if(!*sql){
    return fsl_error_set(&db->error, FSL_RC_RANGE, "SQL is empty.");
  }else{
    fsl_stmt st = fsl_stmt_empty;
    int rc;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(!rc){
      rc = fsl_stmt_each( &st, callback, callbackState );
      fsl_stmt_finalize( &st );
    }
    return rc;
  }
}

int fsl_db_each( fsl_db * const db, fsl_stmt_each_f callback,
                 void * callbackState, char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_eachv( db, callback, callbackState, sql, args );
  va_end(args);
  return rc;
}

int fsl_stmt_each( fsl_stmt * const stmt, fsl_stmt_each_f callback,
                   void * callbackState ){
  if(!callback) return FSL_RC_MISUSE;
  else{
    int strc;
    int rc = 0;
    bool doBreak = false;
    while( !doBreak && (FSL_RC_STEP_ROW == (strc=fsl_stmt_step(stmt)))){
      rc = callback( stmt, callbackState );
      switch(rc){
        case 0: continue;
        case FSL_RC_BREAK:
          rc = 0;
          /* fall through */
        default:
          doBreak = true;
          break;
      }
    }
    return rc
      ? rc
      : ((FSL_RC_STEP_ROW==strc || FSL_RC_STEP_DONE==strc)
         ? 0
         : strc);
  }
}

int fsl_stmt_reset2( fsl_stmt * const stmt, bool resetRowCounter ){
  if(!stmt->stmt || !stmt->db) return FSL_RC_MISUSE;
  else{
    int const rc = sqlite3_reset(stmt->stmt);
    if(resetRowCounter) stmt->rowCount = 0;
    assert(stmt->db);
    return rc
      ? fsl__db_errcode(stmt->db, rc)
      : 0;
  }
}

int fsl_stmt_reset( fsl_stmt * const stmt ){
  return fsl_stmt_reset2(stmt, 0);
}

void fsl_stmt_clear_bindings( fsl_stmt * stmt ){
  if( stmt->stmt ){
    sqlite3_clear_bindings(stmt->stmt);
  }
}

int fsl_stmt_col_count( fsl_stmt const * const stmt ){
  return (!stmt || !stmt->stmt)
    ? -1
    : sqlite3_column_count(stmt->stmt);
}

char const * fsl_stmt_col_name(fsl_stmt * const stmt, int index){
  return (stmt && stmt->stmt
          && (index>=0 && index<sqlite3_column_count(stmt->stmt)))
    ? sqlite3_column_name(stmt->stmt, index)
    : NULL;
}

int fsl_stmt_param_count( fsl_stmt const * const stmt ){
  return (!stmt || !stmt->stmt)
    ? -1
    : sqlite3_bind_parameter_count(stmt->stmt);
}

int fsl_stmt_bind_fmtv( fsl_stmt * st, char const * fmt, va_list args ){
  int rc = 0, ndx;
  char const * pos = fmt;
  if(!fmt ||
     !(st && st->stmt && st->db && st->db->dbh)) return FSL_RC_MISUSE;
  else if(!*fmt){
    return fsl_error_set(&st->db->error, FSL_RC_RANGE,
                         "Bind format string is empty.");
  }
  int const nParam = fsl_stmt_param_count(st);
  assert(nParam>=0);
  for( ndx = 1; !rc && *pos; ++pos, ++ndx ){
    if(' '==*pos){
      --ndx;
      continue;
    }
    if(ndx > nParam){
      rc = fsl_error_set(&st->db->error, FSL_RC_RANGE,
                         "Column index %d is out of bounds.", ndx);
      break;
    }
#define checkMakeCopy bool const makeCopy = ('^'==pos[1] ? (++pos, true) : false)
    switch(*pos){
      case '-':
        (void)va_arg(args,void const *) /* skip arg */;
        rc = fsl_stmt_bind_null(st, ndx);
        break;
      case 'i':
        rc = fsl_stmt_bind_int32(st, ndx, va_arg(args,int32_t));
        break;
      case 'I':
        rc = fsl_stmt_bind_int64(st, ndx, va_arg(args,int64_t));
        break;
      case 'R':
        rc = fsl_stmt_bind_id(st, ndx, va_arg(args,fsl_id_t));
        break;
      case 'f':
        rc = fsl_stmt_bind_double(st, ndx, va_arg(args,double));
        break;
      case 's':{/* C-string as TEXT or NULL */
        checkMakeCopy;
        char const * s = va_arg(args,char const *);
        rc = s
          ? fsl_stmt_bind_text(st, ndx, s, -1, makeCopy)
          : fsl_stmt_bind_null(st, ndx);
        break;
      }
      case 'S':{ /* C-string as BLOB or NULL */
        checkMakeCopy;
        char const * s = va_arg(args,char const *);
        rc = s
          ? fsl_stmt_bind_blob(st, ndx, s, fsl_strlen(s), makeCopy)
          : fsl_stmt_bind_null(st, ndx);
        break;
      }
      case 'b':{ /* fsl_b as TEXT or NULL */
        checkMakeCopy;
        fsl_b const * b = va_arg(args,fsl_b const *);
        rc = (b && b->used)
          ? fsl_stmt_bind_text(st, ndx, (char const *)b->mem,
                               (fsl_int_t)b->used, makeCopy)
          : fsl_stmt_bind_null(st, ndx);
        break;
      }
      case 'B':{ /* fsl_b as BLOB or NULL */
        checkMakeCopy;
        fsl_b const * b = va_arg(args,fsl_b const *);
        rc = (b && b->used)
          ? fsl_stmt_bind_blob(st, ndx, b->mem, b->used, makeCopy)
          : fsl_stmt_bind_null(st, ndx);
        break;
      }
      default:
        rc = fsl_error_set(&st->db->error, FSL_RC_RANGE,
                           "Invalid format character: '%c'", *pos);
        break;
    }
  }
#undef checkMakeCopy
  return rc;
}

/**
   The elipsis counterpart of fsl_stmt_bind_fmtv().
*/
int fsl_stmt_bind_fmt( fsl_stmt * const st, char const * fmt, ... ){
  int rc;
  va_list args;
  va_start(args,fmt);
  rc = fsl_stmt_bind_fmtv(st, fmt, args);
  va_end(args);
  return rc;
}

int fsl_stmt_bind_stepv_v2( fsl_stmt * const st, char const * fmt,
                         va_list args ){
  int rc;
  fsl_stmt_reset(st);
  rc = fsl_stmt_bind_fmtv(st, fmt, args);
  fsl_check_oom_rc(rc);
  if(!rc){
    rc = fsl_stmt_step(st);
    switch(rc){
      case FSL_RC_STEP_DONE: break;
      case FSL_RC_STEP_ROW: return rc
        /* Don't reset() for ROW b/c that clears the column data */;
      default:
        rc = fsl_error_set(&st->db->error, rc,
                           "Error stepping statement: %s",
                           sqlite3_errmsg(st->db->dbh));
        break;
    }
  }
  fsl_stmt_reset(st);
  return rc;
}

int fsl_stmt_bind_step_v2( fsl_stmt * st, char const * fmt, ... ){
  int rc;
  va_list args;
  va_start(args,fmt);
  rc = fsl_stmt_bind_stepv_v2(st, fmt, args);
  fsl_check_oom_rc(rc);
  va_end(args);
  return rc;
}

int fsl_stmt_bind_stepv( fsl_stmt * const st, char const * fmt,
                         va_list args ){
  int const rc = fsl_stmt_bind_stepv_v2(st, fmt, args);
  return (FSL_RC_STEP_DONE==rc) ? 0 : rc;
}

int fsl_stmt_bind_step( fsl_stmt * st, char const * fmt, ... ){
  int rc;
  va_list args;
  va_start(args,fmt);
  rc = fsl_stmt_bind_stepv_v2(st, fmt, args);
  va_end(args);
  return (FSL_RC_STEP_DONE==rc) ? 0 : rc;
}


#define BIND_PARAM_CHECK \
  int const nParam = fsl_stmt_param_count(stmt); \
  if(nParam<0) return FSL_RC_MISUSE; else
#define BIND_PARAM_CHECK2 BIND_PARAM_CHECK \
  if(ndx<1 || ndx>nParam) return FSL_RC_RANGE; else

int fsl_stmt_bind_null( fsl_stmt * const stmt, int ndx ){
  BIND_PARAM_CHECK2 {
    int const rc = sqlite3_bind_null( stmt->stmt, ndx );
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_int32( fsl_stmt * const stmt, int ndx, int32_t v ){
  BIND_PARAM_CHECK2 {
    int const rc = sqlite3_bind_int( stmt->stmt, ndx, (int)v );
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_int64( fsl_stmt * const stmt, int ndx, int64_t v ){
  BIND_PARAM_CHECK2 {
    int const rc = sqlite3_bind_int64( stmt->stmt, ndx, (sqlite3_int64)v );
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_id( fsl_stmt * const stmt, int ndx, fsl_id_t v ){
  BIND_PARAM_CHECK2 {
    int const rc = sqlite3_bind_int64( stmt->stmt, ndx, (sqlite3_int64)v );
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_double( fsl_stmt * const stmt, int ndx, double v ){
  BIND_PARAM_CHECK2 {
    int const rc = sqlite3_bind_double( stmt->stmt, ndx, (double)v );
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_blob( fsl_stmt * const stmt, int ndx, void const * src,
                        fsl_size_t len, bool makeCopy ){
  BIND_PARAM_CHECK2 {
    int rc;
    rc = sqlite3_bind_blob64( stmt->stmt, ndx, src, (sqlite3_uint64)len,
                              makeCopy ? SQLITE_TRANSIENT : SQLITE_STATIC );
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_text( fsl_stmt * const stmt, int ndx, char const * src,
                        fsl_int_t len, bool makeCopy ){
  BIND_PARAM_CHECK {
    int rc;
    if(len<0) len = fsl_strlen((char const *)src);
    rc = sqlite3_bind_text64( stmt->stmt, ndx, src, (sqlite3_uint64)len,
                              makeCopy ? SQLITE_TRANSIENT : SQLITE_STATIC,
                              SQLITE_UTF8 );
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_null_name( fsl_stmt * const stmt, char const * param ){
  BIND_PARAM_CHECK {
    return fsl_stmt_bind_null( stmt,
                               sqlite3_bind_parameter_index( stmt->stmt,
                                                             param) );
  }
}

int fsl_stmt_bind_int32_name( fsl_stmt * const stmt, char const * param, int32_t v ){
  BIND_PARAM_CHECK {
    return fsl_stmt_bind_int32( stmt,
                                sqlite3_bind_parameter_index( stmt->stmt,
                                                              param),
                                v);
  }
}

int fsl_stmt_bind_int64_name( fsl_stmt * const stmt, char const * param, int64_t v ){
  BIND_PARAM_CHECK {
    return fsl_stmt_bind_int64( stmt,
                                sqlite3_bind_parameter_index( stmt->stmt,
                                                              param),
                                v);
  }
}

int fsl_stmt_bind_id_name( fsl_stmt * const stmt, char const * param, fsl_id_t v ){
  BIND_PARAM_CHECK {
    return fsl_stmt_bind_id( stmt,
                             sqlite3_bind_parameter_index( stmt->stmt,
                                                           param),
                             v);
  }
}

int fsl_stmt_bind_double_name( fsl_stmt * const stmt, char const * param, double v ){
  BIND_PARAM_CHECK {
    return fsl_stmt_bind_double( stmt,
                                 sqlite3_bind_parameter_index( stmt->stmt,
                                                               param),
                                 v);
  }
}

int fsl_stmt_bind_text_name( fsl_stmt * const stmt, char const * param,
                             char const * v, fsl_int_t n,
                             bool makeCopy ){
  BIND_PARAM_CHECK {
    return fsl_stmt_bind_text(stmt,
                              sqlite3_bind_parameter_index( stmt->stmt,
                                                            param),
                              v, n, makeCopy);
  }
}

int fsl_stmt_bind_blob_name( fsl_stmt * const stmt, char const * param,
                             void const * v, fsl_int_t len,
                             bool makeCopy ){
  BIND_PARAM_CHECK {
    if(len<0) return FSL_RC_RANGE;
    return fsl_stmt_bind_blob(stmt,
                         sqlite3_bind_parameter_index( stmt->stmt,
                                                       param),
                              v, len, makeCopy);
  }
}

int fsl_stmt_param_index( fsl_stmt * const stmt, char const * const param){
  return (stmt && stmt->stmt)
    ? sqlite3_bind_parameter_index( stmt->stmt, param)
    : -1;
}

#undef BIND_PARAM_CHECK
#undef BIND_PARAM_CHECK2

#define GET_CHECK                                                \
  int const colCount = sqlite3_column_count(stmt->stmt);         \
  if( !colCount ) return FSL_RC_MISUSE;                          \
  else if((ndx<0) || (ndx>=colCount)) return FSL_RC_RANGE; else

int fsl_stmt_get_int32( fsl_stmt * const stmt, int ndx, int32_t * v ){
  GET_CHECK {
    if(v) *v = (int32_t)sqlite3_column_int(stmt->stmt, ndx);
    return 0;
  }
}
int fsl_stmt_get_int64( fsl_stmt * const stmt, int ndx, int64_t * v ){
  GET_CHECK {
    if(v) *v = (int64_t)sqlite3_column_int64(stmt->stmt, ndx);
    return 0;
  }
}

int fsl_stmt_get_double( fsl_stmt * const stmt, int ndx, double * v ){
  GET_CHECK {
    if(v) *v = (double)sqlite3_column_double(stmt->stmt, ndx);
    return 0;
  }
}

int fsl_stmt_get_id( fsl_stmt * const stmt, int ndx, fsl_id_t * v ){
  GET_CHECK {
    if(v) *v = (4==sizeof(fsl_id_t))
      ? (fsl_id_t)sqlite3_column_int(stmt->stmt, ndx)
      : (fsl_id_t)sqlite3_column_int64(stmt->stmt, ndx);
    return 0;
  }
}

int fsl_stmt_get_text( fsl_stmt * const stmt, int ndx, char const **out,
                       fsl_size_t * outLen ){
  GET_CHECK {
    unsigned char const * t = (out || outLen)
      ? sqlite3_column_text(stmt->stmt, ndx)
      : NULL;
    if(out) *out = (char const *)t;
    if(outLen){
      int const x = sqlite3_column_bytes(stmt->stmt, ndx);
      *outLen = (x>0) ? (fsl_size_t)x : 0;
    }
    /* A NULL t is either an SQL NULL or an OOM. Only the latter is
       an error, and an SQL NULL must not reset stmt->db's error
       state. */
    return (t || SQLITE_NOMEM!=(0xff & sqlite3_errcode(stmt->db->dbh)))
      ? 0 : fsl__db_errcode(stmt->db, SQLITE_NOMEM);
  }
}

int fsl_stmt_get_blob( fsl_stmt * const stmt, int ndx, void const **out,
                       fsl_size_t * outLen ){
  GET_CHECK {
    void const * t = (out || outLen)
      ? sqlite3_column_blob(stmt->stmt, ndx)
      : NULL;
    if(out) *out = t;
    if(outLen){
      if(!t) *outLen = 0;
      else{
        int sz = sqlite3_column_bytes(stmt->stmt, ndx);
        *outLen = (sz>=0) ? (fsl_size_t)sz : 0;
      }
    }
    /* See fsl_stmt_get_text(). */
    return (t || SQLITE_NOMEM!=(0xff & sqlite3_errcode(stmt->db->dbh)))
      ? 0 : fsl__db_errcode(stmt->db, SQLITE_NOMEM);
  }
}

#undef GET_CHECK

fsl_id_t fsl_stmt_g_id( fsl_stmt * const stmt, int index ){
  fsl_id_t rv = -1;
  fsl_stmt_get_id(stmt, index, &rv);
  return rv;
}
int32_t fsl_stmt_g_int32( fsl_stmt * const stmt, int index ){
  int32_t rv = 0;
  fsl_stmt_get_int32(stmt, index, &rv);
  return rv;
}
int64_t fsl_stmt_g_int64( fsl_stmt * const stmt, int index ){
  int64_t rv = 0;
  fsl_stmt_get_int64(stmt, index, &rv);
  return rv;
}
double fsl_stmt_g_double( fsl_stmt * const stmt, int index ){
  double rv = 0;
  fsl_stmt_get_double(stmt, index, &rv);
  return rv;
}

char const * fsl_stmt_g_text( fsl_stmt * const stmt, int index,
                              fsl_size_t * outLen ){
  char const * rv = NULL;
  fsl_stmt_get_text(stmt, index, &rv, outLen);
  return rv;
}


/**
   This sqlite3_trace_v2() callback outputs tracing info using
   fprintf() or fsl__db_fire().
*/
static int fsl__db_sq3TraceV2(unsigned t,void*c,void*p,void*x){
  static unsigned int counter = 0;
  switch(t){
    case SQLITE_TRACE_STMT:{
      fsl_db * const db = c;
      assert( !(db->impl.event.maskIds & ~FSL_DB_EVENT_mask_id)
              /* Else internal mask mismanipulation */ );
      if( db->impl.event.maskIds &
          (FSL_DB_EVENT_TRACE_SQL | FSL_DB_EVENT_TRACE_SQLX) ){
        fsl_b * const b = fsl_b_reuse(&db->impl.buffer);
        char const * zSql = (char const *)x;
        bool const isExp = ((FSL_DB_EVENT_TRACE_SQLX
                             & FSL_DB_EVENT_mask_id)
                            & db->impl.event.maskIds);
        char * zExp = isExp
          ? sqlite3_expanded_sql((sqlite3_stmt*)p)
            : 0;
        //MARKER(("mask=%08x isExp=%d\n", db->impl.event.maskIds, isExp));
        fsl_b_appendf(b, "SQL TRACE #%u: %s\n",
                           ++counter,
                           zExp ? zExp : zSql);
        sqlite3_free(zExp);
        if( 0==b->errCode ){
          if( db->impl.event.fpTrace ){
            fwrite(b->mem, b->used, 1, db->impl.event.fpTrace);
            //fflush(db->impl.event.fpTrace);
          }else{
            fsl__db_fire(db, isExp
                         ? FSL_DB_EVENT_TRACE_SQLX
                         : FSL_DB_EVENT_TRACE_SQL, b);
          }
        }
      }
      break;
    }
  }
  return 0;
}

fsl_db * fsl_db_malloc(void){
  fsl_db * const rc = (fsl_db *)fsl_malloc(sizeof(fsl_db));
  if(rc){
    *rc = fsl_db_empty;
    rc->impl.allocStamp = &fsl_db_empty;
  }
  return rc;
}

fsl_stmt * fsl_stmt_malloc(void){
  fsl_stmt * const rc = (fsl_stmt *)fsl_malloc(sizeof(fsl_stmt));
  if(rc){
    *rc = fsl_stmt_empty;
    rc->impl.allocStamp = &fsl_stmt_empty;
  }
  return rc;
}

/**
   Callback for use with sqlite3_commit_hook(). The argument must be a
   (fsl_db*). This function returns 0 only if it surmises that
   fsl_db_txn_end() triggered the COMMIT. On error it might
   assert() or abort() the application, so this really is just a
   sanity check for something which "must not happen."

   2025-08-11: TIL that this hook is only called if something actually
   changes. It won't trigger for read-only transactions.
*/
static int fsl__db_verify_begin_was_not_called(void * db_fsl){
  fsl_db * const db = (fsl_db *)db_fsl;
  assert(db && "What else could it be?");
  assert(db->dbh && "Else we can't have been called by sqlite3");
  //MARKER(("level=%d flags=0x%04x\n", db->impl.txn.level, db->flags));
  if( !db->impl.txn.level ){
    /* COMMIT is okay when we're not managing transaction levels */
    return 0;
  }
  if(FSL__DB_F_IN_COMMIT != (FSL__DB_F_IN_COMMIT & db->impl.flags)){
    /* It turns out that we'll end up losing this message when this
       error code bubbles up and we get a more generic message from
       sqlite. */
    /* A non-0 return makes SQLite turn the COMMIT into a ROLLBACK,
       which the pending fsl_db_txn_end_v2() will then report. */
    fsl_error_set(&db->error, FSL_RC_MISUSE, "SQL: COMMIT was called from "
                  "outside of fsl_db_txn_end_v2() while a "
                  "fsl_db_txn_begin()-started transaction "
                  "is pending. Don't do that.");
    return 2;
  }
  return 0;
}

int fsl_db_open( fsl_db * const db, char const * dbFile,
                 fsl_flag32_t openFlags ){
  int rc;
  fsl_db_t * dbh = NULL;
  if(!db || !dbFile) return FSL_RC_MISUSE;
  else if(db->dbh){
    return fsl_error_set(&db->error, FSL_RC_MISUSE,
                         "Cannot open db file [%s]: the handle "
                         "already has an opened db.", dbFile);
  }
  else if(!(FSL_DB_OPEN_CREATE & openFlags)
          &&  0  != *dbFile /* temp db */
          && ':' != *dbFile /*assume :memory:*/
#if !FSL_PLATFORM_IS_WINDOWS
          && (NULL==strchr(&dbFile[1], ':')/*assume URL*/)
#else
          && (':'==dbFile[1] /* maybe drive letter */
              || NULL==strchr(&dbFile[2], ':'/*assume URL*/))
#endif
          && fsl_file_access(dbFile, 0)){
    return fsl_error_set(&db->error, FSL_RC_NOT_FOUND,
                         "DB file not found: %s", dbFile);
  }else{
    int sOpenFlags = 0;
    if(FSL_DB_OPEN_RO & openFlags){
      sOpenFlags |= SQLITE_OPEN_READONLY;
    }else{
      if(FSL_DB_OPEN_RW & openFlags){
        sOpenFlags |= SQLITE_OPEN_READWRITE;
      }
      if(FSL_DB_OPEN_CREATE & openFlags){
        sOpenFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
      }
      if(!sOpenFlags) sOpenFlags = SQLITE_OPEN_READONLY;
    }
    rc = sqlite3_open_v2( dbFile, &dbh, sOpenFlags, NULL );
    if(rc){
      if(dbh){
        /* By some complete coincidence, FSL_RC_DB==SQLITE_CANTOPEN. */
        rc = fsl_error_set(&db->error, FSL_RC_DB,
                           "Opening db file [%s] failed with "
                           "sqlite code #%d: %s",
                           dbFile, rc, sqlite3_errmsg(dbh));
      }else{
        rc = fsl_error_set(&db->error, FSL_RC_DB,
                           "Opening db file [%s] failed with "
                           "sqlite code #%d",
                           dbFile, rc);
      }
      /* MARKER(("Error msg: %s\n", (char const *)db->error.msg.mem)); */
      goto end;
    }else{
      assert(!db->filename);
      if(!*dbFile || ':'==*dbFile){
        /* assume "" or ":memory:" or some such: don't canonicalize it,
           but copy it nonetheless for consistency. */
        db->filename = fsl_strdup(dbFile);
      }else{
        fsl_b tmp = fsl_b_empty;
        rc = fsl_file_canonical_name(dbFile, &tmp, 0);
        if(!rc){
          db->filename = (char *)tmp.mem
            /* transfering ownership */;
        }else{
          fsl_b_clear(&tmp);
          rc = fsl_error_set(&db->error, rc,
                             "Cannot canonicalize db file name "
                             "[%s]: %R", dbFile, rc);
        }
      }
      if(rc){
        goto end;
      }else if(!db->filename){
        rc = FSL_RC_OOM;
        goto end;
      }
    }
    db->dbh = dbh;
    /* Wait for another connection's write lock instead of failing at
       once with SQLITE_BUSY, as fossil(1)'s db_open() does with the
       same 15 seconds. A host which lends libfossil its own connection
       keeps whatever busy handler it installed. */
    sqlite3_busy_timeout(dbh, FSL__DB_BUSY_TIMEOUT_MS);
    sqlite3_extended_result_codes(dbh, 1);
    sqlite3_commit_hook(dbh, fsl__db_verify_begin_was_not_called, db);
    if(FSL_DB_OPEN_TRACE_SQL & openFlags){
      fsl_db_sqltrace_enable(db, stdout, false);
    }
  }
  end:
  if(rc){
    if(dbh){
      sqlite3_close(dbh);
      db->dbh = NULL;
    }
  }else{
    assert(db->dbh);
  }
  return rc;
}


static int fsl__db_err_not_opened(fsl_db * const db){
  return fsl_error_set(&db->error, FSL_RC_MISUSE,
                       "DB is not opened.");
}
static int fsl__db_err_sql_empty(fsl_db * const db){
  return fsl_error_set(&db->error, FSL_RC_MISUSE,
                       "Empty SQL is not permitted.");
 }

int fsl_db_exec_multiv( fsl_db * const db, const char * sql, va_list args){
  if(!db->dbh) return fsl__db_err_not_opened(db);
  else if(!sql || !*sql) return fsl__db_err_sql_empty(db);
  else{
    fsl_b buf = fsl_b_empty;
    int rc = 0;
    char const * z;
    char const * zEnd = NULL;
    rc = fsl__db_appendfv( db, &buf, sql, args );
    if(rc){
      fsl_b_clear(&buf);
      return rc;
    }
    z = fsl_b_cstr(&buf);
    while( (SQLITE_OK==rc) && *z ){
      fsl_stmt_t * pStmt = NULL;
      rc = sqlite3_prepare_v2(db->dbh, z, buf.used, &pStmt, &zEnd);
      if( SQLITE_OK != rc ){
        rc = fsl__db_errcode(db, rc);
        break;
      }
      if(pStmt){
        while( SQLITE_ROW == fsl__db_step(db, pStmt) ){}
        rc = sqlite3_finalize(pStmt);
        if(rc) rc = fsl__db_errcode(db, rc);
      }
      buf.used -= (zEnd-z);
      z = zEnd;
    }
    fsl_b_reserve(&buf, 0);
    return rc;
  }
}

int fsl_db_exec_multi( fsl_db * const db, const char * sql, ...){
  if(!db->dbh) return fsl__db_err_not_opened(db);
  else if(!sql || !*sql) return fsl__db_err_sql_empty(db);
  else{
    int rc;
    va_list args;
    va_start(args,sql);
    rc = fsl_db_exec_multiv( db, sql, args );
    va_end(args);
    return rc;
  }
}

int fsl_db_execv( fsl_db * const db, const char * sql, va_list args){
  if(!db->dbh) return fsl__db_err_not_opened(db);
  else if(!sql || !*sql) return fsl__db_err_sql_empty(db);
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(0==rc){
      //while(FSL_RC_STEP_ROW == (rc=fsl_stmt_step(&st))){}
      //^^^ why did we historically do this instead of:
      rc = fsl_stmt_step( &st );
      fsl_stmt_finalize(&st);
    }
    switch(rc){
      case FSL_RC_STEP_DONE:
      case FSL_RC_STEP_ROW: rc = 0; break;
    }
    return rc;
  }
}

int fsl_db_exec( fsl_db * const db, const char * sql, ...){
  if(!db->dbh) return fsl__db_err_not_opened(db);
  else if(!sql || !*sql) return fsl__db_err_sql_empty(db);
  else{
    int rc;
    va_list args;
    va_start(args,sql);
    rc = fsl_db_execv( db, sql, args );
    va_end(args);
    return rc;
  }
}

int fsl_db_changes_recent(fsl_db * const db){
  return db->dbh
    ? sqlite3_changes(db->dbh)
    : 0;
}

int fsl_db_changes_total(fsl_db * const db){
  return db->dbh
    ? sqlite3_total_changes(db->dbh)
    : 0;
}

static int fsl__db_step_sp(fsl_db * const db, sqlite3_stmt *q){
  fsl_flag32_t const oldFlags = db->impl.flags;
  db->impl.flags |= FSL__DB_F_IN_COMMIT;
  int const rc = sqlite3_step(q);
  sqlite3_reset(q);
  db->impl.flags = oldFlags;
  return SQLITE_DONE==rc
    ? 0
    : fsl__db_errcode(db, rc);
}

/**
   The registry of db's connection, if db's context is in one, looked
   up afresh (while a connection closes, SQLite may already have freed
   it, and then returns NULL).
*/
static fsl__cxreg * fsl__db_reg(fsl_db const * const db){
  return (db->dbh && db->impl.share.reg)
    ? sqlite3_get_clientdata(db->dbh, "fsl_cxreg") : NULL;
}

/**
   Records that db's context now owns the innermost savepoint of its
   connection (see fsl__cxreg::sp). Returns 0 or FSL_RC_OOM.
*/
static int fsl__db_sp_push(fsl_db * const db){
  fsl__cxreg * const r = fsl__db_reg(db);
  if( !r ) return 0;
  if( r->nSp==r->capSp ){
    unsigned const cap = r->capSp ? r->capSp * 2 : 8;
    fsl_db ** const a = fsl_realloc(r->sp, cap * sizeof(fsl_db*));
    if( !a ) return FSL_RC_OOM;
    r->sp = a;
    r->capSp = cap;
  }
  r->sp[r->nSp++] = db;
  return 0;
}

/** Undoes fsl__db_sp_push() when db's innermost savepoint ends. */
static void fsl__db_sp_pop(fsl_db * const db){
  fsl__cxreg * const r = fsl__db_reg(db);
  if( r && r->nSp && r->sp[r->nSp-1]==db ) --r->nSp;
}

bool fsl__db_txn_is_innermost(fsl_db const * const db){
  fsl__cxreg const * const r = fsl__db_reg(db);
  return !r || !r->nSp || r->sp[r->nSp-1]==db;
}

void fsl__db_txn_abandon(fsl_db * const db){
  fsl__cxreg * const r = fsl__db_reg(db);
  for( unsigned i = 0; r && i < r->nSp; ){
    if( r->sp[i]==db ){
      memmove(&r->sp[i], &r->sp[i+1], (r->nSp - i - 1) * sizeof(fsl_db*));
      --r->nSp;
    }else ++i;
  }
  db->impl.txn.level = 0;
  db->impl.flags &= ~FSL__DB_F_BUBBLING_ROLLBACK;
}

static int fsl__db_step_rollback(fsl_db * const db){
  int rc = fsl__db_step_sp(db, db->impl.txn.sRollback);
  if( 0==rc ){
    rc = fsl__db_step_sp(db, db->impl.txn.sRelease);
  }
  return rc;
}

int fsl_db_txn_begin(fsl_db * const db){
  if( !db ) return FSL_RC_MISUSE;
  else if( !db->dbh ) return fsl__db_err_not_opened(db);
#if 0
  /* 2025-08-06: this really should have been part of the db's
     behavior all along, and activating it now breaks tests. Currently
     those tests are running through certain APIs with this flag set
     and not triggering errors. That's not _entirely_ wrong because
     this flag means they'll get rolled back anyway, but we shouldn't
     be in those routines when this flag is set in the first place.

     TODO: enable this bit and sort out the carnage (mostly, perhaps
     entirely, in f-sanity.c).
  */
  else if( db->impl.flags & FSL__DB_F_BUBBLING_ROLLBACK ){
    return fsl_error_set(&db->error, FSL_RC_DB,
                         "Cowardly refusing to push a new transaction level "
                         "when a rollback is pending. "
                         "Current transaction level=%d",
                         db->impl.txn.level);
  }
#endif
  else {
    int rc = 0;
    if( !db->impl.txn.sSavepoint ){
      /* Each context sharing a connection gets a savepoint name of
         its own, so that their transactions, which must nest, cannot
         release or roll back each other's. */
      char zSp[32] = "fsl_db";
      if( db->impl.share.id>1 ){
        fsl_snprintf(zSp, sizeof(zSp), "fsl_db_%u", db->impl.share.id);
      }
#define P(MEMBER,FMT)                                         \
      if( 0==rc ) {                                           \
        char * const zSql = fsl_mprintf(FMT, zSp);            \
        rc = zSql ? sqlite3_prepare_v3(db->dbh, zSql, -1,     \
                                SQLITE_PREPARE_PERSISTENT,    \
                                &db->impl.txn.MEMBER, NULL )  \
          : SQLITE_NOMEM;                                     \
        fsl_free(zSql);                                       \
      }
      P(sSavepoint, "SAVEPOINT %s /*" __FILE__ "*/");
      P(sRelease, "RELEASE %s /*" __FILE__ "()*/");
      P(sRollback, "ROLLBACK TO %s /*" __FILE__ "()*/")
#undef P
      if( rc ){
        fsl__db_finalize_sp(db);
        return fsl__db_errcode(db, rc);
      }
    }
    rc = fsl__db_step_sp(db, db->impl.txn.sSavepoint);
    if( 0==rc ){
      fsl_error_reset(&db->error);
      if( db->impl.event.f ){
        rc = fsl__db_fire(db, FSL_DB_EVENT_BEGIN, NULL);
        if( rc ){
          fsl__db_step_rollback(db);
        }
      }
      if( 0==rc ){
        rc = fsl__db_sp_push(db);
        if( rc ) fsl__db_step_rollback(db);
      }
      if( 0==rc ){
        ++db->impl.txn.level;
      }
    }
    return rc;
  }
}

/**
   End the current savepoint level. If keepSavepoint is true, it is
   RELEASEd, else it is ROLLBACKed and RELEASEd. Asserts that
   db->impl.txn.level>0 and adjusts db->impl.txn.level when it's done.
*/
static int fsl__db_txn_sp_end(fsl_db * const db, bool keepSavepoint){
  int rc, rc2;
  fsl_flag32_t const oldFlags = db->impl.flags;
  assert( db->impl.txn.level>0 );
  db->impl.flags |= FSL__DB_F_IN_COMMIT;
  if( keepSavepoint ){
    rc2 = fsl__db_fire(db, FSL_DB_EVENT_COMMIT, NULL);
    if( 0==rc2 ){
      rc = fsl__db_step_sp(db, db->impl.txn.sRelease);
    }else{
      rc = fsl__db_step_rollback(db);
      if( 0==rc ) rc = rc2;
    }
  }else{
    rc2 = fsl__db_fire(db, FSL_DB_EVENT_ROLLING_BACK, NULL);
    rc = fsl__db_step_rollback(db);
    if( !rc ) rc = rc2;
    rc2 = fsl__db_fire(db, FSL_DB_EVENT_ROLLED_BACK, NULL);
    if( !rc ) rc = rc2;
  }
  db->impl.flags = oldFlags;
  fsl__db_sp_pop(db);
  if( 0==--db->impl.txn.level ){
    db->impl.flags &= ~FSL__DB_F_BUBBLING_ROLLBACK;
  }
  return rc;
}

int fsl_db_txn_level(fsl_db * const db){
  return (db->impl.flags & FSL__DB_F_BUBBLING_ROLLBACK)
    ? -db->impl.txn.level : db->impl.txn.level;
}

int fsl_db_txn_commit(fsl_db * const db){
  return db->dbh
    ? fsl_db_txn_end_v2(db, true, false)
    : fsl__db_err_not_opened(db);
}

int fsl_db_txn_rollback(fsl_db * const db){
  return db->dbh
    ? fsl_db_txn_end_v2(db, false, true/*historical behavior*/)
    : fsl__db_err_not_opened(db);
}

#if 0
int fsl_db_rollback_force( fsl_db * const db ){
  if(!db->dbh){
    return fsl__db_err_not_opened(db);
  }else{
    db->impl.flags |= FSL__DB_F_BUBBLING_ROLLBACK;
    while( db->impl.txn.level>0 ){
      fsl__db_txn_sp_end(db, false);
      --db->impl.txn.level;
    }
    db->impl.flags &= ~FSL__DB_F_BUBBLING_ROLLBACK;
    return 0;
  }
}
#endif

int fsl_db_txn_end_v2(fsl_db * const db, bool keepSavepoint,
                      bool bubbleRollback){
  if(!db->dbh){
    return fsl__db_err_not_opened(db);
  }else if (db->impl.txn.level<=0){
    return fsl_error_set(&db->error, FSL_RC_RANGE,
                         "No transaction is active.");
  }else if( !fsl__db_txn_is_innermost(db) ){
    return fsl_error_set(&db->error, FSL_RC_MISUSE,
                         "Another context sharing this connection has "
                         "a transaction inside this one, which must "
                         "end first.");
  }
  if(bubbleRollback){
    db->impl.flags |= FSL__DB_F_BUBBLING_ROLLBACK
      /* ACHTUNG: set before continuing so that if we return due to a
         non-0 txn.level that the rollback flag propagates through
         the transaction's stack. */;
  }
  return fsl__db_txn_sp_end(
    db, db->impl.txn.level>1
    ? keepSavepoint
    : (keepSavepoint &&
       !(db->impl.flags & FSL__DB_F_BUBBLING_ROLLBACK))
  );
}

int fsl_db_get_int32v( fsl_db * const db, int32_t * rv,
                       char const * sql, va_list args){
  /* Potential fixme: the fsl_db_get_XXX() funcs are 95%
     code duplicates. We "could" replace these with a macro
     or supermacro, though the latter would be problematic
     in the context of an amalgamation build.
  */
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    rc = fsl_stmt_step( &st );
    switch(rc){
      case FSL_RC_STEP_ROW:
        *rv = sqlite3_column_int(st.stmt, 0);
        /* Fall through */
      case FSL_RC_STEP_DONE:
        rc = 0;
        break;
      default:
        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_int32( fsl_db * const db, int32_t * rv,
                      char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_int32v(db, rv, sql, args);
  va_end(args);
  return rc;
}

int fsl_db_get_int64v( fsl_db * const db, int64_t * rv,
                       char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    rc = fsl_stmt_step( &st );
    switch(rc){
      case FSL_RC_STEP_ROW:
        *rv = sqlite3_column_int64(st.stmt, 0);
        /* Fall through */
      case FSL_RC_STEP_DONE:
        rc = 0;
        break;
      default:
        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_int64( fsl_db * const db, int64_t * rv,
                      char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_int64v(db, rv, sql, args);
  va_end(args);
  return rc;
}


int fsl_db_get_idv( fsl_db * const db, fsl_id_t * rv,
                       char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    rc = fsl_stmt_step( &st );
    switch(rc){
      case FSL_RC_STEP_ROW:
        *rv = (fsl_id_t)sqlite3_column_int64(st.stmt, 0);
        /* Fall through */
      case FSL_RC_STEP_DONE:
        rc = 0;
        break;
      default:
        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_id( fsl_db * const db, fsl_id_t * rv,
                      char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_idv(db, rv, sql, args);
  va_end(args);
  return rc;
}


int fsl_db_get_sizev( fsl_db * const db, fsl_size_t * rv,
                      char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    rc = fsl_stmt_step( &st );
    switch(rc){
      case FSL_RC_STEP_ROW:{
        sqlite3_int64 const i = sqlite3_column_int64(st.stmt, 0);
        if(i<0){
          rc = fsl_error_set(&db->error, FSL_RC_RANGE,
                             "Expecting a non-negative size but "
                             "the query returned %" PRIi64 ".",
                             (int64_t)i);
          break;
        }
        *rv = (fsl_size_t)i;
        rc = 0;
        break;
      }
      case FSL_RC_STEP_DONE:
        rc = 0;
        break;
      default:
        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_size( fsl_db * const db, fsl_size_t * rv,
                      char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_sizev(db, rv, sql, args);
  va_end(args);
  return rc;
}


int fsl_db_get_doublev( fsl_db * const db, double * rv,
                       char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    rc = fsl_stmt_step( &st );
    switch(rc){
      case FSL_RC_STEP_ROW:
        *rv = sqlite3_column_double(st.stmt, 0);
        /* Fall through */
      case FSL_RC_STEP_DONE:
        rc = 0;
        break;
      default:
        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_double( fsl_db * const db, double * rv,
                      char const * sql,
                      ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_doublev(db, rv, sql, args);
  va_end(args);
  return rc;
}


int fsl_db_get_textv( fsl_db * const db, char ** rv,
                      fsl_size_t *rvLen,
                      char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    rc = fsl_stmt_step( &st );
    switch(rc){
      case FSL_RC_STEP_ROW:{
        char const * str = (char const *)sqlite3_column_text(st.stmt, 0);
        int const len = sqlite3_column_bytes(st.stmt,0);
        if(!str){
          *rv = NULL;
          if(rvLen) *rvLen = 0;
        }else{
          char * x = fsl_strndup(str, len);
          if(!x){
            rc = FSL_RC_OOM;
          }else{
            *rv = x;
            if(rvLen) *rvLen = (fsl_size_t)len;
            rc = 0;
          }
        }
        break;
      }
      case FSL_RC_STEP_DONE:
        *rv = NULL;
        if(rvLen) *rvLen = 0;
        rc = 0;
        break;
      default:
        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_text( fsl_db * const db, char ** rv,
                     fsl_size_t * rvLen,
                     char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_textv(db, rv, rvLen, sql, args);
  va_end(args);
  return rc;
}

int fsl_db_get_blobv( fsl_db * const db, void ** rv,
                      fsl_size_t *rvLen,
                      char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    rc = fsl_stmt_step( &st );
    switch(rc){
      case FSL_RC_STEP_ROW:{
        fsl_b buf = fsl_b_empty;
        void const * str = sqlite3_column_blob(st.stmt, 0);
        int const len = sqlite3_column_bytes(st.stmt,0);
        if(!str){
          *rv = NULL;
          if(rvLen) *rvLen = 0;
        }else{
          rc = fsl_b_append(&buf, str, len);
          if(!rc){
            *rv = buf.mem;
            if(rvLen) *rvLen = buf.used;
          }
        }
        break;
      }
      case FSL_RC_STEP_DONE:
        *rv = NULL;
        if(rvLen) *rvLen = 0;
        rc = 0;
        break;
      default:
        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_blob( fsl_db * const db, void ** rv,
                     fsl_size_t * rvLen,
                     char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_blobv(db, rv, rvLen, sql, args);
  va_end(args);
  return rc;
}

int fsl_db_get_bufferv( fsl_db * const db, fsl_b * const b,
                        bool asBlob, char const * sql,
                        va_list args){
  if(!sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    rc = fsl_stmt_step( &st );
    switch(rc){
      case FSL_RC_STEP_ROW:{
        void const * str = asBlob
          ? sqlite3_column_blob(st.stmt, 0)
          : (void const *)sqlite3_column_text(st.stmt, 0);
        int const len = sqlite3_column_bytes(st.stmt,0);
        if(len && !str){
          rc = FSL_RC_OOM;
        }else{
          rc = 0;
          rc = fsl_b_append( b, str, len );
        }
        break;
      }
      case FSL_RC_STEP_DONE:
        rc = 0;
        break;
      default:
        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_buffer( fsl_db * const db, fsl_b * const b,
                       bool asBlob,
                       char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_bufferv(db, b, asBlob, sql, args);
  va_end(args);
  return rc;
}

int32_t fsl_db_g_int32( fsl_db * const db, int32_t dflt,
                        char const * sql, ... ){
  int32_t rv = dflt;
  va_list args;
  va_start(args,sql);
  fsl_db_get_int32v(db, &rv, sql, args);
  va_end(args);
  return rv;
}

int64_t fsl_db_g_int64( fsl_db * const db, int64_t dflt,
                            char const * sql,
                            ... ){
  int64_t rv = dflt;
  va_list args;
  va_start(args,sql);
  fsl_db_get_int64v(db, &rv, sql, args);
  va_end(args);
  return rv;
}

fsl_id_t fsl_db_g_id( fsl_db * const db, fsl_id_t dflt,
                            char const * sql,
                            ... ){
  fsl_id_t rv = dflt;
  va_list args;
  va_start(args,sql);
  fsl_db_get_idv(db, &rv, sql, args);
  va_end(args);
  return rv;
}

fsl_size_t fsl_db_g_size( fsl_db * const db, fsl_size_t dflt,
                        char const * sql,
                        ... ){
  fsl_size_t rv = dflt;
  va_list args;
  va_start(args,sql);
  fsl_db_get_sizev(db, &rv, sql, args);
  va_end(args);
  return rv;
}

double fsl_db_g_double( fsl_db * const db, double dflt,
                              char const * sql,
                              ... ){
  double rv = dflt;
  va_list args;
  va_start(args,sql);
  fsl_db_get_doublev(db, &rv, sql, args);
  va_end(args);
  return rv;
}

char * fsl_db_g_text( fsl_db * const db, fsl_size_t * len,
                      char const * sql,
                      ... ){
  char * rv = NULL;
  va_list args;
  va_start(args,sql);
  fsl_db_get_textv(db, &rv, len, sql, args);
  va_end(args);
  return rv;
}

void * fsl_db_g_blob( fsl_db * const db, fsl_size_t * len,
                      char const * sql,
                      ... ){
  void * rv = NULL;
  va_list args;
  va_start(args,sql);
  fsl_db_get_blobv(db, &rv, len, sql, args);
  va_end(args);
  return rv;
}

double fsl_db_julian_now(fsl_db * const db){
  double rc = -1.0;
  if(db && db->dbh){
    /* TODO? use cached statement? So far not used often enough to
       justify it. */
    fsl_db_get_double( db, &rc, "SELECT julianday('now')");
  }
  return rc;
}

double fsl_db_string_to_julian(fsl_db * const db, char const * str){
  double rc = -1.0;
  if(db && db->dbh){
    /* TODO? use cached statement? So far not used often enough to
       justify it. */
    fsl_db_get_double( db, &rc, "SELECT julianday(%Q)",str);
  }
  return rc;
}

bool fsl_db_existsv(fsl_db * const db, char const * sql, va_list args ){
  if(!db || !db->dbh || !sql) return 0;
  else if(!*sql) return 0;
  else{
    fsl_stmt st = fsl_stmt_empty;
    bool rv = false;
    if(0==fsl_db_preparev(db, &st, sql, args)){
      rv = FSL_RC_STEP_ROW==fsl_stmt_step(&st) ? true : false;
    }
    fsl_stmt_finalize(&st);
    return rv;
  }

}

bool fsl_db_exists(fsl_db * const db, char const * sql, ... ){
  bool rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_existsv(db, sql, args);
  va_end(args);
  return rc;
}

int fsl_db_exists2v(fsl_db * const db, bool * const rv,
                    char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = fsl_db_preparev(db, &st, sql, args);
    if(rc) return rc;
    rc = fsl_stmt_step(&st);
    switch(rc){
      case FSL_RC_STEP_ROW: *rv = true; rc = 0; break;
      case FSL_RC_STEP_DONE: *rv = false; rc = 0; break;
      default: break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_exists2(fsl_db * const db, bool * const rv,
                   char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_exists2v(db, rv, sql, args);
  va_end(args);
  return rc;
}

bool fsl_db_table_exists(fsl_db * const db,
                        fsl_dbrole_e whichDb,
                        const char *zTable
){
  const char *zDb = fsl__db_schema(db, whichDb);
  fsl_b name = fsl_b_empty;
  int rc = !SQLITE_OK;
  if( db->dbh
      && 0==fsl__db_table_name(db, whichDb, zTable, false, &name) ){
    rc = sqlite3_table_column_metadata(db->dbh, zDb, fsl_b_cstr(&name),
                                       0, 0, 0, 0, 0, 0);
  }
  fsl_b_clear(&name);
  return rc==SQLITE_OK ? true : false;
}

bool fsl_db_table_has_column( fsl_db * const db, char const *zTableName, char const *zColName ){
  fsl_stmt q = fsl_stmt_empty;
  int rc = 0;
  bool rv = 0;
  if(!zTableName || !*zTableName || !zColName || !*zColName) return false;
  rc = fsl_db_prepare(db, &q, "PRAGMA table_info(%Q)", zTableName );
  if(!rc) while(FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
    /* Columns: (cid, name, type, notnull, dflt_value, pk) */
    fsl_size_t colLen = 0;
    char const * zCol = fsl_stmt_g_text(&q, 1, &colLen);
    if(0==fsl_strncmp(zColName, zCol, colLen)
       && 0==zColName[colLen]){
      rv = true;
      break;
    }
  }
  fsl_stmt_finalize(&q);
  return rv;
}

bool fsl__db_table_has_column(fsl_db * const db, fsl_dbrole_e r,
                              char const *zTable, char const *zCol){
  /* As fsl_db_table_has_column(), via PRAGMA table_info, which lists
     only declared columns (sqlite3_table_column_metadata() would also
     accept a table's implicit rowid). */
  fsl_stmt q = fsl_stmt_empty;
  fsl_b name = fsl_b_empty;
  bool rv = false;
  if(!zTable || !*zTable || !zCol || !*zCol) return false;
  if(0==fsl__db_table_name(db, r, zTable, false, &name)
     && 0==fsl_db_prepare(db, &q, "PRAGMA %!Q.table_info(%Q)",
                          fsl__db_schema(db, r), fsl_b_cstr(&name))){
    while(FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
      fsl_size_t n = 0;
      char const * const z = fsl_stmt_g_text(&q, 1, &n);
      if(0==fsl_strncmp(zCol, z, n) && 0==zCol[n]){
        rv = true;
        break;
      }
    }
  }
  fsl_stmt_finalize(&q);
  fsl_b_clear(&name);
  return rv;
}

char * fsl_db_random_hex(fsl_db * const db, fsl_size_t n){
  if(!db->dbh || !n) return NULL;
  else{
    fsl_size_t rvLen = 0;
    char * rv = fsl_db_g_text(db, &rvLen,
                              "SELECT lower(hex("
                              "randomblob(%"FSL_SIZE_T_PFMT")))",
                              (fsl_size_t)(n/2+1));
    if(rv){
      assert(rvLen>=n);
      rv[n]=0;
    }
    return rv;
  }
}


int fsl_db_select_slistv( fsl_db * const db, fsl_list * const tgt,
                          char const * fmt, va_list args ){
  if(!db->dbh) return fsl__db_err_not_opened(db);
  else if(!fmt || !*fmt) return fsl__db_err_sql_empty(db);
  else{
    int rc;
    int stepRc = FSL_RC_STEP_DONE;
    fsl_stmt st = fsl_stmt_empty;
    fsl_size_t nlen;
    char const * n;
    char * cp;
    rc = fsl_db_preparev(db, &st, fmt, args);
    while( !rc && (FSL_RC_STEP_ROW==(stepRc = fsl_stmt_step(&st))) ){
      nlen = 0;
      n = fsl_stmt_g_text(&st, 0, &nlen);
      cp = n ? fsl_strndup(n, (fsl_int_t)nlen) : NULL;
      if(n && !cp) rc = FSL_RC_OOM;
      else{
        rc = fsl_list_append(tgt, cp);
        if(rc && cp) fsl_free(cp);
      }
    }
    if(!rc && FSL_RC_STEP_DONE!=stepRc) rc = stepRc;
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_select_slist( fsl_db * const db, fsl_list * const tgt,
                         char const * fmt, ... ){
  int rc;
  va_list va;
  va_start (va,fmt);
  rc = fsl_db_select_slistv(db, tgt, fmt, va);
  va_end(va);
  return rc;
}

void fsl_db_sqltrace_enable( fsl_db * const db, FILE * outStream, bool expandSql ){
  if(db->dbh){
    db->impl.event.fpTrace = outStream;
    fsl_flag32_t m = db->impl.event.maskIds;
    if( expandSql ){
      m &= ~FSL_DB_EVENT_TRACE_SQL;
      m |= FSL_DB_EVENT_TRACE_SQLX;
    }else{
      m &= ~FSL_DB_EVENT_TRACE_SQLX;
      m |= FSL_DB_EVENT_TRACE_SQL;
    }
    db->impl.event.maskIds = m & FSL_DB_EVENT_mask_id;
    sqlite3_trace_v2(db->dbh, SQLITE_TRACE_STMT,
                     fsl__db_sq3TraceV2, db);
  }
}

int fsl_db_init( fsl_error * err,
                 char const * zFilename,
                 char const * zSchema,
                 ... ){
  fsl_db DB = fsl_db_empty;
  fsl_db * db = &DB;
  char const * zSql;
  int rc;
  char inTrans = 0;
  va_list ap;
  rc = fsl_db_open(db, zFilename, FSL_DB_OPEN_RWC);
  if(rc) goto end;
  rc = fsl_db_exec(db, "BEGIN EXCLUSIVE");
  if(rc) goto end;
  inTrans = 1;
  rc = fsl_db_exec_multi(db, "%s", zSchema);
  if(rc) goto end;
  va_start(ap, zSchema);
  while( !rc && (zSql = va_arg(ap, const char*))!=NULL ){
    rc = fsl_db_exec_multi(db, "%s", zSql);
  }
  va_end(ap);
  end:
  if(rc){
    if(inTrans) fsl_db_exec(db, "ROLLBACK");
  }else{
    rc = fsl_db_exec(db, "COMMIT");
  }
  if(err){
    if(db->error.code){
      fsl_error_propagate(&db->error, err);
    }else if(rc){
      fsl_error_set(err, rc, "Initializing db file [%s] failed: %R",
                    zFilename, rc);
    }
  }
  fsl_db_close(db);
  return rc;
}

int fsl_stmt_each_f_dump( fsl_stmt * const stmt, void * state ){
  int i;
  fsl_cx * const f = (fsl_cx*)state;
  char const * sep = "\t";
  assert( f && "Missing fsl_cx* arg to fsl_stmt_each_f_dump()" );
  if( !f->output.out ) return 0;
  int const colCount = fsl_stmt_col_count(stmt);
  if(1==stmt->rowCount){
    for( i = 0; i < colCount; ++i ){
      fsl_outputf(f, "%s%s", fsl_stmt_col_name(stmt, i),
            (i==colCount-1) ? "" : sep);
    }
    fsl_output(f, "\n", 1);
  }
  for( i = 0; i < colCount; ++i ){
    char const * val = fsl_stmt_g_text(stmt, i, NULL);
    fsl_outputf(f, "%s%s", val ? val : "NULL",
          (i==colCount-1) ? "" : sep);
  }
  fsl_output(f, "\n", 1);
  return 0;
}

void fsl_db_event_listener( fsl_db * const db, fsl_db_event_f f,
                            void * pState, fsl_flag32_t mask ){
  db->impl.event.f = f;
  db->impl.event.state = pState;
  db->impl.event.maskIds = mask & FSL_DB_EVENT_mask_id;
}

bool fsl_db_is_writeable( fsl_db * const db, char const * const zSchema ){
  return db->dbh
    && 0==sqlite3_db_readonly(db->dbh, zSchema ? zSchema : "main");
}

#undef MARKER
#undef fsl__db_err_dump
/* end of file src/db.c */
/* start of file src/deck.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*
  This file houses the manifest/control-artifact-related APIs.
*/
#include <assert.h>
#include <stdlib.h> /* qsort() */
#include <memory.h> /* memcmp() */

/* Only for debugging */
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

enum fsl_card_F_list_flags_e {
FSL__CARD_F_LIST_NEEDS_SORT = 0x01
};

/**
   Transfers the contents of d into f->cache.mcache. If d is
   dynamically allocated then it is also freed. In any case, after
   calling this the caller must behave as if the deck had been passed
   to fsl_deck_finalize() and (if it is unknown whether d is stack
   allocated) also freed.

   If manifest caching is disabled for f, d is immediately finalized.
*/
static void fsl__cx_mcache_insert(fsl_cx * const f, fsl_deck * d){
  if(!(f->flags & FSL_CX_F_MANIFEST_CACHE)){
    fsl_deck_finalize(d);
    return;
  }
  static const unsigned cacheLen =
    (unsigned)(sizeof(fsl__mcache_empty.aAge)
               /sizeof(fsl__mcache_empty.aAge[0]));
  fsl__mcache * const mc = &f->cache.mcache;
  while( d ){
    unsigned i;
    fsl_deck *pBaseline = d->B.baseline;
    d->B.baseline = 0;
    for(i=0; i<cacheLen; ++i){
      if( !mc->decks[i].rid ) break;
    }
    if( i>=cacheLen ){
      unsigned oldest = 0;
      unsigned oldestAge = mc->aAge[0];
      for(i=1; i<cacheLen; ++i){
        if( mc->aAge[i]<oldestAge ){
          oldest = i;
          oldestAge = mc->aAge[i];
        }
      }
      fsl_deck_finalize(&mc->decks[oldest]);
      i = oldest;
    }
    mc->aAge[i] = ++mc->nextAge;
    mc->decks[i] = *d;
    *d = fsl_deck_empty;
    if(&fsl_deck_empty == mc->decks[i].allocStamp){
      /* d was fsl_deck_malloc()'d so we need to free it, but cannot
         send it through fsl_deck_finalize() because that would try to
         clean up the memory we just transferred ownership of to
         mc->decks[i]. So... */
      mc->decks[i].allocStamp = NULL;
      fsl_free(d);
    }
    d = pBaseline;
  }
}

/**
   Searches f->cache.mcache for a deck with the given RID. If found,
   it is bitwise copied over tgt, that entry is removed from the
   cache, and true is returned. If no match is found, tgt is not
   modified and false is returned.

   If manifest caching is disabled for f, false is immediately
   returned without causing side effects beyond adjustment of caching
   metrics.
*/
static bool fsl__cx_mcache_search(fsl_cx * const f, fsl_id_t rid,
                                 fsl_deck * const tgt){
  if(!(f->flags & FSL_CX_F_MANIFEST_CACHE)){
    ++f->cache.mcache.misses;
    return false;
  }
  static const unsigned cacheLen =
    (int)(sizeof(fsl__mcache_empty.aAge)
          /sizeof(fsl__mcache_empty.aAge[0]));
  unsigned i;
  assert(cacheLen ==
         (unsigned)(sizeof(fsl__mcache_empty.decks)
                    /sizeof(fsl__mcache_empty.decks[0])));
  for(i=0; i<cacheLen; ++i){
    if( f->cache.mcache.decks[i].rid==rid ){
      *tgt = f->cache.mcache.decks[i];
      f->cache.mcache.decks[i] = fsl_deck_empty;
      ++f->cache.mcache.hits;
      return true;
    }
  }
  ++f->cache.mcache.misses;
  return false;
}

/**
   Code duplication reducer for fsl_deck_parse2() and
   fsl_deck_load_rid(). Checks fsl__cx_mcache_search() for rid.  If
   found, overwrites tgt with its contents and returns true.  If not
   found, returns false. If an entry is found and type!=FSL_SATYPE_ANY
   and the found deck->type differs from the 4th argument (type) then
   false is returned, FSL_RC_TYPE is returned via *rc, and f's error
   state is updated with a description of the problem. In all other
   case *rc is set to 0.
*/
static bool fsl__cx_mcache_search2(fsl_cx * const f, fsl_id_t rid,
                                  fsl_deck * const tgt,
                                  fsl_satype_e type,
                                  int * const rc){
  *rc = 0;
  if(fsl__cx_mcache_search(f, rid, tgt)){
    assert(f == tgt->f);
    if(type!=FSL_SATYPE_ANY && type!=tgt->type){
      *rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                           "RID %" FSL_ID_T_PFMT " is of type %s, "
                           "but the caller requested type %s.",
                           rid, fsl_satype_cstr(tgt->type),
                           fsl_satype_cstr(type));
      fsl__cx_mcache_insert(f, tgt);
      assert(!tgt->f);
      return false;
    }else{
      //MARKER(("Got cached deck: rid=%d\n", (int)d->rid));
      return true;
    }
  }
  return false;
}


/**
   If mem is NULL or inside d->content.mem then this function does
   nothing, else it passes mem to fsl_free(). Intended to be used to
   clean up d->XXX string members (or sub-members) which have been
   optimized away via d->content.
*/
static void fsl_deck_free_string(fsl_deck * d, char * mem){
  assert(d);
  if(mem
     && (!d->content.used
         || !(((unsigned char const *)mem >=d->content.mem)
              &&
              ((unsigned char const *)mem < (d->content.mem+d->content.capacity)))
         )){
    fsl_free(mem);
  }/* else do nothing - the memory is NULL or owned by d->content. */
}

/**
   fsl_list_visitor_f() impl which frees fsl_list-of-(char*) card entries
   in ((fsl_deck*)visitorState).
*/
static int fsl_list_v_card_string_free(void * mCard, void * visitorState ){
  fsl_deck_free_string( (fsl_deck*)visitorState, mCard );
  return 0;
}

/** Evals to a pointer to the F-card at the given index
    in the given fsl_card_F_list pointer. Each arg is
    evaluated only once. */
#define F_at(LISTP,NDX) (&(LISTP)->list[NDX])

static int fsl_card_F_list_reserve2( fsl_card_F_list * li ){
  return (li->used<li->capacity)
    ? 0
    : fsl_card_F_list_reserve(li, li->capacity
                               ? li->capacity*4/3+1
                               : 50);
}

static void fsl_card_F_clean( fsl_card_F * f ){
  if(!f->deckOwnsStrings){
    fsl_free(f->name);
    fsl_free(f->uuid);
    fsl_free(f->priorName);
  }
  *f = fsl_card_F_empty;
}

/**
   Cleans up the F-card at li->list[ndx] and shifts all F-cards to its
   right one entry to the left.
*/
static void fsl_card_F_list_remove(fsl_card_F_list * li,
                                   uint32_t ndx){
  uint32_t i;
  assert(li->used);
  assert(ndx<li->used);
  fsl_card_F_clean(F_at(li,ndx));
  for( i = ndx; i < li->used - 1; ++i ){
    li->list[i] = li->list[i+1];
  }
  li->list[--li->used] = fsl_card_F_empty;
}

void fsl_card_F_list_finalize( fsl_card_F_list * li ){
  uint32_t i;
  for(i=0; i < li->used; ++i){
    fsl_card_F_clean(F_at(li,i));
  }
  li->used = li->capacity = 0;
  fsl_free(li->list);
  *li = fsl_card_F_list_empty;
}

int fsl_card_F_list_reserve( fsl_card_F_list * li, uint32_t n ){
  if(n==0){
    fsl_card_F_list_finalize(li);
    return 0;
  }else if(li->capacity>=n){
    return 0;
  }else{
    fsl_card_F * re = fsl_realloc(li->list,
                                  (fsl_size_t)n * sizeof(fsl_card_F));
    if(re){
      li->list = re;
      li->capacity = n;
    }
    return re ? 0 : FSL_RC_OOM;
  }
}

/**
   Adjusts the end of the give list by +1, reserving more space if
   needed, and returns the next available F-card in a cleanly-wiped
   state. Returns NULL on alloc error.
*/
static fsl_card_F * fsl_card_F_list_push( fsl_card_F_list * li ){
  if(li->used==li->capacity && fsl_card_F_list_reserve2(li)) return NULL;
  li->list[li->used] = fsl_card_F_empty;
  if(li->used){
    li->flags |= FSL__CARD_F_LIST_NEEDS_SORT/*pessimistic assumption*/;
  }
  return &li->list[li->used++];
}
/**
   Chops the last entry off of the given list, freeing any resources
   owned by that entry. Decrements li->used. Asserts that li->used is
   positive.
*/
static void fsl_card_F_list_pop( fsl_card_F_list * li ){
  assert(li->used);
  if(li->used) fsl_card_F_clean(F_at(li, --li->used));
}

fsl_card_Q * fsl_card_Q_malloc(fsl_cherrypick_type_e type,
                               fsl_uuid_cstr target,
                               fsl_uuid_cstr baseline){
  int const targetLen = target ? fsl_is_uuid(target) : 0;
  int const baselineLen = baseline ? fsl_is_uuid(baseline) : 0;
  if((type!=FSL_CHERRYPICK_ADD && type!=FSL_CHERRYPICK_BACKOUT)
     || !target || !targetLen
     || (baseline && !baselineLen)) return NULL;
  else{
    fsl_card_Q * c =
      (fsl_card_Q*)fsl_malloc(sizeof(fsl_card_Q));
    if(c){
      int rc = 0;
      *c = fsl_card_Q_empty;
      c->type = type;
      c->target = fsl_strndup(target, targetLen);
      if(!c->target) rc = FSL_RC_OOM;
      else if(baseline){
        c->baseline = fsl_strndup(baseline, baselineLen);
        if(!c->baseline) rc = FSL_RC_OOM;
      }
      if(rc){
        fsl_card_Q_free(c);
        c = NULL;
      }
    }
    return c;
  }
}

void fsl_card_Q_free( fsl_card_Q * cp ){
  if(cp){
    fsl_free(cp->target);
    fsl_free(cp->baseline);
    *cp = fsl_card_Q_empty;
    fsl_free(cp);
  }
}

fsl_card_J * fsl_card_J_malloc(bool isAppend,
                               char const * field,
                               char const * value){
  if(!field || !*field) return NULL;
  else{
    fsl_card_J * c =
      (fsl_card_J*)fsl_malloc(sizeof(fsl_card_J));
    if(c){
      int rc = 0;
      fsl_size_t const lF = fsl_strlen(field);
      fsl_size_t const lV = value ? fsl_strlen(value) : 0;
      *c = fsl_card_J_empty;
      c->append = isAppend ? 1 : 0;
      c->field = fsl_strndup(field, (fsl_int_t)lF);
      if(!c->field) rc = FSL_RC_OOM;
      else if(value && *value){
        c->value = fsl_strndup(value, (fsl_int_t)lV);
        if(!c->value) rc = FSL_RC_OOM;
      }
      if(rc){
        fsl_card_J_free(c);
        c = NULL;
      }
    }
    return c;
  }
}

void fsl_card_J_free( fsl_card_J * cp ){
  if(cp){
    fsl_free(cp->field);
    fsl_free(cp->value);
    *cp = fsl_card_J_empty;
    fsl_free(cp);
  }
}

/**
    fsl_list_visitor_f() impl which requires that obj be-a (fsl_card_T*),
    which this function passes to fsl_card_T_free().
*/
static int fsl_list_v_card_T_free(void * obj,
                                  void * visitorState fsl__unused){
  if(obj) fsl_card_T_free( (fsl_card_T*)obj );
  (void)visitorState;
  return 0;
}

static int fsl_list_v_card_Q_free(void * obj,
                                  void * visitorState fsl__unused){
  if(obj) fsl_card_Q_free( (fsl_card_Q*)obj );
  (void)visitorState;
  return 0;
}

static int fsl_list_v_card_J_free(void * obj,
                                  void * visitorState fsl__unused){
  if(obj) fsl_card_J_free( (fsl_card_J*)obj );
  (void)visitorState;
  return 0;
}

fsl_deck * fsl_deck_malloc(void){
  fsl_deck * rc = (fsl_deck *)fsl_malloc(sizeof(fsl_deck));
  if(rc){
    *rc = fsl_deck_empty;
    rc->allocStamp = &fsl_deck_empty;
  }
  return rc;
}

void fsl_deck_init( fsl_cx * const f, fsl_deck * const cards, fsl_satype_e type ){
  void const * allocStamp = cards->allocStamp;
  *cards = fsl_deck_empty;
  cards->allocStamp = allocStamp;
  cards->f = f;
  cards->type = type;
}

void fsl__card_J_list_free(fsl_list * li, bool alsoListMem){
  if(li->used) fsl_list_visit(li, 0, fsl_list_v_card_J_free, NULL);
  if(alsoListMem) fsl_list_reserve(li, 0);
  else li->used = 0;
}

/* fsl_deck cleanup helpers... */
#define SFREE(X) fsl_deck_clean_string(m, &m->X)
#define SLIST(X) fsl_list_clear(&m->X, fsl_list_v_card_string_free, m)
#define CBUF(X) fsl_b_clear(&m->X)
static void fsl_deck_clean_string(fsl_deck *m, char **member){
  fsl_deck_free_string(m, *member);
  *member = 0;
}
static void fsl_deck_clean_version(fsl_deck *const m){
  m->rid = 0;
}
static void fsl_deck_clean_A(fsl_deck *const m){
  SFREE(A.name);
  SFREE(A.tgt);
  SFREE(A.src);
}
static void fsl_deck_clean_B(fsl_deck * const m){
  if(m->B.baseline){
    /* The baseline may itself be a delta manifest (see
       fsl__deck_baseline_load()), so it may have a B-card. */
    fsl_deck_finalize(m->B.baseline);
    m->B.baseline = NULL;
  }
  SFREE(B.uuid);
}
static void fsl_deck_clean_C(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->C);
}
static void fsl_deck_clean_E(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->E.uuid);
  m->E = fsl_deck_empty.E;
}
static void fsl_deck_clean_F(fsl_deck * const m){
  if(m->F.list){
    fsl_card_F_list_finalize(&m->F);
    m->F = fsl_deck_empty.F;
  }
}
static void fsl_deck_clean_G(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->G);
}
static void fsl_deck_clean_H(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->H);
}
static void fsl_deck_clean_I(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->I);
}
static void fsl_deck_clean_J(fsl_deck * const m){
  fsl__card_J_list_free(&m->J, true);
}
static void fsl_deck_clean_K(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->K);
}
static void fsl_deck_clean_L(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->L);
}
static void fsl_deck_clean_M(fsl_deck * const m){
  SLIST(M);
}
static void fsl_deck_clean_N(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->N);
}
static void fsl_deck_clean_P(fsl_deck * const m){
  fsl_list_clear(&m->P, fsl_list_v_card_string_free, m);
}
static void fsl_deck_clean_Q(fsl_deck * const m){
  fsl_list_clear(&m->Q, fsl_list_v_card_Q_free, NULL);
}
static void fsl_deck_clean_R(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->R);
}
static void fsl_deck_clean_T(fsl_deck * const m){
  fsl_list_clear(&m->T, fsl_list_v_card_T_free, NULL);
}
static void fsl_deck_clean_U(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->U);
}
static void fsl_deck_clean_W(fsl_deck * const m){
  if(m->W.capacity/*dynamically-allocated buffer*/){
    CBUF(W);
  }else{/*empty or external buffer pointing into to m->content.mem*/
    m->W = fsl_b_empty;
  }
}

void fsl_deck_clean2(fsl_deck * const m, fsl_b * const xferBuf){
  if(!m) return;
  fsl_deck_clean_version(m);
  fsl_deck_clean_A(m);
  fsl_deck_clean_B(m);
  fsl_deck_clean_C(m);
  m->D = 0.0;
  fsl_deck_clean_E(m);
  fsl_deck_clean_F(m);
  fsl_deck_clean_G(m);
  fsl_deck_clean_H(m);
  fsl_deck_clean_I(m);
  fsl_deck_clean_J(m);
  fsl_deck_clean_K(m);
  fsl_deck_clean_L(m);
  fsl_deck_clean_M(m);
  fsl_deck_clean_N(m);
  fsl_deck_clean_P(m);
  fsl_deck_clean_Q(m);
  fsl_deck_clean_R(m);
  fsl_deck_clean_T(m);
  fsl_deck_clean_U(m);
  fsl_deck_clean_W(m);
  if(xferBuf){
    fsl_b_swap(&m->content, xferBuf);
    fsl_b_reuse(xferBuf);
  }
  CBUF(content)/* content must be after all cards because some point
                  back into it and we need this memory intact in order
                  to know that. */;
  {
    void const * const allocStampKludge = m->allocStamp;
    fsl_cx * const f = m->f;
    *m = fsl_deck_empty;
    m->allocStamp = allocStampKludge;
    m->f = f;
  }
}
#undef CBUF
#undef SFREE
#undef SLIST

void fsl_deck_clean(fsl_deck * const m){
  fsl_deck_clean2(m, NULL);
}

void fsl_deck_finalize(fsl_deck * const m){
  void const * allocStamp;
  if(!m) return;
  allocStamp = m->allocStamp;
  fsl_deck_clean(m);
  if(allocStamp == &fsl_deck_empty){
    fsl_free(m);
  }else{
    m->allocStamp = allocStamp;
  }
}

int fsl_card_is_legal( fsl_satype_e t, char card ){
  /*
    Implements this table:

    https://fossil-scm.org/index.html/doc/trunk/www/fileformat.wiki#summary
  */
  if('Z'==card) return 1;
  else switch(t){
    case FSL_SATYPE_ANY:
      switch(card){
        case 'A': case 'B': case 'C': case 'D':
        case 'E': case 'F': case 'J': case 'K':
        case 'L': case 'M': case 'N': case 'P':
        case 'Q': case 'R': case 'T': case 'U':
        case 'W':
          return -1;
        default:
          return 0;
      }
    case FSL_SATYPE_ATTACHMENT:
      switch(card){
        case 'A': case 'D':
          return 1;
        case 'C': case 'N': case 'U':
          return -1;
        default:
          return 0;
      };
    case FSL_SATYPE_CLUSTER:
      return 'M'==card ? 1 : 0;
    case FSL_SATYPE_CONTROL:
      switch(card){
        case 'D': case 'T': case 'U':
          return 1;
        default:
          return 0;
      };
    case FSL_SATYPE_TECHNOTE:
      switch(card){
        case 'D': case 'E':
        case 'W':
          return 1;
        case 'C': case 'N':
        case 'P': case 'T':
        case 'U':
          return -1;
        default:
          return 0;
      };
    case FSL_SATYPE_CHECKIN:
      switch(card){
        case 'C': case 'D':
        case 'U':
          return 1;
        case 'B': case 'F':
        case 'N': case 'P':
        case 'Q': case 'R':
        case 'T':
          return -1;
        default:
          return 0;
      };
    case FSL_SATYPE_TICKET:
      switch(card){
        case 'D': case 'J':
        case 'K': case 'U':
          return 1;
        default:
          return 0;
      };
    case FSL_SATYPE_WIKI:
      switch(card){
        case 'D': case 'L':
        case 'U': case 'W':
          return 1;
        case 'C':
        case 'N': case 'P':
          return -1;
        default:
          return 0;
      };
    case FSL_SATYPE_FORUMPOST:
      switch(card){
        case 'D': case 'U': case 'W':
          return 1;
        case 'G': case 'H': case 'I':
        case 'N': case 'P':
          return -1;
        default:
          return 0;
      };
    default:
      MARKER(("invalid fsl_satype_e value: %d, card=%c\n", t, card));
      assert(!"Invalid fsl_satype_e.");
      return 0;
  };
}

bool fsl_deck_has_required_cards( fsl_deck const * d ){
  if(!d) return false;
  switch(d->type){
    case FSL_SATYPE_ANY:
      fsl_cx_err_set(d->f, FSL_RC_SYNTAX,
                     "Artifact type ANY has no required cards: "
                     "the deck's type must be set first.");
      return false;
#define NEED(CARD,COND) \
      if(!(COND)) {                                         \
        fsl_cx_err_set(d->f, FSL_RC_SYNTAX,                 \
                       "%s artifact: required %c-card is "        \
                       "missing or invalid.",                     \
                       fsl_satype_cstr(d->type), *#CARD);         \
        return false;                                             \
      } (void)0
    case FSL_SATYPE_ATTACHMENT:
      NEED(A,d->A.name);
      NEED(A,d->A.tgt);
      NEED(D,d->D > 0);
      return true;
    case FSL_SATYPE_CLUSTER:
      NEED(M,d->M.used);
      return true;
    case FSL_SATYPE_CONTROL:
      NEED(D,d->D > 0);
      NEED(U,d->U);
      NEED(T,d->T.used>0);
      return true;
    case FSL_SATYPE_EVENT:
      NEED(D,d->D > 0);
      NEED(E,d->E.julian>0);
      NEED(E,d->E.uuid);
      /*may be empty: NEED(W,d->W.used);*/
      return true;
    case FSL_SATYPE_CHECKIN:
      /*
        Historically we need both or neither of F- and R-cards, but
        the R-card has become optional because it's so expensive to
        calculate and verify.

        Manifest #1 has an empty file list and an R-card with a
        constant (repo/manifest-independent) hash
        (d41d8cd98f00b204e9800998ecf8427e, the initial MD5 hash
        state).

        R-card calculation is runtime-configurable option.
      */
      NEED(D,d->D > 0);
      NEED(C,d->C);
      NEED(U,d->U);
#if 0
      /* It turns out that because the R-card is optional,
         we can have a legal manifest with no F-cards. */
      NEED(F,d->F.used || d->R/*with initial-state md5 hash!*/);
#endif
      if(!d->R
         && (FSL_CX_F_CALC_R_CARD & d->f->flags)){
        fsl_cx_err_set(d->f, FSL_RC_SYNTAX,
                       "%s deck is missing an R-card, "
                       "yet R-card calculation is enabled.",
                       fsl_satype_cstr(d->type));
        return false;
      }
#if 0
      /* Is this a valid check or overzealous? It's currently breaking
         clone testing. Possibly rightfully so, but that's as-yet
         undetermined. fossil(1) does not do this check. */
      else if(d->R
               && !d->F.used
               && 0!=fsl_strcmp(d->R, FSL_MD5_INITIAL_HASH)
               ){
        fsl_cx_err_set(d->f, FSL_RC_SYNTAX,
                       "Deck has no F-cards, so we expect its "
                       "R-card is to have the initial-state MD5 "
                       "hash (%.12s...). Instead we got: %s",
                       FSL_MD5_INITIAL_HASH, d->R);
        return false;
      }
#endif
      return true;
    case FSL_SATYPE_TICKET:
      NEED(D,d->D > 0);
      NEED(K,d->K);
      NEED(U,d->U);
      NEED(J,d->J.used)
        /* Is a J strictly required?  Spec is not clear but DRH
           confirms the current fossil(1) code expects a J card. */;
      return true;
    case FSL_SATYPE_WIKI:
      NEED(D,d->D > 0);
      NEED(L,d->L);
      NEED(U,d->U);
      /*may be empty: NEED(W,d->W.used);*/
      return true;
    case FSL_SATYPE_FORUMPOST:
      NEED(D,d->D > 0);
      NEED(U,d->U);
      /*may be empty: NEED(W,d->W.used);*/
      return true;
    case FSL_SATYPE_INVALID:
    default:
      assert(!"Invalid fsl_satype_e.");
      return false;
  }
#undef NEED
}

char const * fsl_satype_cstr(fsl_satype_e t){
again:
  switch(t){

#define C(X,V) case X: return &#X[11];
    fsl_satype_e_map(C)
#undef C

#define C(T1,T2) case T1: t=T2; goto again
    C(FSL_SATYPE_BRANCH_START, FSL_SATYPE_CHECKIN);
    //C(FSL_SATYPE_EVENT, FSL_SATYPE_TECHNOTE);
#undef C

    default:
      assert(!"UNHANDLED fsl_satype_e");
      return "!UNKNOWN!";
  }
}

char const * fsl_satype_event_cstr(fsl_satype_e t){
  switch(t){
    case FSL_SATYPE_ANY: return "*";
    case FSL_SATYPE_BRANCH_START:
    case FSL_SATYPE_CHECKIN: return "ci";
    case FSL_SATYPE_EVENT: return "e";
    case FSL_SATYPE_CONTROL: return "g";
    case FSL_SATYPE_TICKET: return "t";
    case FSL_SATYPE_WIKI: return "w";
    case FSL_SATYPE_FORUMPOST: return "f";
    default:
      return NULL;
  }
}


/**
    If fsl_card_is_legal(d->type, card), returns true, else updates
    d->f->error with a description of the constraint violation and
    returns 0.
 */
static bool fsl_deck_check_type( fsl_deck * const d, char card ){
  if(fsl_card_is_legal(d->type, card)) return true;
  else{
    fsl_cx_err_set(d->f, FSL_RC_TYPE,
                   "Card type '%c' is not allowed "
                   "in artifacts of type %s.",
                   card, fsl_satype_cstr(d->type));
    return false;
  }
}

/**
   If the first n bytes of the given string contain any values <=32,
   returns FSL_RC_SYNTAX, else returns 0. mf->f's error state is
   updated no error. n<0 means to use fsl_strlen() to count the
   length.
*/
static int fsl_deck_strcheck_ctrl_chars(fsl_deck * const mf, char cardName, char const * v, fsl_int_t n){
  const char * z = v;
  int rc = 0;
  if(v && n<0) n = fsl_strlen(v);
  for( ; v && z < v+n; ++z ){
    if((unsigned char)*z <= 32){
      rc = fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Invalid character (0x%02x) at byte %d "
                          "of %c-card.", (unsigned)(unsigned char)*z,
                          (int)(z - v), cardName);
      break;
    }
  }
  return rc;
}

/*
  Implements fsl_deck_LETTER_set() for certain letters: those
  implemented as a fsl_uuid_str or an md5, holding a single hex string
  value.

  The function returns FSL_RC_SYNTAX if
  (valLen!=ASSERTLEN). ASSERTLEN is assumed to be either an SHA1,
  SHA3, or MD5 hash value and it is validated against
  fsl_validate16(value,valLen), returning FSL_RC_SYNTAX if that
  check fails. In debug builds, the expected ranges are assert()ed.

  If value is NULL then it is removed from the card instead
  (semantically freed), *mfMember is set to NULL, and 0 is returned.
*/
static int fsl_deck_sethex_impl( fsl_deck * const mf, fsl_uuid_cstr value,
                                 char letter,
                                 fsl_size_t assertLen,
                                 char ** mfMember ){
  assert(mf);
  assert( value ? (assertLen==FSL_STRLEN_SHA1
                   || assertLen==FSL_STRLEN_K256
                   || assertLen==FSL_STRLEN_MD5)
          : 0==assertLen );
  if(value && !fsl_deck_check_type(mf,letter)) return mf->f->error.code;
  else if(!value){
    fsl_deck_free_string(mf, *mfMember);
    *mfMember = NULL;
    return 0;
  }else if(fsl_strlen(value) != assertLen){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Invalid length for %c-card: expecting %d "
                          "hex digits: %s",
                          letter, (int)assertLen, value);
  }else if(!fsl_validate16(value, assertLen)) {
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Invalid hexadecimal value for %c-card: %s",
                          letter, value);
  }else{
    fsl_deck_free_string(mf, *mfMember);
    *mfMember = fsl_strndup(value, assertLen);
    return *mfMember ? 0 : FSL_RC_OOM;
  }
}

/**
    Implements fsl_set_set_XXX() where XXX is a fsl_b member of fsl_deck.
 */
static int fsl_deck_b_setuffer_impl( fsl_deck * const mf, char const * value,
                                     fsl_int_t valLen,
                                     char letter, fsl_b * buf){
  assert(mf);
  if(!fsl_deck_check_type(mf,letter)) return mf->f->error.code;
  else if(valLen<0) valLen = (fsl_int_t)fsl_strlen(value);
  buf->used = 0;
  if(value && (valLen>0)){
    return fsl_b_append( buf, value, valLen );
  }else{
    if(buf->mem) buf->mem[0] = 0;
    return 0;
  }
}

int fsl_deck_B_set( fsl_deck * const mf, fsl_uuid_cstr uuidBaseline){
  if(!mf) return FSL_RC_MISUSE;
  else{
    int const bLen = uuidBaseline ? fsl_is_uuid(uuidBaseline) : 0;
    if(uuidBaseline && !bLen){
      return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                            "Invalid B-card value: %s", uuidBaseline);
    }
    if(mf->B.baseline){
      fsl_deck_finalize(mf->B.baseline);
      mf->B.baseline = NULL;
    }
    return fsl_deck_sethex_impl(mf, uuidBaseline, 'B',
                                bLen, &mf->B.uuid);
  }
}

/**
    Internal impl for card setters which consist of a simple (char *)
    member. Replaces and frees any prior value. Passing NULL for the
    4th argument unsets the given card (assigns NULL to it).
 */
static int fsl_deck_set_string( fsl_deck * const mf, char letter, char ** member, char const * v, fsl_int_t n ){
  if(!fsl_deck_check_type(mf, letter)) return mf->f->error.code;
  fsl_deck_free_string(mf, *member);
  *member = v ? fsl_strndup(v, n) : NULL;
  if(v && !*member) return FSL_RC_OOM;
  else return 0;
}

int fsl_deck_C_set( fsl_deck * const mf, char const * v, fsl_strlen_t n){
  return fsl_deck_set_string( mf, 'C', &mf->C, v, n );
}

int fsl_deck_G_set( fsl_deck * const mf, fsl_uuid_cstr uuid){
  int const uLen = fsl_is_uuid(uuid);
  return uLen
    ? fsl_deck_sethex_impl(mf, uuid, 'G', uLen, &mf->G)
    : fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                     "Invalid hash on G-card: %s", uuid);
}

int fsl_deck_H_set( fsl_deck * const mf, char const * v, fsl_int_t n){
  if(v && mf->I){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Cannot have I-card and H-card in a "
                          "forum post: the I-card is already set.");
  }
  return fsl_deck_set_string( mf, 'H', &mf->H, v, n );
}

int fsl_deck_I_set( fsl_deck * const mf, fsl_uuid_cstr uuid){
  if(uuid && mf->H){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Cannot have I-card and H-card in a "
                          "forum post: the H-card is already set.");
  }
  int const uLen = uuid ? fsl_is_uuid(uuid) : 0;
  if(uuid && !uLen){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Invalid hash on I-card: %s", uuid);
  }
  return fsl_deck_sethex_impl(mf, uuid, 'I', uLen, &mf->I);
}

int fsl_deck_J_add( fsl_deck * const mf, bool isAppend,
                    char const * field, char const * value){
  if(!field) return FSL_RC_MISUSE;
  else if(!*field){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Name missing from J-card.");
  }
  else if(!fsl_deck_check_type(mf,'J')) return mf->f->error.code;
  else{
    int rc;
    fsl_card_J * cp = fsl_card_J_malloc(isAppend, field, value);
    if(!cp) rc = FSL_RC_OOM;
    else if( 0 != (rc = fsl_list_append(&mf->J, cp))){
      fsl_card_J_free(cp);
    }
    return rc;
  }
}


int fsl_deck_K_set( fsl_deck * const mf, fsl_uuid_cstr uuid){
  if(uuid){
    int const uLen = fsl_is_uuid(uuid);
    if(uLen && FSL_STRLEN_SHA1!=uLen){
      /* draft-fossil-artifact-format-00 (zit 477fc5f186) section
         4.7.9: the ticket ID is always 40 hex digits. */
      return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                            "K-card UUID is the wrong size (%d, "
                            "expecting %d): %s", uLen,
                            (int)FSL_STRLEN_SHA1, uuid);
    }
    return uLen
      ? fsl_deck_sethex_impl(mf, uuid, 'K', uLen, &mf->K)
      : fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                       "Invalid K-card UUID: %s", uuid);
  }else{
    char buf[FSL_STRLEN_SHA1+1];
    unsigned char rnd[FSL_STRLEN_SHA1/2];
    fsl_randomness(FSL_STRLEN_SHA1/2, rnd);
    fsl_sha1_digest_to_base16(rnd, buf);
    return fsl_deck_sethex_impl(mf, buf, 'K', FSL_STRLEN_SHA1, &mf->K);
  }
}

int fsl_deck_L_set( fsl_deck * const mf, char const * v, fsl_int_t n){
  if(!mf) return FSL_RC_MISUSE;
  if(v && !fsl_wiki_name_is_wellformed(v, n)){
    return mf->f
      ? fsl_cx_err_set(mf->f, FSL_RC_RANGE,
                       "Invalid L-card wiki page name: it must be 1 to 100 "
                       "bytes long, with no byte below 0x20, no leading "
                       "or trailing space and no two spaces in a row.")
      : FSL_RC_RANGE;
  }
  return fsl_deck_set_string(mf, 'L', &mf->L, v, n);
}

int fsl_deck_M_add( fsl_deck * const mf, char const *uuid){
  int rc;
  char * dupe;
  int const uLen = uuid ? fsl_is_uuid(uuid) : 0;
  if(!uuid) return FSL_RC_MISUSE;
  else if(!fsl_deck_check_type(mf, 'M')) return mf->f->error.code;
  else if(!uLen){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Invalid hash on M-card: %s", uuid);
  }
  dupe = fsl_strndup(uuid, uLen);
  if(!dupe) rc = FSL_RC_OOM;
  else{
    rc = fsl_list_append( &mf->M, dupe );
    if(rc){
      fsl_free(dupe);
    }
  }
  return rc;
}

int fsl_deck_N_set( fsl_deck * const mf, char const * v, fsl_int_t n){
  int rc = 0;
  if(v && n!=0){
    if(n<0) n = fsl_strlen(v);
    rc = fsl_deck_strcheck_ctrl_chars(mf, 'N', v, n);
  }
  return rc ? rc : fsl_deck_set_string( mf, 'N', &mf->N, v, n );
}


/**
   Adds either parentUuid or takeParentUuid to mf->P. ONE
   of those must e non-NULL and the other must be NULL. If
   takeParentUuid is not NULL then ownership of it is transfered
   to this function regardless of success or failure.
*/
static int fsl__deck_P_add_impl( fsl_deck * const mf,
                                 fsl_uuid_cstr parentUuid,
                                 fsl_uuid_str takeParentUuid){
  if(!fsl_deck_check_type(mf, 'P')){
    fsl_free(takeParentUuid);
    return mf->f->error.code;
  }
  int rc;
  char * dupe;
  fsl_uuid_cstr z = parentUuid ? parentUuid : takeParentUuid;
  assert(parentUuid ? !takeParentUuid : !!takeParentUuid);
  int const uLen = fsl_is_uuid(z);
  if(!uLen){
    rc = fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                        "Invalid hash on P-card: %s", z);
    fsl_free(takeParentUuid);
    return rc;
  }
  dupe = takeParentUuid
    ? takeParentUuid
    : fsl_strndup(parentUuid, uLen);
  if(!dupe) rc = FSL_RC_OOM;
  else{
    rc = fsl_list_append( &mf->P, dupe );
    if(rc){
      fsl_free(dupe);
    }
  }
  return rc;
}


int fsl_deck_P_add(fsl_deck * const mf, char const *parentUuid){
  return fsl__deck_P_add_impl(mf, parentUuid, NULL);
}

int fsl_deck_P_add_rid( fsl_deck * const mf, fsl_id_t rid ){
  fsl_uuid_str pU = fsl_rid_to_uuid(mf->f, rid);
  return pU ? fsl__deck_P_add_impl(mf, NULL, pU) : mf->f->error.code;
}


fsl_id_t fsl_deck_P_get_id(fsl_deck * const d, int index){
  if(!d->f) return -1;
  else if(index<0 || index>=(int)d->P.used) return 0;
  else return fsl_uuid_to_rid(d->f, (char const *)d->P.list[index]);
}


int fsl_deck_Q_add( fsl_deck * const mf, int type,
                    fsl_uuid_cstr target,
                    fsl_uuid_cstr baseline ){
  if(!target) return FSL_RC_MISUSE;
  else if(!fsl_deck_check_type(mf,'Q')) return mf->f->error.code;
  else if(!type){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Q-card type must be positive (cherry-pick) "
                          "or negative (backout), not 0: %s", target);
  }else if(!fsl_is_uuid(target)){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Invalid hash on Q-card: %s", target);
  }else if(baseline && !fsl_is_uuid(baseline)){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Invalid second hash on Q-card: %s", baseline);
  }else{
    int rc;
    fsl_card_Q * cp = fsl_card_Q_malloc(type, target, baseline);
    if(!cp) rc = FSL_RC_OOM;
    else if( 0 != (rc = fsl_list_append(&mf->Q, cp))){
      fsl_card_Q_free(cp);
    }
    return rc;
  }
}

/**
    A comparison routine for qsort(3) which compares fsl_card_F
    instances in a lexical manner based on their names.  The order is
    important for card ordering in generated manifests.

    It expects that each argument is a (fsl_card_F const *).
*/
static int fsl_card_F_cmp( void const * lhs, void const * rhs ){
  fsl_card_F const * const l = (fsl_card_F const *)lhs;
  fsl_card_F const * const r = (fsl_card_F const *)rhs;
  /* Compare NULL as larger so that NULLs move to the right. That said,
     we aren't expecting any NULLs. */
  assert(l);
  assert(r);
  if(!l) return r ? 1 : 0;
  else if(!r) return -1;
  else return fsl_strcmp(l->name, r->name);
}

static void fsl_card_F_list_sort(fsl_card_F_list * li){
  if(FSL__CARD_F_LIST_NEEDS_SORT & li->flags){
    qsort(li->list, li->used, sizeof(fsl_card_F),
          fsl_card_F_cmp );
    li->flags &= ~FSL__CARD_F_LIST_NEEDS_SORT;
  }
}

static void fsl_deck_F_sort(fsl_deck * const mf){
  fsl_card_F_list_sort(&mf->F);
}

int fsl_card_F_compare_name( fsl_card_F const * const lhs,
                             fsl_card_F const * const rhs){
  return (lhs == rhs) ? 0 : fsl_card_F_cmp( lhs, rhs );
}

int fsl__deck_R_set( fsl_deck * const mf, fsl_uuid_cstr md5){
  return mf
    ? fsl_deck_sethex_impl(mf, md5, 'R', md5 ? FSL_STRLEN_MD5 : 0, &mf->R)
    : FSL_RC_MISUSE;
}

int fsl_deck_R_calc2(fsl_deck * const mf, char ** tgt){
  fsl_cx * const f = mf->f;
  char const * theHash = 0;
  char hex[FSL_STRLEN_MD5+1];
  if(!f) return FSL_RC_MISUSE;
  else if(!fsl_needs_repo(f)){
    return FSL_RC_NOT_A_REPO;
  }else if(!fsl_deck_check_type(mf,'R')) {
    assert(mf->f->error.code);
    return mf->f->error.code;
  }else if(!mf->F.used){
    if( mf->B.uuid ){
    /* If mf->B.uuid and !mf->F.used, we can copy the R-card from
       fsl_deck_baseline_fetch(mf). That's an expensive way to copy a
       string, but not nearly as expensive as a full R-card
       calculation. */
      int const rc = fsl_deck_baseline_fetch(mf);
      if( rc ) return rc;
      assert( mf->B.baseline );
      theHash = mf->B.baseline->B.uuid ? NULL : mf->B.baseline->R;
      if( !theHash ){
        /* If the parent parent does not have an R-card, or is itself
           a delta manifest (so its R-card covers files which mf does
           not inherit), do this the hard way. */
        goto calc_R_card;
      }
    }else{
      theHash = FSL_MD5_INITIAL_HASH;
    }
    /* fall through and set hash */
  }else{
  calc_R_card: ;
    int rc = 0;
    fsl_card_F const * fc;
    fsl_id_t fileRid;
    fsl_b * const buf = fsl__cx_content_buffer(f);
    unsigned char digest[16];
    fsl_md5_cx md5 = fsl_md5_cx_empty;
    enum { NumBufSize = 40 };
    char numBuf[NumBufSize] = {0};
    assert(!buf->used && "Misuse of f->fileContent buffer.");
    rc = fsl_deck_F_rewind(mf);
    if(rc) goto end;
    fsl_deck_F_sort(mf);
    fsl_deck_F_each(mf, fc, rc){
      /* MARKER(("R rc=%s file #%d: %s %s\n", fsl_rc_cstr(rc), ++i, fc ? fc->name : "<END>", fc ? fc->uuid : NULL)); */
      assert(fc->uuid && "We no longer iterate over deleted entries.");
      fileRid = fsl_uuid_to_rid( f, fc->uuid );
      if(0==fileRid){
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Cannot resolve RID for F-card UUID [%s].",
                            fc->uuid);
        goto end;
      }else if(fileRid<0){
        assert(f->error.code);
        rc = f->error.code
          ? f->error.code
          : fsl_cx_err_set(f, FSL_RC_ERROR,
                           "Error resolving RID for F-card UUID [%s].",
                           fc->uuid);
        goto end;
      }
      fsl_md5_update_cstr(&md5, fc->name, -1);
      rc = fsl_content_get(f, fileRid, buf);
      if(rc){
        goto end;
      }
      numBuf[0] = 0;
      fsl_snprintf(numBuf, NumBufSize,
                   " %"FSL_SIZE_T_PFMT"\n",
                   buf->used);
      fsl_md5_update_cstr(&md5, numBuf, -1);
      fsl_md5_update_buffer(&md5, buf);
    }
    if(!rc){
      fsl_md5_final(&md5, digest);
      fsl_md5_digest_to_base16(digest, hex);
    }
    end:
    fsl__cx_content_buffer_yield(f);
    assert(0==buf->used);
    if(rc) return rc;
    fsl_deck_F_rewind(mf);
    theHash = hex;
  }
  assert(theHash);
  if(*tgt){
    memcpy(*tgt, theHash, FSL_STRLEN_MD5);
    (*tgt)[FSL_STRLEN_MD5] = 0;
    return 0;
  }else{
    char * x = fsl_strdup(theHash);
    if(x) *tgt = x;
    return x ? 0 : FSL_RC_OOM;
  }
}

int fsl_deck_R_calc(fsl_deck * const mf){
  char R[FSL_STRLEN_MD5+1] = {0};
  char * r = R;
  const int rc = fsl_deck_R_calc2(mf, &r);
  return rc ? rc : fsl__deck_R_set(mf, r);
}

int fsl_deck_T_add2( fsl_deck * const mf, fsl_card_T * t){
  if(!t) return FSL_RC_MISUSE;
  else if(!fsl_deck_check_type(mf, 'T')){
    return mf->f->error.code;
  }else if(FSL_SATYPE_CONTROL==mf->type && NULL==t->uuid){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                            "CONTROL artifacts may not have "
                            "self-referential tags: %s", t->name);
  }else if(FSL_SATYPE_TECHNOTE==mf->type){
    if(NULL!=t->uuid){
      return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                              "TECHNOTE artifacts may not have "
                              "tags which refer to other objects: "
                              "%s %s", t->name, t->uuid);
    }else if(FSL_TAGTYPE_ADD!=t->type){
      return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                            "TECHNOTE artifacts may only have "
                            "ADD-type tags: %c%s",
                            fsl_tag_prefix_char(t->type), t->name);
    }
  }
  if(!t->name || !*t->name){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                         "Tag name may not be empty.");
  }else if(fsl_validate16(t->name, fsl_strlen(t->name))){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "T-card name looks like a hexadecimal hash: %s",
                          t->name);
  }else if(t->uuid && !fsl_is_uuid(t->uuid)){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Malformed artifact hash on T-card "
                          "for tag %s: %s",
                          t->name, t->uuid);
  }
  return fsl_list_append(&mf->T, t);
}

int fsl_deck_T_add( fsl_deck * const mf, fsl_tagtype_e tagType,
                    char const * uuid, char const * name,
                    char const * value){
  if(!name) return FSL_RC_MISUSE;
  else if(!fsl_deck_check_type(mf, 'T')) return mf->f->error.code;
  else if(!*name){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Tag name may not be empty.");
  }else if(uuid && !fsl_is_uuid(uuid)){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Malformed artifact hash on T-card "
                          "for tag %s: %s",
                          name, uuid);
  }
  else switch(tagType){
    case FSL_TAGTYPE_CANCEL:
    case FSL_TAGTYPE_ADD:
    case FSL_TAGTYPE_PROPAGATING:{
      int rc;
      fsl_card_T * t;
      t = fsl_card_T_malloc(tagType, uuid, name, value);
      if(!t) return FSL_RC_OOM;
      rc = fsl_deck_T_add2( mf, t );
      if(rc) fsl_card_T_free(t);
      return rc;
    }
    default:
      assert(!"Invalid tagType value");
      return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                            "Invalid tag-type value: %d",
                            (int)tagType);
  }
}

/**
   Returns true if the NUL-terminated string contains only
   "reasonable" branch name character, with the native assumption that
   anything <=32d is "unreasonable" and anything >=128 is part of a
   multibyte UTF8 character.
*/
static bool fsl_is_valid_branchname(char const * z_){
  unsigned char const * z = (unsigned char const*)z_;
  unsigned len = 0;
  for(; z[len]; ++len){
    if(z[len] <= 32) return false;
  }
  return len>0;
}

int fsl_deck_branch_set( fsl_deck * const d, char const * branchName ){
  if(!branchName || !*branchName){
    return fsl_cx_err_set(d->f, FSL_RC_RANGE,
                          "Branch name may not be empty.");
  }else if(!fsl_is_valid_branchname(branchName)){
    return fsl_cx_err_set(d->f, FSL_RC_RANGE,
                          "Branch name contains invalid characters: %s",
                          branchName);
  }
  int rc= fsl_deck_T_add(d, FSL_TAGTYPE_PROPAGATING, NULL,
                         "branch", branchName);
  if(!rc){
    char * sym = fsl_mprintf("sym-%s", branchName);
    if(sym){
      rc = fsl_deck_T_add(d, FSL_TAGTYPE_PROPAGATING, NULL,
                          sym, NULL);
      fsl_free(sym);
    }else{
      rc = FSL_RC_OOM;
    }
  }
  return rc;
}

int fsl_deck_U_set( fsl_deck * const mf, char const * v){
  return fsl_deck_set_string( mf, 'U', &mf->U, v, -1 );
}

int fsl_deck_W_set( fsl_deck * const mf, char const * v, fsl_int_t n){
  return fsl_deck_b_setuffer_impl(mf, v, n, 'W', &mf->W);
}

int fsl_deck_A_set( fsl_deck * const mf, char const * name,
                    char const * tgt,
                    char const * uuidSrc ){
  int const uLen = (uuidSrc && *uuidSrc) ? fsl_is_uuid(uuidSrc) : 0;
  if(!name || !tgt) return FSL_RC_MISUSE;
  else if(!fsl_deck_check_type(mf, 'A')) return mf->f->error.code;
  else if(!*name){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Invalid filename on A-card: "
                          "the name is empty.");
  }
  else if(!*tgt){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Invalid target on A-card for %s: "
                          "the target is empty.", name);
  }
  /* TODO: validate tgt based on mf->type and require UUID
     for types EVENT/TICKET.
  */
  else if(uuidSrc && *uuidSrc && !uLen){
    return fsl_cx_err_set(mf->f, FSL_RC_SYNTAX,
                          "Invalid source on A-card for %s: %s",
                          name, uuidSrc);
  }
  else{
    int rc = 0;
    fsl_deck_free_string(mf, mf->A.tgt);
    fsl_deck_free_string(mf, mf->A.src);
    fsl_deck_free_string(mf, mf->A.name);
    mf->A.name = mf->A.src = NULL;
    if(! (mf->A.tgt = fsl_strdup(tgt))) rc = FSL_RC_OOM;
    else if( !(mf->A.name = fsl_strdup(name))) rc = FSL_RC_OOM;
    else if(uLen){
      mf->A.src = fsl_strndup(uuidSrc,uLen);
      if(!mf->A.src) rc = FSL_RC_OOM
        /* Leave mf->A.tgt/name for downstream cleanup. */;
    }
    return rc;
  }
}


int fsl_deck_D_set( fsl_deck * const mf, double date){
  if(!mf) return FSL_RC_MISUSE;
  else if(date<0){
    return fsl_cx_err_set(mf->f, FSL_RC_RANGE,
                          "Invalid D-card date: Julian day %f "
                          "is negative.", date);
  }
  else if(date>0 && !fsl_deck_check_type(mf, 'D')){
    return mf->f->error.code;
  }else{
    mf->D = date;
    return 0;
  }
}

int fsl_deck_E_set( fsl_deck * const mf, double date, char const * uuid){
  int const uLen = uuid ? fsl_is_uuid(uuid) : 0;
  if(!mf || !uuid) return FSL_RC_MISUSE;
  else if(date<=0){
    return fsl_cx_err_set(mf->f, FSL_RC_RANGE,
                          "Malformed date on E-card: Julian day %f "
                          "is not positive.", date);
  }else if(!uLen){
    return fsl_cx_err_set(mf->f, FSL_RC_RANGE,
                          "Malformed hash on E-card: %s", uuid);
  }
  else{
    mf->E.julian = date;
    fsl_deck_free_string(mf, mf->E.uuid);
    mf->E.uuid = fsl_strndup(uuid, uLen);
    return mf->E.uuid ? 0 : FSL_RC_OOM;
  }
}

int fsl_deck_F_add( fsl_deck * const mf, char const * name,
                    char const * uuid,
                    fsl_fileperm_e perms,
                    char const * oldName){
  return fsl__deck_F_add2(mf, name, uuid, perms, oldName, true);
}

int fsl__deck_F_add2( fsl_deck * const mf, char const * name,
                      char const * uuid,
                      fsl_fileperm_e perms,
                      char const * oldName,
                      bool strictNames){
  int const uLen = uuid ? fsl_is_uuid(uuid) : 0;
  if(!mf || !name) return FSL_RC_MISUSE;
  else if(!uuid && !mf->B.uuid){
    return fsl_cx_err_set(mf->f, FSL_RC_MISUSE,
                          "Missing hash on F-card %s: a NULL hash "
                          "(deletion) is only valid in a delta "
                          "manifest.", name);
  }
  else if(!fsl_deck_check_type(mf, 'F')) return mf->f->error.code;
  else if(!*name){
    return fsl_cx_err_set(mf->f, FSL_RC_RANGE,
                         "F-card name may not be empty.");
  }
  else if(!fsl_is_simple_pathname(name, strictNames)
          || (oldName && !fsl_is_simple_pathname(oldName, strictNames))){
    return fsl_cx_err_set(mf->f, FSL_RC_RANGE,
                          "Invalid filename for F-card (simple form required): "
                          "name=[%s], oldName=[%s].", name, oldName);
  }
  else if(uuid && !uLen){
    return fsl_cx_err_set(mf->f, FSL_RC_RANGE,
                          "F-card hash invalid for %s: %s",
                          name, uuid);
  }
  else {
    int rc = 0;
    fsl_card_F * t;
    switch(perms){
      case FSL_FILE_PERM_EXE:
      case FSL_FILE_PERM_LINK:
      case FSL_FILE_PERM_REGULAR:
        break;
      default:
        assert(!"Invalid fsl_fileperm_e value");
        return fsl_cx_err_set(mf->f, FSL_RC_RANGE,
                              "Invalid fsl_fileperm_e value "
                              "(%d) for file [%s].",
                              perms, name);
    }
    t = fsl_card_F_list_push(&mf->F);
    if(!t) return FSL_RC_OOM;
    assert(mf->F.used>1
           ? (FSL__CARD_F_LIST_NEEDS_SORT & mf->F.flags)
           : 1);
    assert(!t->name);
    assert(!t->uuid);
    assert(!t->priorName);
    assert(!t->deckOwnsStrings);
    t->perm = perms;
    if(0==(t->name = fsl_strdup(name))){
      rc = FSL_RC_OOM;
    }else if(uuid && 0==(t->uuid = fsl_strdup(uuid))){
      rc = FSL_RC_OOM;
    }else if(oldName && 0==(t->priorName = fsl_strdup(oldName))){
      rc = FSL_RC_OOM;
    }
    if(rc){
      fsl_card_F_list_pop(&mf->F);
    }
    return rc;
  }
}

int fsl_deck_F_foreach( fsl_deck * const d, fsl_card_F_visitor_f cb, void * const visitorState ){
  if(!cb) return FSL_RC_MISUSE;
  else{
    fsl_card_F const * fc;
    int rc = fsl_deck_F_rewind(d);
    fsl_deck_F_each(d, fc, rc) {
      rc = cb( fc, visitorState );
    }
    return (FSL_RC_BREAK==rc) ? 0 : rc;
  }
}

/**
    Output state for fsl_output_f_mf() and friends. Used for managing
    the output of a fsl_deck.
 */
struct fsl_deck_out_state {
  /**
      The set of cards being output. We use this to delegate certain
      output bits.
   */
  fsl_deck const * d;
  /**
      Output routine to send manifest to.
   */
  fsl_output_f out;
  /**
      State to pass as the first arg of this->out().
   */
  void * outState;

  /**
     The previously-visited card, for confirming that all cards are in
     proper lexical order.
   */
  fsl_card_F const * prevCard;
  /**
      f() result code, so that we can feed the code back through the
      fsl_appendf() layer. If this is non-0, processing must stop.  We
      "could" use this->error.code instead, but this is simple.
   */
  int rc;
  /**
      Counter for list-visiting routines. Must be re-set before each
      visit loop if the visitor makes use of this (most do not).
   */
  fsl_int_t counter;

  /**
      Incrementally-calculated MD5 sum of all output sent via
      fsl_output_f_mf().
   */
  fsl_md5_cx md5;

  /* Holds error state for propagating back to the client. */
  fsl_error error;

  /**
      Scratch buffer for fossilizing bytes and other temporary work.
      This value comes from fsl__cx_scratchpad().
  */
  fsl_b * scratch;
};
typedef struct fsl_deck_out_state fsl_deck_out_state;
static const fsl_deck_out_state fsl_deck_out_state_empty = {
NULL/*d*/,
NULL/*out*/,
NULL/*outState*/,
NULL/*prevCard*/,
0/*rc*/,
0/*counter*/,
fsl_md5_cx_empty_m/*md5*/,
fsl_error_empty_m/*error*/,
NULL/*scratch*/
};

/**
    fsl_output_f() impl which forwards its data to arg->out(). arg
    must be a (fsl_deck_out_state *). Updates arg->rc to the result of
    calling arg->out(fp->fState, data, n). If arg->out() succeeds then
    arg->md5 is updated to reflect the given data. i.e. this is where
    the Z-card gets calculated incrementally during output of a deck.
*/
static int fsl_output_f_mf( void * arg, void const * data,
                            fsl_size_t n ){
  fsl_deck_out_state * const os = (fsl_deck_out_state *)arg;
  if((n>0)
     && !(os->rc = os->out(os->outState, data, (fsl_size_t)n))
     && (os->md5.isInit)){
    fsl_md5_update( &os->md5, data, (fsl_size_t)n );
  }
  return os->rc;
}

/**
    Internal helper for fsl_deck_output(). Appends formatted output to
    os->out() via fsl_output_f_mf(). Returns os->rc (0 on success).
 */
static int fsl_deck_append( fsl_deck_out_state * const os,
                            char const * fmt, ... ){
  fsl_int_t rc;
  va_list args;
  assert(os);
  assert(fmt && *fmt);
  va_start(args,fmt);
  rc = fsl_appendfv( fsl_output_f_mf, os, fmt, args);
  va_end(args);
  if(rc<0 && !os->rc) os->rc = FSL_RC_IO;
  return os->rc;
}

/**
    Fossilizes (inp, inp+len] bytes to os->scratch,
    overwriting any existing contents.
    Updates and returns os->rc.
 */
static int fsl_deck_fossilize( fsl_deck_out_state * const os,
                               unsigned char const * inp,
                               fsl_int_t len){
  fsl_b_reuse(os->scratch);
  return os->rc = len
    ? fsl_bytes_fossilize(inp, len, os->scratch)
    : 0;
}

/**
   Confirms that the given card letter is valid for od->d->type, and
   updates os->rc and os->error if it's not. Returns true if it's
   valid.
*/
static bool fsl_deck_out_tcheck(fsl_deck_out_state * const os, char letter){
  if(!fsl_card_is_legal(os->d->type, letter)){
    os->rc = fsl_error_set(&os->error, FSL_RC_TYPE,
                           "%c-card is not valid for deck type %s.",
                           letter, fsl_satype_cstr(os->d->type));
  }
  return os->rc ? false : true;
}

/* Appends a UUID-valued card to os from os->d->{{card}} if the given
   UUID is not NULL, else this is a no-op. */
static int fsl_deck_out_uuid( fsl_deck_out_state * const os, char card, fsl_uuid_str uuid ){
  if(uuid && fsl_deck_out_tcheck(os, card)){
    if(!fsl_is_uuid(uuid)){
      os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                             "Malformed UUID in %c card: %s",
                             card, uuid);
    }else{
      fsl_deck_append(os, "%c %s\n", card, uuid);
    }
  }
  return os->rc;
}

/* Appends the B card to os from os->d->B. */
static int fsl_deck_out_B( fsl_deck_out_state * const os ){
  return fsl_deck_out_uuid(os, 'B', os->d->B.uuid);
}


/* Appends the A card to os from os->d->A. */
static int fsl_deck_out_A( fsl_deck_out_state * const os ){
  if(os->d->A.name && fsl_deck_out_tcheck(os, 'A')){
    if(!os->d->A.name || !*os->d->A.name){
      os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                             "A-card is missing its name property");

    }else if(!os->d->A.tgt || !*os->d->A.tgt){
      os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                             "A-card is missing its tgt property: %s",
                             os->d->A.name);

    }else if(os->d->A.src && !fsl_is_uuid(os->d->A.src)){
      os->rc = fsl_error_set(&os->error, FSL_RC_TYPE,
                             "Invalid src UUID in A-card: name=%s, "
                             "invalid uuid=%s",
                             os->d->A.name, os->d->A.src);
    }else{
      fsl_deck_append(os, "A %F %F",
                      os->d->A.name, os->d->A.tgt);
      if(!os->rc){
        if(os->d->A.src){
          fsl_deck_append(os, " %s", os->d->A.src);
        }
        if(!os->rc) fsl_deck_append(os, "\n");
      }
    }
  }
  return os->rc;
}

/**
    Internal helper for outputing cards which are simple strings.  str
    is the card to output (NULL values are ignored), letter is the
    card letter being output. str gets fossilize-formatted.
 */
static int fsl_deck_out_letter_str(fsl_deck_out_state * const os, char letter,
                                    char const * str){
  if(str && fsl_deck_out_tcheck(os, letter)){
    fsl_deck_append(os, "%c %F\n", letter, str);
  }
  return os->rc;
}

/* Appends the C card to os from os->d->C. */
static int fsl_deck_out_C( fsl_deck_out_state * const os ){
  return fsl_deck_out_letter_str(os, 'C', os->d->C);
}


/* Appends the D card to os from os->d->D. */
static int fsl_deck_out_D( fsl_deck_out_state * const os ){
  if((os->d->D > 0.0) && fsl_deck_out_tcheck(os, 'D')){
    char ds[24];
    if(!fsl_julian_to_iso8601(os->d->D, ds, 1)){
      os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                             "D-card contains invalid "
                             "Julian Day value: %f", os->d->D);
    }else{
      fsl_deck_append(os, "D %s\n", ds);
    }
  }
  return os->rc;
}

/* Appends the E card to os from os->d->E. */
static int fsl_deck_out_E( fsl_deck_out_state * const os ){
  if(os->d->E.uuid && fsl_deck_out_tcheck(os, 'E')){
    char ds[24];
    char msPrecision = FSL_SATYPE_EVENT!=os->d->type
      /* The timestamps on Events historically have seconds precision,
         not ms.
      */;
    if(!fsl_is_uuid(os->d->E.uuid)){
      os->rc = fsl_error_set(&os->error, FSL_RC_TYPE,
                             "Invalid UUID in E-card: %s",
                             os->d->E.uuid);
    }
    else if(!fsl_julian_to_iso8601(os->d->E.julian, ds, msPrecision)){
      os->rc = fsl_error_set(&os->error, FSL_RC_TYPE,
                             "Invalid Julian Day value in E-card: %f",
                             os->d->E.julian);
    }
    else{
      fsl_deck_append(os, "E %s %s\n", ds, os->d->E.uuid);
    }
  }
  return os->rc;
}

/* Appends the G card to os from os->d->G. */
static int fsl_deck_out_G( fsl_deck_out_state * const os ){
  return fsl_deck_out_uuid(os, 'G', os->d->G);
}

/* Appends the H card to os from os->d->H. */
static int fsl_deck_out_H( fsl_deck_out_state * const os ){
  if(os->d->H && os->d->I){
    return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                  "Forum post may not have both H- and I-cards.");
  }
  return fsl_deck_out_letter_str(os, 'H', os->d->H);
}

/* Appends the I card to os from os->d->I. */
static int fsl_deck_out_I( fsl_deck_out_state * const os ){
  if(os->d->I && os->d->H){
    return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                  "Forum post may not have both H- and I-cards.");
  }
  return fsl_deck_out_uuid(os, 'I', os->d->I);
}


static int fsl_deck_out_F_one(fsl_deck_out_state *os,
                              fsl_card_F const * f){
  int rc;
  char hasOldName;
  char const * zPerm;
  assert(f);
  if(os->prevCard){
    int const cmp = fsl_strcmp(os->prevCard->name, f->name);
    if(0==cmp){
      return fsl_error_set(&os->error, FSL_RC_RANGE,
                           "Duplicate F-card name: %s",
                           f->name);
    }else if(cmp>0){
      return fsl_error_set(&os->error, FSL_RC_RANGE,
                           "Out-of-order F-card names: %s before %s",
                           os->prevCard->name, f->name);
    }
  }
  if(!fsl_is_simple_pathname(f->name, false)){
    return fsl_error_set(&os->error, FSL_RC_RANGE,
                         "Filename is invalid as F-card: %s",
                         f->name);
  }
  if(!f->uuid && !os->d->B.uuid){
    return fsl_error_set(&os->error, FSL_RC_MISUSE,
                         "Baseline manifests may not have F-cards "
                         "without UUIDs (file deletion entries). To "
                         "delete files, simply do not inject an F-card "
                         "for them. Delta manifests, however, require "
                         "NULL UUIDs for deletion entries! File: %s",
                         f->name);
  }

  rc = fsl_deck_fossilize(os, (unsigned char const *)f->name, -1);
  if(!rc) rc = fsl_deck_append(os, "F %b", os->scratch);
  if(!rc && f->uuid){
    assert(fsl_is_uuid(f->uuid));
    rc = fsl_deck_append( os, " %s", f->uuid);
    if(rc) return rc;
  }
  if(f->uuid){
    hasOldName = f->priorName && (0!=fsl_strcmp(f->name,f->priorName));
    switch(f->perm){
      case FSL_FILE_PERM_EXE: zPerm = " x"; break;
      case FSL_FILE_PERM_LINK: zPerm = " l"; break;
      default:
        /* When hasOldName, we have to inject an otherwise optional
           'w' to avoid an ambiguity. Or at least that's what the
           fossil F-card-generating code does.
        */
        zPerm = hasOldName ? " w" : ""; break;
    }
    if(*zPerm) rc = fsl_deck_append( os, "%s", zPerm);
    if(!rc && hasOldName){
      assert(*zPerm);
      rc = fsl_deck_fossilize(os, (unsigned char const *)f->priorName, -1);
      if(!rc) rc = fsl_deck_append( os, " %b", os->scratch);
    }
  }
  if(!rc) fsl_output_f_mf(os, "\n", 1);
  return os->rc;
}

static int fsl_deck_out_list_obj( fsl_deck_out_state * const os,
                                  char letter,
                                  fsl_list const * li,
                                  fsl_list_visitor_f visitor){
  if(li->used && fsl_deck_out_tcheck(os, letter)){
    os->rc = fsl_list_visit( li, 0, visitor, os );
  }
  return os->rc;
}

static int fsl_deck_out_F( fsl_deck_out_state * const os ){
  if(os->d->F.used && fsl_deck_out_tcheck(os, 'F')){
    uint32_t i;
    for(i=0; !os->rc && i <os->d->F.used; ++i){
      os->rc = fsl_deck_out_F_one(os, F_at(&os->d->F, i));
    }
  }
  return os->rc;
}


/**
    A comparison routine for qsort(3) which compares fsl_card_J
    instances in a lexical manner based on their names.  The order is
    important for card ordering in generated manifests.
 */
int fsl__qsort_cmp_J_cards( void const * lhs, void const * rhs ){
  fsl_card_J const * l = *((fsl_card_J const **)lhs);
  fsl_card_J const * r = *((fsl_card_J const **)rhs);
  /* Compare NULL as larger so that NULLs move to the right. That said,
     we aren't expecting any NULLs. */
  assert(l);
  assert(r);
  if(!l) return r ? 1 : 0;
  else if(!r) return -1;
  else{
    /* The '+' sorts before any legal field name bits (letters). */
    if(l->append != r->append) return r->append - l->append
      /* Footnote: that will break if, e.g. l->isAppend==2 and
         r->isAppend=1, or some such. Shame C89 doesn't have a true
         boolean.
      */;
    else return fsl_strcmp(l->field, r->field);
  }
}

/**
    fsl_list_visitor_f() impl for outputing J cards. obj must
    be a (fsl_card_J *).
 */
static int fsl_list_v_mf_output_card_J(void * obj, void * visitorState ){
  fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState;
  fsl_card_J const * c = (fsl_card_J const *)obj;
  fsl_deck_fossilize( os, (unsigned char const *)c->field, -1 );
  if(!os->rc){
    fsl_deck_append(os, "J %s%b", c->append ? "+" : "", os->scratch);
    if(!os->rc){
      if(c->value && *c->value){
        fsl_deck_fossilize( os, (unsigned char const *)c->value, -1 );
        if(!os->rc){
          fsl_deck_append(os, " %b\n", os->scratch);
        }
      }else{
        fsl_deck_append(os, "\n");
      }
    }
  }
  return os->rc;
}

static int fsl_deck_out_J( fsl_deck_out_state * const os ){
  return fsl_deck_out_list_obj(os, 'J', &os->d->J,
                               fsl_list_v_mf_output_card_J);
}

/* Appends the K card to os from os->d->K. */
static int fsl_deck_out_K( fsl_deck_out_state * const os ){
  if(os->d->K && fsl_deck_out_tcheck(os, 'K')){
    if(!fsl_is_uuid(os->d->K)){
      os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                             "Invalid UUID in K card: %s", os->d->K);
    }
    else{
      fsl_deck_append(os, "K %s\n", os->d->K);
    }
  }
  return os->rc;
}


/* Appends the L card to os from os->d->L. */
static int fsl_deck_out_L( fsl_deck_out_state * const os ){
  return fsl_deck_out_letter_str(os, 'L', os->d->L);
}

/* Appends the N card to os from os->d->N. */
static int fsl_deck_out_N( fsl_deck_out_state * const os ){
  return fsl_deck_out_letter_str(os, 'N', os->d->N);
}

/**
    fsl_list_visitor_f() impl for outputing P cards. obj must
    be a (fsl_deck_out_state *) and obj->counter must be
    set to 0 before running the visit iteration.
 */
static int fsl_list_v_mf_output_card_P(void * obj, void * visitorState ){
  fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState;
  char const * uuid = (char const *)obj;
  int const uLen = uuid ? fsl_is_uuid(uuid) : 0;
  if(!uLen){
    os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                           "Invalid UUID in P card: %s", uuid);
  }
  else if(!os->counter++) fsl_output_f_mf(os, "P ", 2);
  else fsl_output_f_mf(os, " ", 1);
  /* Reminder: fsl_appendf_f_mf() updates os->rc. */
  if(!os->rc){
    fsl_output_f_mf(os, uuid, (fsl_size_t)uLen);
  }
  return os->rc;
}


static int fsl_deck_out_P( fsl_deck_out_state * const os ){
  if(!fsl_deck_out_tcheck(os, 'P')) return os->rc;
  else if(os->d->P.used){
    os->counter = 0;
    os->rc = fsl_list_visit( &os->d->P, 0, fsl_list_v_mf_output_card_P, os );
    assert(os->counter);
    if(!os->rc) fsl_output_f_mf(os, "\n", 1);
  }
#if 1
  /* Arguable: empty P-cards are harmless but cosmetically unsightly. */
  else if(FSL_SATYPE_CHECKIN==os->d->type){
    /*
      Evil ugly hack, primarily for round-trip compatibility with
      manifest #1, which has an empty P card.

      fossil(1) ignores empty P-cards in all cases, and must continue
      to do so for backwards compatibility with rid #1 in all repos.

      Pedantic note: there must be no space between the 'P' and the
      newline.
    */
    fsl_deck_append(os, "P\n");
  }
#endif
  return os->rc;
}

/**
    A comparison routine for qsort(3) which compares fsl_card_Q
    instances in a lexical manner. The order is important for card
    ordering in generated manifests.
*/
static int qsort_cmp_Q_cards( void const * lhs, void const * rhs ){
  fsl_card_Q const * l = *((fsl_card_Q const **)lhs);
  fsl_card_Q const * r = *((fsl_card_Q const **)rhs);
  /* Compare NULL as larger so that NULLs move to the right. That said,
     we aren't expecting any NULLs. */
  assert(l);
  assert(r);
  if(!l) return r ? 1 : 0;
  else if(!r) return -1;
  else{
    /* Lexical sorting must account for the +/- characters, and a '+'
       sorts before '-', which is why this next part may seem
       backwards at first. */
    assert(l->type);
    assert(r->type);
    if(l->type<0 && r->type>0) return 1;
    else if(l->type>0 && r->type<0) return -1;
    else return fsl_strcmp(l->target, r->target);
  }
}

/**
    fsl_list_visitor_f() impl for outputing Q cards. obj must
    be a (fsl_deck_out_state *).
*/
static int fsl_list_v_mf_output_card_Q(void * obj, void * visitorState ){
  fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState;
  fsl_card_Q const * cp = (fsl_card_Q const *)obj;
  char const prefix = (cp->type==FSL_CHERRYPICK_ADD)
    ? '+' : '-';
  assert(cp->type);
  assert(cp->target);
  if(cp->type != FSL_CHERRYPICK_ADD &&
     cp->type != FSL_CHERRYPICK_BACKOUT){
    os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                           "Invalid type value (%d) in Q-card: %s",
                           cp->type, cp->target);
  }else if(!fsl_card_is_legal(os->d->type, 'Q')){
    os->rc = fsl_error_set(&os->error, FSL_RC_TYPE,
                           "Q-card is not valid for deck type %s",
                           fsl_satype_cstr(os->d->type));
  }else if(!fsl_is_uuid(cp->target)){
    os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                           "Invalid target UUID in Q-card: %s",
                           cp->target);
  }else if(cp->baseline){
    if(!fsl_is_uuid(cp->baseline)){
      os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                             "Invalid baseline UUID in Q-card: %s",
                             cp->baseline);
    }else{
      fsl_deck_append(os, "Q %c%s %s\n", prefix, cp->target, cp->baseline);
    }
  }else{
    fsl_deck_append(os, "Q %c%s\n", prefix, cp->target);
  }
  return os->rc;
}

static int fsl_deck_out_Q( fsl_deck_out_state * const os ){
  return fsl_deck_out_list_obj(os, 'Q', &os->d->Q,
                               fsl_list_v_mf_output_card_Q);
}

/**
    Appends the R card from os->d->R to os.
 */
static int fsl_deck_out_R( fsl_deck_out_state * const os ){
  if(os->d->R && fsl_deck_out_tcheck(os, 'R')){
    if((FSL_STRLEN_MD5!=fsl_strlen(os->d->R))
            || !fsl_validate16(os->d->R, FSL_STRLEN_MD5)){
      os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                             "Malformed MD5 in R-card: %s", os->d->R);
    }
    else{
      fsl_deck_append(os, "R %s\n", os->d->R);
    }
  }
  return os->rc;
}

/**
    fsl_list_visitor_f() impl for outputing T cards. obj must
    be a (fsl_deck_out_state *).
 */
static int fsl_list_v_mf_output_card_T(void * obj, void * visitorState ){
  fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState;
  fsl_card_T * t = (fsl_card_T *)obj;
  char prefix = 0;
  switch(os->d->type){
    case FSL_SATYPE_TECHNOTE:
      if( t->uuid ){
        return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                      "Non-self-referential T-card is not "
                                      "permitted in a technote: %s %s",
                                      t->name, t->uuid);
      }else if(FSL_TAGTYPE_ADD!=t->type){
        return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                      "Non-ADD T-card is not permitted "
                                      "in a technote: %c%s",
                                      fsl_tag_prefix_char(t->type),
                                      t->name);
      }
      break;
    case FSL_SATYPE_CONTROL:
      if( !t->uuid ){
        return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                      "Self-referential T-card is not "
                                      "permitted in a control artifact: "
                                      "%s", t->name);
      }
      break;
    default:
      break;
  }
  /* Determine the prefix character... */
  switch(t->type){
    case FSL_TAGTYPE_CANCEL: prefix = '-'; break;
    case FSL_TAGTYPE_ADD: prefix = '+'; break;
    case FSL_TAGTYPE_PROPAGATING: prefix = '*'; break;
    default:
      return os->rc = fsl_error_set(&os->error, FSL_RC_TYPE,
                                    "Invalid tag type #%d in T-card: %s",
                                    t->type, t->name);
  }
  if(!t->name || !*t->name){
    return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                  "T-card name may not be empty.");
  }else if(fsl_validate16(t->name, fsl_strlen(t->name))){
    return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                  "T-card name looks like a hexadecimal "
                                  "hash: %s", t->name);
  }else if(t->uuid && !fsl_is_uuid(t->uuid)){
      return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                    "Malformed UUID in T-card: %s",
                                    t->uuid);
  }
  /*
     Fossilize and output the prefix, name, and uuid, or a '*' if no
     uuid is set (which is only legal when tagging the current
     artifact, as '*' is a placeholder for the current artifact's
     UUID, which is not yet known).
  */
  fsl_b_reuse(os->scratch);
  fsl_deck_fossilize(os, (unsigned const char *)t->name, -1);
  if(os->rc) return os->rc;
  os->rc = fsl_deck_append(os, "T %c%s %s", prefix,
                           (char const*)os->scratch->mem,
                           t->uuid ? t->uuid : "*");
  if(os->rc) return os->rc;
  if(/*(t->type != FSL_TAGTYPE_CANCEL) &&*/t->value && *t->value){
    /* CANCEL tags historically don't store a value but
       the spec doesn't disallow it and they are harmless
       for (aren't used by) fossil(1). */
    fsl_deck_fossilize(os, (unsigned char const *)t->value, -1);
    if(!os->rc) fsl_output_f_mf(os, " ", 1);
    if(!os->rc) fsl_output_f_mf(os, (char const*)os->scratch->mem,
                                (fsl_int_t)os->scratch->used);
  }
  if(!os->rc){
    fsl_output_f_mf(os, "\n", 1);
  }
  return os->rc;
}


char fsl_tag_prefix_char( fsl_tagtype_e t ){
  switch(t){
    case FSL_TAGTYPE_CANCEL: return '-';
    case FSL_TAGTYPE_ADD: return '+';
    case FSL_TAGTYPE_PROPAGATING: return '*';
    default:
      return 0;
  }
}

/**
    A comparison routine for qsort(3) which compares fsl_card_T
    instances in a lexical manner based on (type, name, uuid, value).
    The order of those is important for card ordering in generated
    manifests. Interestingly, CANCEL tags (with a '-' prefix) sort
    last, meaning it is possible to cancel a tag set in the same
    manifest because crosslinking processes them in the order given
    (which will be lexical order for all legal manifests).

    Reminder: lhs and rhs must be (fsl_card_T**), as we use this to
    qsort() such lists. When using it to compare two tags, make sure
    to pass ptr-to-ptr.
*/
static int fsl_card_T_cmp_strict( void const * lhs, void const * rhs ){
  fsl_card_T const * l = *((fsl_card_T const **)lhs);
  fsl_card_T const * r = *((fsl_card_T const **)rhs);
  /* Compare NULL as larger so that NULLs move to the right. That said,
     we aren't expecting any NULLs. */
  assert(l);
  assert(r);
  if(!l) return r ? 1 : 0;
  else if(!r) return -1;
  else if(l->type != r->type){
    int const lc = fsl_tag_prefix_char(l->type);
    int const rc = fsl_tag_prefix_char(r->type);
    return lc - rc;
  }else{
    int rc = fsl_strcmp(l->name, r->name);
    if(rc) return rc;
    else {
      rc = fsl_uuidcmp(l->uuid, r->uuid);
      /* Fossil only validates that the type, name, and target are
         sorted. libfossil has always sorted the whole thing because
         the docs are a little unclear on what, precisely, must be
         taken into account for the sorting. */
      return rc
        ? rc
        : fsl_strcmp(l->value, r->value);
    }
  }
}

/**
   Like fsl_card_T_cmp_strict() but only compares the tags' types,
   names, and target UUIDs for compatibility with fossil(1).
   See also: fsl_card_T_cmp_strict()
*/
static int fsl_card_T_cmp_lax( void const * lhs, void const * rhs ){
  fsl_card_T const * const l = *((fsl_card_T const **)lhs);
  fsl_card_T const * const r = *((fsl_card_T const **)rhs);
  assert(l);
  assert(r);
  if(!l) return r ? 1 : 0;
  else if(!r) return -1;
  if(l->type != r->type){
    int const lc = fsl_tag_prefix_char(l->type);
    int const rc = fsl_tag_prefix_char(r->type);
    return lc - rc;
  }
  int rc = fsl_strcmp(l->name, r->name);
  if( 0==rc ){
    rc = fsl_uuidcmp(l->uuid, r->uuid);
  }
  return rc;
}

/**
   Confirms that any T-cards in d are properly sorted. If not,
   returns non-0. If err is not NULL, it is updated with a
   description of the problem.

   Possibly fixme one day: this code permits that the same tag/target
   combination may be added or removed, or added as a normal and
   propagating tag, in the same deck. Though that's not technically
   disallowed, we "should" disallow it. That requires a more thorough
   scan of the cards, though.
*/
static int fsl_deck_T_verify_order( fsl_deck const * d, fsl_error * err ){
  if(d->T.used<2) return 0;
  else{
    fsl_size_t i = 0, j;
    int rc = 0;
    fsl_card_T const * tag;
    fsl_card_T const * prev = NULL;
    for( i = 0; i < d->T.used; ++i, prev = tag, rc = 0){
      tag = (fsl_card_T const *)d->T.list[i];
      if(prev){
        if( (rc = fsl_card_T_cmp_lax(&prev, &tag)) >= 0 ){
          if(!err) rc = FSL_RC_SYNTAX;
          else{
            rc = rc
              ? fsl_error_set(err, FSL_RC_SYNTAX,
                              "Invalid T-card order: "
                              "[%c%s] must precede [%c%s]",
                              fsl_tag_prefix_char(prev->type),
                              prev->name,
                              fsl_tag_prefix_char(tag->type),
                              tag->name)
              : fsl_error_set(err, FSL_RC_SYNTAX,
                              "Duplicate T-card: %c%s",
                              fsl_tag_prefix_char(prev->type),
                              prev->name)
              ;
          }
          break;
        }
      }
    }
    /**
       And now, for bonus points: disallow the same tag name/artifact
       combination appearing twice in the deck. Though that's not
       explicitly disallowed by the fossil specs, we "should" disallow
       it. That requires a more thorough scan of the cards, though.

       This logic is NOT in fossil, and though we don't have any such
       tags in the fossil repo, we may have to disable this for
       compatibility's sake. OTOH, we only check this when outputing
       manifests, and we never (aside from testing) have to output
       manifests which were generated by fossil. Thus... this only
       triggers (except for some tests) on manifests generated by
       libfossil, so we can justify having it.
    */
    for( i=0; !rc && i < d->T.used; ++i ){
      fsl_card_T const * t1 = (fsl_card_T const *)d->T.list[i];
      for( j = 0; j < d->T.used; ++j ){
        if(i==j) continue;
        fsl_card_T const * t2 = (fsl_card_T const *)d->T.list[j];
        if(0==fsl_strcmp(t1->name, t2->name)
           && ((!t1->uuid && !t2->uuid)
               || 0==fsl_strcmp(t1->uuid, t2->uuid))){
              rc = fsl_error_set(err, FSL_RC_SYNTAX,
                                 "An artifact may not contain the same "
                                 "T-card name and target artifact "
                                 "multiple times: "
                                 "name=%s target=%s",
                                 t1->name, t1->uuid ? t1->uuid : "*");
              break;
        }
      }
    }
    return rc;
  }
}

/* Appends the T cards to os from os->d->T. */
static int fsl_deck_out_T( fsl_deck_out_state * const os ){
  os->rc = fsl_deck_T_verify_order( os->d, &os->error);
  return os->rc
    ? os->rc
    : fsl_deck_out_list_obj(os, 'T', &os->d->T,
                            fsl_list_v_mf_output_card_T);
}

/* Appends the U card to os from os->d->U. */
static int fsl_deck_out_U( fsl_deck_out_state * const os ){
  return fsl_deck_out_letter_str(os, 'U', os->d->U);
}

/* Appends the W card to os from os->d->W. */
static int fsl_deck_out_W( fsl_deck_out_state * const os ){
  if( fsl_deck_out_tcheck(os, 'W') ){
    if( os->d->W.used ){
      fsl_deck_append(os, "W %"FSL_SIZE_T_PFMT"\n%b\n",
                      (fsl_size_t)os->d->W.used,
                      &os->d->W );
    }else{
      fsl_deck_append(os, "W 0\n\n");
    }
  }
  return os->rc;
}


/* Appends the Z card to os from os' accummulated md5 hash. */
static int fsl_deck_out_Z( fsl_deck_out_state * const os ){
  unsigned char digest[16];
  char md5[FSL_STRLEN_MD5+1];
  fsl_md5_final(&os->md5, digest);
  fsl_md5_digest_to_base16(digest, md5);
  assert(!md5[32]);
  os->md5.isInit = 0 /* Keep further output from updating the MD5 */;
  return fsl_deck_append(os, "Z %.*s\n", FSL_STRLEN_MD5, md5);
}

static int qsort_cmp_strings( void const * lhs, void const * rhs ){
  char const * l = *((char const **)lhs);
  char const * r = *((char const **)rhs);
  return fsl_strcmp(l,r);
}

static int fsl_list_v_mf_output_card_M(void * obj, void * visitorState ){
  fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState;
  char const * m = (char const *)obj;
  return fsl_deck_append(os, "M %s\n", m);
}

static int fsl_deck_output_cluster( fsl_deck_out_state * const os ){
  if(!os->d->M.used){
    os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                           "M-card list may not be empty.");
  }else{
    fsl_deck_out_list_obj(os, 'M', &os->d->M,
                          fsl_list_v_mf_output_card_M);
  }
  return os->rc;
}


/* Helper for fsl_deck_output_CATYPE() */
#define DOUT(LETTER) rc = fsl_deck_out_##LETTER(os); \
  if(rc || os->rc) return os->rc ? os->rc : rc

static int fsl_deck_output_control( fsl_deck_out_state * const os ){
  int rc;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(D);
  DOUT(T);
  DOUT(U);
  return os->rc;
}

static int fsl_deck_output_event( fsl_deck_out_state * const os ){
  int rc = 0;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(C);
  DOUT(D);
  DOUT(E);
  DOUT(N);
  DOUT(P);
  DOUT(T);
  DOUT(U);
  DOUT(W);
  return os->rc;
}

static int fsl_deck_output_mf( fsl_deck_out_state * const os ){
  int rc = 0;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(B);
  DOUT(C);
  DOUT(D);
  DOUT(F);
  DOUT(K);
  DOUT(L);
  DOUT(N);
  DOUT(P);
  DOUT(Q);
  DOUT(R);
  DOUT(T);
  DOUT(U);
  return os->rc;
}


static int fsl_deck_output_ticket( fsl_deck_out_state * const os ){
  int rc;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(D);
  DOUT(J);
  DOUT(K);
  DOUT(U);
  return os->rc;
}

static int fsl_deck_output_wiki( fsl_deck_out_state * const os ){
  int rc;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(C);
  DOUT(D);
  DOUT(L);
  DOUT(N);
  DOUT(P);
  DOUT(U);
  DOUT(W);
  return os->rc;
}

static int fsl_deck_output_attachment( fsl_deck_out_state * const os ){
  int rc = 0;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(A);
  DOUT(C);
  DOUT(D);
  DOUT(N);
  DOUT(U);
  return os->rc;
}

static int fsl_deck_output_forumpost( fsl_deck_out_state * const os ){
  int rc;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(D);
  DOUT(G);
  DOUT(H);
  DOUT(I);
  DOUT(N);
  DOUT(P);
  DOUT(U);
  DOUT(W);
  return os->rc;
}

/**
    Only for testing/debugging purposes, as it allows constructs which
    are not semantically legal and are CERTAINLY not legal to stuff in
    the database.
 */
static int fsl_deck_output_any( fsl_deck_out_state * const os ){
  int rc = 0;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(B);
  DOUT(C);
  DOUT(D);
  DOUT(E);
  DOUT(F);
  DOUT(J);
  DOUT(K);
  DOUT(L);
  DOUT(N);
  DOUT(P);
  DOUT(Q);
  DOUT(R);
  DOUT(T);
  DOUT(U);
  DOUT(W);
  return os->rc;
}

#undef DOUT


int fsl_deck_unshuffle( fsl_deck * const d, bool calculateRCard ){
  fsl_list * li;
  int rc = 0;
  if(!d || !d->f) return FSL_RC_MISUSE;
  fsl_cx_err_reset(d->f);
#define SORT(CARD,CMP) li = &d->CARD; fsl_list_sort(li, CMP)
  SORT(J,fsl__qsort_cmp_J_cards);
  SORT(M,qsort_cmp_strings);
  SORT(Q,qsort_cmp_Q_cards);
  SORT(T,fsl_card_T_cmp_strict);
#undef SORT
  if(FSL_SATYPE_CHECKIN!=d->type){
    assert(!fsl_card_is_legal(d->type,'R'));
    assert(!fsl_card_is_legal(d->type,'F'));
  }else{
    assert(fsl_card_is_legal(d->type, 'R') && "in-lib unit testing");
    if(calculateRCard){
      rc = fsl_deck_R_calc(d) /* F-card list is sorted there */;
    }else{
      fsl_deck_F_sort(d);
      if(!d->R){
        rc = fsl__deck_R_set(d,
                             (d->F.used || d->B.uuid || d->P.used)
                             ? NULL
                             : FSL_MD5_INITIAL_HASH)
          /* Special case: for manifests with no (B,F,P)-cards we inject
             the initial-state R-card, analog to the initial checkin
             (RID 1). We need one of (B,F,P,R) to unambiguously identify
             a MANIFEST from a CONTROL, but RID 1 has an empty P-card,
             no F-cards, and no B-card, so it _needs_ an R-card in order
             to be unambiguously a Manifest. That said, that ambiguity
             is/would be harmless in practice because CONTROLs go
             through most of the same crosslinking processes as
             MANIFESTs (the ones which are important for this purpose,
             anyway).
          */;
      }
    }
  }
  return rc;
}

int fsl_deck_output( fsl_deck * const d, fsl_output_f out,
                     void * outputState ){
  static const bool allowTypeAny = false
    /* Only enable for debugging/testing. Allows outputing decks of
       type FSL_SATYPE_ANY, which bypasses some validation checks and
       may trigger other validation assertions. And may allow you to
       inject garbage into the repo. So be careful.
    */;

  fsl_deck_out_state OS = fsl_deck_out_state_empty;
  fsl_deck_out_state * const os = &OS;
  fsl_cx * const f = d->f;
  int rc = 0;
  if(NULL==out && NULL==outputState && f){
    out = f->output.out;
    outputState = f->output.state;
  }
  if(!f || !out) return FSL_RC_MISUSE;
  else if(FSL_SATYPE_ANY==d->type){
    if(!allowTypeAny){
      return fsl_cx_err_set(d->f, FSL_RC_TYPE,
                            "Artifact type ANY cannot be "
                            "output unless it is enabled in this "
                            "code (it's dangerous).");
    }
    /* fall through ... */
  }
  rc = fsl_deck_unshuffle(d,
                          (FSL_CX_F_CALC_R_CARD & f->flags)
                          ? ((d->F.used && !d->R) ? 1 : 0)
                          : 0);
  /* ^^^^ unshuffling might install an R-card, so we have to
     do that before checking whether all required cards are
     set... */
  if( !rc ) rc = fsl_deck_F_rewind(d);
  if(rc) return rc;
  else if(!fsl_deck_has_required_cards(d)){
    return FSL_RC_SYNTAX;
  }

  os->d = d;
  os->out = out;
  os->outState = outputState;
  os->scratch = fsl__cx_scratchpad(f);
  switch(d->type){
    case FSL_SATYPE_CLUSTER:
      rc = fsl_deck_output_cluster(os);
      break;
    case FSL_SATYPE_CONTROL:
      rc = fsl_deck_output_control(os);
      break;
    case FSL_SATYPE_EVENT:
      rc = fsl_deck_output_event(os);
      break;
    case FSL_SATYPE_CHECKIN:
      rc = fsl_deck_output_mf(os);
      break;
    case FSL_SATYPE_TICKET:
      rc = fsl_deck_output_ticket(os);
      break;
    case FSL_SATYPE_WIKI:
      rc = fsl_deck_output_wiki(os);
      break;
    case FSL_SATYPE_ANY:
      assert(allowTypeAny);
      rc = fsl_deck_output_any(os);
      break;
    case FSL_SATYPE_ATTACHMENT:
      rc = fsl_deck_output_attachment(os);
      break;
    case FSL_SATYPE_FORUMPOST:
      rc = fsl_deck_output_forumpost(os);
      break;
    default:
      rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                          "Invalid/unhandled deck type (#%d).",
                          d->type);
      goto end;
  }
  if(!rc){
    rc = fsl_deck_out_Z( os );
  }
  end:
  fsl__cx_scratchpad_yield(f, os->scratch);
  if(os->rc && os->error.code){
    fsl_error_propagate(&os->error, &f->error);
  }else if(os->rc && !f->error.code && FSL_RC_OOM!=os->rc){
    /* The output callback failed and reports only a result code. */
    fsl_cx_err_set(f, os->rc, "Error %R writing %s artifact output.",
                   os->rc, fsl_satype_cstr(d->type));
  }
  fsl_error_clear(&os->error);
  return os->rc ? os->rc : rc;
}

/* Timestamps might be adjusted slightly to ensure that checkins appear
   on the timeline in chronological order.  This is the maximum amount
   of the adjustment window, in days.
*/
#define AGE_FUDGE_WINDOW      (2.0/86400.0)       /* 2 seconds */

/* This is increment (in days) by which timestamps are adjusted for
   use on the timeline.
*/
#define AGE_ADJUST_INCREMENT  (25.0/86400000.0)   /* 25 milliseconds */

/**
   Adds a record in the pending_xlink temp table, to be processed
   when crosslinking is completed. Returns 0 on success, non-0 for
   db error.
*/
static int fsl__deck_crosslink_add_pending(fsl_cx * f, char cType, fsl_uuid_cstr uuid){
  assert(f->cache.isCrosslinking);
  return fsl_cx_exec(f,
                   "INSERT OR IGNORE INTO {{temp.pending_xlink}} VALUES('%c%q')",
                   cType, uuid);
}

/** @internal

    Add a single entry to the mlink table.  Also add the filename to
    the filename table if it is not there already.

    Parameters:

    pmid: Record for parent manifest. Use 0 to indicate no parent.

    zFromUuid: UUID for the content in parent (the new ==mlink.pid). 0
    or "" to add file.

    mid: The record ID of the manifest

    zToUuid:UUID for the mlink.fid. "" to delete

    zFilename: Filename

    zPrior: Previous filename. NULL if unchanged

    isPublic:True if mid is not a private manifest

    isPrimary: true if pmid is the primary parent of mid.

    mperm: permissions
 */
static
int fsl_mlink_add_one( fsl_cx * f,
                       fsl_id_t pmid, fsl_uuid_cstr zFromUuid,
                       fsl_id_t mid, fsl_uuid_cstr zToUuid,
                       char const * zFilename,
                       char const * zPrior,
                       bool isPublic,
                       bool isPrimary,
                       fsl_fileperm_e mperm){
  fsl_id_t fnid, pfnid, pid, fid;
  fsl_db * db = fsl_cx_db_repo(f);
  fsl_stmt * s1 = NULL;
  int rc;
  bool doInsert = false;
  assert(f);
  assert(db);
  assert(db->impl.txn.level>0);
  //MARKER(("%s() pmid=%d mid=%d\n", __func__, (int)pmid, (int)mid));

  rc = fsl__repo_filename_fnid2(f, zFilename, &fnid, 1);
  if(rc) return rc;
  if( zPrior && *zPrior ){
    rc = fsl__repo_filename_fnid2(f, zPrior, &pfnid, 1);
    if(rc) return rc;
  }else{
    pfnid = 0;
  }
  if( zFromUuid && *zFromUuid ){
    pid = fsl__uuid_to_rid2(f, zFromUuid, FSL_PHANTOM_PUBLIC);
    if(pid<0){
      assert(f->error.code);
      if(FSL_RC_SHUNNED==f->error.code){
        /* The prior file version was shunned: unavailable, not an
        ** error. Mirror fossil(1)'s content_new(), which returns 0
        ** for a shunned uuid. */
        fsl_cx_err_reset(f);
        pid = 0;
      }else{
        return f->error.code;
      }
    }
  }else{
    pid = 0;
  }

  if( zToUuid && *zToUuid ){
    fid = fsl__uuid_to_rid2(f, zToUuid, FSL_PHANTOM_PUBLIC);
    if(fid<0){
      assert(f->error.code);
      if(FSL_RC_SHUNNED==f->error.code){
        fsl_cx_err_reset(f);
        fid = 0;
      }else{
        return f->error.code;
      }
    }else if( isPublic ){
      rc = fsl_content_make_public(f, fid);
      if(rc) return rc;
    }
  }else{
    fid = 0;
  }

  if(isPrimary){
    doInsert = true;
  }else{
    fsl_stmt * sInsCheck = 0;
    rc = fsl_db_prepare_cached(db, &sInsCheck,
                               "SELECT 1 FROM {{dbname.repo}}.mlink WHERE "
                               "mid=? AND fnid=? AND NOT isaux"
                               "/*%s()*/",__func__);
    if(rc){
      rc = fsl_cx_uplift_db_error(f, db);
      goto end;
    }
    fsl_stmt_bind_id(sInsCheck, 1, mid);
    fsl_stmt_bind_id(sInsCheck, 2, fnid);
    rc = fsl_stmt_step(sInsCheck);
    fsl_stmt_cached_yield(sInsCheck);
    doInsert = (FSL_RC_STEP_ROW==rc) ? true : false;
    rc = 0;
  }
  if(doInsert){
    rc = fsl_db_prepare_cached(db, &s1,
                               "INSERT INTO {{dbname.repo}}.mlink("
                               "mid,fid,pmid,pid,"
                               "fnid,pfnid,mperm,isaux"
                               ")VALUES("
                               ":m,:f,:pm,:p,:n,:pfn,:mp,:isaux"
                               ")"
                               "/*%s()*/",__func__);
    if(!rc){
      fsl_stmt_bind_id_name(s1, ":m", mid);
      fsl_stmt_bind_id_name(s1, ":f", fid);
      fsl_stmt_bind_id_name(s1, ":pm", pmid);
      fsl_stmt_bind_id_name(s1, ":p", pid);
      fsl_stmt_bind_id_name(s1, ":n", fnid);
      fsl_stmt_bind_id_name(s1, ":pfn", pfnid);
      fsl_stmt_bind_int32_name(s1, ":mp", (int32_t)mperm);
      fsl_stmt_bind_int32_name(s1, ":isaux", isPrimary ? 0 : 1);
      rc = fsl_stmt_step(s1);
      fsl_stmt_cached_yield(s1);
      if(FSL_RC_STEP_DONE==rc){
        rc = 0;
      }else{
        fsl_cx_uplift_db_error(f, db);
      }
    }
  }
  if(!rc && pid>0 && fid){
    /* Reminder to self: this costs almost 1ms per checkin in very
       basic tests with 2003 checkins on my NUC unit. */
    rc = fsl__content_deltify(f, pid, fid, 0);
  }
  end:
  if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  return rc;
}

/**
    Do a binary search to find a file in d->F.list.

    As an optimization, guess that the file we seek is at index
    d->F.cursor.  That will usually be the case.  If it is not found
    there, then do the actual binary search.

    Update d->F.cursor to be the index of the file that is found.

    If d->f is NULL then this perform a case-sensitive search,
    otherwise it uses case-sensitive or case-insensitive,
    depending on f->cache.caseInsensitive.

    If the 3rd argument is not NULL and non-NULL is returned then
    *atNdx gets set to the d->F.list index of the resulting object.
    If NULL is returned, *atNdx is not modified.

    Reminder to self: if this requires a non-const deck (and it does
    right now) then the whole downstream chain will require a
    non-const instance or they'll have to make local copies to make
    the manipulation of d->F.cursor legal (but that would break
    following of baselines without yet more trickery).

    Reminder to self:

    Fossil(1) added another parameter to this since it was ported,
    indicating whether only an exact match or the "closest match" is
    acceptable, but currently (2021-03-10) only the fusefs module uses
    the closest-match option. It's a trivial code change but currently
    looks like YAGNI.
*/
static fsl_card_F * fsl__deck_F_seek_base(fsl_deck * d,
                                         char const * zName,
                                         uint32_t * atNdx,
                                         bool nocase ){
  /* Maintenance reminder: this algo relies on the various
     counters being signed. */
  fsl_int_t lwr, upr;
  int c;
  fsl_int_t i;
  assert(d);
  assert(zName && *zName);
  if(!d->F.used) return NULL;
  else if(FSL__CARD_F_LIST_NEEDS_SORT & d->F.flags){
    fsl_card_F_list_sort(&d->F);
  }
  /* The list is sorted by fsl_strcmp(), so the binary search must
     compare with fsl_strcmp() too: fsl_stricmp() orders some names
     differently (for example "Zy" and "_x") and would miss entries.
     If nocase is true and filenames are case-insensitive, a
     case-insensitive match is then found by a linear scan. Artifact
     processing such as crosslinking passes false, so that names match
     byte for byte, as in fossil(1). */
  bool const caseSensitive = d->f
    ? fsl_cx_is_case_sensitive(d->f, false) : true;
#define FCARD(NDX) F_at(&d->F, (NDX))
  lwr = 0;
  upr = d->F.used-1;
  if( d->F.cursor>=lwr && d->F.cursor<upr ){
    c = fsl_strcmp(FCARD(d->F.cursor+1)->name, zName);
    if( c==0 ){
      if(atNdx) *atNdx = (uint32_t)d->F.cursor+1;
      return FCARD(++d->F.cursor);
    }else if( c>0 ){
      upr = d->F.cursor;
    }else{
      lwr = d->F.cursor+1;
    }
  }
  while( lwr<=upr ){
    i = (lwr+upr)/2;
    c = fsl_strcmp(FCARD(i)->name, zName);
    if( c<0 ){
      lwr = i+1;
    }else if( c>0 ){
      upr = i-1;
    }else{
      d->F.cursor = i;
      if(atNdx) *atNdx = (uint32_t)i;
      return FCARD(i);
    }
  }
  if( nocase && !caseSensitive ){
    for( i=0; i<(fsl_int_t)d->F.used; ++i ){
      if( 0==fsl_stricmp(FCARD(i)->name, zName) ){
        d->F.cursor = i;
        if(atNdx) *atNdx = (uint32_t)i;
        return FCARD(i);
      }
    }
  }
  return NULL;
#undef FCARD
}

/**
   Implementation of fsl__deck_F_seek2() and fsl_deck_F_search2():
   sets *rv to d's entry for zName or NULL, and returns 0, or an error
   code if the search cannot be done (a delta manifest's baseline
   cannot be loaded). nocase is passed on to fsl__deck_F_seek_base().
*/
static int fsl__deck_F_seek_impl(fsl_deck * const d, const char *zName,
                                 bool nocase, fsl_card_F ** rv){
  fsl_card_F *pFile;
  assert(d);
  assert(zName && *zName);
  *rv = NULL;
  if(!d || (FSL_SATYPE_CHECKIN!=d->type) || !zName || !*zName
     || (!d->F.used && !d->B.uuid)) return 0;
  /* A delta manifest with no F-cards of its own still has its
     baseline's files, so only a baseline with no F-cards is empty. */
  pFile = d->F.used ? fsl__deck_F_seek_base(d, zName, NULL, nocase) : NULL;
  if( !pFile &&
      (d->B.baseline /* we have a baseline or... */
       || (d->f && d->B.uuid) /* we can load the baseline */
       )){
        /* Check baseline manifest...

           Sidebar: while the delta manifest model outwardly appears
           to support recursive delta manifests, fossil(1) does not
           use them and there would seem to be little practical use
           for them (no notable size benefit for the majority of
           cases), so we're not recursing here. If the baseline is
           itself a delta manifest, only its own F-cards are searched,
           as fossil(1) does.
         */
    int const rc = d->B.baseline ? 0 : fsl_deck_baseline_fetch(d);
    if(rc){
      assert(d->f->error.code);
      return rc;
    }else if( d->B.baseline ){
      assert(d->B.baseline->f && "How can this happen?");
      assert((d->B.baseline->f == d->f) &&
             "Universal laws are out of balance.");
      pFile = fsl__deck_F_seek_base(d->B.baseline, zName, NULL, nocase);
      if(pFile && !pFile->uuid){
        /* Per fossil-dev thread with DRH on 20140422, baselines never
           have removed files, but a baseline which is itself a delta
           manifest can. Such a file is not in d. */
        pFile = NULL;
      }
    }
  }
  *rv = pFile;
  return 0;
}

int fsl__deck_F_seek2(fsl_deck * const d, const char *zName,
                      fsl_card_F ** rv){
  return fsl__deck_F_seek_impl(d, zName, false, rv);
}

fsl_card_F * fsl__deck_F_seek(fsl_deck * const d, const char *zName){
  fsl_card_F * fc = NULL;
  (void)fsl__deck_F_seek_impl(d, zName, false, &fc);
  return fc;
}

int fsl_deck_F_search2(fsl_deck * d, const char *zName,
                       fsl_card_F const ** rv){
  fsl_card_F * fc = NULL;
  int const rc = fsl__deck_F_seek_impl(d, zName, true, &fc);
  *rv = fc;
  return rc;
}

fsl_card_F const * fsl_deck_F_search(fsl_deck *d, const char *zName){
  fsl_card_F * fc = NULL;
  assert(d);
  (void)fsl__deck_F_seek_impl(d, zName, true, &fc);
  return fc;
}

int fsl_deck_F_set( fsl_deck * d, char const * zName,
                    char const * uuid,
                    fsl_fileperm_e perms,
                    char const * priorName){
  uint32_t fcNdx = 0;
  fsl_card_F * fc = 0;
  if(d->rid>0){
    return fsl_cx_err_set(d->f, FSL_RC_MISUSE,
                          "%s() cannot be applied to a saved deck.",
                          __func__);
  }else if(!fsl_deck_check_type(d, 'F')){
    return d->f->error.code;
  }
  fc = fsl__deck_F_seek_base(d, zName, &fcNdx, false);
  if(!uuid){
    if(fc){
      fsl_card_F_list_remove(&d->F, fcNdx);
      return 0;
    }else{
      return FSL_RC_NOT_FOUND;
    }
  }else if(!fsl_is_uuid(uuid)){
    return fsl_cx_err_set(d->f, FSL_RC_RANGE,
                          "F-card hash invalid for %s: %s",
                          zName, uuid);
  }
  if(fc){
    /* Got a match. Replace its contents. */
    char * n = 0;
    if(!fc->deckOwnsStrings){
      /* We can keep fc->name but need a tiny bit of hoop-jumping
         to do so. */
      n = fc->name;
      fc->name = 0;
    }
    fsl_card_F_clean(fc);
    assert(!fc->deckOwnsStrings);
    if(!(fc->name = n ? n : fsl_strdup(zName))) return FSL_RC_OOM;
    if(!(fc->uuid = fsl_strdup(uuid))) return FSL_RC_OOM;
    if(priorName && *priorName){
      if(0==fsl_cx_filename_cmp(d->f, priorName, fc->name)){
        return fsl_cx_err_set(d->f, FSL_RC_MISUSE,
                              "An F-card's priorName must not be the same "
                              "as its original name: %s", priorName);
      }else if(!fsl_is_simple_pathname(priorName, true)){
        return fsl_cx_err_set(d->f, FSL_RC_RANGE,
                              "Invalid priorName for F-card "
                              "(simple form required): %s", priorName);
      }else if(!(fc->priorName = fsl_strdup(priorName))){
        return FSL_RC_OOM;
      }
    }
    fc->perm = perms;
    return 0;
  }else{
    return fsl_deck_F_add(d, zName, uuid, perms, priorName);
  }
}

int fsl_deck_F_set_content( fsl_deck * const d, char const * zName,
                            fsl_b const * const src,
                            fsl_fileperm_e perm,
                            char const * priorName){
  fsl_uuid_str zHash = 0;
  fsl_id_t rid = 0;
  fsl_id_t prevRid = 0;
  int rc = 0;
  assert(d->f);
  if(d->rid>0){
    return fsl_cx_err_set(d->f, FSL_RC_MISUSE,
                          "%s() cannot be applied to a saved deck.",
                          __func__);
  }else if(!fsl_cx_txn_level(d->f)){
    return fsl_cx_err_set(d->f, FSL_RC_MISUSE,
                          "%s() requires that a transaction is active.",
                          __func__);
  }else if(!fsl_is_simple_pathname(zName, true)){
    return fsl_cx_err_set(d->f, FSL_RC_RANGE,
                          "Filename is not valid for use as a repository "
                          "entry: %s", zName);
  }
  rc = fsl_repo_blob_lookup(d->f, src, &rid, &zHash);
  if(rc && FSL_RC_NOT_FOUND!=rc) goto end;
  assert(zHash);
  if(rid>0 && fsl_content_size(d->f, rid)<0){
    /* A phantom: this is the content it is waiting for. Storing it
       dephantomizes it, as receiving it by sync would. */
    rc = fsl__content_put_ex(d->f, src, zHash, 0, 0, false, &rid);
    if(rc) goto end;
  }else if(!rid){
    fsl_card_F const * fc;
    /* This is new content. Save it, then see if we have a previous version
       to delta against this one. */
    rc = fsl__content_put_ex(d->f, src, zHash, 0, 0, false, &rid);
    if(rc) goto end;
    fc = fsl__deck_F_seek(d, zName);
    if(fc){
      prevRid = fsl_uuid_to_rid(d->f, fc->uuid);
      if(prevRid<0){
        rc = d->f->error.code
          ? d->f->error.code
          : fsl_cx_err_set(d->f, FSL_RC_RANGE,
                           "Cannot resolve hash of previous version "
                           "of %s: [%s]", fc->name, fc->uuid);
        goto end;
      }
      else if(!prevRid){
        assert(!"cannot happen");
        rc = fsl_cx_err_set(d->f, FSL_RC_NOT_FOUND,
                            "Cannot find RID of file content %s [%s]\n",
                            fc->name, fc->uuid);
        goto end;
      }
      rc = fsl__content_deltify(d->f, prevRid, rid, false);
      if(rc) goto end;
    }
  }
  rc = fsl_deck_F_set(d, zName, zHash, perm, priorName);
  end:
  fsl_free(zHash);
  return rc;
}

void fsl__deck_clean_cards(fsl_deck * const d, char const * letters){
  char const * c = letters
    ? letters
    : "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for( ; *c; ++c ){
    switch(*c){
      case 'A': fsl_deck_clean_A(d); break;
      case 'B': fsl_deck_clean_B(d); break;
      case 'C': fsl_deck_clean_C(d); break;
      case 'D': d->D = 0.0; break;
      case 'E': fsl_deck_clean_E(d); break;
      case 'F': fsl_deck_clean_F(d); break;
      case 'G': fsl_deck_clean_G(d); break;
      case 'H': fsl_deck_clean_H(d); break;
      case 'I': fsl_deck_clean_I(d); break;
      case 'J': fsl_deck_clean_J(d); break;
      case 'K': fsl_deck_clean_K(d); break;
      case 'L': fsl_deck_clean_L(d); break;
      case 'M': fsl_deck_clean_M(d); break;
      case 'N': fsl_deck_clean_N(d); break;
      case 'P': fsl_deck_clean_P(d); break;
      case 'Q': fsl_deck_clean_Q(d); break;
      case 'R': fsl_deck_clean_R(d); break;
      case 'T': fsl_deck_clean_T(d); break;
      case 'U': fsl_deck_clean_U(d); break;
      case 'W': fsl_deck_clean_W(d); break;
      default: break;
    }
  }
}

int fsl_deck_derive(fsl_deck * const d){
  int rc = 0;
  assert(d->f);
  if(d->rid<=0){
    return fsl_cx_err_set(d->f, FSL_RC_MISUSE,
                          "Cannot derive from a %s deck which has not "
                          "been saved (rid=%" FSL_ID_T_PFMT ").",
                          fsl_satype_cstr(d->type), d->rid);
  }
  if(FSL_SATYPE_CHECKIN!=d->type){
    return fsl_cx_err_set(d->f, FSL_RC_TYPE,
                          "Cannot derive from %s artifact rid %"
                          FSL_ID_T_PFMT ": only check-ins are "
                          "supported.",
                          fsl_satype_cstr(d->type), d->rid);
  }
  fsl_deck_clean_P(d);
  {
    fsl_uuid_str pUuid = fsl_rid_to_uuid(d->f, d->rid);
    if(pUuid){
      rc = fsl_list_append(&d->P, pUuid);
      if(rc){
        assert(NULL==d->P.list);
        fsl_free(pUuid);
      }
    }else{
      assert(d->f->error.code);
      rc = d->f->error.code;
    }
    if(rc) return rc;
  }
  d->rid = 0;
  fsl__deck_clean_cards(d, "ACDEGHIJKLMNQRTUW");
  while(d->B.uuid){
    /* This is a delta manifest. Convert this deck into a baseline by
       building a new, complete F-card list. */
    fsl_card_F const * fc;
    fsl_card_F_list flist = fsl_card_F_list_empty;
    uint32_t fCount = 0;
    rc = fsl_deck_F_rewind(d);
    if(rc) return rc;
    fsl_deck_F_each(d, fc, rc){
      ++fCount;
    }
    rc = fsl_deck_F_rewind(d);
    assert(0==rc
           && "fsl_deck_F_rewind() cannot fail after initial call.");
    assert(0==d->F.cursor);
    assert(0==d->B.baseline->F.cursor);
    rc = fsl_card_F_list_reserve(&flist, fCount);
    fsl_deck_F_each(d, fc, rc){
      fsl_card_F * const fNew = fsl_card_F_list_push(&flist);
      assert(fc->uuid);
      assert(fc->name);
      /* We must copy these strings because their ownership is
         otherwise unmanageable. e.g. they might live in d->content
         or d->B.baseline->content. */
      if(!(fNew->name = fsl_strdup(fc->name))
         || !(fNew->uuid = fsl_strdup(fc->uuid))){
        /* Reminder: we do not want/need to copy fc->priorName. Those
           renames were already applied in the parent checkin. */
        rc = FSL_RC_OOM;
        break;
      }
      fNew->perm = fc->perm;
    }
    fsl_deck_clean_B(d);
    fsl_deck_clean_F(d);
    if(rc) fsl_card_F_list_finalize(&flist);
    else d->F = flist/*transfer ownership*/;
    break;
  }
  return rc;
}

/**
    Returns true if repo contains an mlink entry where mid=rid, else
    false. Errors are ingored.
*/
static bool fsl_repo_has_mlink_mid( fsl_db * repo, fsl_id_t rid ){
#if 0
  return fsl_db_exists(repo,
                       "SELECT 1 FROM {{dbname.repo}}.mlink WHERE mid=%"FSL_ID_T_PFMT,
                       rid);
#else
  fsl_stmt * st = NULL;
  bool gotone = false;
  int rc = fsl_db_prepare_cached(repo, &st,
                                 "SELECT 1 FROM {{dbname.repo}}.mlink WHERE mid=?"
                                 "/*%s()*/",__func__);
  if(!rc){
    fsl_stmt_bind_id(st, 1, rid);
    rc = fsl_stmt_step(st);
    fsl_stmt_cached_yield(st);
    gotone = rc==FSL_RC_STEP_ROW;
  }
  return gotone;
#endif
}

static bool fsl_repo_has_mlink_pmid_mid( fsl_db * repo, fsl_id_t pmid, fsl_id_t mid ){
  fsl_stmt * st = NULL;
  int rc = fsl_db_prepare_cached(repo, &st,
                                 "SELECT 1 FROM {{dbname.repo}}.mlink WHERE mid=? "
                                 "AND pmid=?"
                                 "/*%s()*/",__func__);
  if(!rc){
    fsl_stmt_bind_id(st, 1, mid);
    fsl_stmt_bind_id(st, 2, pmid);
    rc = fsl_stmt_step(st);
    fsl_stmt_cached_yield(st);
    if( rc==FSL_RC_STEP_ROW ) rc = 0;
  }
  /* MARKER(("fsl_repo_has_mlink_mid(%d) rc=%d\n", (int)rid, rc)); */
  return rc ? false : true;
}

/**
    Add mlink table entries associated with manifest cid, pChild.  The
    parent manifest is pid, pParent.  One of either pChild or pParent
    will be NULL and it will be computed based on cid/pid.

    A single mlink entry is added for every file that changed content,
    name, and/or permissions going from pid to cid.

    Deleted files have mlink.fid=0.

    Added files have mlink.pid=0.

    File added by merge have mlink.pid=-1.

    Edited files have both mlink.pid!=0 and mlink.fid!=0

    Comments from the original implementation:

    Many mlink entries for merge parents will only be added if another
    mlink entry already exists for the same file from the primary
    parent.  Therefore, to ensure that all merge-parent mlink entries
    are properly created:

    (1) Make this routine a no-op if pParent is a merge parent and the
        primary parent is a phantom.

    (2) Invoke this routine recursively for merge-parents if pParent
        is the primary parent.
*/
static int fsl_mlink_add( fsl_cx * const f,
                          fsl_id_t pmid, fsl_deck /*const*/ * pParent,
                          fsl_id_t cid, fsl_deck /*const*/ * pChild,
                          bool isPrimary){
#if 0
  fsl_cx_err_reset(f);
#endif
  fsl_b * const otherContent = fsl__cx_buffer_borrow(f, false);
  if( !otherContent ) return FSL_RC_OOM;
  fsl_id_t otherRid;
  fsl_size_t i = 0;
  int rc = 0;
  fsl_card_F const * pChildFile = NULL;
  fsl_card_F const * pParentFile = NULL;
  /* A lookup which fails is an error here, never an absent file. */
#define SEEK(DECK,NAME,DEST) do{                                   \
    fsl_card_F * fc__ = NULL;                                      \
    rc = fsl__deck_F_seek2((DECK), (NAME), &fc__);                 \
    (DEST) = fc__;                                                 \
  }while(0)
  fsl_deck dOther = fsl_deck_empty;
  fsl_db * const db = fsl_cx_db_repo(f);
  bool isPublic;
  assert(db);
  assert(db->impl.txn.level>0);
  /* If mlink table entires are already set for pmid/cid, then abort
     early doing no work.
  */
  //MARKER(("%s() pmid=%d cid=%d\n", __func__, (int)pmid, (int)cid));
  if(fsl_repo_has_mlink_pmid_mid(db, pmid, cid)) goto end;
  /* Compute the value of the missing pParent or pChild parameter.
     Fetch the baseline checkins for both.
  */
  assert( pParent==0 || pChild==0 );
  if( pParent ){
    assert(!pChild);
    pChild = &dOther;
    otherRid = cid;
  }else{
    pParent = &dOther;
    otherRid = pmid;
  }

  if(otherRid && !fsl__cx_mcache_search(f, otherRid, &dOther)){
    rc = fsl_content_get(f, otherRid, otherContent);
    if(rc){
      fsl_check_oom_rc(rc);
      /* fossil(1) treats a not-yet-available parent/child as a no-op:
         content_get() yields empty content for a phantom and add_mlink()
         does "if(blob_size==0) return;" with no error. libfossil's
         fsl_content_get() instead returns FSL_RC_PHANTOM (size<0 row) or
         FSL_RC_NOT_FOUND (rid in the "missing" ptl-set) for that same
         not-available condition. BOTH must be treated as the no-op:
         catching only FSL_RC_PHANTOM (the previous behavior) let
         FSL_RC_NOT_FOUND propagate, aborting crosslink and rolling back
         the savepoint -- which dropped a checkin's plink and its
         freshly-created parent phantom. The mlink entries are (re)computed
         when the parent dephantomizes. */
      if(FSL_RC_PHANTOM==rc || FSL_RC_NOT_FOUND==rc){
        /* Tolerated, not a real error -- but fsl_content_get()/
        ** fsl_content_raw() called fsl_cx_err_set() on the way to
        ** this rc, and f->error is process-wide state, not scoped to
        ** this call. Left uncleared, it lingers after this function
        ** returns 0: fsl_cx_b_borrow() refuses to hand out a
        ** buffer at all while f->error.code is set ("if(f->error.code)
        ** return 0"), so the next unrelated caller anywhere in the
        ** same crosslink/rebuild pass that borrows a buffer silently
        ** gets NULL/FSL_RC_OOM instead of the real buffer it needed --
        ** which is how a phantom tolerated *here* previously caused an
        ** unrelated, already-delivered blob to be misreported as an
        ** unfetchable phantom later in the same pass. */
        fsl_cx_err_reset(f);
        rc = 0;
      }else if(!f->error.msg.used && FSL_RC_OOM!=rc){
        rc = fsl_cx_err_set(f, rc,
                            "Fetching content of rid %"FSL_ID_T_PFMT" failed: %s",
                            otherRid, fsl_rc_cstr(rc));
        fsl_check_oom_rc(rc);
      }
      goto end;
    }
    if( !otherContent->used ){
      /* ??? fossil(1) ignores this case and returns. Same
      ** stale-f->error hazard as the FSL_RC_PHANTOM/FSL_RC_NOT_FOUND
      ** case above: clear it so it can't block a later, unrelated
      ** fsl_cx_b_borrow() call in this same crosslink pass. */
      fsl_cx_err_reset(f);
      rc = 0;
      goto end;
    }
    dOther.f = f;
    rc = fsl_deck_parse2(&dOther, otherContent, otherRid);
    assert(dOther.f == f);
    if(rc){
      fsl_check_oom_rc(rc);
      if(FSL_RC_SYNTAX==rc){
        /* The other side isn't actually a manifest. Rare, but real: a
        ** parent/child reference can resolve to non-manifest content
        ** in a real-world repository. fossil(1)'s own add_mlink() is
        ** null-tolerant here by construction (manifest_parse() returns
        ** NULL, the caller just returns); mirror that instead of
        ** propagating the parse failure as a hard error. No file-level
        ** diff is possible for this pairing, which is not itself an
        ** error condition. */
        fsl_cx_err_reset(f);
        rc = 0;
      }
      goto end;
    }
  }
  if( (pParent->f && (rc=fsl_deck_baseline_fetch(pParent)))
      || (pChild->f && (rc=fsl_deck_baseline_fetch(pChild)))){
    /* fossil(1)'s add_mlink() does "if(fetch_baseline(...)) return;" with
    ** no error when a baseline is not yet available; the mlink entries are
    ** computed later, when the baseline dephantomizes.
    ** fsl_deck_baseline_fetch() reports that deferred condition as
    ** FSL_RC_PHANTOM (it has recorded an orphan row). Treat it as the same
    ** no-op rather than propagating the error. */
    if(FSL_RC_PHANTOM==rc){
      fsl_cx_err_reset(f);
      rc = 0;
    }
    goto end;
  }
  isPublic = !fsl_content_is_private(f, cid);

  /* If pParent is not the primary parent of pChild, and the primary
  ** parent of pChild is a phantom, then abort this routine without
  ** doing any work.  The mlink entries will be computed when the
  ** primary parent dephantomizes.
  */
  if( !isPrimary && otherRid==cid ){
    assert(pChild->P.used);
    if(!fsl_db_exists(db,"SELECT 1 FROM {{dbname.repo}}.blob WHERE uuid=%Q AND size>0",
                      (char const *)pChild->P.list[0])){
      rc = 0;
      fsl_cx_err_reset(f);
      fsl__cx_mcache_insert(f, &dOther);
      goto end;
    }
  }

  if(pmid>0){
    /* Try to make the parent manifest a delta from the child, if that
       is an appropriate thing to do.  For a new baseline, make the
       previous baseline a delta from the current baseline.
    */
    if( (pParent->B.uuid==0)==(pChild->B.uuid==0) ){
      rc = fsl__content_deltify(f, pmid, cid, 0);
      fsl_check_oom_rc(rc);
    }else if( pChild->B.uuid==NULL && pParent->B.uuid!=NULL ){
      rc = fsl__content_deltify(f, pParent->B.baseline->rid, cid, 0);
      fsl_check_oom_rc(rc);
    }
    if(rc) goto end;
  }

  /* Remember all children less than a few seconds younger than their parent,
     as we might want to fudge the times for those children.
  */
  if( f->cache.isCrosslinking &&
      (pChild->D < pParent->D+AGE_FUDGE_WINDOW)
  ){
    rc = fsl_db_exec(db, "INSERT OR REPLACE INTO {{temp.time_fudge}} VALUES"
                     "(%"FSL_ID_T_PFMT", %"FSL_JULIAN_T_PFMT
                     ", %"FSL_ID_T_PFMT", %"FSL_JULIAN_T_PFMT");",
                     pParent->rid, pParent->D,
                     pChild->rid, pChild->D);
    fsl_check_oom_rc(rc);
    if(rc) goto end;
  }

  /* First look at all files in pChild, ignoring its baseline.  This
     is where most of the changes will be found.
  */
#define FCARD(DECK,NDX) \
  ((((NDX)<(DECK)->F.used)) \
   ? F_at(&(DECK)->F,NDX)  \
   : NULL)
  for(i=0, pChildFile=FCARD(pChild,0);
      0==rc && i<pChild->F.used;
      ++i, pChildFile=FCARD(pChild,i)){
    fsl_fileperm_e const mperm = pChildFile->perm;
    if( pChildFile->priorName ){
      pParentFile = NULL;
      if( pmid ){
        SEEK(pParent, pChildFile->priorName, pParentFile);
        if( rc ) break;
      }
      if( pParentFile ){
        /* File with name change */
        /*
          libfossil checkin 8625a31eff708dea93b16582e4ec5d583794d1af
          contains these two interesting F-cards:

F src/net/wanderinghorse/libfossil/FossilCheckout.java
F src/org/fossil_scm/libfossil/Checkout.java 6e58a47089d3f4911c9386c25bac36c8e98d4d21 w src/net/wanderinghorse/libfossil/FossilCheckout.java

          Note the placement of FossilCheckout.java (twice).

          Up until then, i thought a delete/rename combination was not possible.
        */
        rc = fsl_mlink_add_one(f, pmid, pParentFile->uuid,
                               cid, pChildFile->uuid, pChildFile->name,
                               pChildFile->priorName, isPublic,
                               isPrimary, mperm);
        fsl_check_oom_rc(rc);
      }else{
         /* File name changed, but the old name is not found in the parent!
            Treat this like a new file. */
        rc = fsl_mlink_add_one(f, pmid, 0, cid, pChildFile->uuid,
                               pChildFile->name, 0,
                               isPublic, isPrimary, mperm);
        fsl_check_oom_rc(rc);
      }
    }else if(pmid){
      SEEK(pParent, pChildFile->name, pParentFile);
      if( rc ) break;
      if(!pParentFile || !pParentFile->uuid){
        /* Parent does not have it or it was removed in parent. */
        if( pChildFile->uuid ){
          /* A new or re-added file */
          rc = fsl_mlink_add_one(f, pmid, 0, cid, pChildFile->uuid,
                                 pChildFile->name, 0,
                                 isPublic, isPrimary, mperm);
          fsl_check_oom_rc(rc);
        }
      }else if( fsl_strcmp(pChildFile->uuid, pParentFile->uuid)!=0
                || (pParentFile->perm!=mperm) ){
        /* Changes in file content or permissions */
        rc = fsl_mlink_add_one(f, pmid, pParentFile->uuid,
                               cid, pChildFile->uuid,
                               pChildFile->name, 0,
                               isPublic, isPrimary, mperm);
        fsl_check_oom_rc(rc);
      }
    }
  }/* end pChild card list loop */
  if(rc) goto end;
  else if( pParent->B.uuid && pChild->B.uuid ){
    /* Both parent and child are delta manifests.  Look for files that
       are deleted or modified in the parent but which reappear or revert
       to baseline in the child and show such files as being added or changed
       in the child. */
    for(i=0, pParentFile=FCARD(pParent,0);
        i<pParent->F.used;
        ++i, pParentFile = FCARD(pParent,i)){
      if( pParentFile->uuid ){
        pChildFile = fsl__deck_F_seek_base(pChild, pParentFile->name, NULL,
                                           false);
        if( !pChildFile || !pChildFile->uuid){
          /* The child file reverts to baseline or is deleted.
             Show this as a change. */
          if(!pChildFile){
            SEEK(pChild, pParentFile->name, pChildFile);
            if( rc ) goto end;
          }
          if( pChildFile && pChildFile->uuid ){
            rc = fsl_mlink_add_one(f, pmid, pParentFile->uuid, cid,
                                   pChildFile->uuid, pChildFile->name,
                                   0, isPublic, isPrimary,
                                   pChildFile->perm);
            fsl_check_oom_rc(rc);
          }
        }
      }else{
        /* Was deleted in the parent. */
        SEEK(pChild, pParentFile->name, pChildFile);
        if( rc ) goto end;
        if( pChildFile && pChildFile->uuid ){
          /* File resurrected in the child after having been deleted in
             the parent.  Show this as an added file. */
          rc = fsl_mlink_add_one(f, pmid, 0, cid, pChildFile->uuid,
                                 pChildFile->name, 0, isPublic,
                                 isPrimary, pChildFile->perm);
          fsl_check_oom_rc(rc);
        }
      }
      if(rc) goto end;
    }
    assert(0==rc);
  }else if( pmid && !pChild->B.uuid ){
    /* pChild is a baseline with a parent.  Look for files that are
       present in pParent but are missing from pChild and mark them as
       having been deleted. */
    fsl_card_F const * cfc = NULL;
    fsl_deck_F_rewind(pParent);
    assert( 0==rc );
    fsl_deck_F_each(pParent, cfc, rc){
      pParentFile = cfc;
      SEEK(pChild, pParentFile->name, pChildFile);
      if( rc ) break;
      if( (!pChildFile || !pChildFile->uuid) && pParentFile->uuid ){
        rc = fsl_mlink_add_one(f, pmid, pParentFile->uuid, cid, 0,
                               pParentFile->name, 0, isPublic,
                               isPrimary, pParentFile->perm);
        fsl_check_oom_rc(rc);
      }
    }
    if(rc) goto end;
  }

  /* If pParent is the primary parent of pChild, also run this analysis
  ** for all merge parents of pChild */
  if( pmid && isPrimary ){
    for(i=1; i<pChild->P.used; i++){
      pmid = fsl_uuid_to_rid(f, (char const*)pChild->P.list[i]);
      if( pmid<=0 ) continue;
      rc = fsl_mlink_add(f, pmid, 0, cid, pChild, false);
      fsl_check_oom_rc(rc);
      if(rc) goto end;
    }
    for(i=0; i<pChild->Q.used; i++){
      fsl_card_Q const * q = (fsl_card_Q const *)pChild->Q.list[i];
      if( q->type>0 && (pmid = fsl_uuid_to_rid(f, q->target))>0 ){
        rc = fsl_mlink_add(f, pmid, 0, cid, pChild, false);
        fsl_check_oom_rc(rc);
        if(rc) goto end;
      }
    }
  }
  fsl__cx_mcache_insert(f, &dOther);

  end:
  fsl_check_oom_rc(rc);
  fsl_cx_b_return(f, otherContent);
  fsl_deck_finalize(&dOther);
  if(rc && !f->error.code && db->error.code){
    rc = fsl_cx_uplift_db_error(f, db);
    fsl_check_oom_rc(rc);
  }
  return rc;
#undef SEEK
#undef FCARD
}

/**
   Apply all tags defined in deck d. If parentId is >0 then any
   propagating tags from that parent are well and duly propagated.
   Returns 0 on success. Potential TODO: if parentId<=0 and
   d->P.used>0 then use d->P.list[0] in place of parentId. Or apply
   from all parents (each one may propagate different tags).

   2026-06-16: does libf properly propagate tags from multiple
   parents?
*/
static int fsl__deck_crosslink_apply_tags(fsl_cx * f, fsl_deck *d,
                                         fsl_db * db, fsl_id_t rid,
                                         fsl_id_t parentId){
  int rc = 0;
  fsl_size_t i;
  fsl_list const * li = &d->T;
  double tagTime = d->D;
  fsl__phantom_e const fantomMode = fsl_content_is_private(f, rid)
    ? FSL_PHANTOM_PRIVATE : FSL_PHANTOM_PUBLIC;
  if(li->used && tagTime<=0){
    tagTime = fsl_db_julian_now(db);
    if(tagTime<=0){
      rc = fsl_cx_uplift_db_error2(f, db, FSL_RC_DB);
      if(!f->error.code){
        rc = fsl_cx_err_set(f, rc, "Could not get the current time "
                            "for the T-cards of rid %" FSL_ID_T_PFMT ".",
                            rid);
      }
      goto end;
    }
  }
  for( i = 0; !rc && (i < li->used); ++i){
    fsl_id_t tid;
    fsl_card_T const * tag = (fsl_card_T const *)li->list[i];
    assert(tag);
    if(!tag->uuid){
      tid = rid;
    }else{
      /* A T-card may tag an artifact we have not received yet (common
      ** when cloning a large repo across many round-trips). fossil(1)'s
      ** manifest_crosslink() resolves the target with
      ** uuid_to_rid(zUuid, 1) -- i.e. phantomize=1 -- creating a phantom
      ** placeholder rather than failing (manifest.c). Mirror that with
      ** fsl__uuid_to_rid2(..., fantomMode) instead of the previous plain
      ** fsl_uuid_to_rid(), which returned 0 and tripped a fatal
      ** FSL_RC_RANGE below. */
      tid = fsl__uuid_to_rid2( f, tag->uuid, fantomMode);
    }
    if(tid<0){
      assert(f->error.code);
      if(FSL_RC_SHUNNED==f->error.code){
        /* The tag's target was shunned: unavailable, not an error.
        ** Falls through to the 0==tid skip below. */
        fsl_cx_err_reset(f);
        tid = 0;
      }else{
        rc = f->error.code;
        break;
      }
    }
    if(0==tid){
      /* fossil(1) silently skips a tag whose target still resolves to 0
      ** (manifest.c: "if( tid ){ ... tag_insert ... }"); do likewise
      ** rather than failing the whole crosslink. */
      continue;
    }
    rc = fsl__tag_insert(f, tag->type,
                        tag->name, tag->value,
                        rid, tagTime, tid, NULL);
  }
  if( !rc && (parentId>0) ){
    rc = fsl__tag_propagate_all(f, parentId);
  }
  end:
  return rc;
}

/**
   Part of the checkin crosslink machinery: create all appropriate
   plink and mlink table entries for d->P.

   If parentId is not NULL, *parentId gets assigned to the rid of the
   first parent, or 0 if d->P is empty.
*/
static int fsl_deck_add_checkin_linkages(fsl_deck *d, fsl_id_t * parentId){
  int rc = 0;
  fsl_size_t nLink = 0;
  char zBaseId[30] = {0}/*RID of baseline or "NULL" if no baseline */;
  fsl_size_t i;
  fsl_stmt q = fsl_stmt_empty;
  fsl_id_t _parentId = 0;
  fsl_cx * const f = d->f;
  fsl_db * const db = fsl_cx_db_repo(f);
  assert(f && db);
  if(!parentId) parentId = &_parentId;
  if(d->B.uuid){
    fsl_id_t const baseid = d->B.baseline
      ? d->B.baseline->rid
      : fsl_uuid_to_rid(d->f, d->B.uuid);
    if(baseid<0){
      rc = d->f->error.code;
      assert(0 != rc);
      fsl_check_oom_rc(rc);
      goto end;
    }
    assert(baseid>0);
    fsl_snprintf( zBaseId, sizeof(zBaseId),
                  "%"FSL_ID_T_PFMT,
                  baseid );
  }else{
    fsl_snprintf( zBaseId, sizeof(zBaseId), "NULL" );
  }
  *parentId = 0;
  for(i=0; i<d->P.used; ++i){
    char const * parentUuid = (char const *)d->P.list[i];
    fsl_id_t const pid = fsl__uuid_to_rid2(f, parentUuid, FSL_PHANTOM_PUBLIC);
    if(pid<0){
      assert(f->error.code);
      if(FSL_RC_SHUNNED==f->error.code){
        /* A shunned ancestor is simply unavailable, not an error: mirror
        ** fossil(1)'s content_new(), which returns 0 (not an error) for
        ** a shunned uuid. Skip recording this parent link; *parentId
        ** stays 0 if this was the primary (i==0) parent. */
        fsl_cx_err_reset(f);
        continue;
      }
      rc = f->error.code;
      goto end;
    }
    rc = fsl_db_exec(db, "INSERT OR IGNORE "
                     "INTO {{dbname.repo}}.plink(pid, cid, isprim, mtime, baseid) "
                     "VALUES(%"FSL_ID_T_PFMT", %"FSL_ID_T_PFMT
                     ", %d, %"FSL_JULIAN_T_PFMT", %s)",
                     pid, d->rid,
                     ((i==0) ? 1 : 0), d->D, zBaseId);
    fsl_check_oom_rc(rc);
    if(rc) goto end;
    if(0==i) *parentId = pid;
  }
  rc = fsl_mlink_add(f, *parentId, NULL, d->rid, d, true);
  fsl_check_oom_rc(rc);
  if(rc) goto end;
  nLink = d->P.used;
  for(i=0; i<d->Q.used; ++i){
    fsl_card_Q const * q = (fsl_card_Q const *)d->Q.list[i];
    if(q->type>0) ++nLink;
  }
  if(nLink>1){
    /* https://fossil-scm.org/home/info/8e44cf6f4df4f9f0 */
    /* Change MLINK.PID from 0 to -1 for files that are added by merge. */
    rc = fsl_db_exec(db,
                     "UPDATE {{dbname.repo}}.mlink SET pid=-1"
                     " WHERE mid=%"FSL_ID_T_PFMT
                     "   AND pid=0"
                     "   AND fnid IN "
                     "  (SELECT fnid FROM {{dbname.repo}}.mlink WHERE mid=%"FSL_ID_T_PFMT
                     " GROUP BY fnid"
                     "    HAVING count(*)<%d)",
                     d->rid, d->rid, (int)nLink
                     );
    fsl_check_oom_rc(rc);
    if(rc) goto end;
  }
  rc = fsl_db_prepare(db, &q,
                      "SELECT cid, isprim FROM {{dbname.repo}}.plink "
                      "WHERE pid=%"FSL_ID_T_PFMT,
                      d->rid);
  fsl_check_oom_rc(rc);
  while( !rc && (FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&q))) ){
    fsl_id_t const cid = fsl_stmt_g_id(&q, 0);
    int const isPrim = fsl_stmt_g_int32(&q, 1);
    /* This block is only hit a couple of times during a fresh rebuild (empty mlink/plink
       tables), but many times on a rebuilds if those tables are not emptied in advance? */
    assert(cid>0);
    rc = fsl_mlink_add(f, d->rid, d, cid, NULL, isPrim ? true : false);
    fsl_check_oom_rc(rc);
  }
  if(FSL_RC_STEP_DONE==rc) rc = 0;
  fsl_stmt_finalize(&q);
  if(rc) goto end;
  if( !d->P.used ){
    /* For root files (files without parents) add mlink entries
       showing all content as new.

       Historically, fossil has been unable to create such checkins
       because the initial checkin has no files.
    */
    int const isPublic = !fsl_content_is_private(f, d->rid);
    for(i=0; !rc && (i<d->F.used); ++i){
      fsl_card_F const * fc = F_at(&d->F, i);
      rc = fsl_mlink_add_one(f, 0, 0, d->rid, fc->uuid, fc->name, 0,
                             isPublic, 1, fc->perm);
    }
    fsl_check_oom_rc(rc);
  }
  end:
  fsl_check_oom_rc(rc);
  if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  return rc;
}

/**
   Applies the value of a "parent" tag (reparent) to the given
   artifact id. zTagVal must be the value of a parent tag (a list of
   full UUIDs). This is only to be run as part of fsl__crosslink_end().

   Returns 0 on success.

   POTENTIAL fixme: perhaps return without side effects if rid is not
   found (like fossil(1) does). That said, this step is only run after
   crosslinking and would only result in a not-found if the tagxref
   table contents is out of date.

   POTENTIAL fixme: fail without error if the tag value is malformed,
   under the assumption that the tag was intended for some purpose
   other than reparenting.
*/
static int fsl_crosslink_reparent(fsl_cx * f, fsl_id_t rid, char const *zTagVal){
  int rc = 0;
  char * zDup = 0;
  char * zPos;
  fsl_size_t maxP, nP = 0;
  fsl_deck d = fsl_deck_empty;
  fsl_list fakeP = fsl_list_empty
    /* fake P-card for purposes of passing the reparented deck through
       fsl_deck_add_checkin_linkages() */;
  maxP = (fsl_strlen(zTagVal)+1) / (FSL_STRLEN_SHA1+1);
  if(!maxP){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Reparent tag value [%s] for rid %"
                          FSL_ID_T_PFMT " is too short to hold a "
                          "parent hash.", zTagVal, rid);
  }
  rc = fsl_list_reserve(&fakeP, maxP);
  if(rc) return rc;
  zDup = fsl_strdup(zTagVal);
  if(!zDup){
    rc = FSL_RC_OOM;
    goto end;
  }
  /* Split zTagVal into list of parent IDs... */
  for( nP = 0, zPos = zDup; *zPos; ){
    char const * zBegin = zPos;
    for( ; *zPos && ' '!=*zPos; ++zPos){}
    if(' '==*zPos){
      *zPos = 0;
      ++zPos;
    }
    if(!fsl_is_uuid(zBegin)){
      rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid value [%s] in reparent tag value "
                          "[%s] for rid %"FSL_ID_T_PFMT".",
                          zBegin, zTagVal, rid);
      goto end;
    }
    fakeP.list[nP++] = (void *)zBegin;
  }
  assert(!rc);
  fakeP.used = nP;
  rc = fsl_deck_load_rid(f, &d, rid, FSL_SATYPE_ANY);
  if(rc) goto end;
  switch(d.type){
    case FSL_SATYPE_CHECKIN:
    case FSL_SATYPE_TECHNOTE:
    case FSL_SATYPE_WIKI:
    case FSL_SATYPE_FORUMPOST:
      break;
    default:
      rc = fsl_cx_err_set(f, FSL_RC_TYPE, "Invalid deck type (%s) "
                          "for use with the 'parent' tag.",
                          fsl_satype_cstr(d.type));
      goto end;
  }
  assert(d.rid==rid);
  assert(d.f);
  fsl_db * const db = fsl_cx_db_repo(f);
  rc = fsl_db_exec_multi(db,
                         "DELETE FROM {{dbname.repo}}.plink WHERE cid=%"FSL_ID_T_PFMT";"
                         "DELETE FROM {{dbname.repo}}.mlink WHERE mid=%"FSL_ID_T_PFMT";",
                         rid, rid);
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, db, rc);
    goto end;
  }
  fsl_list const origP = d.P;
  d.P = fakeP;
  rc = fsl_deck_add_checkin_linkages(&d, NULL);
  d.P = origP;

  end:
  fsl_deck_finalize(&d);
  fsl_list_reserve(&fakeP, 0);
  fsl_free(zDup);
  return rc;
}

/**
   Inserts plink entries for FORUM, WIKI, and TECHNOTE manifests. May
   assert for other manifest types. If a parent entry exists, it also
   propagates any tags for that parent. This is a no-op if
   the deck has no parents.
*/
static int fsl__deck_crosslink_fwt_plink(fsl_deck * d){
  int i;
  fsl_id_t parentId = 0;
  fsl_db * db;
  int rc = 0;
  assert(d->type==FSL_SATYPE_WIKI ||
         d->type==FSL_SATYPE_FORUMPOST ||
         d->type==FSL_SATYPE_TECHNOTE);
  assert(d->f);
  assert(d->rid>0);
  if(!d->P.used) return rc;
  db = fsl_cx_db_repo(d->f);
  fsl__phantom_e const fantomMode = fsl_content_is_private(d->f, d->rid)
    ? FSL_PHANTOM_PRIVATE : FSL_PHANTOM_PUBLIC;
  for(i=0; 0==rc && i<(int)d->P.used; ++i){
    fsl_id_t pid = fsl__uuid_to_rid2(d->f, (char const *)d->P.list[i],
                                    fantomMode);
    if(pid<0){
      assert(d->f->error.code);
      if(FSL_RC_SHUNNED==d->f->error.code){
        /* Unavailable, not an error: mirror fossil(1)'s content_new(),
        ** which returns 0 for a shunned uuid. Skip this parent link
        ** rather than inserting a bogus negative pid. */
        fsl_cx_err_reset(d->f);
        continue;
      }
      rc = d->f->error.code;
      break;
    }
    if(0==i) parentId = pid;
    rc = fsl_db_exec_multi(db,
                           "INSERT OR IGNORE INTO {{dbname.repo}}.plink"
                           "(pid, cid, isprim, mtime, baseid)"
                           "VALUES(%"FSL_ID_T_PFMT", %"FSL_ID_T_PFMT", "
                           "%d, %"FSL_JULIAN_T_PFMT", NULL)",
                           pid, d->rid, i==0, d->D);
    if(rc) rc = fsl_cx_uplift_db_error2(d->f, db, rc);
  }
  if(!rc && parentId){
    rc = fsl__tag_propagate_all(d->f, parentId);
  }
  return rc;
}

int fsl__call_xlink_listeners(fsl_deck * const d){
  int rc = 0;
  fsl_xlinker * xl = NULL;
  fsl_cx_err_reset(d->f);
  for( fsl_size_t i = 0; !rc && (i < d->f->xlinkers.used); ++i ){
    xl = d->f->xlinkers.list+i;
    rc = xl->f( d, xl->state );
  }
  if(rc && !d->f->error.code){
    assert(xl);
    rc = fsl_cx_err_set(d->f, rc, "Crosslink callback handler "
                        "'%s' failed with code %d (%s) for "
                        "artifact RID #%" FSL_ID_T_PFMT ".",
                        xl->name, rc, fsl_rc_cstr(rc),
                        d->rid);
  }
  return rc;
}

/**
   Overrideable crosslink listener which updates the timeline for
   attachment records.
*/
static int fsl_deck_xlink_f_attachment(fsl_deck * const d,
                                       void * state fsl__unused){
  if(FSL_SATYPE_ATTACHMENT!=d->type) return 0;
  int rc;
  fsl_db * const db = fsl_cx_db_repo(d->f);
  fsl_b * const comment = fsl__cx_scratchpad(d->f);
  const bool isAdd = (d->A.src && *d->A.src) ? 1 : 0;
  char attachToType = 'w'
    /* Assume wiki until we know otherwise, keeping in mind that the
       d->A.tgt might not yet be in the blob table, in which case
       we are unable to know, for certain, what the target is.
       That only affects the timeline (event table), though, not
       the crosslinking of the attachment itself. */;
  assert(db);
  (void)state;
  if(fsl_is_uuid(d->A.tgt)){
    if( fsl_db_exists(db, "SELECT 1 FROM {{dbname.repo}}.tag WHERE tagname='tkt-%q'",
                      d->A.tgt)){
      attachToType = 't' /* attach to a known ticket */;
    }else if( fsl_db_exists(db, "SELECT 1 FROM {{dbname.repo}}.tag WHERE tagname='event-%q'",
                            d->A.tgt)){
      attachToType = 'e' /* attach to a known technote (event) */;
    }
  }
  if('w'==attachToType){
    /* Attachment applies to a wiki page */
    if(isAdd){
      rc = fsl_b_appendf(comment,
                              "Add attachment \"%h\" "
                              "to wiki page [%h]",
                              d->A.name, d->A.tgt);
    }else{
      rc = fsl_b_appendf(comment,
                              "Delete attachment \"%h\" "
                              "from wiki page [%h]",
                              d->A.name, d->A.tgt);
    }
  }else if('e' == attachToType){/*technote*/
    if(isAdd){
      rc = fsl_b_appendf(comment,
                              "Add attachment [/artifact/%!S|%h] to "
                              "tech note [/technote/%!S|%S]",
                              d->A.src, d->A.name, d->A.tgt, d->A.tgt);
    }else{
      rc = fsl_b_appendf(comment,
                              "Delete attachment \"/artifact/%!S|%h\" "
                              "from tech note [/technote/%!S|%S]",
                              d->A.name, d->A.name, d->A.tgt,
                              d->A.tgt);
    }
  }else{
    /* Attachment applies to a ticket */
    if(isAdd){
      rc = fsl_b_appendf(comment,
                              "Add attachment [/artifact/%!S|%h] "
                              "to ticket [%!S|%S]",
                              d->A.src, d->A.name, d->A.tgt, d->A.tgt);
    }else{
      rc = fsl_b_appendf(comment,
                              "Delete attachment \"%h\" "
                              "from ticket [%!S|%S]",
                              d->A.name, d->A.tgt, d->A.tgt);
    }
  }
  if(!rc){
    rc = fsl_db_exec(db,
                     "REPLACE INTO {{dbname.repo}}.event(type,mtime,objid,user,comment)"
                     "VALUES("
                     "'%c',%"FSL_JULIAN_T_PFMT",%"FSL_ID_T_PFMT","
                     "%Q,%B)",
                     attachToType, d->D, d->rid, d->U, comment);
    if(rc) rc = fsl_cx_uplift_db_error2(d->f, db, rc);
  }
  fsl__cx_scratchpad_yield(d->f, comment);
  return rc;
}

/**
   Overrideable crosslink listener which updates the timeline for
   checkin records.
*/
static int fsl_deck_xlink_f_checkin(fsl_deck * const d,
                                    void * state fsl__unused){
  if(FSL_SATYPE_CHECKIN!=d->type) return 0;
  int rc;
  fsl_db * db;
  (void)state;
  db = fsl_cx_db_repo(d->f);
  assert(db);
  rc = fsl_db_exec(db,
       "REPLACE INTO {{dbname.repo}}.event(type,mtime,objid,user,comment,"
       "bgcolor,euser,ecomment,omtime)"
       "VALUES('ci',"
       "  coalesce(" /*mtime*/
       "    (SELECT julianday(value) FROM {{dbname.repo}}.tagxref "
       "      WHERE tagid=%d AND rid=%"FSL_ID_T_PFMT
       "    ),"
       "    %"FSL_JULIAN_T_PFMT""
       "  ),"
       "  %"FSL_ID_T_PFMT","/*objid*/
       "  %Q," /*user*/
#if 1
       "  %Q," /*comment. No, the comment _field_. */
#else
       /* just for testing... */
       "  'xlink: %q'," /*comment. No, the comment _field_. */
#endif
       "  (SELECT value FROM {{dbname.repo}}.tagxref " /*bgcolor*/
       "    WHERE tagid=%d AND rid=%"FSL_ID_T_PFMT
       "    AND tagtype>0"
       "  ),"
       "  (SELECT value FROM {{dbname.repo}}.tagxref " /*euser*/
       "    WHERE tagid=%d AND rid=%"FSL_ID_T_PFMT
       "  ),"
       "  (SELECT value FROM {{dbname.repo}}.tagxref " /*ecomment*/
       "    WHERE tagid=%d AND rid=%"FSL_ID_T_PFMT
       "  ),"
       "  %"FSL_JULIAN_T_PFMT/*omtime*/
       /* RETURNING coalesce(ecomment,comment)
          see comments below about zCom */
       ")",
       /* The casts here are to please the va_list. */
       (int)FSL_TAGID_DATE, d->rid, d->D,
       d->rid, d->U, d->C,
       (int)FSL_TAGID_BGCOLOR, d->rid,
       (int)FSL_TAGID_USER, d->rid,
       (int)FSL_TAGID_COMMENT, d->rid, d->D
  );
  if(0==rc){
    /* The comment as it now is, which a tag may have changed. */
    char * const zCom =
      fsl_db_g_text(db, NULL, "SELECT coalesce(ecomment,comment) "
                    "FROM {{dbname.repo}}.event "
                    "WHERE objid=%"FSL_ID_T_PFMT, d->rid);
    if(zCom){
      rc = fsl__backlink_extract(d->f, zCom, FSL_BKLNK_MT_NONE, d->rid,
                                 FSL_BKLNK_COMMENT, d->D, true);
      fsl_free(zCom);
      return rc;
    }
  }
  return fsl_cx_uplift_db_error2(d->f, db, rc);
}

static int fsl_deck_xlink_f_control(fsl_deck * const d,
                                    void * state fsl__unused){
  if(FSL_SATYPE_CONTROL!=d->type) return 0;
  /*
    Create timeline event entry for all tags in this control
    construct. Note that we are using a lot of historical code which
    hard-codes english-lanuage text and links which only work in
    fossil(1). This crosslinker can, however, be replaced by users
    concerned by that.
  */
  int rc = 0;
  fsl_b * const comment = fsl__cx_scratchpad(d->f);
  fsl_size_t i;
  const char *zName;
  const char *zValue;
  const char *zUuid;
  fsl_size_t nName;
  int branchMove = 0;
  int const uuidLen = 8;
  fsl_card_T const * tag = NULL;
  fsl_card_T const * prevTag = NULL;
  fsl_list const * li = &d->T;
  fsl_db * const db = fsl_cx_db_repo(d->f);
  double mtime = (d->D>0)
    ? d->D
    : fsl_db_julian_now(db);
  assert(db);
  (void)state;
  /**
     Reminder to self: fossil(1) has a comment here:

     // Next loop expects tags to be sorted on UUID, so sort it.
     qsort(p->aTag, p->nTag, sizeof(p->aTag[0]), tag_compare);

     That sort plays a role in hook code execution and is needed to
     avoid duplicate hook execution in some cases. libfossil
     outsources that type of thing to crosslink callbacks, though,
     so we won't concern ourselves with it here. We also don't
     really want to modify the deck during crosslinking. The only
     reason the deck is not const in this routine is because of the
     fsl_deck::F::cursor bits inherited from fossil(1), largely
     worth its cost except that many routines can no longer be
     const. Shame C doesn't have C++'s "mutable" keyword.

     That said, sorting by UUID would have a nice side-effect on the
     output of grouping tags by the UUID they tag. So far
     (201404) such groups of tags have not appeared in the wild
     because fossil(1) has no mechanism for creating them.
  */
  for( i = 0; !rc && (i < li->used); ++i, prevTag = tag){
    bool isProp = 0, isAdd = 0, isCancel = 0;
    tag = (fsl_card_T const *)li->list[i];
    zUuid = tag->uuid;
    if(!zUuid /*tag on self*/) continue;
    if( i==0 || 0!=fsl_uuidcmp(tag->uuid, prevTag->uuid)){
      rc = fsl_b_appendf(comment,
                              " Edit [%.*s]:", uuidLen, zUuid);
      branchMove = 0;
    }
    if(rc) goto end;
    isProp = FSL_TAGTYPE_PROPAGATING==tag->type;
    isAdd = FSL_TAGTYPE_ADD==tag->type;
    isCancel = FSL_TAGTYPE_CANCEL==tag->type;
    assert(isProp || isAdd || isCancel);
    zName = tag->name;
    nName = fsl_strlen(zName);
    zValue = tag->value;
    if( isProp && 0==fsl_strcmp(zName, "branch")){
      rc = fsl_b_appendf(comment,
                              " Move to branch %s"
                              "[/timeline?r=%h&nd&dp=%.*s | %h].",
                              zValue, zValue, uuidLen, zUuid, zValue);
      branchMove = 1;
    }else if( isProp && fsl_strcmp(zName, "bgcolor")==0 ){
      rc = fsl_b_appendf(comment,
                              " Change branch background color to \"%h\".", zValue);
    }else if( isAdd && fsl_strcmp(zName, "bgcolor")==0 ){
      rc = fsl_b_appendf(comment,
                              " Change background color to \"%h\".", zValue);
    }else if( isCancel && fsl_strcmp(zName, "bgcolor")==0 ){
      rc = fsl_b_appendf(comment, " Cancel background color.");
    }else if( isAdd && fsl_strcmp(zName, "comment")==0 ){
      rc = fsl_b_appendf(comment, " Edit check-in comment.");
    }else if( isAdd && fsl_strcmp(zName, "user")==0 ){
      rc = fsl_b_appendf(comment, " Change user to \"%h\".", zValue);
    }else if( isAdd && fsl_strcmp(zName, "date")==0 ){
      rc = fsl_b_appendf(comment, " Timestamp %h.", zValue);
    }else if( isCancel && nName>4 && fsl_strncmp(zName, "sym-",4)==0 ){
      if( !branchMove ){
        rc = fsl_b_appendf(comment, " Cancel tag %h.", zName+4);
      }
    }else if( isProp && nName>4 && fsl_strncmp(zName, "sym-",4)==0 ){
      if( !branchMove ){
        rc = fsl_b_appendf(comment, " Add propagating tag \"%h\".", zName+4);
      }
    }else if( isAdd && nName>4 && fsl_strncmp(zName, "sym-",4)==0 ){
      rc = fsl_b_appendf(comment, " Add tag \"%h\".", zName+4);
    }else if( isCancel && nName>4 && fsl_strncmp(zName, "sym-",4)==0 ){
      rc = fsl_b_appendf(comment, " Cancel tag \"%h\".", zName+4);
    }else if( isAdd && fsl_strcmp(zName, "closed")==0 ){
      rc = fsl_b_append(comment, " Marked \"Closed\"", -1);
      if( !rc && zValue && *zValue ){
        rc = fsl_b_appendf(comment, " with note \"%h\"", zValue);
      }
      if(!rc) rc = fsl_b_append(comment, ".", 1);
    }else if( isCancel && fsl_strcmp(zName, "closed")==0 ){
      rc = fsl_b_append(comment, " Removed the \"Closed\" mark", -1);
      if( !rc && zValue && *zValue ){
        rc = fsl_b_appendf(comment, " with note \"%h\"", zValue);
      }
      if(!rc) rc = fsl_b_append(comment, ".", 1);
    }else {
      if( isCancel ){
        rc = fsl_b_appendf(comment, " Cancel \"%h\"", zName);
      }else if( isAdd ){
        rc = fsl_b_appendf(comment, " Add \"%h\"", zName);
      }else{
        assert(isProp);
        rc = fsl_b_appendf(comment, " Add propagating \"%h\"", zName);
      }
      if(rc) goto end;
      if( zValue && zValue[0] ){
        rc = fsl_b_appendf(comment, " with value \"%h\".", zValue);
      }else{
        rc = fsl_b_append(comment, ".", 1);
      }
    }
  } /* foreach tag loop */
  if(!rc){
    /* TODO: cached statement */
    rc = fsl_db_exec(db,
                     "REPLACE INTO {{dbname.repo}}.event"
                     "(type,mtime,objid,user,comment) "
                     "VALUES('g',"
                     "%"FSL_JULIAN_T_PFMT","
                     "%"FSL_ID_T_PFMT","
                     "%Q,%Q)",
                     mtime, d->rid, d->U,
                     (comment->used>1)
                     ? (fsl_b_cstr(comment)
                        +1/*leading space on all entries*/)
                     : NULL);
    if(rc) rc = fsl_cx_uplift_db_error2(d->f, db, rc);
  }

  end:
  fsl__cx_scratchpad_yield(d->f, comment);
  return rc;

}

static fsl_id_t fsl__forum_ref_rid(fsl_cx * const f, fsl_uuid_cstr uuid,
                                   fsl__phantom_e mode, int * const rc);

static int fsl_deck_xlink_f_forum(fsl_deck * const d,
                                  void * state fsl__unused){
  if(FSL_SATYPE_FORUMPOST!=d->type) return 0;
  int rc = 0;
  fsl_db * const db = fsl_cx_db_repo(d->f);
  assert(db);
  fsl_cx * const f = d->f;
  fsl__phantom_e const fantomMode = fsl_content_is_private(f, d->rid)
    ? FSL_PHANTOM_PRIVATE : FSL_PHANTOM_PUBLIC;
  fsl_id_t froot = d->rid, fprev = 0, firt = 0;
  if( d->G ){ froot = fsl__forum_ref_rid(f, d->G, fantomMode, &rc); if(rc) return rc; }
  if( !rc && d->P.used ){ fprev = fsl__forum_ref_rid(f, (char const *)d->P.list[0], fantomMode, &rc); if(rc) return rc; }
  if( !rc && d->I ){ firt = fsl__forum_ref_rid(f, d->I, fantomMode, &rc); if(rc) return rc; }
  (void)state;
  if( 0==firt ){
    /* This is the start of a new thread, either the initial entry
    ** or an edit of the initial entry. */
    const char * zTitle = d->H;
    const char * zFType;
    if(!zTitle || !*zTitle){
      zTitle = "(Deleted)";
    }
    zFType = fprev ? "Edit" : "Post";
    /* FSL-MISSING:
       assert( manifest_event_triggers_are_enabled ); */
    rc = fsl_db_exec_multi(db,
        "REPLACE INTO {{dbname.repo}}.event(type,mtime,objid,user,comment)"
        "VALUES('f',%"FSL_JULIAN_T_PFMT",%" FSL_ID_T_PFMT
        ",%Q,'%q: %q')",
        d->D, d->rid, d->U, zFType, zTitle);
    if(rc) goto dberr;
      /*
      ** If this edit is the most recent, then make it the title for
      ** all other entries for the same thread
      */
    bool newer = false;
    rc = fsl_db_exists2(db, &newer, "SELECT 1 FROM {{dbname.repo}}.forumpost "
                        "WHERE froot=%" FSL_ID_T_PFMT " AND firt=0"
                        " AND fpid!=%" FSL_ID_T_PFMT
                        " AND fmtime>%"FSL_JULIAN_T_PFMT,
                        froot, d->rid, d->D);
    if(rc) goto dberr;
    if( !newer ){
        /* This entry establishes a new title for all entries on the thread */
      rc = fsl_db_exec_multi(db,
          "UPDATE {{dbname.repo}}.event"
          " SET comment=substr(comment,1,instr(comment,':')) || ' %q'"
          " WHERE objid IN (SELECT fpid FROM {{dbname.repo}}.forumpost WHERE froot=% " FSL_ID_T_PFMT ")",
          zTitle, froot);
      if(rc) goto dberr;
    }
  }else{
      /* This is a reply to a prior post.  Take the title from the root. */
    char const * zFType = 0;
    char * zTitle = fsl_db_g_text(
           db, 0, "SELECT substr(comment,instr(comment,':')+2)"
           "  FROM {{dbname.repo}}.event WHERE objid=%"FSL_ID_T_PFMT, froot);
    if( zTitle==0 ){
      zTitle = fsl_strdup("<i>Unknown</i>");
      if(!zTitle){
        rc = FSL_RC_OOM;
        goto end;
      }
    }
    if( !d->W.used ){
      zFType = "Delete reply";
    }else if( fprev ){
      zFType = "Edit reply";
    }else{
      zFType = "Reply";
    }
    /* FSL-MISSING:
       assert( manifest_event_triggers_are_enabled ); */
    rc = fsl_db_exec_multi(db,
        "REPLACE INTO {{dbname.repo}}.event(type,mtime,objid,user,comment)"
        "VALUES('f',%"FSL_JULIAN_T_PFMT
        ",%"FSL_ID_T_PFMT",%Q,'%q: %q')",
        d->D, d->rid, d->U, zFType, zTitle);
    fsl_free(zTitle);
    if(rc) goto dberr;
  }
  if( d->W.used ){
    rc = fsl__backlink_extract(f, fsl_b_cstr(&d->W),
                               fsl__backlink_mimetype(d->N), d->rid,
                               FSL_BKLNK_FORUM, d->D, true);
    if(rc) goto end;
  }
  end:
  return rc;
  dberr:
  assert(rc);
  assert(db->error.code);
  return fsl_cx_uplift_db_error(f, db);
}


static int fsl_deck_xlink_f_technote(fsl_deck * const d,
                                     void * state fsl__unused){
  if(FSL_SATYPE_TECHNOTE!=d->type) return 0;
  char buf[FSL_STRLEN_K256 + 7 /* event-UUID\0 */] = {0};
  fsl_id_t tagid;
  char const * zTag;
  int rc = 0;
  fsl_cx * const f = d->f;
  fsl_db * const db = fsl_cx_db_repo(d->f);

  (void)state;
  fsl_snprintf(buf, sizeof(buf), "event-%s", d->E.uuid);
  zTag = buf;
  tagid = fsl_tag_id( f, zTag, 1 );
  if(tagid<=0){
    return f->error.code ? f->error.code :
      fsl_cx_err_set(f, FSL_RC_RANGE,
                     "Got unexpected RID (%"FSL_ID_T_PFMT") "
                     "for tag [%s].",
                     tagid, zTag);
  }
  fsl_id_t const subsequent
    = fsl_db_g_id(db, 0,
                  "SELECT rid FROM {{dbname.repo}}.tagxref"
                  " WHERE tagid=%"FSL_ID_T_PFMT
                  " AND mtime>=%"FSL_JULIAN_T_PFMT
                  " AND rid!=%"FSL_ID_T_PFMT
                  " ORDER BY mtime",
                  tagid, d->D, d->rid);
  if(subsequent<0){
    rc = fsl_cx_uplift_db_error(d->f, db);
  }else if( 0==subsequent ){
    /* Only the newest version of a technote gets a timeline
       entry, as in fossil. */
    rc = fsl_db_exec(db,
                     "REPLACE INTO {{dbname.repo}}.event("
                     "type,mtime,"
                     "objid,tagid,"
                     "user,comment,bgcolor"
                     ")VALUES("
                     "'e',%"FSL_JULIAN_T_PFMT","
                     "%"FSL_ID_T_PFMT",%"FSL_ID_T_PFMT","
                     "%Q,%Q,"
                     "  (SELECT value FROM {{dbname.repo}}.tagxref WHERE "
                     "   tagid=%d"
                     "   AND rid=%"FSL_ID_T_PFMT")"
                     ");",
                     d->E.julian, d->rid, tagid,
                     d->U, d->C,
                     (int)FSL_TAGID_BGCOLOR, d->rid);
    if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  }
  return rc;
}

static int fsl_deck_xlink_f_wiki(fsl_deck * const d,
                                 void * state fsl__unused){
  if(FSL_SATYPE_WIKI!=d->type) return 0;
  int rc;
  char const * zWiki;
  fsl_size_t nWiki = 0;
  char cPrefix = 0;
  char * zTag = fsl_mprintf("wiki-%s", d->L);
  if(!zTag) return FSL_RC_OOM;
  fsl_id_t const tagid = fsl_tag_id( d->f, zTag, 1 );

  (void)state;
  if(tagid<=0){
    rc = fsl_cx_err_set(d->f, FSL_RC_ERROR,
                        "Tag [%s] must have been added by main wiki crosslink step.",
                        zTag);
    goto end;
  }
  /* Some of this is duplicated in the main wiki crosslinking code :/. */
  zWiki = d->W.used ? fsl_b_cstr(&d->W) : "";
  while( *zWiki && fsl_isspace(*zWiki) ){
    ++zWiki;
    /* Historical behaviour: strip leading spaces. */
  }
  /* As of late 2020, fossil changed the conventions for how wiki
     entries are to be added to the timeline. They requrie a prefix
     character which tells the timeline display and email notification
     generator code what type of change this is: create/update/delete */
  nWiki = fsl_strlen(zWiki);
  if(!nWiki) cPrefix = '-';
  else if( !d->P.used ) cPrefix = '+';
  else cPrefix = ':';
  fsl_db * const db = fsl_cx_db_repo(d->f);
  rc = fsl_db_exec(db,
                   "REPLACE INTO {{dbname.repo}}.event(type,mtime,objid,user,comment) "
                   "VALUES('w',%"FSL_JULIAN_T_PFMT
                   ",%"FSL_ID_T_PFMT",%Q,'%c%q%q%q');",
                   d->D, d->rid, d->U, cPrefix, d->L,
                   ((d->C && *d->C) ? ": " : ""),
                   ((d->C && *d->C) ? d->C : ""));
  /* Note that wiki pages optionally support d->C (change comment),
     but it's historically unused because it was a late addition to
     the artifact format and is not supported by older fossil
     versions. */
  rc = fsl_cx_uplift_db_error2(d->f, db, rc);
  end:
  fsl_free(zTag);
  return rc;
}


/** @internal

    Installs the core overridable crosslink listeners. "The plan" is
    to do all updates to the event (timeline) table via these
    crosslinkers and perform the core, UI-agnostic, crosslinking bits
    in the internal fsl__deck_crosslink_XXX() functions. That should
    allow clients to override how the timeline is updated without
    requiring them to understand the rest of the required schema
    updates.
*/
int fsl__cx_install_timeline_crosslinkers(fsl_cx * const f){
  int rc;
  assert(!f->xlinkers.used);
  assert(!f->xlinkers.list);
  rc = fsl_xlink_listener(f, "fsl/attachment/timeline",
                          fsl_deck_xlink_f_attachment, 0);
  if(!rc) rc = fsl_xlink_listener(f, "fsl/checkin/timeline",
                          fsl_deck_xlink_f_checkin, 0);
  if(!rc) rc = fsl_xlink_listener(f, "fsl/control/timeline",
                          fsl_deck_xlink_f_control, 0);
  if(!rc) rc = fsl_xlink_listener(f, "fsl/forumpost/timeline",
                          fsl_deck_xlink_f_forum, 0);
  if(!rc) rc = fsl_xlink_listener(f, "fsl/technote/timeline",
                          fsl_deck_xlink_f_technote, 0);
  if(!rc) rc = fsl_xlink_listener(f, "fsl/wiki/timeline",
                          fsl_deck_xlink_f_wiki, 0);
  return rc;
}


static int fsl__deck_crosslink_checkin(fsl_deck * const d,
                                      fsl_id_t *parentid ){
  int rc = 0;
  fsl_cx * const f = d->f;
  fsl_db * const db = fsl_cx_db_repo(f);

  /* TODO: convert these queries to cached statements, for
     the sake of rebuild and friends. And bind() doubles
     instead of %FSL_JULIAN_T_PFMT'ing them.
  */
  if(d->Q.used && fsl_db_table_exists(db, FSL_DBROLE_REPO,
                                      "cherrypick")){
    fsl_size_t i;
    for(i=0; i < d->Q.used; ++i){
      fsl_card_Q const * q = (fsl_card_Q const *)d->Q.list[i];
      rc = fsl_db_exec(db,
          "REPLACE INTO {{dbname.repo}}.cherrypick(parentid,childid,isExclude)"
          " SELECT rid, %"FSL_ID_T_PFMT", %d"
          " FROM {{dbname.repo}}.blob WHERE uuid=%Q",
          d->rid, q->type<0 ? 1 : 0, q->target
      );
      fsl_check_oom_rc(rc);
      if(rc) goto end;
    }
  }
  if(!fsl_repo_has_mlink_mid(db, d->rid)){
    rc = fsl_deck_add_checkin_linkages(d, parentid);
    fsl_check_oom_rc(rc);
    if(rc) goto end;
    /* FSL-MISSING:
       assert( manifest_event_triggers_are_enabled ); */
    rc = fsl__search_doc_touch(f, d->type, d->rid, 0);
    fsl_check_oom_rc(rc);
    if(rc) goto end;
    /* If this is a delta-manifest, record the fact that this repository
       contains delta manifests, to free the "commit" logic to generate
       new delta manifests. */
    if(d->B.uuid){
      rc = fsl__cx_update_seen_delta_deck(f);
      fsl_check_oom_rc(rc);
      if(rc) goto end;
    }
    assert(!rc);
  }/*!exists mlink*/
  end:
  if(rc && !f->error.code && db->error.code){
    fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}

static int fsl__deck_crosslink_wiki(fsl_deck *d){
  char zLength[40] = {0};
  fsl_id_t prior = 0;
  char const * zWiki;
  fsl_size_t nWiki = 0;
  int rc;
  char * zTag = fsl_mprintf("wiki-%s", d->L);
  fsl_cx * const f = d->f;
  fsl_db * const db = fsl_cx_db_repo(f);
  if(!zTag){
    return FSL_RC_OOM;
  }
  assert(f && db);
  zWiki = d->W.used ? fsl_b_cstr(&d->W) : "";
  while( *zWiki && fsl_isspace(*zWiki) ){
    ++zWiki;
    /* Historical behaviour: strip leading spaces. */
  }
  nWiki = fsl_strlen(zWiki)
    /* Reminder: use strlen instead of d->W.used just in case that
       one contains embedded NULs in the content. "Shouldn't
       happen," but the API doesn't explicitly prohibit it.
    */;
  fsl_snprintf(zLength, sizeof(zLength), "%"FSL_SIZE_T_PFMT,
               (fsl_size_t)nWiki);
  rc = fsl__tag_insert(f, FSL_TAGTYPE_ADD, zTag, zLength,
                      d->rid, d->D, d->rid, NULL );
  if(rc) goto end;
  if(d->P.used){
    prior = fsl_uuid_to_rid(f, (const char *)d->P.list[0]);
    if(prior<0){
      rc = f->error.code
        ? f->error.code
        : fsl_cx_err_set(f, FSL_RC_RANGE, "Cannot resolve P-card "
                         "of wiki page %s: %s", d->L,
                         (const char *)d->P.list[0]);
      goto end;
    }
  }
  if(prior>0){
    rc = fsl__content_deltify(f, prior, d->rid, 0);
    if(rc) goto end;
  }
  rc = fsl__search_doc_touch(f, d->type, d->rid, d->L);
  if(rc) goto end;
  if( f->cache.isCrosslinking ){
    rc = fsl__deck_crosslink_add_pending(f, 'w',d->L);
    if(rc) goto end;
  }else{
    rc = fsl__backlink_wiki_refresh(f, d->L);
    if(rc) goto end;
  }
  assert(0==rc);
  rc = fsl__deck_crosslink_fwt_plink(d);
  end:
  fsl_free(zTag);
  return rc;
}

static int fsl__deck_crosslink_attachment(fsl_deck * const d){
  int rc;
  fsl_cx * const f = d->f;
  fsl_db * const db = fsl_cx_db_repo(f);

  rc = fsl_db_exec(db,
                   /* REMINDER: fossil(1) uses INSERT here, but that
                      breaks libfossil crosslinking tests due to a
                      unique constraint violation on attachid. */
                   "REPLACE INTO {{dbname.repo}}.attachment(attachid, mtime, src, target,"
                   "filename, comment, user) VALUES("
                   "%"FSL_ID_T_PFMT",%"FSL_JULIAN_T_PFMT","
                   "%Q,%Q,%Q,"
                   "%Q,%Q);",
                   d->rid, d->D,
                   d->A.src, d->A.tgt, d->A.name,
                   (d->C ? d->C : ""), d->U);
  if(!rc){
    rc = fsl_db_exec(db,
                   "UPDATE {{dbname.repo}}.attachment SET isLatest = (mtime=="
                   "(SELECT max(mtime) FROM {{dbname.repo}}.attachment"
                   "  WHERE target=%Q AND filename=%Q))"
                   " WHERE target=%Q AND filename=%Q",
                   d->A.tgt, d->A.name,
                   d->A.tgt, d->A.name);
  }
  return rc;
}

static int fsl__deck_crosslink_cluster(fsl_deck * const d){
  /* Clean up the unclustered table... */
  fsl_size_t i;
  fsl_stmt * st = NULL;
  int rc;
  fsl_cx * const f = d->f;
  fsl_db * const db = fsl_cx_db_repo(f);

  assert(d->rid>0);
  rc = fsl__tag_insert(f, FSL_TAGTYPE_ADD, "cluster", NULL,
                       d->rid, d->D, d->rid, NULL);
  if(rc){
    fsl_check_oom_rc(rc);
    return rc;
  }

  rc = fsl_db_prepare_cached(db, &st,
                             "DELETE FROM {{dbname.repo}}.unclustered WHERE rid=?"
                             "/*%s()*/",__func__);
  if(rc){
    fsl_check_oom_rc(rc);
    return fsl_cx_uplift_db_error(f, db);
  }
  assert(st);
  fsl__phantom_e const fantomMode = fsl_content_is_private(f, d->rid)
    ? FSL_PHANTOM_PRIVATE : FSL_PHANTOM_PUBLIC;
  for( i = 0; i < d->M.used; ++i ){
    fsl_id_t mid;
    char const * uuid = (char const *)d->M.list[i];
    /* fossil(1) resolves cluster children with uuid_to_rid(uuid, 1)
    ** (manifest.c), creating a phantom placeholder for any child not yet
    ** present. That phantom is what lets a later sync/clone discover the
    ** missing artifact and request it (gimme). The previous plain
    ** fsl_uuid_to_rid() never created the placeholder, so libfossil
    ** clones silently lacked these rows. Mirror fossil here.
    **
    ** fossil's content_new() returns rid 0 for a shunned uuid (a silent
    ** skip); libfossil's fsl__uuid_to_rid2() instead returns <0 with
    ** FSL_RC_SHUNNED set. Treat that as the same skip rather than
    ** failing the crosslink. */
    mid = fsl__uuid_to_rid2(f, uuid, fantomMode);
    if(mid<0){
      if(FSL_RC_SHUNNED==f->error.code){
        fsl_cx_err_reset(f);
        continue;
      }
      rc = f->error.code ? f->error.code : FSL_RC_RANGE;
      fsl_check_oom_rc(rc);
      break;
    }
    if(mid>0){
      fsl_stmt_bind_id(st, 1, mid);
      if(FSL_RC_STEP_DONE!=fsl_stmt_step(st)){
        rc = fsl_cx_uplift_db_error(f, db);
        break;
      }
      fsl_stmt_reset(st);
    }
  }
  fsl_stmt_cached_yield(st);
  return rc;
}

#if 0
static int fsl__deck_crosslink_control(fsl_deck *const d){
}
#endif

/**
   Resolves a forum cross-reference UUID (thread-root G, parent P, or
   in-reply-to I) to a rid, creating a phantom if absent, mirroring
   fossil(1)'s uuid_to_rid(uuid, 1) in manifest_crosslink(). On a shunned
   referent fsl__uuid_to_rid2() returns <0 with FSL_RC_SHUNNED; fossil's
   content_new() returns 0 in that case, so we reset the error and return
   0 (the REPLACE's nullif(...,0) then stores NULL). *rc is set to a real
   error only for genuine failures.
*/
static fsl_id_t fsl__forum_ref_rid(fsl_cx * const f, fsl_uuid_cstr uuid,
                                   fsl__phantom_e mode, int * const rc){
  fsl_id_t const id = fsl__uuid_to_rid2(f, uuid, mode);
  if( id>=0 ) return id;
  if( FSL_RC_SHUNNED==f->error.code ){
    fsl_cx_err_reset(f);
    return 0;
  }
  *rc = f->error.code
    ? f->error.code
    : fsl_cx_err_set(f, FSL_RC_RANGE,
                     "Cannot resolve forum post reference [%s].", uuid);
  return 0;
}

static int fsl__deck_crosslink_forum(fsl_deck * const d){
  int rc = 0;
  fsl_cx * const f = d->f;
  rc = fsl_repo_install_schema_forum(f);
  if(rc) return rc;
  fsl_db * const db = fsl_cx_db_repo(f);
  /* fossil(1) resolves the thread-root (G), parent (P) and in-reply-to
  ** (I) with uuid_to_rid(...,1) -- phantomize -- so a not-yet-received
  ** referent gets a phantom placeholder (manifest.c). The previous plain
  ** fsl_uuid_to_rid() left no record of the missing referent. Mirror
  ** fossil. fsl__forum_ref_rid() maps a shunned/absent-creation case
  ** back to 0 so the REPLACE's nullif(...,0) stores NULL, as fossil's
  ** content_new()-returns-0 path does. */
  fsl__phantom_e const fantomMode = fsl_content_is_private(f, d->rid)
    ? FSL_PHANTOM_PRIVATE : FSL_PHANTOM_PUBLIC;
  fsl_id_t froot = d->rid, fprev = 0, firt = 0;
  if( d->G ){ froot = fsl__forum_ref_rid(f, d->G, fantomMode, &rc); if(rc) return rc; }
  if( !rc && d->P.used ){ fprev = fsl__forum_ref_rid(f, (char const *)d->P.list[0], fantomMode, &rc); if(rc) return rc; }
  if( !rc && d->I ){ firt = fsl__forum_ref_rid(f, d->I, fantomMode, &rc); if(rc) return rc; }
  assert(f && db);
  rc = fsl_db_exec_multi(db,
      "REPLACE INTO {{dbname.repo}}.forumpost(fpid,froot,fprev,firt,fmtime)"
      "VALUES(%" FSL_ID_T_PFMT ",%" FSL_ID_T_PFMT ","
      "nullif(%" FSL_ID_T_PFMT ",0),"
      "nullif(%" FSL_ID_T_PFMT ",0),%"FSL_JULIAN_T_PFMT")",
      d->rid, froot, fprev, firt, d->D
  );
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  if(!rc){
    rc = fsl__search_doc_touch(f, d->type, d->rid, 0);
  }
  if(!rc){
    rc = fsl__deck_crosslink_fwt_plink(d);
  }
  return rc;
}

static int fsl__deck_crosslink_technote(fsl_deck * const d){
  char buf[FSL_STRLEN_K256 + 7 /* event-UUID\0 */] = {0};
  char zLength[40] = {0};
  fsl_id_t tagid;
  fsl_id_t prior = 0, subsequent;
  char const * zWiki;
  char const * zTag;
  fsl_size_t nWiki = 0;
  int rc;
  fsl_cx * const f = d->f;
  fsl_db * const db = fsl_cx_db_repo(f);
  fsl_snprintf(buf, sizeof(buf), "event-%s", d->E.uuid);
  zTag = buf;
  tagid = fsl_tag_id( f, zTag, 1 );
  if(tagid<=0){
    rc = f->error.code ? f->error.code :
      fsl_cx_err_set(f, FSL_RC_RANGE,
                     "Got unexpected RID (%"FSL_ID_T_PFMT") "
                     "for tag [%s].",
                     tagid, zTag);
    goto end;
  }
  zWiki = d->W.used ? fsl_b_cstr(&d->W) : "";
  while( *zWiki && fsl_isspace(*zWiki) ){
    ++zWiki;
    /* Historical behaviour: strip leading spaces. */
  }
  nWiki = fsl_strlen(zWiki);
  fsl_snprintf( zLength, sizeof(zLength), "%"FSL_SIZE_T_PFMT,
                (fsl_size_t)nWiki);
  rc = fsl__tag_insert(f, FSL_TAGTYPE_ADD, zTag, zLength,
                      d->rid, d->D, d->rid, NULL );
  if(rc) goto end;
  if(d->P.used){
    prior = fsl_uuid_to_rid(f, (const char *)d->P.list[0]);
    if(prior<0){
      assert(f->error.code);
      rc = f->error.code;
      goto end;
    }
  }
  subsequent = fsl_db_g_id(db, 0,
  /* BUG: see:
     https://fossil-scm.org/forum/forumpost/c58fd8de53 */
                           "SELECT rid FROM {{dbname.repo}}.tagxref"
                           " WHERE tagid=%"FSL_ID_T_PFMT
                           " AND mtime>=%"FSL_JULIAN_T_PFMT
                           " AND rid!=%"FSL_ID_T_PFMT
                           " ORDER BY mtime",
                           tagid, d->D, d->rid);
  if(subsequent<0){
    assert(db->error.code);
    rc = fsl_cx_uplift_db_error(f, db);
    goto end;
  }
  else if( prior > 0 ){
    rc = fsl__content_deltify(f, prior, d->rid, 0);
    if( !rc && !subsequent ){
      rc = fsl_db_exec(db,
                       "DELETE FROM {{dbname.repo}}.event"
                       " WHERE type='e'"
                       "   AND tagid=%"FSL_ID_T_PFMT
                       "   AND objid IN"
                       " (SELECT rid FROM {{dbname.repo}}.tagxref "
                       " WHERE tagid=%"FSL_ID_T_PFMT")",
                       tagid, tagid);
    }
  }
  if(rc) goto end;
  if( subsequent>0 ){
    rc = fsl__content_deltify(f, d->rid, subsequent, 0);
  }else{
    /* timeline update is deferred to another crosslink
       handler */
    rc = fsl__search_doc_touch(f, d->type, d->rid, 0);
    /* FSL-MISSING:
       assert( manifest_event_triggers_are_enabled ); */
  }
  if(!rc){
    rc = fsl__deck_crosslink_fwt_plink(d);
  }
  end:
  return rc;
}

static int fsl__deck_crosslink_ticket(fsl_deck * const d){
  int rc;
  fsl_cx * const f = d->f;
  char * zTag;
  fsl_stmt qAtt = fsl_stmt_empty;
  assert(f->cache.isCrosslinking
         && "This only works if fsl__crosslink_begin() is active.");
  zTag = fsl_mprintf("tkt-%s", d->K);
  if(!zTag) return FSL_RC_OOM;
  rc = fsl__tag_insert(f, FSL_TAGTYPE_ADD, zTag, NULL,
                       d->rid, d->D, d->rid, NULL);
  fsl_free(zTag);
  if(rc) goto end;
  assert(d->K);
  rc = fsl__deck_crosslink_add_pending(f, 't', d->K);
  if(rc) goto end;
  /* Locate and update comment for any attachments */
  rc = fsl_cx_prepare(f, &qAtt,
                      "SELECT attachid, src, target, filename FROM {{dbname.repo}}.attachment"
                      " WHERE target=%Q",
                      d->K);
  while(0==rc && fsl__cx_stmt_step_each(f, &qAtt, &rc)){
    const char *zAttachId = fsl_stmt_g_text(&qAtt, 0, NULL);
    const char *zSrc = fsl_stmt_g_text(&qAtt, 1, NULL);
    const char *zTarget = fsl_stmt_g_text(&qAtt, 2, NULL);
    const char *zName = fsl_stmt_g_text(&qAtt, 3, NULL);
    const bool isAdd = (zSrc && zSrc[0]) ? true : false;
    char *zComment;
    if( isAdd ){
      zComment =
        fsl_mprintf(
                    "Add attachment [/artifact/%!S|%h] to ticket [%!S|%S]",
                    zSrc, zName, zTarget, zTarget);
    }else{
      zComment =
        fsl_mprintf("Delete attachment \"%h\" from ticket [%!S|%S]",
                    zName, zTarget, zTarget);
    }
    if(!zComment){
      rc = FSL_RC_OOM;
      break;
    }
    rc = fsl_cx_exec_multi(f, "UPDATE {{dbname.repo}}.event SET comment=%Q, type='t'"
                           " WHERE objid=%Q",
                           zComment, zAttachId);
    fsl_free(zComment);
  }
  end:
  fsl_stmt_finalize(&qAtt);
  return rc;
}

int fsl__deck_crosslink_one( fsl_deck * const d ){
  int rc;
  assert(d->f && "API misuse:fsl_deck::f == NULL");
  rc = fsl__crosslink_begin(d->f);
  if(rc) return rc;
  rc = fsl__deck_crosslink(d);
  assert(0!=fsl_db_txn_level(fsl_cx_db_repo(d->f))
         && "Expecting transaction level from fsl__crosslink_begin()");
  rc = fsl__crosslink_end(d->f, rc);
  return rc;
}

/**
   Prefixes f's error message with the formatted text and ": ", so
   that an error from deep within crosslinking or saving says which
   artifact it concerns. If f has no error state, it is set to rc,
   with the formatted text followed by rc's name. Does nothing if rc
   is 0 or FSL_RC_OOM. Returns rc or FSL_RC_OOM if formatting a
   message OOMs.
*/
static int fsl__deck_err_prefix(fsl_cx * const f, int rc,
                                char const * fmt, ...){
  fsl_b b = fsl_b_empty;
  va_list args;
  int rc2;
  if(!rc || FSL_RC_OOM==rc || FSL_RC_OOM==f->error.code) return rc;
  va_start(args, fmt);
  rc2 = fsl_b_appendfv(&b, fmt, args);
  va_end(args);
  if(!rc2){
    rc2 = f->error.msg.used
      ? fsl_b_appendf(&b, ": %b", &f->error.msg)
      : fsl_b_appendf(&b, ": %R", f->error.code ? f->error.code : rc);
  }
  if(!rc2){
    if(!f->error.code) f->error.code = rc;
    fsl_b_swap(&b, &f->error.msg);
  }
  fsl_b_clear(&b);
  return rc;
}

int fsl__deck_crosslink( fsl_deck /* const */ * const d ){
  int rc = 0;
  fsl_cx * f = d->f;
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  fsl_id_t parentid = 0;
  fsl_id_t const rid = d->rid;
  if(!f) return FSL_RC_MISUSE;
  else if(rid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid RID for crosslink: %"FSL_ID_T_PFMT,
                          rid);
  }
  else if(!db) return FSL_RC_NOT_A_REPO;
  else if(!fsl_deck_has_required_cards(d)){
    assert(d->f->error.code);
    if(0){
      fsl_uuid_str zUuid = fsl_rid_to_uuid(f, d->rid);
      MARKER(("CARD-DIAG: rid=%"FSL_ID_T_PFMT" uuid=%s\n",
              (fsl_id_t)d->rid, zUuid ? zUuid : "(none)"));
      fsl_free(zUuid);
    }
    return fsl__deck_err_prefix(f, d->f->error.code,
                                "Crosslinking %s artifact rid %"
                                FSL_ID_T_PFMT, fsl_satype_cstr(d->type),
                                rid);
  }else if(f->cache.xlinkClustersOnly && (FSL_SATYPE_CLUSTER!=d->type)){
    /* is it okay to bypass the registered xlink listeners here?  The
       use case called for by this is not yet implemented in
       libfossil. */
    return 0;
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if(rc) goto end;
  if(FSL_SATYPE_CHECKIN==d->type
     && d->B.uuid && !d->B.baseline){
    rc = fsl_deck_baseline_fetch(d);
    if(FSL_RC_PHANTOM==rc){
      /* Baseline not yet available; fsl_deck_baseline_fetch() has recorded
      ** an orphan row so this delta-manifest is re-crosslinked when the
      ** baseline dephantomizes. fossil(1)'s manifest_crosslink() returns 0
      ** (success) in this case. COMMIT (not roll back) so the orphan row
      ** persists, then return cleanly. */
      fsl_cx_err_reset(f);
      return fsl_cx_txn_end(f, false);
    }
    fsl_check_oom_rc(rc);
    if(rc) goto end;
    assert(d->B.baseline);
  }
  switch(d->type){
    case FSL_SATYPE_CHECKIN:
      rc = fsl__deck_crosslink_checkin(d, &parentid);
      fsl_check_oom_rc(rc);
      if( 0==rc ){
        /* This check-in's plink rows can make a parent stop being a
           leaf, e.g. when a branch edit was crosslinked in an earlier
           round while this check-in was still a phantom. A new child
           can only take leaf status away, so recheck just the parents
           now in the leaf table. Rechecking anything else would add
           untagged check-ins, which stay out of it. */
        fsl_stmt q = fsl_stmt_empty;
        rc = fsl_cx_prepare(d->f, &q,
               "SELECT pid FROM {{dbname.repo}}.plink WHERE cid=%" FSL_ID_T_PFMT
               " AND pid IN {{dbname.repo}}.leaf", d->rid);
        while( fsl__cx_stmt_step_each(d->f, &q, &rc) ){
          fsl_id_t const pid = fsl_stmt_g_id(&q, 0);
          if( !fsl_rid_is_leaf(d->f, pid) ){
            rc = d->f->error.code ? d->f->error.code
              : fsl_cx_exec(d->f, "DELETE FROM {{dbname.repo}}.leaf WHERE rid=%"
                            FSL_ID_T_PFMT, pid);
          }
        }
        fsl_stmt_finalize(&q);
      }
      break;
    case FSL_SATYPE_CLUSTER:
      rc = fsl__deck_crosslink_cluster(d);
      fsl_check_oom_rc(rc);
      break;
    default:
      break;
  }
  if(rc) goto end;
  switch(d->type){
    case FSL_SATYPE_CONTROL:
    case FSL_SATYPE_CHECKIN:
    case FSL_SATYPE_TECHNOTE:
      rc = fsl__deck_crosslink_apply_tags(f, d, db, rid, parentid);
      break;
    default:
      break;
  }
  fsl_check_oom_rc(rc);
  if(rc) goto end;
  switch(d->type){
    case FSL_SATYPE_WIKI:
      rc = fsl__deck_crosslink_wiki(d);
      break;
    case FSL_SATYPE_FORUMPOST:
      rc = fsl__deck_crosslink_forum(d);
      break;
    case FSL_SATYPE_TECHNOTE:
      rc = fsl__deck_crosslink_technote(d);
      break;
    case FSL_SATYPE_TICKET:
      rc = fsl__deck_crosslink_ticket(d);
      break;
    case FSL_SATYPE_ATTACHMENT:
      rc = fsl__deck_crosslink_attachment(d);
      break;
    /* FSL_SATYPE_CONTROL is handled above except for the timeline
       update, which is handled by a callback below */
    default:
      break;
  }
  fsl_check_oom_rc(rc);
  /* Call any crosslink callbacks... */
  if(0==rc && FSL_SATYPE_TICKET!=d->type){
    /* ^^^ the real work of ticket crosslinking is delated until
       fsl__crosslink_end(), for reasons lost to history, so we'll skip
       calling the xlink listeners for those until that step. */
    rc = fsl__call_xlink_listeners(d);
    fsl_check_oom_rc(rc);
  }
  end:
  if(!rc){
    rc = fsl_cx_txn_end(f, false);
    fsl_check_oom_rc(rc);
  }else{
    fsl_check_oom_rc(rc);
    if(db->error.code && !f->error.code){
      fsl_cx_uplift_db_error(f,db);
    }
    fsl__deck_err_prefix(f, rc, "Crosslinking %s artifact rid %"
                         FSL_ID_T_PFMT, fsl_satype_cstr(d->type), rid);
    fsl_cx_txn_end(f, true);
  }
  return rc ? rc : f->interrupted;
}/*end fsl__deck_crosslink()*/


/**
    Return true if z points to the first character after a blank line.
    Tolerate either \r\n or \n line endings. As this looks backwards
    in z, z must point to at least 3 characters past the beginning of
    a legal string.
 */
static bool fsl__is_after_blank_line(const char *z){
  if( z[-1]!='\n' ) return false;
  if( z[-2]=='\n' ) return true;
  if( z[-2]=='\r' && z[-3]=='\n' ) return true;
  return false;
}

/**
    Verifies that ca points to at least 35 bytes of memory
    which hold (at the end) a Z card and its hash value.

    Returns 0 if the string does not contain a Z card,
    a positive value if it can validate the Z card's hash,
    and a negative value on hash mismatch.
*/
static int fsl_deck_verify_Z_card(unsigned char const * ca, fsl_size_t n){
  if( n<35 ) return 0;
  if( ca[n-35]!='Z' || ca[n-34]!=' ' ) return 0;
  else{
    unsigned char digest[16];
    char hex[FSL_STRLEN_MD5+1];
    unsigned char const * zHash = ca+n-FSL_STRLEN_MD5-1;
    fsl_md5_cx md5 = fsl_md5_cx_empty;
    unsigned char const * zHashEnd =
      ca + n -
      2 /* "Z " */
      - FSL_STRLEN_MD5
      - 1 /* \n */;
    assert( 'Z' == (char)*zHashEnd );
    fsl_md5_update(&md5, ca, zHashEnd-ca);
    fsl_md5_final(&md5, digest);
    fsl_md5_digest_to_base16(digest, hex);
    return (0==memcmp(zHash, hex, FSL_STRLEN_MD5))
      ? 1
      : -1;
  }
}

bool fsl_signature_strip(char const **pz, fsl_size_t *pn){
  unsigned char const *z = (unsigned char const *)*pz;
  fsl_size_t n = (fsl_size_t)*pn;
  fsl_size_t i;
  bool stripped = false;
  char const * const aMsg[2] = {
    // must all be 34 bytes
    "-----BEGIN PGP SIGNED MESSAGE-----",
    "-----BEGIN SSH SIGNED MESSAGE-----"
  };
  char const * const aSig[2] = {
    "\n-----BEGIN PGP SIGNATURE-",
    "\n-----BEGIN SSH SIGNATURE-"
  };
  if( n<59 ) return false;
  for(int m = 0; m < 2; ++m ){
    if( 0==memcmp(z, aMsg[m], 34) ){
      for(i=34; i<n && !fsl__is_after_blank_line((char const *)(z+i)); i++){}
      if( i>=n ) continue;
      z += i;
      n -= i;
      *pz = (char const *)z;
      unsigned char const * bps =
        (unsigned char const *)strstr((char const *)z, aSig[m]);
      if( bps ){
        n = (fsl_int_t)(bps - z) + 1 /*newline*/;
      }
      *pn = (fsl_size_t)n;
      stripped = true;
      break;
    }
  }
  return stripped;
}

/** @internal

    Unsigned-char variant of fsl_signature_strip() for the parsers.
*/
static void fsl__remove_pgp_signature(unsigned char const **pz, fsl_size_t *pn){
  char const * z = (char const *)*pz;
  fsl_signature_strip(&z, pn);
  *pz = (unsigned char const *)z;
}

unsigned char * fsl__tokenizer_next(fsl__tokenizer * const p,
                                    fsl_size_t * const pLen){
  if( p->atEol ) return NULL;
  unsigned char * const zStart = p->z;
#if 1
  /* HOLY COW, this impl requires some 1/3rd the CPU instructions of
     the one in the #else block, despite ostensibly doing the same
     work! */
  size_t const n = strcspn((const char *)p->z, (char const *)" \n");
  p->atEol = p->z[n]=='\n';
  p->z[n] = 0;
  p->z += n+1;
  *pLen = n;
#else
  unsigned char * z = p->z;
  while( *z!=' ' && *z!='\n' ) ++z;
  p->atEol = *z=='\n';
  *z = 0;
  p->z = &z[1];
  *pLen = z - zStart;
#endif
  return zStart;
}

/**
    Return the card-type for the next card. Return 0 if there are no
    more cards or if we are not at the end of the current card.
 */
static unsigned char deck__next_card(fsl__tokenizer * const p){
  unsigned char c;
  if( !p->atEol || p->z>=p->zEnd ) return 0;
  c = p->z[0];
  if( p->z[1]==' ' ){
    p->z += 2;
    p->atEol = false;
  }else if( p->z[1]=='\n' ){
    p->z += 2;
    p->atEol = true;
  }else{
    c = 0;
  }
  return c;
}

/**
    Internal helper for fsl_deck_parse(). Expects l to be an array of
    26 entries, representing the letters of the alphabet (A-Z), with a
    value of 0 if the card was not seen during parsing and a value >0
    if it was. nF is the number of F-cards actually recorded, which
    excludes those dropped for having a reserved name (their letters
    are still counted in l). Returns the deduced artifact type. If
    nothing else matches, it falls back to FSL_SATYPE_CONTROL, as
    fossil(1) does, and the post-parse card checks reject the deck if
    it is not really one.

    Note that we cannot reliably guess until we've seen at least 3
    cards. 2 cards is enough for most cases but can lead to
    FSL_SATYPE_CHECKIN being prematurely selected in one case.

    It should guess right for any legal manifests, but it does not go
    out of its way to detect incomplete/invalid ones.
 */
static fsl_satype_e fsl_deck_guess_type( const int * l, fsl_size_t nF ){
#if 0
  /* For parser testing only... */
  int i;
  assert(!l[26]);
  MARKER(("Cards seen during parse:\n"));
  for( i = 0; i < 26; ++i ){
    if(l[i]) putchar('A'+i);
  }
  putchar('\n');
#endif
  /*
     Now look for combinations of cards which will uniquely
     identify any syntactically-legal combination of cards.

     The order of these checks is sometimes significant, which is why
     we don't put them in expected order of frequency (i.e. checkins
     first).
  */
#define L(X) l[X-'A']
#define CHECK(T,COND) if(COND) return T
  CHECK(FSL_SATYPE_CLUSTER,    L('M'));
  CHECK(FSL_SATYPE_EVENT,      L('E'));
  CHECK(FSL_SATYPE_FORUMPOST,  L('G') || L('H') || L('I'));
  CHECK(FSL_SATYPE_WIKI,       L('L') || L('W'));
  CHECK(FSL_SATYPE_TICKET,     L('J') || L('K'));
  CHECK(FSL_SATYPE_ATTACHMENT, L('A'));
  CHECK(FSL_SATYPE_CHECKIN,
        nF || L('C') || L('P') ||
        L('Q') || L('R') || L('B'));
#undef CHECK
#undef L
  return FSL_SATYPE_CONTROL;
}

bool fsl_might_be_artifact(fsl_b const * const src){
  unsigned const char * z = src->mem;
  fsl_size_t n = src->used;
  if(n<36) return false;
  fsl__remove_pgp_signature(&z, &n);
  if(n<36) return false;
  else if(z[1]!=' ' || z[0]<'A' || z[0]>'M'
          /* We "could" check for ^^^^^^^^ 'D' instead, but cluster
             artifacts are the exception to the D-card requirement
             rule. */
          || z[n-35]!='Z'
          || z[n-34]!=' '
          || !fsl_validate16((const char *)z+n-33, FSL_STRLEN_MD5)){
    return false;
  }
  return true;
}

/**
   Internal helper for fsl_deck_parse2() and fsl_deck_load_rid().
   Prefixes f's current error message with the artifact and line it
   refers to, in the form fossil(1)'s manifest_parse() uses:

   artifact [HASH] line N: MESSAGE

   The artifact part is added if rid>0, using the hash from the
   repository or, failing that, the rid. The line part is added if
   line>0. If line is 0 and the message already starts with "line "
   then the artifact part is joined to it with a space. Does nothing
   if f has no error, the error is FSL_RC_OOM, or there is nothing to
   add. Returns f's error code.
*/
static int fsl__deck_err_context(fsl_cx * const f, fsl_id_t rid,
                                 unsigned line){
  int const rc = f->error.code;
  if( !rc || FSL_RC_OOM==rc || (rid<=0 && !line) ) return rc;
  fsl_db * const db = rid>0 ? fsl_cx_db_repo(f) : NULL;
  char * const zUuid = db
    ? fsl_rid_to_uuid(f, rid)
    : NULL;
  fsl_b msg = fsl_b_empty;
  fsl_b * const old = &f->error.msg;
  if( zUuid ) fsl_b_appendf(&msg, "artifact [%s]", zUuid);
  else if( rid>0 ){
    fsl_b_appendf(&msg, "artifact rid %" FSL_ID_T_PFMT, rid);
  }
  if( line ){
    fsl_b_appendf(&msg, "%sline %u: ", msg.used ? " " : "", line);
  }else{
    bool const hasLine = old->used>5 && 0==memcmp(old->mem, "line ", 5);
    fsl_b_append(&msg, hasLine ? " " : ": ", -1);
  }
  if( old->used ) fsl_b_append(&msg, old->mem, (fsl_int_t)old->used);
  else fsl_b_append(&msg, fsl_rc_cstr(rc), -1);
  if(!msg.errCode) fsl_b_swap(&msg, old);
  fsl_b_clear(&msg);
  fsl_free(zUuid);
  return rc;
}

int fsl_deck_parse2(fsl_deck * const d, fsl_b * const src, fsl_id_t rid){
#ifdef ERROR
#  undef ERROR
#endif
#define ERROR(RC,MSG) { rc = (RC); zMsg = (MSG); goto bailout; } (void)0
#define SYNTAX(MSG) ERROR(rc ? rc : FSL_RC_SYNTAX,MSG)
  bool isRepeat = 0/* , hasSelfRefTag = 0 */;
  int rc = 0;
  fsl__tokenizer x = fsl__tokenizer_empty;
  char const * zMsg = NULL;
  unsigned char cType = 0, cPrevType = 0;
  unsigned char * z = src ? src->mem : NULL;
  unsigned char const * const zBegin = z;
  bool inCards = true /* false once all cards are read */;
  fsl_size_t tokLen = 0;
  unsigned char * token;
  fsl_size_t n = z ? src->used : 0;
  unsigned char * uuid;
  double ts;
  int cardCount = 0;
  fsl_cx * const f = d->f;
  fsl_error * const err = f ? &f->error : 0;
  int stealBuf = 0 /* gets incremented if we need to steal src->mem. */;
  unsigned nSelfTag = 0 /* number of T cards which refer to '*' (this artifact). */;
  unsigned nSimpleTag = 0 /* number of T cards with "+" prefix */;
  char const * zPrevJ = NULL /* previous J-card name, for order checks */;
  /*
    lettersSeen keeps track of the card letters we have seen so that
    we can then relatively quickly figure out what type of manifest we
    have parsed without having to inspect the card contents. Each
    index records a count of how many of that card we've seen.
  */
  int lettersSeen[27] = {0/*A*/,0,0,0,0,0,0,0,0,0,0,0,0,
                         0,0,0,0,0,0,0,0,0,0,0,0,0/*Z*/,
                         0 /* sentinel element for reasons lost to
                             history but removing it breaks stuff. */};
  if(!f) return FSL_RC_MISUSE;
  else if(!src){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "%s() requires a source buffer.", __func__);
  }
  if(rid>0 && (fsl__cx_mcache_search2(f, rid, d, FSL_SATYPE_ANY, &rc)
               || rc)){
    if(0==rc){
      assert(d->rid == rid);
      fsl_b_reuse(src);
    }
    return rc;
  }else if(rid<0){
    return fsl_error_set(err, FSL_RC_RANGE,
                         "Invalid (negative) RID %" FSL_ID_T_PFMT
                         " for %s()", rid, __func__);
  }else if(!z || !*z || !n || ( '\n' != z[n-1]) ){
    /* Every control artifact ends with a '\n' character. Exit early
       if that is not the case for this artifact. Messages are those
       of fossil(1)'s manifest_parse(). */
    if( z && n ){
      ERROR(FSL_RC_SYNTAX, "not terminated with \\n");
    }else{
      ERROR(FSL_RC_SYNTAX, "zero-length");
    }
  }

  /*
    Verify that the first few characters of the artifact look like a
    control artifact.
  */
  if( !fsl_might_be_artifact(src) ){
    SYNTAX("Content does not look like a structural artifact");
  }

  fsl_deck_clean(d);
  fsl_deck_init(f, d, FSL_SATYPE_ANY);

  /*
    Strip off the PGP signature if there is one. Example of signed
    manifest:

    https://fossil-scm.org/index.html/artifact/28987096ac
  */
  {
    unsigned char const * zz = z;
    fsl__remove_pgp_signature(&zz, &n);
    z = (unsigned char *)zz;
  }

  /* Verify the Z card */
  if( fsl_deck_verify_Z_card(z, n) < 0 ){
    ERROR(FSL_RC_CONSISTENCY, "Z-card checksum mismatch");
  }

  /* legacy: not yet clear if we need this:
     if( !isRepeat ) g.parseCnt[0]++; */

  /*
    Reminder: parsing modifies the input (to simplify the
    tokenization/parsing).

    As of mid-201403, we recycle as much as possible from the source
    buffer.
  */
  /* Now parse, card by card... */
  x.z = z;
  x.zEnd = z+n;
  x.atEol= true;

  /* Parsing helpers... */
  /* Only a card's final token may be empty: two consecutive spaces
     are malformed. */
#define TOKEN(DEFOS) tokLen=0; token = fsl__tokenizer_next(&x,&tokLen); \
  if(token && !tokLen && !x.atEol){ SYNTAX("Empty token in card"); } \
  if(token && tokLen && (DEFOS)) fsl_bytes_defossilize(token, &tokLen)
#define TOKEN_EXISTS(MSG_IF_NOT) if(!token){ SYNTAX(MSG_IF_NOT); }(void)0
  /* An empty (final) token is present, so it must be a valid hash
     like any other, as in fossil(1). */
#define TOKEN_CHECKHEX(MSG) if(token && (!tokLen || (int)tokLen!=fsl_is_uuid((char const *)token))) \
  { SYNTAX(MSG); }
#define TOKEN_UUID(CARD) TOKEN_CHECKHEX("Malformed UUID in " #CARD "-card")
#define TOKEN_MD5(ERRMSG) if(!token || FSL_STRLEN_MD5!=(int)tokLen) \
  {SYNTAX(ERRMSG);}
  /**
     Reminder: we do not know the type of the manifest at this point,
     so all of the fsl_deck_add/set() bits below can't do their
     validation. We have to determine at parse-time (or afterwards)
     which type of deck it is based on the cards we've seen. We guess
     the type as early as possible to enable during-parse validation,
     and do a post-parse check for the legality of cards added before
     validation became possible.
   */

#define SEEN(CARD) lettersSeen[*#CARD - 'A']
  for( cPrevType=1; !rc && (0 < (cType = deck__next_card(&x)));
       cPrevType = cType ){
    ++cardCount;
    if(cType<cPrevType){
      if(d->E.uuid && 'N'==cType && 'P'==cPrevType){
        /* Workaround for a pair of historical fossil bugs
           which synergized to allow malformed technotes to
           be saved:
           https://fossil-scm.org/home/info/023fddeec4029306 */
      }else{
        SYNTAX("Cards are not in strict lexical order");
      }
    }
    if(cType>='A' && cType<='Z'){
        ++lettersSeen[cType-'A'];
    }else{
      SYNTAX("Invalid card name");
    }
    switch(cType){
      /*
             A <filename> <target> ?<source>?

         Identifies an attachment to either a wiki page, a ticket, or
         a technote.  <source> is the artifact that is the attachment.
         <source> is omitted to delete an attachment.  <target> is the
         name of a wiki page, technote, or ticket to which that
         attachment is connected.
      */
      case 'A':{
        unsigned char * name, * src;
        if(1<SEEN(A)){
          SYNTAX("Multiple A-cards");
        }
        TOKEN(1);
        TOKEN_EXISTS("Missing filename for A-card");
        name = token;
        if(!fsl_is_simple_pathname( (char const *)name, 0 )){
          SYNTAX("Invalid filename in A-card");
        }
        TOKEN(1);
        TOKEN_EXISTS("Missing target name in A-card");
        if((int)tokLen!=fsl_is_uuid((char const *)token)
           && !fsl_wiki_name_is_wellformed((char const *)token,
                                           (fsl_int_t)tokLen)){
          SYNTAX("Invalid target in A-card");
        }
        uuid = token;
        TOKEN(0);
        TOKEN_UUID(A);
        src = token;
        d->A.name = (char *)name;
        d->A.tgt = (char *)uuid;
        d->A.src = (char *)src;
        ++stealBuf;
        /*rc = fsl_deck_A_set(d, (char const *)name,
          (char const *)uuid, (char const *)src);*/
        d->type = FSL_SATYPE_ATTACHMENT;
        break;
      }
      /*
            B <uuid>

         A B-line gives the UUID for the baseline of a delta-manifest.
      */
      case 'B':{
        if(d->B.uuid){
          SYNTAX("Multiple B-cards");
        }
        TOKEN(0);
        TOKEN_UUID(B);
        d->B.uuid = (char *)token;
        ++stealBuf;
        d->type = FSL_SATYPE_CHECKIN;
        /* rc = fsl_deck_B_set(d, (char const *)token); */
        break;
      }
      /*
             C <comment>

         Comment text is fossil-encoded.  There may be no more than
         one C line.  C lines are required for manifests, are optional
         for Wiki pages, Events, Attachments, and are disallowed on
         all other control files.
      */
      case 'C':{
        if( d->C ){
          SYNTAX("more than one C-card");
        }
        TOKEN(1);
        TOKEN_EXISTS("Missing comment text for C-card");
        /* rc = fsl_deck_C_set(d, (char const *)token, (fsl_int_t)tokLen); */
        d->C = (char *)token;
        ++stealBuf;
        break;
      }
      /*
             D <timestamp>

         The timestamp should be ISO 8601 YYYY-MM-DDtHH:MM:SS[.sss].
         There can be no more than 1 D line.  D lines are required for
         all control files except for clusters.
      */
      case 'D':{
#define TOKEN_DATETIME(LETTER,MEMBER)                                     \
        if( d->MEMBER>0.0 ) { SYNTAX("More than one "#LETTER"-card"); } \
        TOKEN(0); \
        TOKEN_EXISTS("Missing date part of "#LETTER"-card"); \
        if(!fsl_iso8601_to_julian((char const *)token, &ts)){   \
          SYNTAX("Malformed date in "#LETTER"-card"); \
        } (void)0

        TOKEN_DATETIME(D,D);
        rc = fsl_deck_D_set(d, ts);
        break;
      }
      /*
             E <timestamp> <uuid>

         An "event" (technote) card that contains the timestamp of the
         event in the format YYYY-MM-DDtHH:MM:SS[.sss] and a unique
         identifier for the event. The event timestamp is distinct
         from the D timestamp. The D timestamp is when the artifact
         was created whereas the E timestamp is when the specific
         event is said to occur.
      */
      case 'E':{
        TOKEN_DATETIME(E,E.julian);
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID part of E-card");
        TOKEN_UUID(E);
        d->E.julian = ts;
        d->E.uuid = (char *)token;
        ++stealBuf;
        d->type = FSL_SATYPE_EVENT;
        break;
      }
      /*
             F <filename> ?<uuid>? ?<permissions>? ?<old-name>?

         Identifies a file in a manifest.  Multiple F lines are
         allowed in a manifest.  F lines are not allowed in any other
         control file.  The filename and old-name are fossil-encoded.

         In delta manifests, deleted files are denoted by the 1-arg
         form. In baseline manifests, deleted files simply are not in
         the manifest.
      */
      case 'F':{
        char * name;
        char * perms = NULL;
        char * priorName = NULL;
        fsl_fileperm_e perm = FSL_FILE_PERM_REGULAR;
        fsl_card_F * fc = NULL;
        rc = 0;
        if(!d->F.capacity){
          /**
             Basic tests with various repos have shown that the
             approximate number of F-cards in a manifest is roughly
             the manifest size/75. We'll use that as an initial alloc
             size.
          */
          rc = fsl_card_F_list_reserve(&d->F, src->used/75+10);
          if( rc ){
            zMsg = "OOM";
            goto bailout;
          }
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing name for F-card");
        name = (char *)token;
        TOKEN(0);
        TOKEN_UUID(F);
        uuid = token;
        if(!uuid && !d->B.uuid){
          /* Only a delta manifest may omit the hash, to mark a
             deletion. (The B-card, if any, precedes all F-cards.) */
          SYNTAX("Missing hash on F-card");
        }
        TOKEN(0);
        if(token){
          perms = (char *)token;
          switch(*perms){
            case 0:
              /* Some (maybe only 1) ancient fossil(1) artifact(s) have a trailing
                 space which triggers this. e.g.

                 https://fossil-scm.org/home/info/32b480faa3465591b8549bdfd889d62d7a8d16a8
              */
            default:
              perm = FSL_FILE_PERM_REGULAR;
              break;
            case 'w': perm = FSL_FILE_PERM_REGULAR; break;
            case 'x': perm = FSL_FILE_PERM_EXE; break;
            case 'l': perm = FSL_FILE_PERM_LINK; break;
          }
          TOKEN(0);
          if(token) priorName = (char *)token;
        }
        fsl_bytes_defossilize( (unsigned char *)name, 0 );
        if(!fsl_is_simple_pathname(name, false)){
          SYNTAX("F-card filename is not a simple path");
        }
        if(priorName){
          fsl_bytes_defossilize( (unsigned char *)priorName, 0 );
          if(!fsl_is_simple_pathname(priorName, false)){
            SYNTAX("F-card old filename is not a simple path");
          }
        }
        if(d->F.used
           && fsl_strcmp(F_at(&d->F, d->F.used-1)->name, name)>=0){
          /* As in fossil(1), this is checked before reserved names
             are dropped, against the previous non-dropped name. */
          SYNTAX("Incorrect F-card sort order");
        }
        if(fsl_is_reserved_fn(name, -1)){
          /* Some historical (pre-late-2020) manifests contain files
             they really shouldn't, like _FOSSIL_ and .fslckout.
             Since late 2020, fossil simply skips over these when
             parsing manifests, so we'll do the same. */
          break;
        }
        fc = rc ? 0 : fsl_card_F_list_push(&d->F);
        if(!fc){
          rc = FSL_RC_OOM;
          zMsg = "OOM";
          goto bailout;
        }
        ++stealBuf;
        assert(d->F.used>1
               ? (FSL__CARD_F_LIST_NEEDS_SORT & d->F.flags)
               : 1);
        fc->deckOwnsStrings = true;
        fc->name = name;
        fc->priorName = priorName;
        fc->perm = perm;
        fc->uuid = (fsl_uuid_str)uuid;
        d->type = FSL_SATYPE_CHECKIN;
        break;
      }
      /*
        G <uuid>

        A G-line gives the UUID for the thread root of a forum post.
      */
      case 'G':{
        if(d->G){
          SYNTAX("Multiple G-cards");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID in G-card");
        TOKEN_UUID(G);
        d->G = (char*)token;
        ++stealBuf;
        d->type = FSL_SATYPE_FORUMPOST;
        break;
      }
     /*
         H <forum post title>

         H text is fossil-encoded.  There may be no more than one H
         line.  H lines are optional for forum posts and are
         disallowed on all other control files.
      */
      case 'H':{
        if( d->H ){
          SYNTAX("more than one H-card");
        }
        TOKEN(1);
        TOKEN_EXISTS("Missing text for H-card");
        d->H = (char *)token;
        ++stealBuf;
        d->type = FSL_SATYPE_FORUMPOST;
        break;
      }
      /*
        I <uuid>

        A I-line gives the UUID for the in-response-to UUID for
        a forum post.
      */
      case 'I':{
        if(d->I){
          SYNTAX("Multiple I-cards");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID in I-card");
        TOKEN_UUID(I);
        d->I = (char*)token;
        ++stealBuf;
        d->type = FSL_SATYPE_FORUMPOST;
        break;
      }
      /*
         J <name> ?<value>?

         Specifies a name value pair for ticket.  If the first character
         of <name> is "+" then the <value> is appended to any preexisting
         value.  If <value> is omitted then it is understood to be an
         empty string.
      */
      case 'J':{
        char const * field;
        bool isAppend = 0;
        TOKEN(1);
        TOKEN_EXISTS("Missing field name for J-card");
        field = (char const *)token;
        if('+'==*field){
          isAppend = 1;
          ++field;
        }
        if(!*field){
          SYNTAX("Missing field name for J-card");
        }
        if(zPrevJ && fsl_strcmp(zPrevJ, (char const *)token)>=0){
          /* fossil(1) compares the names with their '+' prefix. */
          SYNTAX("Incorrect J-card sort order");
        }
        zPrevJ = (char const *)token;
        TOKEN(1);
        rc = fsl_deck_J_add(d, isAppend, field,
                            (char const *)token);
        d->type = FSL_SATYPE_TICKET;
        break;
      }
      /*
         K <uuid>

         A K-line gives the UUID for the ticket which this control file
         is amending.
      */
      case 'K':{
        if(d->K){
          SYNTAX("Multiple K-cards");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID in K-card");
        TOKEN_UUID(K);
        if(FSL_STRLEN_SHA1!=(int)tokLen){
          /* Ticket IDs are always SHA1-sized, regardless of hash
             policy. */
          SYNTAX("K-card UUID is the wrong size");
        }
        d->K = (char*)token;
        ++stealBuf;
        d->type = FSL_SATYPE_TICKET;
        break;
      }
      /*
         L <wikititle>

         The wiki page title is fossil-encoded.  There may be no more than
         one L line.
      */
      case 'L':{
        if(d->L){
          SYNTAX("Multiple L-cards");
        }
        TOKEN(1);
        TOKEN_EXISTS("Missing text for L-card");
        if(!fsl_wiki_name_is_wellformed((char const *)token,
                                        (fsl_int_t)tokLen)){
          SYNTAX("Malformed wiki name in L-card");
        }
        d->L = (char*)token;
        ++stealBuf;
        d->type = FSL_SATYPE_WIKI;
        break;
      }
      /*
         M <uuid>

         An M-line identifies another artifact by its UUID.  M-lines
         occur in clusters only.
      */
      case 'M':{
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID for M-card");
        TOKEN_UUID(M);
        ++stealBuf;
        d->type = FSL_SATYPE_CLUSTER;
        rc = fsl_list_append(&d->M, token);
        if( !rc && d->M.used>1 &&
            fsl_strcmp((char const *)d->M.list[d->M.used-2],
                       (char const *)token)>=0 ){
          SYNTAX("M-card in the wrong order");
        }
        break;
      }
      /*
         N <uuid>

         An N-line identifies the mimetype of wiki or comment text.
      */
      case 'N':{
        if(1<SEEN(N)){
          SYNTAX("Multiple N-cards");
        }
        TOKEN(1);
        TOKEN_EXISTS("Missing UUID on N-card");
        ++stealBuf;
        d->N = (char *)token;
        break;
      }

      /*
         P <uuid> ...

         Specify one or more other artifacts which are the parents of
         this artifact.  The first parent is the primary parent.  All
         others are parents by merge.
      */
      case 'P':{
        if(1<SEEN(P)){
          SYNTAX("More than one P-card");
        }
        TOKEN(0);
#if 0
        /* The docs all claim that this card does not exist on the first
           manifest, but in fact it does exist but has no UUID,
           which is invalid per all the P-card docs. Skip this
           check (A) for the sake of manifest #1 and (B) because
           fossil(1) does it this way.
        */
        TOKEN_EXISTS("Missing primary parent UUID for P-card");
#endif
        while( token && !rc ){
          TOKEN_UUID(P);
          ++stealBuf;
          rc = fsl_list_append(&d->P, token);
          if(!rc){
            TOKEN(0);
          }
        }
        break;
      }
      /*
         Q (+|-)<uuid> ?<uuid>?

         Specify one or a range of checkins that are cherrypicked into
         this checkin ("+") or backed out of this checkin ("-").
      */
      case 'Q':{
        fsl_cherrypick_type_e qType = FSL_CHERRYPICK_INVALID;
        TOKEN(0);
        TOKEN_EXISTS("Missing target UUID for Q-card");
        switch((char)*token){
          case '-': qType = FSL_CHERRYPICK_BACKOUT; break;
          case '+': qType = FSL_CHERRYPICK_ADD; break;
          default:
            SYNTAX("Malformed target UUID in Q-card");
        }
        assert(qType);
        uuid = ++token; --tokLen;
        TOKEN_UUID(Q);
        TOKEN(0);
        if(token){
          TOKEN_UUID(Q);
        }
        d->type = FSL_SATYPE_CHECKIN;
        rc = fsl_deck_Q_add(d, qType, (char const *)uuid,
                            (char const *)token);
        break;
      }
      /*
         R <md5sum>

         Specify the MD5 checksum over the name and content of all files
         in the manifest.
      */
      case 'R':{
        if(1<SEEN(R)){
          SYNTAX("More than one R-card");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing MD5 token in R-card");
        TOKEN_MD5("Malformed MD5 token in R-card");
        if(!fsl_validate16((char const *)token, tokLen)){
          SYNTAX("Malformed MD5 token in R-card");
        }
        d->R = (char *)token;
        ++stealBuf;
        d->type = FSL_SATYPE_CHECKIN;
        break;
      }
      /*
         T (+|*|-)<tagname> <uuid> ?<value>?

         Create or cancel a tag or property. The tagname is fossil-encoded.
         The first character of the name must be either "+" to create a
         singleton tag, "*" to create a propagating tag, or "-" to create
         anti-tag that undoes a prior "+" or blocks propagation of of
         a "*".

         The tag is applied to <uuid>. If <uuid> is "*" then the tag is
         applied to the current manifest. If <value> is provided then
         the tag is really a property with the given value.

         Tags are not allowed in clusters.  Multiple T lines are allowed.
      */
      case 'T':{
        unsigned char * name, * value;
        fsl_tagtype_e tagType = FSL_TAGTYPE_INVALID;
        int uglyKludge = 0;
        TOKEN(1);
        TOKEN_EXISTS("Missing name for T-card");
        name = token;
        if( fsl_validate16((char const *)&name[1],
                           fsl_strlen((char const *)&name[1])) ){
          /* Do not allow tags whose names look like a hash */
          SYNTAX("T-card name looks like a hexadecimal hash");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID on T-card");
        if(fsl_is_uuid_len((int)tokLen)){
          TOKEN_UUID(T);
          uuid = token;
        }else if( 1==tokLen && '*'==(char)*token ){
          /* tag for the current artifact */
          ++nSelfTag;
          uuid = NULL;
          if( (int)d->D == 2456537/*2013-09-01*/ && 631==d->F.used ){
            /* An ugly, UGLY hack to work around two invalid checkin
               artifacts in fossil(1)'s history which a developer
               creatively hand-crafted to replace the C- and U-cards
               with ostensibly semantically equivalent tags:

               ad0d6aed184d121
               0a24d431c7a1359

               The problem with that is that they are only
               semantically equivalent after the tags have been
               crosslinked and only for cases which use the [event]
               table as their source, not for cases which directly
               inspect the manifest. The 'user' and 'comment' tags,
               when applied to a checkin, update [event].[euser] resp.
               [event].[ecomment], they do not update the manifest.

               Fossil's manifest_parse() accepts that (possibly
               because the developer in question had a hand in shaping
               it), but this impl conforms to the docs which require
               C- and U-cards for check-ins. Except for these two
               artifacts because it'd be a poor fossil library if it
               could not read fossil's own history. _Sigh_.
            */
            if( 0==fsl_strcmp("+user", (char const *)name) ){
              uglyKludge = 2;
            }else if( !d->C && 0==fsl_strcmp("+comment", (char const *)name) ){
              uglyKludge = 1;
            }
          }
        }else{
          SYNTAX("Malformed UUID in T-card");
        }
        TOKEN(1);
        value = token;
        switch(*name){
          case '*': tagType = FSL_TAGTYPE_PROPAGATING; break;
          case '+': tagType = FSL_TAGTYPE_ADD;
            ++nSimpleTag;
            switch( uglyKludge ){
              case 1:
                assert( !d->C );
                d->C = (char*)value; ++stealBuf;
                //MARKER(("Forcing C-card via tag! %s\n", d->C));
                break;
              case 2: d->U = (char*)value; ++stealBuf;
                //MARKER(("Forcing U-card via tag! %s\n", d->U));
                break;
            }
            break;
          case '-': tagType = FSL_TAGTYPE_CANCEL; break;
          default: SYNTAX("Malformed tag name");
        }
        ++name /* skip type marker byte */;
        /* Tag order check from:

           https://fossil-scm.org/home/info/55cacfcace

           (It was subsequently made stricter so that the same tag
           type/name/target combination fails.)

           That's difficult to do here until _after_ we add the new
           tag to the list... */
        rc = fsl_deck_T_add(d, tagType, (fsl_uuid_cstr)uuid,
                            (char const *)name,
                            (char const *)value);
        if(0==rc && d->T.used>1){
          fsl_card_T const * const tagPrev =
            (fsl_card_T const *)d->T.list[d->T.used-2];
          fsl_card_T const * const tagSelf =
            (fsl_card_T const *)d->T.list[d->T.used-1];
          int const cmp = fsl_card_T_cmp_lax(&tagPrev, &tagSelf);
          if(cmp>=0){
            rc = fsl_cx_err_set(d->f, FSL_RC_SYNTAX,
                                "T-cards are not in lexical order: "
                                "%c%s %s %c%s",
                                fsl_tag_prefix_char(tagPrev->type),
                                tagPrev->name,
                                cmp ? ">=" : "==",
                                fsl_tag_prefix_char(tagSelf->type),
                                tagSelf->name);
            goto bailout;
          }
        }
        break;
      }
      /*
         U ?<login>?

         Identify the user who created this control file by their
         login.  Only one U line is allowed.  Prohibited in clusters.
         If the user name is omitted, take that to be "anonymous".
      */
      case 'U':{
        if(d->U) SYNTAX("More than one U-card");
        TOKEN(1);
        if(token){
          /* rc = fsl_deck_U_set( d, (char const *)token, (fsl_int_t)tokLen ); */
          ++stealBuf;
          d->U = (char *)token;
        }else{
          rc = fsl_deck_U_set( d, "anonymous" );
        }
        break;
      }
      /*
             W <size>

         The next <size> bytes of the file contain the text of the wiki
         page.  There is always an extra \n before the start of the next
         record.
      */
      case 'W':{
        fsl_size_t wlen;
        if(1<SEEN(W)){
          /* Not d->W.used, which is 0 for an empty "W 0" body. */
          SYNTAX("More than one W-card");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing size token for W-card");
        wlen = fsl_str_to_size((char const *)token);
        if((fsl_size_t)-1==wlen){
          SYNTAX("Wiki size token is invalid");
        }
        if( (&x.z[wlen+1]) > x.zEnd){
          SYNTAX("Not enough content after W-card");
        }
        //rc = fsl_b_append(&d->W, x.z, wlen);
        //if(rc) goto bailout;
        fsl_b_external(&d->W, x.z, wlen);
        ++stealBuf;
        x.z += wlen;
        if( '\n' != x.z[0] ){
          SYNTAX("W-card content not \\n terminated");
        }
        x.z[0] = 0;
        ++x.z;
        break;
      }
      /*
             Z <md5sum>

         MD5 checksum on this control file.  The checksum is over all
         lines (other than PGP-signature lines) prior to the current
         line.  This must be the last record.

         This card is required for all control file types except for
         Manifest. It is not required for manifest only for historical
         compatibility reasons.
      */
      case 'Z':{
        /* We validated the Z card first. We cannot compare against
           the original blob now because we've modified it.
        */
        goto end;
      }
      default:
        rc = fsl_cx_err_set(f, FSL_RC_SYNTAX,
                            "Unknown card '%c' in manifest",
                            cType);
        goto bailout;
    }/*switch(cType)*/
    if(rc) goto bailout;
  }/* for-each-card */
  if( x.z < x.zEnd ){
    /* deck__next_card() stopped before the end of the artifact,
       either because a card has more tokens than its type takes or
       because a line does not start with a card letter and a space
       or newline. fossil(1)'s manifest_parse() rejects both with
       this message. */
    if( x.atEol ) ++cardCount /* The text starts a new line. */;
    SYNTAX("extra characters at end of card");
  }

#if 1
  /* Remove these when we are done porting
     resp. we can avoid these unused-var warnings. */
  (void)isRepeat;
#endif

  end:
  assert(0==rc);
  inCards = false;
  if(cardCount>2 && FSL_SATYPE_ANY==d->type){
    /* See if we need to guess the type now.
       We need(?) at least two card to ensure that this is
       free of ambiguities. */
    d->type = fsl_deck_guess_type(lettersSeen, d->F.used);
    if(FSL_SATYPE_ANY!=d->type){
      assert(FSL_SATYPE_INVALID!=d->type);
#if 0
      MARKER(("Guessed manifest type with %d cards: %s\n",
                cardCount, fsl_satype_cstr(d->type)));
#endif
    }
  }

#if 1
  /*
    The problem (2026-06-24): fossil's age-old wiki-append feature
    effectively changes the ownership of the page with each append and
    fails to add a U-card if a wiki edit or append was by the user
    "nobody". This violates the wiki artifact spec, thus upsetting
    libf (and, it turns out, fossil, which refuses to validate those
    later). This problem went long-unrecognized, only showing itself
    in 2026-06 when libf sync testing against fossil stumbled over it.

    The obligatory workaround is: if it's a wiki, tolerate a missing
    U-card and substitute one as "nobody".

    Trivia: the UI for wiki-append was removed in 2020-08 when
    /wikiedit was reimplemented and nobody (least of all /wikiedit's
    developer) noticed.
  */
  if( FSL_SATYPE_WIKI==d->type && !d->U ){
    //MARKER(("Wiki no-U workaround\n"));
    if( !(d->U = fsl_strndup("nobody", 6)) ){
      rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
      goto bailout;
    }
  }
#endif
  /* Make sure all of the cards we put in it belong to that deck
     type. */
  if( !fsl_deck_check_type(d, cType) ){
    rc = d->f->error.code;
    goto bailout;
  }

  if(FSL_SATYPE_ANY==d->type){
    rc = fsl_cx_err_set(f, FSL_RC_ERROR,
                        "Internal error: could not determine type of "
                        "artifact we just (successfully!) parsed.");
    goto bailout;
  }else {
    /*
      Make sure we didn't pick up any cards which were picked up
      before d->type was guessed and are invalid for the post-guessed
      type.
    */
    int i = 0;
    for( ; i < 27; ++i ){
      if((lettersSeen[i]>0) && !fsl_card_is_legal(d->type, 'A'+i )){
        rc = fsl_cx_err_set(f, FSL_RC_SYNTAX,
                            "Determined during post-parse processing that "
                            "the parsed deck (type %s) contains an illegal "
                            "card type (%c).", fsl_satype_cstr(d->type),
                            'A'+i);
        goto bailout;
      }
    }
  }
  assert(FSL_SATYPE_CHECKIN==d->type ||
         FSL_SATYPE_CLUSTER==d->type ||
         FSL_SATYPE_CONTROL==d->type ||
         FSL_SATYPE_WIKI==d->type ||
         FSL_SATYPE_TICKET==d->type ||
         FSL_SATYPE_ATTACHMENT==d->type ||
         FSL_SATYPE_TECHNOTE==d->type ||
         FSL_SATYPE_FORUMPOST==d->type);
  assert(0==rc);

  {
    /* Required cards per type, from fossil(1)'s manifestCardTypes[],
       less the Z-card (verified above) and a wiki's U-card (see the
       workaround above). These are looser than
       fsl_deck_has_required_cards(), which applies to decks we
       write. */
    char const * zReq = NULL;
    switch( d->type ){
      case FSL_SATYPE_CHECKIN:    zReq = "D"; break;
      case FSL_SATYPE_CLUSTER:    zReq = "M"; break;
      case FSL_SATYPE_CONTROL:    zReq = "DTU"; break;
      case FSL_SATYPE_WIKI:       zReq = "DLW"; break;
      case FSL_SATYPE_TICKET:     zReq = "DJKU"; break;
      case FSL_SATYPE_ATTACHMENT: zReq = "AD"; break;
      case FSL_SATYPE_TECHNOTE:   zReq = "DEW"; break;
      case FSL_SATYPE_FORUMPOST:  zReq = "DUW"; break;
      default: break;
    }
    for( ; zReq && *zReq; ++zReq ){
      if( !lettersSeen[*zReq - 'A'] ){
        rc = fsl_cx_err_set(f, FSL_RC_SYNTAX,
                            "%c-card missing in %s artifact",
                            *zReq, fsl_satype_cstr(d->type));
        goto bailout;
      }
    }
  }

  /* Additional checks based on artifact type */
  switch( d->type ){
    case FSL_SATYPE_CONTROL: {
      if( nSelfTag ){
        SYNTAX("Self-referential T-card in control artifact");
      }
      break;
    }
    case FSL_SATYPE_TECHNOTE: {
      if( d->T.used!=nSelfTag ){
        SYNTAX("Non-self-referential T-card in technote");
      }else if( d->T.used!=nSimpleTag ){
        SYNTAX("T-card with '*' or '-' in technote");
      }
      break;
    }
    case FSL_SATYPE_FORUMPOST: {
      if( d->H && d->I ){
        SYNTAX("Cannot have I-card and H-card in a forum post");
      }else if( d->P.used>1 ){
        SYNTAX("Too many arguments to P-card");
      }
      break;
    }
    default: break;
  }

  assert(!d->content.mem);
  if(stealBuf>0){
    /* We stashed something which points to src->mem, so we need to
       steal that memory. */
    fsl_b_swap_free( &d->content, src, 1 );
  }else{
    /* Clearing the source buffer if we don't take it over
       provides more consistency in the public API than _sometimes_
       requiring the client to clear it. */
    fsl_b_reuse(src);
  }
  d->rid = rid;
  d->F.flags &= ~FSL__CARD_F_LIST_NEEDS_SORT/*we know all cards were read in order*/;
  return 0;

  bailout:
  if(stealBuf>0){
    fsl_b_swap_free( &d->content, src, 1 );
  }
  assert(0 != rc);
  assert( FSL_RC_NOT_FOUND!=rc );
  if(zMsg){
    fsl_error_set(err, rc, "%s", zMsg);
  }else if(err->code!=rc){
    /* A callee returned rc without describing it. */
    if(inCards && cType>='A' && cType<='Z'){
      fsl_error_set(err, rc, "malformed %c-card", cType);
    }else{
      fsl_error_set(err, rc, "malformed artifact");
    }
  }
  if(FSL_RC_OOM!=rc
     && (cardCount>0 || !inCards || FSL_RC_SYNTAX!=rc)){
    /* Skipped for input rejected before its first card, which is
       how most non-artifact blobs fail during a rebuild, so that
       they do not each cost a hash lookup. */
    unsigned line = 0;
    if(inCards && cardCount>0){
      /* Count the lines before the first card (a PGP/SSH signature
         header, if any), then one line per card. Neither the header
         nor the cards before this one contain a W-card's text, which
         can only be followed by the Z-card. */
      unsigned char const * zz = zBegin;
      line = (unsigned)cardCount;
      for( ; zz < (unsigned char const *)z; ++zz ){
        if('\n'==*zz) ++line;
      }
    }
    fsl__deck_err_context(f, rid, line);
  }
  return rc;
#undef SEEN
#undef TOKEN_DATETIME
#undef SYNTAX
#undef TOKEN_CHECKHEX
#undef TOKEN_EXISTS
#undef TOKEN_UUID
#undef TOKEN_MD5
#undef TOKEN
#undef ERROR
}

int fsl_deck_parse(fsl_deck * const d, fsl_b * const src){
  return fsl_deck_parse2(d, src, 0);
}

int fsl_deck_load_rid( fsl_cx * const f, fsl_deck * const d,
                       fsl_id_t rid, fsl_satype_e type ){
  fsl_b * const buf = fsl_cx_b_borrow(f);
  if( !buf ) return FSL_RC_OOM;
  int rc = 0;
  if(0==rid){
    rid = f->db.ckout.rid;
    if(rid<=0){
      rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                          "fsl_deck_load_rid() was given rid 0 (the "
                          "current checkout) but no checkout is open.");
      goto end;
    }
  }
  if(rid<0){
    rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                        "Invalid RID for fsl_deck_load_rid(): "
                        "%"FSL_ID_T_PFMT, rid);
    goto end;
  }
  fsl_deck_clean(d);
  d->f = f;
  if(fsl__cx_mcache_search2(f, rid, d, type, &rc) || rc){
    goto end;
  }
  rc = fsl_content_get(f, rid, buf);
  if(rc) goto end;
#if 0
  MARKER(("fsl_content_get(%d) len=%d =\n%.*s\n",
          (int)rid, (int)buf->used, (int)buf->used, (char const*)buf->mem));
#endif
  fsl_deck_init(f, d, type);
#if 0
  /*
    If we set d->type=type, the parser can fail more
    quickly. However, that failure will bypass our more specific
    reporting of the problem (see below).  As the type mismatch case
    is expected to be fairly rare, we'll leave this out for now, but
    it might be worth considering as a small optimization later on.
  */
  d->type = type /* may help parsing fail more quickly if
                    it's not the type we want.*/;
#endif
  rc = fsl_deck_parse(d, buf);
  if(!rc){
    if( type!=FSL_SATYPE_ANY && d->type!=type ){
      rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                          "RID %"FSL_ID_T_PFMT" is of type %s, "
                          "but the caller requested type %s.",
                          rid,
                          fsl_satype_cstr(d->type),
                          fsl_satype_cstr(type));
    }else if(d->B.uuid ){
      rc = fsl__cx_update_seen_delta_deck(f);
    }
  }else{
    /* fsl_deck_parse() does not know rid. */
    fsl__deck_err_context(f, rid, 0);
  }
  end:
  if(0==rc) d->rid = rid;
  fsl_cx_b_return(f, buf);
  return rc;
}

int fsl_deck_load_sym( fsl_cx * const f, fsl_deck * const d,
                       char const * symbolicName, fsl_satype_e type ){
  if(!symbolicName || !d) return FSL_RC_MISUSE;
  else{
    fsl_id_t vid = 0;
    int rc = fsl_sym_to_rid(f, symbolicName, type, &vid);
    if(!rc){
      assert(vid>0);
      rc = fsl_deck_load_rid(f, d, vid, type);
    }
    return rc;
  }
}

static int fsl__deck_baseline_load( fsl_deck * d ){
  int rc = 0;
  fsl_deck bl = fsl_deck_empty;
  fsl_id_t rid;
  fsl_cx * const f = d ? d->f : NULL;
  fsl_db * const db = f ? fsl_needs_repo(f) : NULL;
  assert(d->f);
  assert(d);
  if(!d->f) return FSL_RC_MISUSE;
  else if(d->B.baseline || !d->B.uuid) return 0 /* nothing to do! */;
  else if(!db) return FSL_RC_NOT_A_REPO;
#if 0
  else if(d->rid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "fsl__deck_baseline_load(): "
                          "fsl_deck::rid is not set.");
  }
#endif
  /* fossil(1)'s fetch_baseline() resolves the baseline with
  ** uuid_to_rid(zBaseline, 1) -- phantomize -- so an as-yet-unreceived
  ** baseline becomes a phantom placeholder with a real (positive) rid,
  ** records orphan(p->rid, thatRid), and returns a deferred (non-fatal)
  ** status. The previous code used plain fsl_uuid_to_rid() (rid 0 for a
  ** missing baseline), recorded orphan(d->rid, 0) -- a row the
  ** dephantomize retry (after_dephantomize: WHERE baseline=<rid>) can
  ** never match -- and then set a fatal FSL_RC_RANGE that aborts crosslink
  ** and rolls back. Mirror fossil: phantomize, record orphan with the real
  ** rid, and report the deferrable FSL_RC_PHANTOM.
  ** (Availability is detected via the load attempt below, as fossil
  ** detects it via manifest_get()==0.) */
  rid = fsl__uuid_to_rid2(f, d->B.uuid, FSL_PHANTOM_PUBLIC);
  if(rid<0 && FSL_RC_SHUNNED==f->error.code){
    /* A shunned baseline will never arrive, so this delta-manifest
    ** cannot be crosslinked. fossil(1)'s fetch_baseline() gets rid 0
    ** for it, records orphan(p->rid, 0) and skips the artifact, and its
    ** manifest_crosslink() returns success. Do the same, and report the
    ** FSL_RC_PHANTOM that fsl__deck_crosslink() treats as deferred, so
    ** that one hostile or stale artifact does not fail every sync that
    ** delivers it. */
    fsl_cx_err_reset(f);
    if(d->rid>0){
      int const rc2 = fsl_cx_exec(f,
                    "INSERT OR IGNORE INTO {{dbname.repo}}.orphan(rid, baseline) "
                    "VALUES(%"FSL_ID_T_PFMT",0)",
                    d->rid);
      if(rc2) return rc2;
    }
    return fsl_cx_err_set(f, FSL_RC_PHANTOM,
                          "Baseline manifest [%s] of manifest rid #%"
                          FSL_ID_T_PFMT" is shunned.",
                          d->B.uuid, d->rid);
  }else if(rid<0){
    assert(f->error.code);
    return f->error.code;
  }else{
    /* The baseline "should" be a baseline manifest, but fossil(1)
       accepts one which is itself a delta manifest and uses only that
       delta's own F-cards, never what it inherits from its own
       baseline. We do the same: its baseline is never loaded here,
       and fsl_deck_F_next() and fsl__deck_F_seek_impl() skip its
       deletion markers. */
    rc = fsl_deck_load_rid(f, &bl, rid, FSL_SATYPE_CHECKIN);
    if( FSL_RC_PHANTOM==rc || FSL_RC_NOT_FOUND==rc
        || FSL_RC_TYPE==rc || FSL_RC_SYNTAX==rc ){
      /* Baseline is a phantom (not yet received): defer this
      ** delta-manifest until the baseline dephantomizes. If it is
      ** stored but is not a check-in manifest, do the same, as
      ** fossil(1)'s fetch_baseline() does whenever manifest_get()
      ** fails: record the orphan and skip this artifact. */
      fsl_deck_clean(&bl);
      fsl_cx_err_reset(f);
      if(d->rid>0){
        rc = fsl_cx_exec(f,
                    "INSERT OR IGNORE INTO {{dbname.repo}}.orphan(rid, baseline) "
                    "VALUES(%"FSL_ID_T_PFMT",%"FSL_ID_T_PFMT")",
                    d->rid, rid);
        if(rc) return rc;
      }
      return fsl_cx_err_set(f, FSL_RC_PHANTOM,
                          "Baseline manifest [%s] (parent of manifest rid #%"
                          FSL_ID_T_PFMT") is not yet available; deferred.",
                          d->B.uuid, d->rid);
    }
    if(!rc){
      d->B.baseline = fsl_deck_malloc();
      if(!d->B.baseline){
        fsl_report_oom;
        fsl_deck_clean(&bl);
        rc = FSL_RC_OOM;
      }else{
        void const * allocStampKludge = d->B.baseline->allocStamp;
        *d->B.baseline = bl /* Transfer ownership */;
        d->B.baseline->allocStamp = allocStampKludge /* But we need this intact
                                                        for deallocation to work */;
        assert(f==d->B.baseline->f);
      }
    }else{
      /* bl might be partially populated */
      fsl_deck_finalize(&bl);
    }
  }
  return rc;
}

int fsl_deck_baseline_fetch( fsl_deck * d ){
  return (d->B.baseline || !d->B.uuid)
    ? 0
    : fsl__deck_baseline_load(d);
}

int fsl_deck_F_rewind( fsl_deck * d ){
  int rc = 0;
  d->F.cursor = 0;
  assert(d->f);
  if(d->B.uuid){
    rc = fsl_deck_baseline_fetch(d);
    if(!rc){
      assert(d->B.baseline);
      d->B.baseline->F.cursor = 0;
    }
  }
  return rc;
}

int fsl_deck_F_next( fsl_deck * d, fsl_card_F const ** rv ){
  assert(d);
  assert(d->f);
  assert(rv);
#define FCARD(DECK,NDX) F_at(&(DECK)->F, NDX)
  *rv = NULL;
  if(!d->B.baseline){
    /* Manifest d is a baseline-manifest.  Just scan down the list
       of files. */
    if(d->B.uuid){
      return fsl_cx_err_set(d->f, FSL_RC_MISUSE,
                            "Deck has a B-card (%s) but no baseline "
                            "loaded. Load the baseline before calling "
                            "%s().",
                            d->B.uuid, __func__)
        /* We "could" just load the baseline from here. */;
    }
    if( d->F.cursor < (int32_t)d->F.used ){
      *rv = FCARD(d, d->F.cursor++);
      assert(*rv);
      assert((*rv)->uuid && "Baseline manifest has deleted F-card entry!");
    }
    return 0;
  }else{
    /* Manifest d is a delta-manifest.  Scan the baseline but amend the
       file list in the baseline with changes described by d.
    */
    fsl_deck * const pB = d->B.baseline;
    int cmp;
    while(1){
      /* If pB is itself a delta manifest, skip its deletion
         markers. */
      while( pB->F.cursor < (fsl_int_t)pB->F.used
             && !FCARD(pB, pB->F.cursor)->uuid ){
        ++pB->F.cursor;
      }
      if( pB->F.cursor >= (fsl_int_t)pB->F.used ){
        /* We have used all entries out of the baseline.  Return the next
           entry from the delta, skipping deletions of files which are
           not in the baseline. */
        while( d->F.cursor < (fsl_int_t)d->F.used
               && !FCARD(d, d->F.cursor)->uuid ){
          ++d->F.cursor;
        }
        if( d->F.cursor < (fsl_int_t)d->F.used ) *rv = FCARD(d, d->F.cursor++);
        break;
      }else if( d->F.cursor >= (fsl_int_t)d->F.used ){
        /* We have used all entries from the delta.  Return the next
           entry from the baseline. */
        if( pB->F.cursor < (fsl_int_t)pB->F.used ) *rv = FCARD(pB, pB->F.cursor++);
        break;
      }else if( (cmp = fsl_strcmp(FCARD(pB,pB->F.cursor)->name,
                                  FCARD(d, d->F.cursor)->name)) < 0){
        /* The next baseline entry comes before the next delta entry.
           So return the baseline entry. */
        *rv = FCARD(pB, pB->F.cursor++);
        break;
      }else if( cmp>0 ){
        /* The next delta entry comes before the next baseline
           entry so return the delta entry, unless it deletes a file
           which is not in the baseline. */
        if( !FCARD(d, d->F.cursor)->uuid ){
          ++d->F.cursor;
          continue;
        }
        *rv = FCARD(d, d->F.cursor++);
        break;
      }else if( FCARD(d, d->F.cursor)->uuid ){
        /* The next delta entry is a replacement for the next baseline
           entry.  Skip the baseline entry and return the delta entry */
        pB->F.cursor++;
        *rv = FCARD(d, d->F.cursor++);
        break;
      }else{
        assert(0==cmp);
        /*
          The next delta entry is a delete of the next baseline entry.
        */
        /* Skip them both.  Repeat the loop to find the next
           non-delete entry. */
        pB->F.cursor++;
        d->F.cursor++;
        continue;
      }
    }
    return 0;
  }
#undef FCARD
}

int fsl__deck_deltify_parent(fsl_deck * d){
  int rc = 0;
  assert( d->f );
  assert( d->rid>0 );
  if(d->P.used){
    assert(FSL_SATYPE_CHECKIN == d->type
           || FSL_SATYPE_WIKI == d->type
           || FSL_SATYPE_FORUMPOST == d->type
           || FSL_SATYPE_EVENT == d->type);
    fsl_id_t const prid =
      fsl_uuid_to_rid(d->f, (char const *)d->P.list[0]);
    /* Parent-deltification is a space optimization. In fossil(1)
    ** content_deltify() gracefully ignores a source rid of 0 and a
    ** phantom source (content.c: "if(0==rid) return 0" and the
    ** content_is_available() check), so the caller may pass a missing
    ** parent through harmlessly. libfossil's fsl__content_deltify()
    ** instead rejects srcid<=0 (FSL_RC_RANGE / assert), so we must guard
    ** here: deltify only when the parent is present (prid>0); skip when
    ** it is not yet in the repo (prid==0, e.g. a phantom during a
    ** multi-trip clone); propagate a real lookup error (prid<0). */
    rc = prid>0
      ? fsl__content_deltify(d->f, prid, d->rid, 0)
      : (prid<0 ? d->f->error.code : 0);
#if 0
    MARKER(("Deltifying parent(%d) of deck(%d) rc=%s...\n",
            (int)prid, (int)d->rid, fsl_rc_cstr(rc) ));
    fsl_db_each( fsl_cx_db(d->f), fsl_stmt_each_f_dump,
                 d->f, "SELECT CAST(fsl_uncompress(content) AS text) "
                 "FROM {{dbname.repo}}.blob WHERE rid=%d",(int)prid);
#endif

  }
  return rc;
}

/**
   Parses a copy of src, the output of fsl_deck_output() for d, and
   fails if it does not parse or parses to a deck of a different type
   or with a different number of F-cards. fossil(1) parses an artifact
   before crosslinking it, so text which fails here would be crosslinked
   locally but rejected by fossil(1), by other replicas and by a
   rebuild. The parser drops F-cards with reserved names, such as
   ".fslckout", so a lost F-card shows up only in the count. Returns 0
   on success, else an error code with d->f's error state set.
*/
static int fsl__deck_save_reparse(fsl_deck const * const d,
                                  fsl_b const * const src){
  fsl_cx * const f = d->f;
  fsl_b * const copy = fsl_cx_b_borrow(f);
  fsl_deck dp = fsl_deck_empty;
  int rc = copy ? fsl_b_copy(copy, src) : FSL_RC_OOM;
  if( rc ) goto end;
  dp.f = f;
  rc = fsl_deck_parse(&dp, copy);
  if( rc ){
    if( !f->error.code ) rc = fsl_cx_err_set(f, rc, "%s", fsl_rc_cstr(rc));
    goto end;
  }
  if( dp.type!=d->type ){
    rc = fsl_cx_err_set(f, FSL_RC_SYNTAX,
                        "The %s deck's text parses as a %s artifact.",
                        fsl_satype_cstr(d->type),
                        fsl_satype_cstr(dp.type));
  }else if( dp.F.used!=d->F.used ){
    fsl_card_F const * fc = NULL;
    uint32_t i;
    for( i = 0; i < d->F.used; ++i ){
      fc = F_at(&d->F, i);
      if( fsl_is_reserved_fn(fc->name, -1) ) break;
      fc = NULL;
    }
    rc = fc
      ? fsl_cx_err_set(f, FSL_RC_RANGE,
                       "F-card name is reserved: %s", fc->name)
      : fsl_cx_err_set(f, FSL_RC_SYNTAX,
                       "The deck's text parses with %u F-card(s), "
                       "not %u.", (unsigned)dp.F.used,
                       (unsigned)d->F.used);
  }
  end:
  fsl_deck_finalize(&dp);
  if( copy ) fsl_cx_b_return(f, copy);
  return rc;
}

int fsl_deck_save( fsl_deck * const d, bool isPrivate ){
  int rc;
  fsl_cx * const f = d->f;
  fsl_db * const db = fsl_needs_repo(f);
  fsl_b * const buf = &d->f->cache.fileContent;
  fsl_id_t newRid = 0;
  bool const oldPrivate = f->cache.markPrivate;
  if(!f || !d ) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  if(d->rid>0){
#if 1
    return 0;
#else
    return fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                          "Cannot re-save an existing deck, as that could "
                          "lead to inconsistent data.");
#endif
  }
  if(d->B.uuid && fsl_repo_forbids_delta_manifests(f)){
    return fsl_cx_err_set(f, FSL_RC_ACCESS,
                          "This deck is a delta manifest, but this "
                          "repository has disallowed those via the "
                          "forbid-delta-manifests config option.");
  }

  fsl_cx_err_reset(f);
  /* fossil(1) makes private a commit whose primary parent is
     private, and leaves private merge parents out of a public commit.
     A public child would sync and leave replicas with a permanent
     phantom for the parent. */
  for(uint32_t i = 0; !isPrivate && i < d->P.used; ++i){
    fsl_id_t const prid = fsl_deck_P_get_id(d, (int)i);
    if(prid<0){
      return f->error.code
        ? f->error.code
        : fsl_cx_err_set(f, FSL_RC_ERROR, "Cannot resolve P-card %s.",
                         (char const *)d->P.list[i]);
    }
    if(prid>0 && fsl_content_is_private(f, prid)){
      if(0==i) isPrivate = true;
      else{
        fsl_deck_free_string(d, (char *)d->P.list[i]);
        memmove(&d->P.list[i], &d->P.list[i+1],
                sizeof(void*) * (--d->P.used - i));
        --i;
      }
    }
  }
  fsl_size_t const reserveSize =
    (1024 * 10)
    + (50 * d->T.used)
    + (50 * d->M.used)
    + (120 * d->F.used)
    + d->W.used;
  fsl_b_reuse(buf);
  /* Start the transaction before generating the output: that can load
     the baseline, which creates a phantom for a missing one. */
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if(rc){
    return fsl_cx_uplift_db_error2(f, db, rc);
  }
  if(d->R && FSL_SATYPE_CHECKIN==d->type
     && (FSL_CX_F_CALC_R_CARD & f->flags)){
    /* fsl_deck_output() calculates the R-card only if it is unset.
       Check one the caller set, as fossil(1) checks its own after a
       commit: a wrong one makes every checkout of the artifact report
       a checksum mismatch. This runs before the output because the
       calculation uses buf. */
    char zR[FSL_STRLEN_MD5+1] = {0};
    char * pR = zR;
    rc = fsl_deck_R_calc2(d, &pR);
    if(0==rc && 0!=fsl_strcmp(zR, d->R)){
      rc = fsl_cx_err_set(f, FSL_RC_CONSISTENCY,
                          "The R-card, %s, does not match the "
                          "F-cards' checksum, %s.", d->R, zR);
    }
  }
  if(0==rc) rc = fsl_b_reserve(buf, reserveSize);
  if(0==rc) rc = fsl_deck_output(d, fsl_output_f_b, buf);
  if(0==rc && f->signer.callback && !isPrivate){
    /* Sign the complete text, Z-card included, before it is hashed
       and stored, and never a private artifact, as fossil(1)'s
       clearsign() does. The hash then covers the envelope. */
    fsl_b * const orig = fsl_cx_b_borrow(f);
    rc = orig ? fsl_b_copy(orig, buf) : f->error.code;
    if(0==rc) rc = f->signer.callback(d, buf, f->signer.state);
    if(rc){
      if(!f->error.code){
        rc = fsl_cx_err_set(f, rc, "The artifact signer failed: %s",
                            fsl_rc_cstr(rc));
      }
    }else if(0!=fsl_b_compare(orig, buf)){
      /* The signer changed the text: it must strip back to what it
         was given, or no reader could parse the artifact. */
      char const * z = fsl_b_cstr(buf);
      fsl_size_t n = buf->used;
      if( !fsl_signature_strip(&z, &n) || n!=orig->used
          || 0!=memcmp(z, orig->mem, n) ){
        rc = fsl_cx_err_set(f, FSL_RC_CONSISTENCY,
                            "The artifact signer did not return the "
                            "artifact text in a PGP or SSH clearsign "
                            "envelope.");
      }
    }
    fsl_cx_b_return(f, orig);
  }
  if(rc){
    fsl_db_txn_end(db, 1);
    fsl_b_reuse(buf);
    return rc;
  }
  if(0){
    MARKER(("Saving deck:\n%s\n", fsl_b_cstr(buf)));
  }

  /* Starting here, don't return, use (goto end) instead. */

  if( d->B.uuid ){
    /* Artifact draft 4.7.3: a writer must not create a delta manifest
       whose baseline is itself a delta manifest. fossil(1) never
       does: it always names its parent's baseline. */
    rc = d->B.baseline ? 0 : fsl_deck_baseline_fetch(d);
    if( 0==rc && d->B.baseline && d->B.baseline->B.uuid ){
      rc = fsl_cx_err_set(f, FSL_RC_SYNTAX,
                          "Baseline %s is itself a delta manifest. "
                          "Name its baseline, %s, instead.",
                          d->B.uuid, d->B.baseline->B.uuid);
    }
    if(rc) goto end;
  }

  rc = fsl__deck_save_reparse(d, buf);
  if(rc) goto end;

  f->cache.markPrivate = isPrivate;
  {
    rc = fsl__content_put_ex(f, buf, NULL, 0,
                            0U, isPrivate, &newRid);
    if(rc) goto end;
    assert(newRid>0);
  }

  /* We need d->rid for crosslinking purposes, but will unset it on
     error because its value will no longer be in the db after
     rollback...
  */
  d->rid = newRid;

  /* If d has a parent, deltify the parent. */
  rc = fsl__deck_deltify_parent(d);
  if( rc ) goto end;
#if 0
  if(FSL_SATYPE_WIKI==d->type){
    /*
      MISSING: fossil's wiki.c:wiki_put() handles the moderation bits.
    */
  }
#endif
  assert( 0==rc );
  if( !isPrivate ){
    rc = fsl__unsent_rid_add(f, d->rid);
  }
  if( 0==rc ){
    rc = f->cache.isCrosslinking
      ? fsl__deck_crosslink(d)
      : fsl__deck_crosslink_one(d);
  }
  end:
  f->cache.markPrivate = oldPrivate;
  if(!rc) rc = fsl_db_txn_end(db, 0);
  else fsl_db_txn_end(db, 1);
  if(rc){
    d->rid = 0 /* this blob.rid will be lost after rollback */;
    if(!f->error.code && db->error.code){
      rc = fsl_cx_uplift_db_error(f, db);
    }
    if(FSL_RC_OOM!=rc){
      /* The artifact's hash is the hash of buf. */
      fsl_b hash = fsl_b_empty;
      if(0==fsl_cx_hash_buffer(f, false, buf, &hash)){
        fsl__deck_err_prefix(f, rc, "Saving %s artifact %b",
                             fsl_satype_cstr(d->type), &hash);
      }else{
        fsl__deck_err_prefix(f, rc, "Saving %s artifact",
                             fsl_satype_cstr(d->type));
      }
      fsl_b_clear(&hash);
    }
  }
  fsl_b_reuse(buf);
  return rc;
}

int fsl__crosslink_end(fsl_cx * const f, int resultCode){
  int rc = 0;
  fsl_db * const db = fsl_cx_db_repo(f);
  fsl_stmt q = fsl_stmt_empty;
  fsl_stmt u = fsl_stmt_empty;
  int i;
  assert(f);
  assert(db);
  assert(f->cache.isCrosslinking && "Internal API misuse.");
  if(!f->cache.isCrosslinking){
    fsl__fatal(FSL_RC_MISUSE,
              "Internal API misuse: %s() called while "
              "f->cache.isCrosslinking is false.", __func__);
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Crosslink is not running.");
  }
  f->cache.isCrosslinking = false;
  if(resultCode){
    assert(0!=fsl_cx_txn_level(f)
           && "Expecting a transaction level from fsl__crosslink_begin()");
    fsl_db_txn_end(db, true)
      /* pop transaction started from fsl__crosslink_begin().  We use
         fsl_db_txn_end() instead of fsl_cx_txn_end()
         so that any db-level error which is set during a failed
         rollback does not trump any pending f->error.code. */;
    return resultCode;
  }
  assert(db->impl.txn.level > 0);

  /* Handle any reparenting via tags... */
  rc = fsl_cx_prepare(f, &q,
                     "SELECT rid, value FROM {{dbname.repo}}.tagxref"
                      " WHERE tagid=%d AND tagtype=%d",
                      (int)FSL_TAGID_PARENT, (int)FSL_TAGTYPE_ADD);
  if(rc) goto end;
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    fsl_id_t const rid = fsl_stmt_g_id(&q, 0);
    const char *zTagVal = fsl_stmt_g_text(&q, 1, 0);
    rc = fsl_crosslink_reparent(f,rid, zTagVal);
    if(rc){
      fsl__deck_err_prefix(f, rc, "Applying parent tag to rid %"
                           FSL_ID_T_PFMT, rid);
      break;
    }
  }
  fsl_stmt_finalize(&q);
  if(rc) goto end;

  /* Process entries from pending_xlink temp table... */
  rc = fsl_cx_prepare(f, &q, "SELECT id FROM {{temp.pending_xlink}}");
  while( 0==rc && fsl__cx_stmt_step_each(f, &q, &rc) ){
    const char *zId = fsl_stmt_g_text(&q, 0, NULL);
    char cType;
    if(!zId || !*zId) continue;
    cType = zId[0];
    ++zId;
    if('t'==cType){
      rc = fsl__ticket_rebuild(f, zId);
      continue;
    }else if('w'==cType){
      rc = fsl__backlink_wiki_refresh(f, zId);
      continue;
    }
  }
  fsl_stmt_finalize(&q);
  if(rc) goto end;
  rc = fsl_cx_exec(f, "DELETE FROM {{temp.pending_xlink}}");
  if(rc) goto end;
  /* If multiple check-ins happen close together in time, adjust their
     times by a few milliseconds to make sure they appear in chronological
     order.
  */
  rc = fsl_cx_prepare(f, &q,
                      "UPDATE {{temp.time_fudge}} SET m1=m2-:incr "
                      "WHERE m1>=m2 AND m1<m2+:window"
  );
  if(rc) goto end;
  fsl_stmt_bind_double_name(&q, ":incr", AGE_ADJUST_INCREMENT);
  fsl_stmt_bind_double_name(&q, ":window", AGE_FUDGE_WINDOW);
  rc = fsl_cx_prepare(f, &u,
                      "UPDATE {{temp.time_fudge}} AS time_fudge SET m2="
                      "(SELECT x.m1 FROM {{temp.time_fudge}} AS x"
                      " WHERE x.mid=time_fudge.cid)");
  for(i=0; !rc && i<30; i++){ /* where does 30 come from? */
    rc = fsl_stmt_step(&q);
    if(FSL_RC_STEP_DONE==rc) rc=0;
    else break;
    fsl_stmt_reset(&q);
    if( fsl_db_changes_recent(db)==0 ) break;
    rc = fsl_stmt_step(&u);
    if(FSL_RC_STEP_DONE==rc) rc=0;
    else break;
    fsl_stmt_reset(&u);
  }
  fsl_stmt_finalize(&q);
  fsl_stmt_finalize(&u);
  bool fudged = false;
  if(!rc) rc = fsl_db_exists2(db, &fudged, "SELECT 1 FROM {{temp.time_fudge}}");
  if(!rc && fudged){
    rc = fsl_cx_exec(f, "UPDATE {{dbname.repo}}.event SET"
                     " mtime=(SELECT m1 FROM {{temp.time_fudge}} WHERE mid=objid)"
                     " WHERE objid IN (SELECT mid FROM {{temp.time_fudge}})"
                     " AND (mtime=omtime OR omtime IS NULL)"
                     );
  }
  end:
  if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  fsl_cx_exec(f, "DELETE FROM {{temp.time_fudge}}");
  if(rc) fsl_cx_txn_end(f, true);
  else rc = fsl_cx_txn_end(f, false);
  return rc;
}

int fsl__crosslink_begin(fsl_cx * const f){
  int rc;
  assert(f);
  assert(0==f->cache.isCrosslinking);
  if(f->cache.isCrosslinking){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Crosslink is already running.");
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if(rc) return rc;
  rc = fsl_cx_exec_multi(f,
     "CREATE TEMP TABLE IF NOT EXISTS "
     "{{temp.pending_xlink}}(id TEXT PRIMARY KEY)WITHOUT ROWID;"
     "CREATE TEMP TABLE IF NOT EXISTS {{temp.time_fudge}}("
     "  mid INTEGER PRIMARY KEY,"    /* The rid of a manifest */
     "  m1 REAL,"                    /* The timestamp on mid */
     "  cid INTEGER,"                /* A child or mid */
     "  m2 REAL"                     /* Timestamp on the child */
     ");"
     "DELETE FROM {{temp.pending_xlink}}; "
     "DELETE FROM {{temp.time_fudge}};");
  if(0==rc){
    f->cache.isCrosslinking = true;
  }else{
    fsl_cx_txn_end(f, true);
  }
  return rc;
}

int fsl_deck_foreach(fsl_cx * const f, fsl_satype_e type,
                     fsl_deck_visitor_f visitor,
                     void * visitorState){
  int rc = 0;
  fsl_stmt q = fsl_stmt_empty;
  switch(type){
    case FSL_SATYPE_CHECKIN:
    case FSL_SATYPE_FORUMPOST:
    case FSL_SATYPE_CONTROL:
      rc = fsl_cx_prepare(f, &q,
                          "SELECT objid FROM {{dbname.repo}}.event WHERE type=%Q",
                          fsl_satype_event_cstr(type));
      break;
    case FSL_SATYPE_WIKI:
      rc = fsl_cx_prepare(f, &q,
                          "SELECT x.rid AS mrid FROM {{dbname.repo}}.tag t, {{dbname.repo}}.tagxref x "
                          "WHERE x.tagid=t.tagid "
                          "AND t.tagname LIKE 'wiki-%%' "
                          "AND TYPEOF(x.value+0)='integer'"
                          // ^^^^ only 'wiki-%' tags which are wiki pages
                          "ORDER BY x.mtime DESC");
      break;
    case FSL_SATYPE_TICKET:
      rc = fsl_cx_prepare(f, &q,
                          "SELECT rid FROM {{dbname.repo}}.tagxref WHERE tagid IN "
                          "(SELECT tagid FROM {{dbname.repo}}.tag WHERE tagname LIKE "
                          "'tkt-%%' AND LENGTH(tagname)=44) "
                          "ORDER BY mtime");
      break;
    case FSL_SATYPE_TECHNOTE:
      rc = fsl_cx_prepare(f, &q,
                          "SELECT x.rid AS mrid FROM {{dbname.repo}}.tag t, {{dbname.repo}}.tagxref x "
                          "WHERE x.tagid=t.tagid "
                          "AND t.tagname LIKE 'event-%%' "
                          //"AND TYPEOF(x.value+0)='integer'"
                          // ^^^^ only 'event-%' tags which are technotes.
                          // UNTESTED on technotes (see WIKI, above) except
                          // in the SQLite shell, where it seems to behave.
                          "ORDER BY x.mtime DESC");
      break;
#if 0
    case FSL_SATYPE_ANY:
      /* This case leads to confusion because ATTACHMENT records are
         recorded in the timeline as the underlying type of record to
         which the attachment is applied. e.g. an attachment on a wiki
         page is listed as a 'w' event. */
      rc = fsl_cx_prepare(f, &q,
                          "SELECT objid FROM {{dbname.repo}}.event WHERE type IN"
                          "(%Q, %Q, %Q, %Q, %Q) /*%s()*/",
                          fsl_satype_event_cstr(FSL_SATYPE_CHECKIN),
                          fsl_satype_event_cstr(FSL_SATYPE_TICKET),
                          fsl_satype_event_cstr(FSL_SATYPE_FORUMPOST),
                          fsl_satype_event_cstr(FSL_SATYPE_WIKI),
                          fsl_satype_event_cstr(FSL_SATYPE_CONTROL),
                          __func__);
      break;
#endif
    default:
      return fsl_cx_err_set(f, FSL_RC_TYPE,
                            "Artifact type [%s] is not currently "
                            "supported by %s().",
                            fsl_satype_cstr(type),
                            __func__);
  }
  while(0==rc && (fsl__cx_stmt_step_each(f, &q, &rc))){
    fsl_id_t const rid = fsl_stmt_g_id(&q, 0);
    fsl_deck d = fsl_deck_empty;
    rc = fsl_deck_load_rid(f, &d, rid, type);
    if(0==rc){
      rc = visitor(f, &d, visitorState);
    }
    fsl_deck_finalize(&d);
    if(FSL_RC_BREAK==rc){
      rc = 0;
      break;
    }
  }
  fsl_stmt_finalize(&q);
  return rc;
}

static const char * fsl__deck_type_json(fsl_satype_e t){
  switch(t){
    case FSL_SATYPE_CHECKIN: return "checkin";
    case FSL_SATYPE_CLUSTER: return "cluster";
    case FSL_SATYPE_CONTROL: return "tag"/*by request from drh*/;
    case FSL_SATYPE_WIKI: return "wiki";
    case FSL_SATYPE_TICKET: return "ticket";
    case FSL_SATYPE_ATTACHMENT: return "attachment";
    case FSL_SATYPE_TECHNOTE: return "technote";
    case FSL_SATYPE_FORUMPOST: return "forumpost";
    default:
      return NULL;
  }
}

int fsl_deck_to_json(fsl_deck const * d, fsl_output_f fn, void * fState){
  fsl_cx * const f = d->f;
  int rc = 0;
  char * z = 0;
  if( !f ) return FSL_RC_MISUSE;
  /** Maintenance reminder: this output is intended to remain
      compatible with fossil(1)'s. */
#define RC if(rc) goto end
#define APPN0(...) rc = fsl_appendn(fn, fState, __VA_ARGS__)
#define APPN(...) APPN0(__VA_ARGS__); RC
#define APPF0(...) rc = fsl_appendf(fn, fState, __VA_ARGS__)
#define APPF(...) APPF0(__VA_ARGS__); RC
  APPN("{", 1);
  if( d->rid ){
    z = fsl_rid_to_uuid(f, d->rid);
    if( !z ){
      /* fsl_rid_to_uuid() describes all failures except OOM. */
      return f->error.code ? f->error.code : FSL_RC_OOM;
    }
    APPF0("\"uuid\":%!j", z);
    fsl_free(z);
    z = 0;
    RC;
  }else{
    APPF0("\"uuid\":null");
  }
#define ISA(TYPE) if( d->type==TYPE )
#define CARD_LETTER(LETTER) \
  APPN(",\"" #LETTER "\":", -1)
  /*blob_appendf(b, ", \"rid\": %d", p->rid); not portable across repos*/
  APPF(", \"type\":%!j", fsl__deck_type_json(d->type));
#define CARD_STR(LETTER, VAL) \
  assert( VAL ); CARD_LETTER(LETTER); APPF("%!j", VAL)
#define CARD_STR2(LETTER, VAL) \
  if( VAL ) { CARD_STR(LETTER, VAL); } (void)0
#define STR_OR_NULL(VAL)                 \
  if( VAL ) { APPF("%!j", VAL); }        \
  else { APPN("null", 4); } (void)0
#define KVP_STR(ADDCOMMA, KEY,VAL)  \
  if(ADDCOMMA) {APPN(",",1);}       \
  APPF("%!j:", #KEY);              \
  STR_OR_NULL(VAL)

  ISA( FSL_SATYPE_ATTACHMENT ){
    CARD_LETTER(A);
    APPN("{",1);
    KVP_STR(0, filename, d->A.name);
    KVP_STR(1, target, d->A.tgt);
    KVP_STR(1, source, d->A.src);
    APPN("}",1);
  }
  CARD_STR2(B, d->B.uuid);
  CARD_STR2(C, d->C);
  CARD_LETTER(D); APPF("%f", d->D);
  ISA( FSL_SATYPE_TECHNOTE ){
    APPF(", \"E\":{\"time\":%f,\"id\":%!j}",
         d->E.julian, d->E.uuid);
  }
  ISA( FSL_SATYPE_CHECKIN ){
    CARD_LETTER(F);
    APPN("[",1);
    for( fsl_size_t i = 0; i < d->F.used; ++i ){
      fsl_card_F const * const cf = &d->F.list[i];
      char perms[] = {0,0,0};
      short iPerm = 0;
      if( i>0 ) {APPN(",",1);}
      APPN("{",1);
      KVP_STR(0, name, cf->name);
      KVP_STR(1, uuid, cf->uuid);
      if( cf->perm & FSL_FILE_PERM_EXE ) perms[iPerm++] = 'x';
      if( cf->perm & FSL_FILE_PERM_LINK ) perms[iPerm++] = 'l';
      KVP_STR(1, perm, iPerm ? &perms[0] : NULL);
      KVP_STR(1, rename, cf->priorName);
      APPN("}",1);
    }
    /* Special case: model checkins with no F-card as having an empty
    ** array, rather than no F-cards, to hypothetically simplify
    ** handling in JSON queries. */
    APPN("]",1);
  }
  CARD_STR2(G, d->G);
  ISA( FSL_SATYPE_FORUMPOST ){
    CARD_LETTER(H);
    STR_OR_NULL((d->H && *d->H) ? d->H : NULL);
    CARD_STR2(I, d->I);
  }
  if( d->J.used ){
    CARD_LETTER(J);
    APPN("[",1);
    for( fsl_size_t i = 0; i < d->J.used; ++i ){
      fsl_card_J const * const cj = d->J.list[i];
      if( i>0 ) {APPN(",",1);}
      APPN("{",1);
      KVP_STR(0, name, cj->field);
      APPF(",\"append\":%s", cj->append ? "true" : "false");
      KVP_STR(1, value, cj->value);
      APPN("}",1);
    }
    APPN("]",1);
  }
  CARD_STR2(K, d->K);
  CARD_STR2(L, d->L);
  ISA( FSL_SATYPE_CLUSTER ){
    CARD_LETTER(M);
    APPN("[",1);
    for( fsl_size_t i = 0; i < d->M.used; ++i ){
      if( i>0 ) {APPN(",",1);}
      APPF("%!j", (const char *)d->M.list[i]);
    }
    APPN("]",1);
  }
  CARD_STR2(N, d->N);
  ISA( FSL_SATYPE_CHECKIN || d->P.used ){
    CARD_LETTER(P);
    APPN("[",1);
    for( fsl_size_t i = 0; i < d->P.used; ++i ){
      if( i>0 ) {APPN(",",1);}
      APPF("%!j", (const char *)d->P.list[i]);
    }
    /* Special case: model checkins with no P-card as having an empty
    ** array, as per F-cards. */
    APPN("]",1);
  }
  if( d->Q.used ){
    CARD_LETTER(Q);
    APPN("[",1);
    for( fsl_size_t i = 0; i < d->Q.used; ++i ){
      fsl_card_Q const * const cq = (fsl_card_Q const *)d->Q.list[i];
      if( i>0 ) {APPN(",",1);}
      APPN("{",1);
      char type = '?';
      switch( cq->type ){
        case FSL_CHERRYPICK_ADD: type = '+'; break;
        case FSL_CHERRYPICK_BACKOUT: type = '-'; break;
        default: assert(!"Invalid Q-card"); break;
      }
      APPF("\"type\":\"%c\"", type);
      KVP_STR(1, target, cq->target);
      KVP_STR(1, base, cq->baseline);
      APPN("}",1);
    }
    APPN("]",1);
  }
  CARD_STR2(R, d->R);
  if( d->T.used ){
    CARD_LETTER(T);
    APPN("[",1);
    for( fsl_size_t i = 0; i < d->T.used; ++i ){
      fsl_card_T const * const c = (fsl_card_T const *)d->T.list[i];
      if( i>0 ) {APPN(",",1);}
      APPN("{",1);
      char type = '?';
      switch(c->type){
        case FSL_TAGTYPE_ADD: type = '+'; break;
        case FSL_TAGTYPE_CANCEL: type = '-'; break;
        case FSL_TAGTYPE_PROPAGATING: type = '*'; break;
        default: assert(!"Invalid tag type!"); break;
      }
      APPF("\"type\":\"%c\"", type);
      KVP_STR(1, name, c->name);
      KVP_STR(1, target, c->uuid ? c->uuid : "*");
      KVP_STR(1, value, c->value);
      APPN("}",1);
    }
    APPN("]",1);
  }
  CARD_STR2(U, d->U);
  ISA( FSL_SATYPE_WIKI || FSL_SATYPE_FORUMPOST==d->type
       || FSL_SATYPE_TECHNOTE==d->type || d->W.used ){
    CARD_LETTER(W);
    if( d->W.used ){ APPF("%!j", fsl_b_cstr(&d->W)); }
    else{ APPN("null", 4); }
  }
  APPN("}", 1);
end:
  return rc;
#undef APPF
#undef APPF0
#undef APPN
#undef APPN0
#undef CARD_FMT
#undef CARD_LETTER
#undef CARD_STR
#undef CARD_STR2
#undef ISA
#undef KVP_STR
#undef RC
#undef STR_OR_NULL
}


#undef MARKER
#undef AGE_FUDGE_WINDOW
#undef AGE_ADJUST_INCREMENT
#undef F_at
/* end of file src/deck.c */
/* start of file src/delta.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**************************************************************************
  This file houses Fossil's delta generation and application
  routines. This code is functionally independent of the rest of the
  library, relying only on fsl_malloc(), fsl_free(), and the integer
  typedefs defined by the configuration process. i.e. it can easily
  be pulled out and used in arbitrary projects.
*/
#include <memory.h>
#include <stdlib.h>

/**
   2021-03-10: The delta checksum self-test is a significant run-time
   sink when processing many deltas. Fossil does not enable this
   feature by default so we'll leave it off by default, too.
*/
#if !defined(FSL_OMIT_DELTA_CKSUM_TEST)
#  define FSL_OMIT_DELTA_CKSUM_TEST
#endif

/*
   Macros for turning debugging printfs on and off
*/
#if 0
# define DEBUG1(X) X
#else
# define DEBUG1(X)
#endif
#if 0
#define DEBUG2(X) X
/*
   For debugging:
   Print 16 characters of text from zBuf
*/
static const char *print16(const char *z){
  int i;
  static char zBuf[20];
  for(i=0; i<16; i++){
    if( z[i]>=0x20 && z[i]<=0x7e ){
      zBuf[i] = z[i];
    }else{
      zBuf[i] = '.';
    }
  }
  zBuf[i] = 0;
  return zBuf;
}
#else
# define DEBUG2(X)
#endif

/*
   The width of a hash window in bytes.  The algorithm only works if this
   is a power of 2.
*/
#define NHASH 16

/*
   The current state of the rolling hash.

   z[] holds the values that have been hashed.  z[] is a circular buffer.
   z[i] is the first entry and z[(i+NHASH-1)%NHASH] is the last entry of
   the window.

   Hash.a is the sum of all elements of hash.z[].  Hash.b is a weighted
   sum.  Hash.b is z[i]*NHASH + z[i+1]*(NHASH-1) + ... + z[i+NHASH-1]*1.
   (Each index for z[] should be modulo NHASH, of course.  The %NHASH operator
   is omitted in the prior expression for brevity.)
*/
typedef struct fsl__delta_hash fsl__delta_hash;
struct fsl__delta_hash {
  uint16_t a, b;         /* Hash values */
  uint16_t i;            /* Start of the hash window */
  unsigned char z[NHASH];    /* The values that have been hashed */
};

/*
   Initialize the rolling hash using the first NHASH characters of z[]
*/
static void fsl__delta_hash_init(fsl__delta_hash *pHash,
                                unsigned char const *z){
  uint16_t a, b, i;
  a = b = 0;
  for(i=0; i<NHASH; i++){
    a += z[i];
    b += a;
  }
  memcpy(pHash->z, z, NHASH);
  pHash->a = a & 0xffff;
  pHash->b = b & 0xffff;
  pHash->i = 0;
}

/*
   Advance the rolling hash by a single character "c"
*/
static void fsl__delta_hash_next(fsl__delta_hash *pHash, int c){
  const uint16_t old = pHash->z[pHash->i];
  pHash->z[pHash->i] = c;
  pHash->i = (pHash->i+1)&(NHASH-1);
  pHash->a = pHash->a - old + c;
  pHash->b = pHash->b - NHASH*old + pHash->a;
}

/*
   Return a 32-bit hash value
*/
static uint32_t fsl__delta_hash_32bit(fsl__delta_hash *pHash){
  return (pHash->a & 0xffff) | (((uint32_t)(pHash->b & 0xffff))<<16);
}

/**
   Compute a hash on NHASH bytes.

   This routine is intended to be equivalent to:
   fsl__delta_hash h;
   fsl__delta_hash_init(&h, zInput);
   return fsl__delta_hash_32bit(&h);
*/
static uint32_t fsl__delta_hash_once(unsigned const char *z){
  uint16_t a = 0, b = 0, i = 0;
  for(i=0; i<NHASH; ++i){
    a += z[i];
    b += a;
  }
  return a | (((uint32_t)b)<<16);
}

/*
   Write an base-64 integer into the given buffer. Return its length.
*/
static unsigned int fsl__delta_int_put(uint32_t v, unsigned char **pz){
  static const char zDigits[] =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~";
  /*  123456789 123456789 123456789 123456789 123456789 123456789 123 */
  int i, j;
  unsigned char zBuf[20];
  fsl_size_t rc = 0;
  if( v==0 ){
    *(*pz)++ = '0';
    rc = 1;
  }else{
    for(i=0; v>0; ++rc, ++i, v>>=6){
      zBuf[i] = zDigits[v&0x3f];
    }
    zBuf[i]=0;
    for(j=i-1; j>=0; j--){
      *(*pz)++ = zBuf[j];
    }
  }
  return rc;
}

/*
   Read bytes from *pz and convert them into a positive integer.  When
   finished, leave *pz pointing to the first character past the end of
   the integer.  The *pLen parameter holds the length of the string
   in *pz and is decremented once for each character in the integer.
*/
static fsl_size_t fsl__delta_int_get(unsigned char const **pz, fsl_int_t *pLen){
  static const signed char zValue[] = {
    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
     0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
    -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
    25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
    -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
    52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,

    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1
  };
  fsl_size_t v = 0;
  fsl_int_t c;
  unsigned char *z = (unsigned char*)*pz;
  unsigned char *zEnd = z + (*pLen);
  while( z<zEnd && (c = zValue[*z])>=0 ){
    v = (v<<6) + c;
    z++;
  }
  *pLen -= (fsl_int_t)(z - *pz);
  *pz = z;
  return v;
}

/*
   Return the number digits in the base-64 representation of a positive integer
*/
static int fsl__delta_digit_count(fsl_int_t v){
  unsigned int x;
  int i;
  for(i=1, x=64; v>=(fsl_int_t)x; i++, x <<= 6){}
  return i;
}

/*
   Compute a 32-bit checksum on the N-byte buffer.  Return the result.
*/
static unsigned int fsl__delta_checksum(unsigned const char *zIn, fsl_size_t N){
  static const int byteOrderTest = 1;
  const unsigned char *z = (const unsigned char *)zIn;

  unsigned sum = 0;
  if( N>0 ){
    const unsigned char *zEnd = (const unsigned char*)&zIn[N&~3];
    /* zIn may have any alignment: callers of the public delta APIs
       pass their own buffers, so words are loaded with memcpy(). */
    if( 0==*(char*)&byteOrderTest ){
      /* This is a big-endian machine */
      while( z<zEnd ){
        unsigned w;
        memcpy(&w, z, 4);
        sum += w;
        z += 4;
      }
    }else{
      /* A little-endian machine */
#if GCC_VERSION>=4003000
      while( z<zEnd ){
        unsigned w;
        memcpy(&w, z, 4);
        sum += __builtin_bswap32(w);
        z += 4;
      }
#elif defined(_MSC_VER) && _MSC_VER>=1300
      while( z<zEnd ){
        unsigned w;
        memcpy(&w, z, 4);
        sum += _byteswap_ulong(w);
        z += 4;
      }
#else
      unsigned sum0 = 0;
      unsigned sum1 = 0;
      unsigned sum2 = 0;
      while(N >= 16){
        sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
        sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
        sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
        sum  += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
        z += 16;
        N -= 16;
      }
      while(N >= 4){
        sum0 += z[0];
        sum1 += z[1];
        sum2 += z[2];
        sum  += z[3];
        z += 4;
        N -= 4;
      }
      sum += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
#endif
    }
    switch(N&3){
      case 3:   sum += (z[2] << 8);
        FSL_SWITCH_FALL_THROUGH;
      case 2:   sum += (z[1] << 16);
        FSL_SWITCH_FALL_THROUGH;
      case 1:   sum += ((unsigned)z[0] << 24);
        FSL_SWITCH_FALL_THROUGH;
      default:  ;
    }
  }
  return sum;
}

int fsl_delta_create2( unsigned char const *zSrc, fsl_size_t lenSrc,
                       unsigned char const *zOut, fsl_size_t lenOut,
                       fsl_output_f out, void * outState){
  enum { IntegerBufSize = 50 /* buffer size for integer conversions. */};
  unsigned int i, base;
  unsigned int nHash;          /* Number of hash table entries */
  unsigned int *landmark;      /* Primary hash table */
  unsigned int *collide = NULL;  /* Collision chain */
  int lastRead = -1;           /* Last byte of zSrc read by a COPY command */
  int rc;                      /* generic return code checker. */
  unsigned int olen = 0;       /* current output length. */
  fsl__delta_hash h;
  unsigned char theBuf[IntegerBufSize] = {0,};
  unsigned char * intBuf = theBuf;
  if(!zSrc || !zOut || !out) return FSL_RC_MISUSE;
  else if(lenSrc>UINT32_MAX || lenOut>UINT32_MAX){
    /* The delta format encodes sizes and offsets in 32 bits. */
    return FSL_RC_RANGE;
  }
  /* Add the target file size to the beginning of the delta
  */
#ifdef DELTA_OUT
#undef DELTA_OUT
#endif
#define DELTA_OUT(BLOB,LEN) rc=out(outState, BLOB, LEN); if(0 != rc) {fsl_free(collide); return rc;} else (void)0
#define OUTCH(CHAR) DELTA_OUT(CHAR,1)
#define PINT(I) intBuf = theBuf; olen=fsl__delta_int_put(I, &intBuf); DELTA_OUT(theBuf,olen)
  PINT(lenOut);
  OUTCH("\n");

  /* If the source file is very small, it means that we have no
     chance of ever doing a copy command.  Just output a single
     literal segment for the entire target and exit.
  */
  if( lenSrc<=NHASH ){
    PINT(lenOut);
    OUTCH(":");
    DELTA_OUT(zOut,lenOut);
    PINT((fsl__delta_checksum(zOut, lenOut)));
    OUTCH(";");
    return 0;
  }

  /* Compute the hash table used to locate matching sections in the
     source file.
  */
  nHash = lenSrc/NHASH;
  collide = (unsigned int *)fsl_malloc(
    (fsl_size_t)nHash * 2 * sizeof(int) );
  if(!collide){
    return FSL_RC_OOM;
  }
  landmark = &collide[nHash];
  memset(landmark, -1, nHash*sizeof(int));
  memset(collide, -1, nHash*sizeof(int));
  for(i=0; i<lenSrc-NHASH; i+=NHASH){
    uint32_t const hv = fsl__delta_hash_once(&zSrc[i]) % nHash;
    collide[i/NHASH] = landmark[hv];
    landmark[hv] = i/NHASH;
  }

  /* Begin scanning the target file and generating copy commands and
     literal sections of the delta.
  */
  base = 0;    /* We have already generated everything before zOut[base] */
  while( base+NHASH<lenOut ){
    fsl_int_t iSrc;
    int iBlock
      /* WEIRD: if i change this from int to fsl_int_t
         we end up in an infinite loop somewhere. int
         and short both work*/;
    fsl_int_t bestCnt, bestOfst=0, bestLitsz=0;
    fsl__delta_hash_init(&h, &zOut[base]);
    i = 0;     /* Trying to match a landmark against zOut[base+i] */
    bestCnt = 0;
    while( 1 ){
      uint32_t hv;
      int limit = 250;

      hv = fsl__delta_hash_32bit(&h) % nHash;
      DEBUG2( printf("LOOKING: %4d [%s]\n", base+i, print16(&zOut[base+i])); )
      iBlock = (int)landmark[hv];
      while( iBlock>=0 && (limit--)>0 ){
        /*
           The hash window has identified a potential match against
           landmark block iBlock.  But we need to investigate further.

           Look for a region in zOut that matches zSrc. Anchor the search
           at zSrc[iSrc] and zOut[base+i].  Do not include anything prior to
           zOut[base] or after zOut[outLen] nor anything after zSrc[srcLen].

           Set cnt equal to the length of the match and set ofst so that
           zSrc[ofst] is the first element of the match.  litsz is the number
           of characters between zOut[base] and the beginning of the match.
           sz will be the overhead (in bytes) needed to encode the copy
           command.  Only generate copy command if the overhead of the
           copy command is less than the amount of literal text to be copied.
        */
        fsl_int_t cnt = 0, ofst = 0, litsz = 0;
        fsl_int_t j = 0, k = 0, x = 0, y = 0;
        fsl_int_t sz = 0;
        fsl_int_t limitX = 0;

        /* Beginning at iSrc, match forwards as far as we can.  j counts
           the number of characters that match */
        iSrc = iBlock*NHASH;
        y = base + i;
        limitX = ( lenSrc-iSrc <= lenOut-y ) ? lenSrc : iSrc + lenOut - y;
        for(x=iSrc; x<limitX; ++x, ++y){
          if( zSrc[x]!=zOut[y] ) break;
        }
        j = x - iSrc - 1;

        /* Beginning at iSrc-1, match backwards as far as we can.  k counts
           the number of characters that match */
        for(k=1; k<iSrc && k<=i; ++k){
          if( zSrc[iSrc-k]!=zOut[base+i-k] ) break;
        }
        --k;

        /* Compute the offset and size of the matching region */
        ofst = iSrc-k;
        cnt = j+k+1;
        litsz = i-k;  /* Number of bytes of literal text before the copy */
        DEBUG2( printf("MATCH %d bytes at %d: [%s] litsz=%d\n",
                        cnt, ofst, print16(&zSrc[ofst]), litsz); )
        /* sz will hold the number of bytes needed to encode the "insert"
           command and the copy command, not counting the "insert" text */
        sz = fsl__delta_digit_count(i-k)
          +fsl__delta_digit_count(cnt)
          +fsl__delta_digit_count(ofst)
          +3;
        if( cnt>=sz && cnt>bestCnt ){
          /* Remember this match only if it is the best so far and it
             does not increase the file size */
          bestCnt = cnt;
          bestOfst = iSrc-k;
          bestLitsz = litsz;
          DEBUG2( printf("... BEST SO FAR\n"); )
        }

        /* Check the next matching block */
        iBlock = collide[iBlock];
      }

      /* We have a copy command that does not cause the delta to be larger
         than a literal insert.  So add the copy command to the delta.
      */
      if( bestCnt>0 ){
        if( bestLitsz>0 ){
          /* Add an insert command before the copy */
          PINT(bestLitsz);
          OUTCH(":");
          DELTA_OUT(zOut+base, bestLitsz);
          base += bestLitsz;
          DEBUG2( printf("insert %d\n", bestLitsz); )
        }
        base += bestCnt;
        PINT(bestCnt);
        OUTCH("@");
        PINT(bestOfst);
        DEBUG2( printf("copy %d bytes from %d\n", bestCnt, bestOfst); )
        OUTCH(",");
        if( bestOfst + bestCnt -1 > lastRead ){
          lastRead = bestOfst + bestCnt - 1;
          DEBUG2( printf("lastRead becomes %d\n", lastRead); )
        }
        bestCnt = 0;
        break;
      }

      /* If we reach this point, it means no match is found so far */
      if( base+i+NHASH>=lenOut ){
        /* We have reached the end of the input and have not found any
           matches.  Do an "insert" for everything that does not match */
        PINT(lenOut-base);
        OUTCH(":");
        DELTA_OUT(zOut+base, lenOut-base);
        base = lenOut;
        break;
      }

      /* Advance the hash by one character.  Keep looking for a match */
      fsl__delta_hash_next(&h, zOut[base+i+NHASH]);
      i++;
    }
  }
  fsl_free(collide);
  /* Output a final "insert" record to get all the text at the end of
     the file that does not match anything in the source file.
  */
  if( base<lenOut ){
    PINT(lenOut-base);
    OUTCH(":");
    DELTA_OUT(zOut+base, lenOut-base);
  }
  /* Output the final checksum record. */
  PINT(fsl__delta_checksum(zOut, lenOut));
  OUTCH(";");
  return 0;
#undef PINT
#undef DELTA_OUT
#undef OUTCH
}

struct DeltaOutputString {
  unsigned char * mem;
  unsigned int cursor;
};
typedef struct DeltaOutputString DeltaOutputString;

/** fsl_output_f() impl which requires state to be a
    (DeltaOutputString*). Copies the first n bytes of src to
    state->mem, increments state->cursor by n, and returns 0.
 */
static int fsl__output_f_ostring( void * state, void const * src,
                                 fsl_size_t n ){
  DeltaOutputString * os = (DeltaOutputString*)state;
  memcpy( os->mem + os->cursor, src, n );
  os->cursor += n;
  return 0;
}

int fsl_delta_create( unsigned char const *zSrc, fsl_size_t lenSrc,
                      unsigned char const *zOut, fsl_size_t lenOut,
                      unsigned char *zDelta, fsl_size_t * deltaSize){
  int rc;
  DeltaOutputString os;
  os.mem = (unsigned char *)zDelta;
  os.cursor = 0;
  rc = fsl_delta_create2( zSrc, lenSrc, zOut, lenOut,
                          fsl__output_f_ostring, &os );
  if(!rc){
    os.mem[os.cursor] = 0;
    *deltaSize = os.cursor;
  }
  return rc;
}

int fsl_delta_applied_size(unsigned char const *zDelta, fsl_size_t lenDelta_,
                           fsl_size_t * deltaSize){
  if(!zDelta || !deltaSize) return FSL_RC_MISUSE;
  else if(lenDelta_<2) return FSL_RC_RANGE;
  else{
    fsl_int_t lenDelta = (fsl_int_t)lenDelta_;
    fsl_size_t size = fsl__delta_int_get(&zDelta, &lenDelta);
    if( lenDelta<=0 || *zDelta!='\n' ){
      /* ERROR: size integer not terminated by "\n" */
      return FSL_RC_DELTA_INVALID_TERMINATOR;
    }
    if( size > (fsl_size_t)0xffffffff ){
      /* Reject a declared output size that reaches 2^32. libfossil
      ** treats the delta size integer as a 32-bit unsigned value
      ** (conformance delta.policy.3.1.overflow-reject and
      ** delta.3.1.max-value), so a larger header is malformed. This
      ** also stops a hostile delta from driving an unbounded
      ** allocation in fsl_b_delta_apply2(). */
      return FSL_RC_RANGE;
    }
    *deltaSize = size;
    return 0;
  }
}


int fsl_delta_apply2(
  unsigned char const *zSrc,      /* The source or pattern file */
  fsl_size_t lenSrc_,            /* Length of the source file */
  unsigned char const *zDelta,    /* Delta to apply to the pattern */
  fsl_size_t lenDelta_,          /* Length of the delta */
  unsigned char *zOut,             /* Write the output into this preallocated buffer */
  fsl_error * pErr
){
  fsl_size_t limit = 0;
  fsl_size_t total = 0;
#if !defined(FSL_OMIT_DELTA_CKSUM_TEST)
  unsigned char *zOrigOut = zOut;
#endif
  /* lenSrc/lenDelta are cast to ints to avoid any potential side-effects
     caused by changing the function signature from signed to unsigned
     int types when porting from v1.
  */
  fsl_int_t lenSrc = (fsl_int_t)lenSrc_;
  fsl_int_t lenDelta = (fsl_int_t)lenDelta_;
  unsigned char const * const zDelta0 = zDelta;
  if(!zSrc || !zDelta || !zOut){
    if(pErr){
      fsl_error_set(pErr, FSL_RC_MISUSE,
                    "Delta: NULL source, delta, or output buffer");
    }
    return FSL_RC_MISUSE;
  }else if(lenSrc<0 || lenDelta<=0){
    if(pErr){
      fsl_error_set(pErr, FSL_RC_RANGE, lenDelta<=0
                    ? "Delta: delta is empty or too large"
                    : "Delta: source is too large");
    }
    return FSL_RC_RANGE;
  }
  limit = fsl__delta_int_get(&zDelta, &lenDelta);
  if( lenDelta<=0 || *zDelta!='\n' ){
    if(pErr){
      fsl_error_set(pErr,
                    FSL_RC_DELTA_INVALID_TERMINATOR,
                    "Delta: size integer not terminated by \\n");
    }
    return FSL_RC_DELTA_INVALID_TERMINATOR;
  }
  zDelta++; lenDelta--;
  while( *zDelta && lenDelta>0 ){
    fsl_int_t ofst = 0,
      cnt = fsl__delta_int_get(&zDelta, &lenDelta);
    if( lenDelta<=0 ){
      /* The integer ran to the end of the input, so there is no
         operator byte to read. */
      break;
    }
    switch( zDelta[0] ){
      case '@': {
        zDelta++; lenDelta--;
        ofst = fsl__delta_int_get(&zDelta, &lenDelta);
        if( lenDelta<=0 || zDelta[0]!=',' ){
          /* ERROR: copy command not terminated by ',' */
          if(pErr){
            fsl_error_set(pErr,
                          FSL_RC_DELTA_INVALID_TERMINATOR,
                          "Delta: copy command not terminated by ',' "
                          "at byte %" FSL_INT_T_PFMT,
                          (fsl_int_t)(zDelta - zDelta0));
          }
          return FSL_RC_DELTA_INVALID_TERMINATOR;
        }
        zDelta++; lenDelta--;
        DEBUG1( printf("COPY %d from %d\n", cnt, ofst); )
        total += cnt;
        if( total>limit ){
          if(pErr){
            fsl_error_set(pErr, FSL_RC_RANGE,
                          "Delta: copy exceeds output file size "
                          "(%" FSL_SIZE_T_PFMT " > %" FSL_SIZE_T_PFMT
                          " bytes)", total, limit);
          }
          return FSL_RC_RANGE;
        }
        if( ofst<0 || cnt<0
            || (uint64_t)ofst+(uint64_t)cnt > (uint64_t)lenSrc ){
          if(pErr){
            fsl_error_set(pErr, FSL_RC_RANGE,
                          "Delta: copy extends past end of input "
                          "(offset %" FSL_INT_T_PFMT " + count %"
                          FSL_INT_T_PFMT " > %" FSL_INT_T_PFMT
                          " bytes)", ofst, cnt, lenSrc);
          }
          return FSL_RC_RANGE;
        }
        memcpy(zOut, &zSrc[ofst], cnt);
        zOut += cnt;
        break;
      }
      case ':': {
        zDelta++; lenDelta--;
        total += cnt;
        if( total>limit ){
          if(pErr){
            fsl_error_set(pErr, FSL_RC_RANGE,
                          "Delta: insert command gives an output "
                          "larger than predicted (%" FSL_SIZE_T_PFMT
                          " > %" FSL_SIZE_T_PFMT " bytes)",
                          total, limit);
          }
          return FSL_RC_RANGE;
        }
        DEBUG1( printf("INSERT %d\n", cnt); )
        if( cnt<0 || cnt>lenDelta ){
          if(pErr){
            fsl_error_set(pErr, FSL_RC_RANGE,
                          "Delta: insert count exceeds size of delta "
                          "(%" FSL_INT_T_PFMT " > %" FSL_INT_T_PFMT
                          " bytes)", cnt, lenDelta);
          }
          return FSL_RC_RANGE;
        }
        memcpy(zOut, zDelta, cnt);
        zOut += cnt;
        zDelta += cnt;
        lenDelta -= cnt;
        break;
      }
      case ';': {
        zDelta++; lenDelta--;
        zOut[0] = 0;
#if !defined(FSL_OMIT_DELTA_CKSUM_TEST)
        if( cnt!=fsl__delta_checksum(zOrigOut, total) ){
          if(pErr){
            fsl_error_set(pErr, FSL_RC_CHECKSUM_MISMATCH,
                          "Delta: bad checksum");
          }
          return FSL_RC_CHECKSUM_MISMATCH;
        }
#endif
        if( total!=limit ){
          if(pErr){
            fsl_error_set(pErr, FSL_RC_SIZE_MISMATCH,
                          "Delta: generated size does not match "
                          "predicted size (%" FSL_SIZE_T_PFMT " != %"
                          FSL_SIZE_T_PFMT " bytes)", total, limit);
          }
          return FSL_RC_SIZE_MISMATCH;
        }
        return 0;
      }
      default: {
        if(pErr){
          fsl_error_set(pErr, FSL_RC_DELTA_INVALID_OPERATOR,
                        "Delta: unknown delta operator 0x%02x "
                        "at byte %" FSL_INT_T_PFMT, (int)zDelta[0],
                        (fsl_int_t)(zDelta - zDelta0));
        }
        return FSL_RC_DELTA_INVALID_OPERATOR;
      }
    }
  }
  /* ERROR: unterminated delta */
  if(pErr){
    fsl_error_set(pErr, FSL_RC_DELTA_INVALID_TERMINATOR,
                  "Delta: unterminated delta");
  }
  return FSL_RC_DELTA_INVALID_TERMINATOR;
}

int fsl_delta_apply(
  unsigned char const *zSrc,      /* The source or pattern file */
  fsl_size_t lenSrc_,            /* Length of the source file */
  unsigned char const *zDelta,    /* Delta to apply to the pattern */
  fsl_size_t lenDelta_,          /* Length of the delta */
  unsigned char *zOut             /* Write the output into this preallocated buffer */
){
  return fsl_delta_apply2(zSrc, lenSrc_, zDelta, lenDelta_, zOut, NULL);
}

#undef NHASH
#undef DEBUG1
#undef DEBUG2
/* end of file src/delta.c */
/* start of file src/dibu.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2022 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2013-2022 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/************************************************************************
  This file houses the "dibu" (Diff Builder) routines.
*/
#include <assert.h>
#include <memory.h>
#include <stdlib.h>
#include <string.h> /* for memmove()/strlen() */


#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


const fsl_dibu_opt fsl_dibu_opt_empty = fsl_dibu_opt_empty_m;
const fsl_dibu fsl_dibu_empty = fsl_dibu_empty_m;


fsl_dibu * fsl_dibu_alloc(fsl_size_t extra){
  if(extra > (fsl_size_t)SIZE_MAX - sizeof(fsl_dibu)) return NULL;
  fsl_dibu * rc =
    (fsl_dibu*)fsl_malloc(sizeof(fsl_dibu) + extra);
  if(rc){
    *rc = fsl_dibu_empty;
    if(extra){
      rc->pimpl = ((unsigned char *)rc)+sizeof(fsl_dibu);
    }
  }
  return rc;
}

static int fdb__out(fsl_dibu *const b,
                    char const *z, fsl_int_t n){
  if(n<0) n = (fsl_int_t)fsl_strlen(z);
  return b->opt->out(b->opt->outState, z, (fsl_size_t)n);
}
static int fdb__outf(fsl_dibu * const b,
                     char const *fmt, ...){
  int rc = 0;
  va_list va;
  assert(b->opt->out);
  va_start(va,fmt);
  rc = fsl_appendfv(b->opt->out, b->opt->outState, fmt, va);
  va_end(va);
  return rc;
}


/**
   Column indexes for DiffCounter::cols.
*/
enum DiffCounterCols {
DICO_NUM1 = 0, DICO_TEXT1,
DICO_MOD,
DICO_NUM2, DICO_TEXT2,
DICO_count
};
/**
   Internal state for the text-mode split diff builder. Used for
   calculating column widths in the builder's first pass so that
   the second pass can output everything in a uniform width.
*/
struct DiffCounter {
  /**
     Largest column width we've yet seen. These are only updated for
     DICO_TEXT1 and DICO_TEXT2. The others currently have fixed widths.

     FIXME: these are in bytes, not text columns. The current code may
     truncate multibyte characters.
  */
  uint32_t maxWidths[DICO_count];
  /**
     Max line numbers seen for the LHS/RHS input files. This is likely
     much higher than the number of diff lines.

     This can be used, e.g., to size and allocate a curses PAD in the
     second pass of the start() method.
  */
  uint32_t lineCount[2];
  /**
     The actual number of lines needed for rendering the file.
  */
  uint32_t displayLines;
};
typedef struct DiffCounter DiffCounter;
static const DiffCounter DiffCounter_empty = {{1,25,3,1,25},{0,0},0};
#define DICOSTATE(VNAME) DiffCounter * const VNAME = (DiffCounter *)b->pimpl

static int maxColWidth(fsl_dibu const * const b,
                       DiffCounter const * const sst,
                       int mwIndex){
  static const short minColWidth =
    10/*b->opt.columnWidth values smaller than this are treated as
        this value*/;
  switch(mwIndex){
    case DICO_NUM1:
    case DICO_NUM2:
    case DICO_MOD: return sst->maxWidths[mwIndex];
    case DICO_TEXT1: case DICO_TEXT2: break;
    default:
      assert(!"internal API misuse: invalid column index.");
      break;
  }
  int const y =
    (b->opt->columnWidth>0
     && b->opt->columnWidth<=sst->maxWidths[mwIndex])
    ? (int)b->opt->columnWidth
    : (int)sst->maxWidths[mwIndex];
  return minColWidth > y ? minColWidth : y;
}

static void fdb__dico_update_maxlen(DiffCounter * const sst,
                                    int col,
                                    char const * const z,
                                    uint32_t n){
  if(sst->maxWidths[col]<n){
#if 0
    sst->maxWidths[col] = n;
#else
    n = (uint32_t)fsl_strlen_utf8(z, (fsl_int_t)n);
    if(sst->maxWidths[col]<n) sst->maxWidths[col] = n;
#endif
  }
}

static int fdb__debug_start(fsl_dibu * const b){
  int rc = fdb__outf(b, "DEBUG builder starting pass #%d.\n",
                     b->passNumber);
  if(1==b->passNumber){
    DICOSTATE(sst);
    *sst = DiffCounter_empty;
    if(b->opt->nameLHS) ++sst->displayLines;
    if(b->opt->nameRHS) ++sst->displayLines;
    if(b->opt->hashLHS) ++sst->displayLines;
    if(b->opt->hashRHS) ++sst->displayLines;
    ++b->fileCount;
    return rc;
  }
  if(0==rc && b->opt->nameLHS){
    rc = fdb__outf(b,"LHS: %s\n", b->opt->nameLHS);
  }
  if(0==rc && b->opt->nameRHS){
    rc = fdb__outf(b,"RHS: %s\n", b->opt->nameRHS);
  }
  if(0==rc && b->opt->hashLHS){
    rc = fdb__outf(b,"LHS hash: %s\n", b->opt->hashLHS);
  }
  if(0==rc && b->opt->hashRHS){
    rc = fdb__outf(b,"RHS hash: %s\n", b->opt->hashRHS);
  }
  return rc;
}


static int fdb__debug_chunkHeader(fsl_dibu* const b,
                                  uint32_t lnnoLHS, uint32_t linesLHS,
                                  uint32_t lnnoRHS, uint32_t linesRHS ){
#if 1
  if(1==b->passNumber){
    DICOSTATE(sst);
    ++sst->displayLines;
    return 0;
  }
  if(b->lnLHS+1==lnnoLHS && b->lnRHS+1==lnnoRHS){
    int const rc = fdb__outf(b, "<<<Unfortunate chunk separator."
              "Ticket 746ebbe86c20b5c0f96cdadd19abd8284770de16.>>>\n");
    if(rc) return rc;
  }
  //fdb__outf(b, "lnLHS=%d, lnRHS=%d\n", (int)b->lnLHS, (int)b->lnRHS);
  return fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32
                " +%" PRIu32 ",%" PRIu32 " @@\n",
                lnnoLHS, linesLHS, lnnoRHS, linesRHS);
#else
  return 0;
#endif
}

static int fdb__debug_skip(fsl_dibu * const b, uint32_t n){
  if(1==b->passNumber){
    DICOSTATE(sst);
    b->lnLHS += n;
    b->lnRHS += n;
    ++sst->displayLines;
    return 0;
  }
  const int rc = fdb__outf(b, "SKIP %u (%u..%u left and %u..%u right)\n",
                           n, b->lnLHS+1, b->lnLHS+n, b->lnRHS+1, b->lnRHS+n);
  b->lnLHS += n;
  b->lnRHS += n;
  return rc;
}
static int fdb__debug_common(fsl_dibu * const b, fsl_dline const * pLine){
  DICOSTATE(sst);
  ++b->lnLHS;
  ++b->lnRHS;
  if(1==b->passNumber){
    ++sst->displayLines;
    fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n);
    return 0;
  }
  return fdb__outf(b, "COMMON  %8u %8u %.*s\n",
                   b->lnLHS, b->lnRHS, (int)pLine->n, pLine->z);
}
static int fdb__debug_insertion(fsl_dibu * const b, fsl_dline const * pLine){
  DICOSTATE(sst);
  ++b->lnRHS;
  if(1==b->passNumber){
    ++sst->displayLines;
    fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n);
    return 0;
  }
  return fdb__outf(b, "INSERT           %8u %.*s\n",
                   b->lnRHS, (int)pLine->n, pLine->z);
}
static int fdb__debug_deletion(fsl_dibu * const b, fsl_dline const * pLine){
  DICOSTATE(sst);
  ++b->lnLHS;
  if(1==b->passNumber){
    ++sst->displayLines;
    fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n);
    return 0;
  }
  return fdb__outf(b, "DELETE  %8u          %.*s\n",
                   b->lnLHS, (int)pLine->n, pLine->z);
}
static int fdb__debug_replacement(fsl_dibu * const b,
                                  fsl_dline const * lineLhs,
                                  fsl_dline const * lineRhs) {
#if 0
  int rc = b->deletion(b, lineLhs);
  if(0==rc) rc = b->insertion(b, lineRhs);
  return rc;
#else    
  DICOSTATE(sst);
  ++b->lnLHS;
  ++b->lnRHS;
  if(1==b->passNumber){
    ++sst->displayLines;
    fdb__dico_update_maxlen(sst, DICO_TEXT1, lineLhs->z, lineLhs->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, lineRhs->z, lineRhs->n);
    return 0;
  }
  int rc = fdb__outf(b, "REPLACE %8u          %.*s\n",
                     b->lnLHS, (int)lineLhs->n, lineLhs->z);
  if(!rc){
    rc = fdb__outf(b, "            %8u %.*s\n",
                   b->lnRHS, (int)lineRhs->n, lineRhs->z);
  }
  return rc;
#endif
}
                 
static int fdb__debug_edit(fsl_dibu * const b,
                           fsl_dline const * lineLHS,
                           fsl_dline const * lineRHS){
#if 0
  int rc = b->deletion(b, lineLHS);
  if(0==rc) rc = b->insertion(b, lineRHS);
  return rc;
#else    
  int rc = 0;
  DICOSTATE(sst);
  ++b->lnLHS;
  ++b->lnRHS;
  if(1==b->passNumber){
    sst->displayLines += 4
      /* this is actually 3 or 4, but we don't know that from here */;
    fdb__dico_update_maxlen(sst, DICO_TEXT1, lineLHS->z, lineLHS->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, lineRHS->z, lineRHS->n);
    return 0;
  }
  int i, j;
  int x;
  fsl_dline_change chng = fsl_dline_change_empty;
#define RC if(rc) goto end
  rc = fdb__outf(b, "EDIT    %8u          %.*s\n",
                 b->lnLHS, (int)lineLHS->n, lineLHS->z);
  RC;
  fsl_dline_change_spans(lineLHS, lineRHS, &chng);
  for(i=x=0; i<chng.n; i++){
    int ofst = chng.a[i].iStart1;
    int len = chng.a[i].iLen1;
    if( len ){
      char c = '0' + i;
      if( x==0 ){
        rc = fdb__outf(b, "%*s", 26, "");
        RC;
      }
      while( ofst > x ){
        if( (lineLHS->z[x]&0xc0)!=0x80 ){
          rc = fdb__out(b, " ", 1);
          RC;
        }
        x++;
      }
      for(j=0; j<len; j++, x++){
        if( (lineLHS->z[x]&0xc0)!=0x80 ){
          rc = fdb__out(b, &c, 1);
          RC;
        }
      }
    }
  }
  if( x ){
    rc = fdb__out(b, "\n", 1);
    RC;
  }
  rc = fdb__outf(b, "                 %8u %.*s\n",
                 b->lnRHS, (int)lineRHS->n, lineRHS->z);
  RC;
  for(i=x=0; i<chng.n; i++){
    int ofst = chng.a[i].iStart2;
    int len = chng.a[i].iLen2;
    if( len ){
      char c = '0' + i;
      if( x==0 ){
        rc = fdb__outf(b, "%*s", 26, "");
        RC;
      }
      while( ofst > x ){
        if( (lineRHS->z[x]&0xc0)!=0x80 ){
          rc = fdb__out(b, " ", 1);
          RC;
        }
        x++;
      }
      for(j=0; j<len; j++, x++){
        if( (lineRHS->z[x]&0xc0)!=0x80 ){
          rc = fdb__out(b, &c, 1);
          RC;
        }
      }
    }
  }
  if( x ){
    rc = fdb__out(b, "\n", 1);
  }
  end:
#undef RC
  return rc;
#endif
}

static int fdb__debug_finish(fsl_dibu * const b){
  DICOSTATE(sst);
  if(1==b->passNumber){
    sst->lineCount[0] = b->lnLHS;
    sst->lineCount[1] = b->lnRHS;
    return 0;
  }
  int rc = fdb__outf(b, "END with %u LHS file lines "
                     "and %u RHS lines (max. %u display lines)\n",
                     b->lnLHS, b->lnRHS, sst->displayLines);
  if(0==rc){
    rc = fdb__outf(b,"Col widths: num left=%u, col left=%u, "
                   "modifier=%u, num right=%u, col right=%u\n",
                   sst->maxWidths[0], sst->maxWidths[1],
                   sst->maxWidths[2], sst->maxWidths[3],
                   sst->maxWidths[4]);
  }
  return rc;
}

void fsl_dibu_finalizer(fsl_dibu * const b){
  *b = fsl_dibu_empty;
  fsl_free(b);
}

static fsl_dibu * fsl__diff_builder_debug(void){
  fsl_dibu * rc =
    fsl_dibu_alloc((fsl_size_t)sizeof(DiffCounter));
  if(rc){
    rc->chunkHeader = fdb__debug_chunkHeader;
    rc->start = fdb__debug_start;
    rc->skip = fdb__debug_skip;
    rc->common = fdb__debug_common;
    rc->insertion = fdb__debug_insertion;
    rc->deletion = fdb__debug_deletion;
    rc->replacement = fdb__debug_replacement;
    rc->edit = fdb__debug_edit;
    rc->finish = fdb__debug_finish;
    rc->finalize = fsl_dibu_finalizer;
    rc->twoPass = true;
    assert(0!=rc->pimpl);
    DiffCounter * const sst = (DiffCounter*)rc->pimpl;
    *sst = DiffCounter_empty;
    assert(0==rc->implFlags);
    assert(0==rc->lnLHS);
    assert(0==rc->lnRHS);
    assert(NULL==rc->opt);
  }
  return rc;
}

/******************** json1 diff builder ********************/
/* Description taken verbatim from fossil(1): */
/*
** This formatter generates a JSON array that describes the difference.
**
** The Json array consists of integer opcodes with each opcode followed
** by zero or more arguments:
**
**   Syntax        Mnemonic    Description
**   -----------   --------    --------------------------
**   0             END         This is the end of the diff
**   1  INTEGER    SKIP        Skip N lines from both files
**   2  STRING     COMMON      The line show by STRING is in both files
**   3  STRING     INSERT      The line STRING is in only the right file
**   4  STRING     DELETE      The STRING line is in only the left file
**   5  SUBARRAY   EDIT        One line is different on left and right.
**
** The SUBARRAY is an array of 3*N+1 strings with N>=0.  The triples
** represent common-text, left-text, and right-text.  The last string
** in SUBARRAY is the common-suffix.  Any string can be empty if it does
** not apply.
*/

static int fdb__outj(fsl_dibu * const b,
                     char const *zJson, int n){
  return n<0
    ? fdb__outf(b, "%!j", zJson)
    : fdb__outf(b, "%!.*j", n, zJson);
}

static int fdb__json1_start(fsl_dibu * const b){
  int rc = fdb__outf(b, "{\"hashLHS\": %!j, \"hashRHS\": %!j, ",
                     b->opt->hashLHS, b->opt->hashRHS);
  if(0==rc && b->opt->nameLHS){
    rc = fdb__outf(b, "\"nameLHS\": %!j, ", b->opt->nameLHS);
  }
  if(0==rc && b->opt->nameRHS){
    rc = fdb__outf(b, "\"nameRHS\": %!j, ", b->opt->nameRHS);
  }
  if(0==rc){
    rc = fdb__out(b, "\"diff\":[", 8);
  }
  return rc;
}

static int fdb__json1_skip(fsl_dibu * const b, uint32_t n){
  return fdb__outf(b, "1,%" PRIu32 ",\n", n);
}
static int fdb__json1_common(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = fdb__out(b, "2,",2);
  if(!rc) {
    rc = fdb__outj(b, pLine->z, (int)pLine->n);
    if(!rc) rc = fdb__out(b, ",\n",2);
  }
  return rc;
}
static int fdb__json1_insertion(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = fdb__out(b, "3,",2);
  if(!rc){
    rc = fdb__outj(b, pLine->z, (int)pLine->n);
    if(!rc) rc = fdb__out(b, ",\n",2);
  }
  return rc;
}
static int fdb__json1_deletion(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = fdb__out(b, "4,",2);
  if(!rc){
    rc = fdb__outj(b, pLine->z, (int)pLine->n);
    if(!rc) rc = fdb__out(b, ",\n",2);
  }
  return rc;
}
static int fdb__json1_replacement(fsl_dibu * const b,
                              fsl_dline const * lineLhs,
                              fsl_dline const * lineRhs) {
  int rc = fdb__out(b, "5,[\"\",",6);
  if(!rc) rc = fdb__outf(b,"%!.*j", (int)lineLhs->n, lineLhs->z);
  if(!rc) rc = fdb__out(b, ",", 1);
  if(!rc) rc = fdb__outf(b,"%!.*j", (int)lineRhs->n, lineRhs->z);
  if(!rc) rc = fdb__out(b, ",\"\"],\n",6);
  return rc;
}
                 
static int fdb__json1_edit(fsl_dibu * const b,
                           fsl_dline const * lineLHS,
                           fsl_dline const * lineRHS){
  int rc = 0;
  int i,x;
  fsl_dline_change chng = fsl_dline_change_empty;

#define RC if(rc) goto end
  rc = fdb__out(b, "5,[", 3); RC;
  fsl_dline_change_spans(lineLHS, lineRHS, &chng);
  for(i=x=0; i<(int)chng.n; i++){
    if(i>0){
      rc = fdb__out(b, ",", 1); RC;
    }
    rc = fdb__outj(b, lineLHS->z + x, (int)chng.a[i].iStart1 - x); RC;
    x = chng.a[i].iStart1;
    rc = fdb__out(b, ",", 1); RC;
    rc = fdb__outj(b, lineLHS->z + x, (int)chng.a[i].iLen1); RC;
    x += chng.a[i].iLen1;
    rc = fdb__out(b, ",", 1); RC;
    rc = fdb__outj(b, lineRHS->z + chng.a[i].iStart2,
                   (int)chng.a[i].iLen2); RC;
  }
  rc = fdb__out(b, ",", 1); RC;
  rc = fdb__outj(b, lineLHS->z + x, (int)(lineLHS->n - x)); RC;
  rc = fdb__out(b, "],\n",3); RC;
  end:
  return rc;
#undef RC
}

static int fdb__json1_finish(fsl_dibu * const b){
  return fdb__out(b, "0]}", 3);
}

static fsl_dibu * fsl__diff_builder_json1(void){
  fsl_dibu * rc = fsl_dibu_alloc(0);
  if(rc){
    rc->chunkHeader = NULL;
    rc->start = fdb__json1_start;
    rc->skip = fdb__json1_skip;
    rc->common = fdb__json1_common;
    rc->insertion = fdb__json1_insertion;
    rc->deletion = fdb__json1_deletion;
    rc->replacement = fdb__json1_replacement;
    rc->edit = fdb__json1_edit;
    rc->finish = fdb__json1_finish;
    rc->finalize = fsl_dibu_finalizer;
    assert(!rc->pimpl);
    assert(0==rc->implFlags);
    assert(0==rc->lnLHS);
    assert(0==rc->lnRHS);
    assert(NULL==rc->opt);
  }
  return rc;
}

/**
   State for the text-mode unified(-ish) diff builder.  We do some
   hoop-jumping here in order to combine runs of delete/insert pairs
   into a group of deletes followed by a group of inserts. It's a
   cosmetic detail only but it makes for more readable output.
*/
struct DiBuUnified {
  /** True if currently processing a block of deletes, else false. */
  bool deleting;
  /** Buffer for insertion lines which are part of delete/insert
      pairs. */
  fsl_b bufIns;
};
typedef struct DiBuUnified DiBuUnified;

#define UIMPL(V) DiBuUnified * const V = (DiBuUnified*)b->pimpl
/**
   If utxt diff builder b has any INSERT lines to flush, this
   flushes them. Sets b->impl->deleting to false. Returns non-0
   on output error.
*/
static int fdb__utxt_flush_ins(fsl_dibu * const b){
  int rc = 0;
  UIMPL(p);
  p->deleting = false;
  if(p->bufIns.used>0){
    rc = fdb__out(b, fsl_b_cstr(&p->bufIns), p->bufIns.used);
    fsl_b_reuse(&p->bufIns);
  }
  return rc;
}

static int fdb__utxt_start(fsl_dibu * const b){
  int rc = 0;
  UIMPL(p);
  p->deleting = false;
  if(p->bufIns.mem) fsl_b_reuse(&p->bufIns);
  else fsl_b_reserve(&p->bufIns, 1024 * 2);
  if(0==(FSL_DIFF2_NOINDEX & b->opt->diffFlags)){
    rc = fdb__outf(b,"Index: %s\n%.66c\n",
                   b->opt->nameLHS/*RHS?*/, '=');
  }
  if(0==rc){
    rc = fdb__outf(b, "--- %s\n+++ %s\n",
                   b->opt->nameLHS, b->opt->nameRHS);
  }
  return rc;
}

static int fdb__utxt_chunkHeader(fsl_dibu* const b,
                                 uint32_t lnnoLHS, uint32_t linesLHS,
                                 uint32_t lnnoRHS, uint32_t linesRHS ){
  /*
    Ticket 746ebbe86c20b5c0f96cdadd19abd8284770de16:

    Annoying cosmetic bug: the libf impl of this diff will sometimes
    render two directly-adjecent chunks with a separator, e.g.:
  */

  // $ f-vdiff --format u 072d63965188 a725befe5863 -l '*vdiff*' | head -30
  // Index: f-apps/f-vdiff.c
  // ==================================================================
  // --- f-apps/f-vdiff.c
  // +++ f-apps/f-vdiff.c
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  //     36     36    fsl_b fname;
  //     37     37    fsl_b fcontent1;
  //     38     38    fsl_b fcontent2;
  //     39     39    fsl_b fhash;
  //     40     40    fsl_list globs;
  //            41 +  fsl_dibu_opt diffOpt;
  //            42 +  fsl_diff_builder * diffBuilder;
  //     41     43  } VDiffApp = {
  //     42     44  NULL/*glob*/,
  //     43     45  5/*contextLines*/,
  //     44     46  0/*sbsWidth*/,
  //     45     47  0/*diffFlags*/,
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  //     46     48  0/*brief*/,
  //     47     49  fsl_b_empty_m/*fname*/,
  //     48     50  fsl_b_empty_m/*fcontent1*/,

  /*
    Note now the chunks before/after the second ~~~ line are
    consecutive lines of code. In fossil(1) that case is accounted for
    in the higher-level diff engine, which can not only collapse
    adjacent blocks but also does the rendering of chunk headers in
    that main algorithm (something we cannot do in the library because
    we need the fsl_dibu to be able to output to arbitrary
    destinations). We can only _partially_ account for it here,
    eliminating the extraneous ~~~ line when we're in line-number
    mode. In non-line-number mode we have to output the chunk header
    as-is. If we skip it then the _previous_ chunk header, if any,
    will contain incorrect numbers for the chunk, invaliding the diff
    for purposes of tools which import unified-format diffs.
  */
  int rc = fdb__utxt_flush_ins(b);
  if(0==rc){
    if(FSL_DIFF2_LINE_NUMBERS & b->opt->diffFlags){
      rc = (lnnoLHS == b->lnLHS+1 && lnnoRHS == b->lnRHS+1)
        ? 0
        : fdb__outf(b, "%.40c\n", '~');
    }else{
      rc = fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32
                     " +%" PRIu32 ",%" PRIu32 " @@\n",
                     lnnoLHS, linesLHS, lnnoRHS, linesRHS);
    }
  }
  return rc;
}


static int fdb__utxt_skip(fsl_dibu * const b, uint32_t n){
  //MARKER(("SKIP\n"));
  int rc = fdb__utxt_flush_ins(b);
  b->lnLHS += n;
  b->lnRHS += n;
  return rc;
}

/**
   Outputs line numbers, if configured to, to b->opt->out.

   - 2 line numbers = common lines
   - lnL only = deletion
   - lnR only = insertion
*/
static int fdb__utxt_lineno(fsl_dibu * const b, uint32_t lnL, uint32_t lnR){
  int rc = 0;
  if(FSL_DIFF2_LINE_NUMBERS & b->opt->diffFlags){
    UIMPL(p);
    if(lnL){ // common or delete
      rc = fdb__outf(b, "%s%6" PRIu32 "%s ",
                     (lnR ? "" : b->opt->ansiColor.deletion),
                     lnL,
                     (lnR ? "" : b->opt->ansiColor.reset));
    }else if(p->deleting){ // insert during deletion grouping
      rc = fsl_b_append(&p->bufIns, "       ", 7);
    }else{ // insert w/o deleting grouping
      rc = fdb__out(b, "       ", 7);
    }
    if(0==rc){
      if(!lnL && lnR && p->deleting){ // insert during deletion grouping
        rc = fsl_b_appendf(&p->bufIns, "%s%6" PRIu32 "%s ",
                                b->opt->ansiColor.insertion,
                                lnR, b->opt->ansiColor.reset);
      }else if(lnR){ // common or insert w/o deletion grouping.
        rc = fdb__outf(b, "%s%6" PRIu32 "%s ",
                       (lnL ? "" : b->opt->ansiColor.insertion),
                       lnR,
                       (lnL ? "" : b->opt->ansiColor.reset));
      }else{ // deletion
        rc = fdb__out(b, "       ", 7);
      }
    }
  }
  return rc;
}

static int fdb__utxt_common(fsl_dibu * const b, fsl_dline const * pLine){
  //MARKER(("COMMON\n"));
  int rc = fdb__utxt_flush_ins(b);
  if(0==rc){
    ++b->lnLHS;
    ++b->lnRHS;
    rc = fdb__utxt_lineno(b, b->lnLHS, b->lnRHS);
  }
  return rc ? rc : fdb__outf(b, " %.*s\n", (int)pLine->n, pLine->z);
}

static int fdb__utxt_insertion(fsl_dibu * const b, fsl_dline const * pLine){
  //MARKER(("INSERT\n"));
  int rc;
  ++b->lnRHS;
  rc = fdb__utxt_lineno(b, 0, b->lnRHS);
  if(0==rc){
    UIMPL(p);
    if(p->deleting){
      rc = fsl_b_appendf(&p->bufIns, "%s+%.*s%s\n",
                              b->opt->ansiColor.insertion,
                              (int)pLine->n, pLine->z,
                              b->opt->ansiColor.reset);
    }else{
      rc = fdb__outf(b, "%s+%.*s%s\n",
                     b->opt->ansiColor.insertion,
                     (int)pLine->n, pLine->z,
                     b->opt->ansiColor.reset);
    }
  }
  return rc;
}
static int fdb__utxt_deletion(fsl_dibu * const b, fsl_dline const * pLine){
  //MARKER(("DELETE\n"));
  UIMPL(p);
  int rc = p->deleting ? 0 : fdb__utxt_flush_ins(b);
  if(0==rc){
    p->deleting = true;
    ++b->lnLHS;
    rc = fdb__utxt_lineno(b, b->lnLHS, 0);
  }
  return rc ? rc : fdb__outf(b, "%s-%.*s%s\n",
                             b->opt->ansiColor.deletion,
                             (int)pLine->n, pLine->z,
                             b->opt->ansiColor.reset);
}
static int fdb__utxt_replacement(fsl_dibu * const b,
                                 fsl_dline const * lineLhs,
                                 fsl_dline const * lineRhs) {
  //MARKER(("REPLACE\n"));
  int rc = b->deletion(b, lineLhs);
  if(0==rc) rc = b->insertion(b, lineRhs);
  return rc;
}
static int fdb__utxt_edit(fsl_dibu * const b,
                           fsl_dline const * lineLhs,
                           fsl_dline const * lineRhs){
  //MARKER(("EDIT\n"));
  int rc = b->deletion(b, lineLhs);
  if(0==rc) rc = b->insertion(b, lineRhs);
  return rc;
}

static int fdb__utxt_finish(fsl_dibu * const b){
  int rc = fdb__utxt_flush_ins(b);
  UIMPL(p);
  fsl_b_reuse(&p->bufIns);
  return rc;
}

static void fdb__utxt_finalize(fsl_dibu * const b){
  UIMPL(p);
  fsl_b_clear(&p->bufIns);
  fsl_free(b);
}

static fsl_dibu * fsl__diff_builder_utxt(void){
  const DiBuUnified DiBuUnified_empty = {
  false, fsl_b_empty_m
  };
  fsl_dibu * rc = fsl_dibu_alloc(sizeof(DiBuUnified));
  if(!rc) return NULL;
  assert(NULL!=rc->pimpl);
  assert(NULL==rc->finally);
  *((DiBuUnified*)rc->pimpl) = DiBuUnified_empty;
  rc->chunkHeader = fdb__utxt_chunkHeader;
  rc->start = fdb__utxt_start;
  rc->skip = fdb__utxt_skip;
  rc->common = fdb__utxt_common;
  rc->insertion = fdb__utxt_insertion;
  rc->deletion = fdb__utxt_deletion;
  rc->replacement = fdb__utxt_replacement;
  rc->edit = fdb__utxt_edit;
  rc->finish = fdb__utxt_finish;
  rc->finalize = fdb__utxt_finalize;
  return rc;
}
#undef UIMPL

struct DiBuTcl {
  /** Buffer for TCL-format string conversion */
  fsl_b str;
};
typedef struct DiBuTcl DiBuTcl;
static const DiBuTcl DiBuTcl_empty = {fsl_b_empty_m};

#define BR_OPEN if(FSL_DIBU_TCL_BRACES & b->implFlags) \
    rc = fdb__out(b, "{", 1)
#define BR_CLOSE if(FSL_DIBU_TCL_BRACES & b->implFlags) \
    rc = fdb__out(b, "}", 1)

#define DTCL_BUFFER(B) &((DiBuTcl*)(B)->pimpl)->str
static int fdb__outtcl(fsl_dibu * const b,
                       char const *z, unsigned int n,
                       char chAppend ){
  int rc;
  fsl_b * const o = DTCL_BUFFER(b);
  fsl_b_reuse(o);
  rc = fsl_b_append_tcl_literal(o,
                                     (b->implFlags & FSL_DIBU_TCL_BRACES_ESC),
                                     z, n);
  if(0==rc) rc = fdb__out(b, (char const *)o->mem, o->used);
  if(chAppend && 0==rc) rc = fdb__out(b, &chAppend, 1);
  return rc;
}

static int fdb__tcl_start(fsl_dibu * const b){
  int rc = 0;
  fsl_b_reuse(DTCL_BUFFER(b));
  if(1==++b->fileCount &&
     FSL_DIBU_TCL_TK==(b->implFlags & FSL_DIBU_TCL_TK)){
    rc = fdb__out(b, "set difftxt {\n", -1);
  }
  if(0==rc && b->fileCount>1) rc = fdb__out(b, "\n", 1);
  if(0==rc && b->opt->nameLHS){
    char const * zRHS =
      b->opt->nameRHS ? b->opt->nameRHS : b->opt->nameLHS;
    BR_OPEN;
    if(0==rc) rc = fdb__out(b, "FILE ", 5);
    if(0==rc) rc = fdb__outtcl(b, b->opt->nameLHS,
                               (unsigned)fsl_strlen(b->opt->nameLHS), ' ');
    if(0==rc) rc = fdb__outtcl(b, zRHS,
                               (unsigned)fsl_strlen(zRHS), 0);
    if(0==rc) {BR_CLOSE;}
    if(0==rc) rc = fdb__out(b, "\n", 1);
  }
  return rc;
}

static int fdb__tcl_skip(fsl_dibu * const b, uint32_t n){
  int rc = 0;
  BR_OPEN;
  if(0==rc) rc = fdb__outf(b, "SKIP %" PRIu32, n);
  if(0==rc) {BR_CLOSE;}
  if(0==rc) rc = fdb__out(b, "\n", 1);
  return rc;
}

static int fdb__tcl_common(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = 0;
  BR_OPEN;
  if(0==rc) rc = fdb__out(b, "COM  ", 5);
  if(0==rc) rc= fdb__outtcl(b, pLine->z, pLine->n, 0);
  if(0==rc) {BR_CLOSE;}
  if(0==rc) rc = fdb__out(b, "\n", 1);
  return rc;
}
static int fdb__tcl_insertion(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = 0;
  BR_OPEN;
  if(0==rc) rc = fdb__out(b, "INS  ", 5);
  if(0==rc) rc = fdb__outtcl(b, pLine->z, pLine->n, 0);
  if(0==rc) {BR_CLOSE;}
  if(0==rc) rc = fdb__out(b, "\n", 1);
  return rc;
}
static int fdb__tcl_deletion(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = 0;
  BR_OPEN;
  if(0==rc) rc = fdb__out(b, "DEL  ", 5);
  if(0==rc) rc = fdb__outtcl(b, pLine->z, pLine->n, 0);
  if(0==rc) {BR_CLOSE;}
  if(0==rc) rc = fdb__out(b, "\n", 1);
  return rc;
}
static int fdb__tcl_replacement(fsl_dibu * const b,
                                fsl_dline const * lineLhs,
                                fsl_dline const * lineRhs) {
  int rc = 0;
  BR_OPEN;
  if(0==rc) rc = fdb__out(b, "EDIT \"\" ", 8);
  if(0==rc) rc = fdb__outtcl(b, lineLhs->z, lineLhs->n, ' ');
  if(0==rc) rc = fdb__outtcl(b, lineRhs->z, lineRhs->n, 0);
  if(0==rc) {BR_CLOSE;}
  if(0==rc) rc = fdb__out(b, "\n", 1);
  return rc;
}

static int fdb__tcl_edit(fsl_dibu * const b,
                         fsl_dline const * lineLHS,
                         fsl_dline const * lineRHS){
  int rc = 0;
  int i, x;
  fsl_dline_change chng = fsl_dline_change_empty;
#define RC if(rc) goto end
  BR_OPEN;
  rc = fdb__out(b, "EDIT", 4); RC;
  fsl_dline_change_spans(lineLHS, lineRHS, &chng);
  for(i=x=0; i<chng.n; i++){
    rc = fdb__out(b, " ", 1); RC;
    rc = fdb__outtcl(b, lineLHS->z + x, chng.a[i].iStart1 - x, ' '); RC;
    x = chng.a[i].iStart1;
    rc = fdb__outtcl(b, lineLHS->z + x, chng.a[i].iLen1, ' '); RC;
    x += chng.a[i].iLen1;
    rc = fdb__outtcl(b, lineRHS->z + chng.a[i].iStart2,
                     chng.a[i].iLen2, 0); RC;
  }
  assert(0==rc);
  if( x < lineLHS->n ){
    rc = fdb__out(b, " ", 1); RC;
    rc = fdb__outtcl(b, lineLHS->z + x, lineLHS->n - x, 0); RC;
  }
  BR_CLOSE; RC;
  rc = fdb__out(b, "\n", 1);
  end:
#undef RC
  return rc;
}

static int fdb__tcl_finish(fsl_dibu * const b fsl__unused){
  int rc = 0;
  (void)b;
#if 0
  BR_CLOSE;
  if(0==rc && FSL_DIBU_TCL_BRACES & b->implFlags){
    rc = fdb__out(b, "\n", 1);
  }
#endif
  return rc;
}
static int fdb__tcl_finally(fsl_dibu * const b){
  int rc = 0;
  if(FSL_DIBU_TCL_TK==(b->implFlags & FSL_DIBU_TCL_TK)){
    extern char const * fsl_difftk_cstr;
    if(!b->fileCount) rc = fdb__out(b,"set difftxt {\n",-1);
    if(0==rc) rc = fdb__out(b, "}\nset fossilcmd {}\n", -1);
    if(0==rc) rc = fdb__out(b, fsl_difftk_cstr, -1);
  }
  return rc;
}

#undef BR_OPEN
#undef BR_CLOSE

static void fdb__tcl_finalize(fsl_dibu * const b){
  fsl_b_clear( &((DiBuTcl*)b->pimpl)->str );
  *b = fsl_dibu_empty;
  fsl_free(b);
}

static fsl_dibu * fsl__diff_builder_tcl(void){
  fsl_dibu * rc =
    fsl_dibu_alloc((fsl_size_t)sizeof(DiBuTcl));
  if(rc){
    rc->chunkHeader = NULL;
    rc->start = fdb__tcl_start;
    rc->skip = fdb__tcl_skip;
    rc->common = fdb__tcl_common;
    rc->insertion = fdb__tcl_insertion;
    rc->deletion = fdb__tcl_deletion;
    rc->replacement = fdb__tcl_replacement;
    rc->edit = fdb__tcl_edit;
    rc->finish = fdb__tcl_finish;
    rc->finally = fdb__tcl_finally;
    rc->finalize = fdb__tcl_finalize;
    assert(0!=rc->pimpl);
    DiBuTcl * const dbt = (DiBuTcl*)rc->pimpl;
    *dbt = DiBuTcl_empty;
    if(fsl_b_reserve(&dbt->str, 120)){
      rc->finalize(rc);
      rc = 0;
    }
  }
  return rc;
}

static int fdb__splittxt_mod(fsl_dibu * const b, char ch){
  assert(2==b->passNumber);
  return fdb__outf(b, " %c ", ch);
}

static int fdb__splittxt_lineno(fsl_dibu * const b,
                                DiffCounter const * const sst,
                                bool isLeft, uint32_t n){
  assert(2==b->passNumber);
  int const col = isLeft ? DICO_NUM1 : DICO_NUM2;
  return n
    ? fdb__outf(b, "%*" PRIu32 " ", sst->maxWidths[col], n)
    : fdb__outf(b, "%.*c ", sst->maxWidths[col], ' ');
}

static int fdb__splittxt_start(fsl_dibu * const b){
  int rc = 0;
  if(1==b->passNumber){
    DICOSTATE(sst);
    *sst = DiffCounter_empty;
    ++b->fileCount;
    return rc;
  }
  if(b->fileCount>1){
    rc = fdb__out(b, "\n", 1);
  }
  if(0==rc){
    fsl_dibu_opt const * const o = b->opt;
    if(o->nameLHS || o->nameRHS
       || o->hashLHS || o->hashRHS){
      rc = fdb__outf(b, "--- %s%s%s\n+++ %s%s%s\n",
                     o->nameLHS ? o->nameLHS : "",
                     (o->nameLHS && o->hashLHS) ? " " : "",
                     o->hashLHS ? o->hashLHS : "",
                     o->nameRHS ? o->nameRHS : "",
                     (o->nameRHS && o->hashRHS) ? " " : "",
                     o->hashRHS ? o->hashRHS : "");
    }
  }
  return rc;
}

static int fdb__splittxt_skip(fsl_dibu * const b, uint32_t n){
  b->lnLHS += n;
  b->lnRHS += n;
  if(1==b->passNumber) return 0;
  DICOSTATE(sst);
  int const maxWidth1 = maxColWidth(b, sst, DICO_TEXT1);
  int const maxWidth2 = maxColWidth(b, sst, DICO_TEXT2);
  return fdb__outf(b, "%.*c %.*c   %.*c %.*c\n",
                 sst->maxWidths[DICO_NUM1], '~',
                 maxWidth1, '~',
                 sst->maxWidths[DICO_NUM2], '~',
                 maxWidth2, '~');
}

static int fdb__splittxt_color(fsl_dibu * const b,
                               int modType){
  char const *z = 0;
  switch(modType){
    case (int)'i': z = b->opt->ansiColor.insertion; break;
    case (int)'d': z = b->opt->ansiColor.deletion; break;
    case (int)'r'/*replacement*/: 
    case (int)'e': z = b->opt->ansiColor.edit; break;
    case 0: z = b->opt->ansiColor.reset; break;
    default:
      assert(!"invalid color op!");
  }
  return z&&*z ? fdb__outf(b, "%s", z) : 0;
}

static int fdb__splittxt_side(fsl_dibu * const b,
                              DiffCounter * const sst,
                              bool isLeft,
                              fsl_dline const * const pLine){
  int rc = fdb__splittxt_lineno(b, sst, isLeft,
                                pLine ? (isLeft ? b->lnLHS : b->lnRHS) : 0U);
  if(0==rc){
    uint32_t const w = maxColWidth(b, sst, isLeft ? DICO_TEXT1 : DICO_TEXT2);
    if(pLine){
      fsl_size_t const nU =
        /* Measure column width in UTF8 characters, not bytes! */
        fsl_strlen_utf8(pLine->z, (fsl_int_t)pLine->n);
      rc = fdb__outf(b, "%#.*s", (int)(w < nU ? w : nU), pLine->z);
      if(0==rc && w>nU){
        rc = fdb__outf(b, "%.*c", (int)(w - nU), ' ');
      }
    }else{
      rc = fdb__outf(b, "%.*c", (int)w, ' ');
    }
    if(0==rc && !isLeft) rc = fdb__out(b, "\n", 1);
  }
  return rc;
}

static int fdb__splittxt_common(fsl_dibu * const b,
                                fsl_dline const * const pLine){
  int rc = 0;
  DICOSTATE(sst);
  ++b->lnLHS;
  ++b->lnRHS;
  if(1==b->passNumber){
    fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n);
    return 0;
  }
  rc = fdb__splittxt_side(b, sst, true, pLine);
  if(0==rc) rc = fdb__splittxt_mod(b, ' ');
  if(0==rc) rc = fdb__splittxt_side(b, sst, false, pLine);
  return rc;
}

static int fdb__splittxt_insertion(fsl_dibu * const b,
                                   fsl_dline const * const pLine){
  int rc = 0;
  DICOSTATE(sst);
  ++b->lnRHS;
  if(1==b->passNumber){
    fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n);
    return rc;
  }
  rc = fdb__splittxt_color(b, 'i');
  if(0==rc) rc = fdb__splittxt_side(b, sst, true, NULL);
  if(0==rc) rc = fdb__splittxt_mod(b, '>');
  if(0==rc) rc = fdb__splittxt_side(b, sst, false, pLine);
  if(0==rc) rc = fdb__splittxt_color(b, 0);
  return rc;
}

static int fdb__splittxt_deletion(fsl_dibu * const b,
                                  fsl_dline const * const pLine){
  int rc = 0;
  DICOSTATE(sst);
  ++b->lnLHS;
  if(1==b->passNumber){
    fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n);
    return rc;
  }
  rc = fdb__splittxt_color(b, 'd');
  if(0==rc) rc = fdb__splittxt_side(b, sst, true, pLine);
  if(0==rc) rc = fdb__splittxt_mod(b, '<');
  if(0==rc) rc = fdb__splittxt_side(b, sst, false, NULL);
  if(0==rc) rc = fdb__splittxt_color(b, 0);
  return rc;
}

static int fdb__splittxt_replacement(fsl_dibu * const b,
                                     fsl_dline const * const lineLhs,
                                     fsl_dline const * const lineRhs) {
#if 0
  int rc = b->deletion(b, lineLhs);
  if(0==rc) rc = b->insertion(b, lineRhs);
  return rc;
#else    
  int rc = 0;
  DICOSTATE(sst);
  ++b->lnLHS;
  ++b->lnRHS;
  if(1==b->passNumber){
    fdb__dico_update_maxlen(sst, DICO_TEXT1, lineLhs->z, lineLhs->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, lineRhs->z, lineRhs->n);
    return 0;
  }
  rc = fdb__splittxt_color(b, 'e');
  if(0==rc) rc = fdb__splittxt_side(b, sst, true, lineLhs);
  if(0==rc) rc = fdb__splittxt_mod(b, '|');
  if(0==rc) rc = fdb__splittxt_side(b, sst, false, lineRhs);
  if(0==rc) rc = fdb__splittxt_color(b, 0);
  return rc;
#endif
}

static int fdb__splittxt_finish(fsl_dibu * const b){
  int rc = 0;
  if(1==b->passNumber){
    DICOSTATE(sst);
    uint32_t ln = b->lnLHS;
    /* Calculate width of line number columns. */
    sst->maxWidths[DICO_NUM1] = sst->maxWidths[DICO_NUM2] = 1;
    for(; ln>=10; ln/=10) ++sst->maxWidths[DICO_NUM1];
    ln = b->lnRHS;
    for(; ln>=10; ln/=10) ++sst->maxWidths[DICO_NUM2];
  }
  return rc;
}

static void fdb__splittxt_finalize(fsl_dibu * const b){
  *b = fsl_dibu_empty;
  fsl_free(b);
}

static fsl_dibu * fsl__diff_builder_splittxt(void){
  fsl_dibu * rc =
    fsl_dibu_alloc((fsl_size_t)sizeof(DiffCounter));
  if(rc){
    rc->twoPass = true;
    rc->chunkHeader = NULL;
    rc->start = fdb__splittxt_start;
    rc->skip = fdb__splittxt_skip;
    rc->common = fdb__splittxt_common;
    rc->insertion = fdb__splittxt_insertion;
    rc->deletion = fdb__splittxt_deletion;
    rc->replacement = fdb__splittxt_replacement;
    rc->edit = fdb__splittxt_replacement;
    rc->finish = fdb__splittxt_finish;
    rc->finalize = fdb__splittxt_finalize;
    assert(0!=rc->pimpl);
    DiffCounter * const sst = (DiffCounter*)rc->pimpl;
    *sst = DiffCounter_empty;
  }
  return rc;
}

int fsl_dibu_factory( fsl_dibu_e type,
                              fsl_dibu **pOut ){
  int rc = FSL_RC_TYPE;
  fsl_dibu * (*factory)(void) = NULL;
  switch(type){
    case FSL_DIBU_DEBUG:
      factory = fsl__diff_builder_debug;
      break;
    case FSL_DIBU_JSON1:
      factory = fsl__diff_builder_json1;
      break;
    case FSL_DIBU_UNIFIED_TEXT:
      factory = fsl__diff_builder_utxt;
      break;
    case FSL_DIBU_TCL:
      factory = fsl__diff_builder_tcl;
      break;
    case FSL_DIBU_SPLIT_TEXT:
      factory = fsl__diff_builder_splittxt;
      break;
    case FSL_DIBU_INVALID: break;
  }
  if(NULL!=factory){
    *pOut = factory();
    rc = *pOut ? 0 : FSL_RC_OOM;
  }
  return rc;
}

#undef MARKER
#undef DICOSTATE
#undef DTCL_BUFFER
/* end of file src/dibu.c */
/* start of file src/diff.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2022 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2013-2022 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/************************************************************************
  This file houses Fossil's diff-generation routines (as opposed to
  the delta-generation). This code is a straight port of those
  algorithms from the Fossil SCM project, initially implemented by
  D. Richard Hipp, ported and the license re-assigned to this project
  with this consent.
*/
#include <assert.h>
#include <limits.h> /* INT_MAX */
#include <memory.h>
#include <stdlib.h>
#include <string.h> /* for memmove()/strlen() */

#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


const fsl_dline fsl_dline_empty = fsl_dline_empty_m;
const fsl_dline_change fsl_dline_change_empty = fsl_dline_change_empty_m;
const fsl__diff_cx fsl__diff_cx_empty = fsl__diff_cx_empty_m;

void fsl__diff_cx_clean(fsl__diff_cx * const cx){
  fsl_free(cx->aFrom);
  fsl_free(cx->aTo);
  fsl_free(cx->aEdit);
  cx->aFrom = cx->aTo = NULL;
  cx->aEdit = NULL;
  *cx = fsl__diff_cx_empty;
}

/* Fast isspace for use by diff */
static const char diffIsSpace[] = {
  0, 0, 0, 0, 0, 0, 0, 0,   1, 1, 1, 0, 1, 1, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  1, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,

  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
};
#define diff_isspace(X)  (diffIsSpace[(unsigned char)(X)])


/**
   Length of a dline.
*/
#define LENGTH(X) ((X)->n)


/**
   Minimum of two values
*/
static int minInt(int a, int b){ return a<b ? a : b; }

/** @internal

   Compute the optimal longest common subsequence (LCS) using an
   exhaustive search. This version of the LCS is only used for
   shorter input strings since runtime is O(N*N) where N is the
   input string length.
*/
static void fsl__diff_optimal_lcs(
  fsl__diff_cx * const p,     /* Two files being compared */
  int iS1, int iE1,          /* Range of lines in p->aFrom[] */
  int iS2, int iE2,          /* Range of lines in p->aTo[] */
  int *piSX, int *piEX,      /* Write p->aFrom[] common segment here */
  int *piSY, int *piEY       /* Write p->aTo[] common segment here */
){
  int mxLength = 0;          /* Length of longest common subsequence */
  int i, j;                  /* Loop counters */
  int k;                     /* Length of a candidate subsequence */
  int iSXb = iS1;            /* Best match so far */
  int iSYb = iS2;            /* Best match so far */

  for(i=iS1; i<iE1-mxLength; i++){
    for(j=iS2; j<iE2-mxLength; j++){
      if( p->cmpLine(&p->aFrom[i], &p->aTo[j]) ) continue;
      if( mxLength && p->cmpLine(&p->aFrom[i+mxLength], &p->aTo[j+mxLength]) ){
        continue;
      }
      k = 1;
      while( i+k<iE1 && j+k<iE2 && p->cmpLine(&p->aFrom[i+k],&p->aTo[j+k])==0 ){
        k++;
      }
      if( k>mxLength ){
        iSXb = i;
        iSYb = j;
        mxLength = k;
      }
    }
  }
  *piSX = iSXb;
  *piEX = iSXb + mxLength;
  *piSY = iSYb;
  *piEY = iSYb + mxLength;
}

/**
    Compare two blocks of text on lines iS1 through iE1-1 of the aFrom[]
    file and lines iS2 through iE2-1 of the aTo[] file.  Locate a sequence
    of lines in these two blocks that are exactly the same.  Return
    the bounds of the matching sequence.
   
    If there are two or more possible answers of the same length, the
    returned sequence should be the one closest to the center of the
    input range.
   
    Ideally, the common sequence should be the longest possible common
    sequence.  However, an exact computation of LCS is O(N*N) which is
    way too slow for larger files.  So this routine uses an O(N)
    heuristic approximation based on hashing that usually works about
    as well.  But if the O(N) algorithm doesn't get a good solution
    and N is not too large, we fall back to an exact solution by
    calling fsl__diff_optimal_lcs().
*/
static void fsl__diff_lcs(
  fsl__diff_cx * const p,     /* Two files being compared */
  int iS1, int iE1,          /* Range of lines in p->aFrom[] */
  int iS2, int iE2,          /* Range of lines in p->aTo[] */
  int *piSX, int *piEX,      /* Write p->aFrom[] common segment here */
  int *piSY, int *piEY       /* Write p->aTo[] common segment here */
){
  int i, j, k;               /* Loop counters */
  int n;                     /* Loop limit */
  fsl_dline *pA, *pB;            /* Pointers to lines */
  int iSX, iSY, iEX, iEY;    /* Current match */
  int skew = 0;              /* How lopsided is the match */
  int dist = 0;              /* Distance of match from center */
  int mid;                   /* Center of the chng */
  int iSXb, iSYb, iEXb, iEYb;   /* Best match so far */
  int iSXp, iSYp, iEXp, iEYp;   /* Previous match */
  sqlite3_int64 bestScore;      /* Best score so far */
  sqlite3_int64 score;          /* Score for current candidate LCS */
  int span;                     /* combined width of the input sequences */
  int cutoff = 4;            /* Max hash chain entries to follow */
  int nextCutoff = -1;       /* Value of cutoff for next iteration */

  span = (iE1 - iS1) + (iE2 - iS2);
  bestScore = -9223300000*(sqlite3_int64)1000000000;
  score = 0;
  iSXb = iSXp = iS1;
  iEXb = iEXp = iS1;
  iSYb = iSYp = iS2;
  iEYb = iEYp = iS2;
  mid = (iE1 + iS1)/2;
  do{
    nextCutoff = 0;
    for(i=iS1; i<iE1; i++){
      int limit = 0;
      j = p->aTo[p->aFrom[i].h % p->nTo].iHash;
      while( j>0
        && (j-1<iS2 || j>=iE2 || p->cmpLine(&p->aFrom[i], &p->aTo[j-1]))
      ){
        if( limit++ > cutoff ){
          j = 0;
          nextCutoff = cutoff*4;
          break;
        }
        j = p->aTo[j-1].iNext;
      }
      if( j==0 ) continue;
      assert( i>=iSXb && i>=iSXp );
      if( i<iEXb && j>=iSYb && j<iEYb ) continue;
      if( i<iEXp && j>=iSYp && j<iEYp ) continue;
      iSX = i;
      iSY = j-1;
      pA = &p->aFrom[iSX-1];
      pB = &p->aTo[iSY-1];
      n = minInt(iSX-iS1, iSY-iS2);
      for(k=0; k<n && p->cmpLine(pA,pB)==0; k++, pA--, pB--){}
      iSX -= k;
      iSY -= k;
      iEX = i+1;
      iEY = j;
      pA = &p->aFrom[iEX];
      pB = &p->aTo[iEY];
      n = minInt(iE1-iEX, iE2-iEY);
      for(k=0; k<n && p->cmpLine(pA,pB)==0; k++, pA++, pB++){}
      iEX += k;
      iEY += k;
      skew = (iSX-iS1) - (iSY-iS2);
      if( skew<0 ) skew = -skew;
      dist = (iSX+iEX)/2 - mid;
      if( dist<0 ) dist = -dist;
      score = (iEX - iSX)*(sqlite3_int64)span - (skew + dist);
      if( score>bestScore ){
        bestScore = score;
        iSXb = iSX;
        iSYb = iSY;
        iEXb = iEX;
        iEYb = iEY;
      }else if( iEX>iEXp ){
        iSXp = iSX;
        iSYp = iSY;
        iEXp = iEX;
        iEYp = iEY;
      }
    }
  }while( iSXb==iEXb && nextCutoff && (cutoff=nextCutoff)<=64 );
  if( iSXb==iEXb && (sqlite3_int64)(iE1-iS1)*(iE2-iS2)<2500 ){
    fsl__diff_optimal_lcs(p, iS1, iE1, iS2, iE2, piSX, piEX, piSY, piEY);
  }else{
    *piSX = iSXb;
    *piSY = iSYb;
    *piEX = iEXb;
    *piEY = iEYb;
  }
}

void fsl__dump_triples(fsl__diff_cx const * const p,
                       char const * zFile, int ln ){
  // Compare this with (fossil xdiff --raw) on the same inputs
  fprintf(stderr,"%s:%d: Compare this with (fossil xdiff --raw) on the same inputs:\n",
          zFile, ln);
  for(int i = 0; p->aEdit[i] || p->aEdit[i+1] || p->aEdit[i+2]; i+=3){
    printf(" copy %6d  delete %6d  insert %6d\n",
           p->aEdit[i], p->aEdit[i+1], p->aEdit[i+2]);
  }
}

/** @internal
    Expand the size of p->aEdit array to hold at least nEdit elements.
 */
static int fsl__diff_expand_edit(fsl__diff_cx * const p, int nEdit){
  void * re = fsl_realloc(p->aEdit, nEdit*sizeof(int));
  if(!re) return FSL_RC_OOM;
  else{
    p->aEdit = (int*)re;
    p->nEditAlloc = nEdit;
    return 0;
  }
}

/**
    Append a new COPY/DELETE/INSERT triple.
   
    Returns 0 on success, FSL_RC_OOM on OOM.
 */
static int appendTriple(fsl__diff_cx *p, int nCopy, int nDel, int nIns){
  /* printf("APPEND %d/%d/%d\n", nCopy, nDel, nIns); */
  if( p->nEdit>=3 ){
    if( p->aEdit[p->nEdit-1]==0 ){
      if( p->aEdit[p->nEdit-2]==0 ){
        p->aEdit[p->nEdit-3] += nCopy;
        p->aEdit[p->nEdit-2] += nDel;
        p->aEdit[p->nEdit-1] += nIns;
        return 0;
      }
      if( nCopy==0 ){
        p->aEdit[p->nEdit-2] += nDel;
        p->aEdit[p->nEdit-1] += nIns;
        return 0;
      }
    }
    if( nCopy==0 && nDel==0 ){
      p->aEdit[p->nEdit-1] += nIns;
      return 0;
    }
  }
  if( p->nEdit+3>p->nEditAlloc ){
    int const rc = fsl__diff_expand_edit(p, p->nEdit*2 + 15);
    if(rc) return rc;
    else if( p->aEdit==0 ) return 0;
  }
  p->aEdit[p->nEdit++] = nCopy;
  p->aEdit[p->nEdit++] = nDel;
  p->aEdit[p->nEdit++] = nIns;
  return 0;
}

/*
** A common subsequene between p->aFrom and p->aTo has been found.
** This routine tries to judge if the subsequence really is a valid
** match or rather is just an artifact of an indentation change.
**
** Return non-zero if the subsequence is valid.  Return zero if the
** subsequence seems likely to be an editing artifact and should be
** ignored.
**
** This routine is a heuristic optimization intended to give more
** intuitive diff results following an indentation change it code that
** is formatted similarly to C/C++, Javascript, Go, TCL, and similar
** languages that use {...} for nesting.  A correct diff is computed
** even if this routine always returns true (non-zero).  But sometimes
** a more intuitive diff can result if this routine returns false.
**
** The subsequences consists of the rows iSX through iEX-1 (inclusive)
** in p->aFrom[].  The total sequences is iS1 through iE1-1 (inclusive)
** of p->aFrom[].
**
** Example where this heuristic is useful, see the diff at
** https://www.sqlite.org/src/fdiff?v1=0e79dd15cbdb4f48&v2=33955a6fd874dd97
**
** See also discussion at https://fossil-scm.org/forum/forumpost/9ba3284295
**
** ALGORITHM (subject to change and refinement):
**
**    1.  If the subsequence is larger than 1/7th of the original span,
**        then consider it valid.  --> return 1
**
**    2.  If no lines of the subsequence contains more than one
**        non-whitespace character,  --> return 0
**
**    3.  If any line of the subsequence contains more than one non-whitespace
**        character and is unique across the entire sequence after ignoring
**        leading and trailing whitespace   --> return 1
**
**    4.  Otherwise, it is potentially an artifact of an indentation
**        change. --> return 0
*/
static bool likelyNotIndentChngArtifact(
  fsl__diff_cx const * const p,     /* The complete diff context */
  int iS1,         /* Start of the main segment */
  int iSX,         /* Start of the subsequence */
  int iEX,         /* First row past the end of the subsequence */
  int iE1          /* First row past the end of the main segment */
){
  int i, j, n;

  /* Rule (1) */
  if( (iEX-iSX)*7 >= (iE1-iS1) ) return 1;

  /* Compute fsl_dline.indent and fsl_dline.nw for all lines of the subsequence.
  ** If no lines contain more than one non-whitespace character return
  ** 0 because the subsequence could be due to an indentation change.
  ** Rule (2).
  */
  n = 0;
  for(i=iSX; i<iEX; i++){
    fsl_dline *pA = &p->aFrom[i];
    if( pA->nw==0 && pA->n ){
      const char *zA = pA->z;
      const int nn = pA->n;
      int ii, jj;
      for(ii=0; ii<nn && diff_isspace(zA[ii]); ii++){}
      pA->indent = ii;
      for(jj=nn-1; jj>ii && diff_isspace(zA[jj]); jj--){}
      pA->nw = jj - ii + 1;
    }
    if( pA->nw>1 ) n++;
  }
  if( n==0 ) return 0;

  /* Compute fsl_dline.indent and fsl_dline.nw for the entire sequence */
  for(i=iS1; i<iE1; i++){
    fsl_dline *pA;
    if( i==iSX ){
      i = iEX;
      if( i>=iE1 ) break;
    }
    pA = &p->aFrom[i];
    if( pA->nw==0 && pA->n ){
      const char *zA = pA->z;
      const int nn = pA->n;
      int ii, jj;
      for(ii=0; ii<nn && diff_isspace(zA[ii]); ii++){}
      pA->indent = ii;
      for(jj=nn-1; jj>ii && diff_isspace(zA[jj]); jj--){}
      pA->nw = jj - ii + 1;
    }
  }

  /* Check to see if any subsequence line that has more than one
  ** non-whitespace character is unique across the entire sequence.
  ** Rule (3)
  */
  for(i=iSX; i<iEX; i++){
    const char *z = p->aFrom[i].z + p->aFrom[i].indent;
    const int nw = p->aFrom[i].nw;
    if( nw<=1 ) continue;
    for(j=iS1; j<iSX; j++){
      if( p->aFrom[j].nw!=nw ) continue;
      if( memcmp(p->aFrom[j].z+p->aFrom[j].indent,z,nw)==0 ) break;
    }
    if( j<iSX ) continue;
    for(j=iEX; j<iE1; j++){
      if( p->aFrom[j].nw!=nw ) continue;
      if( memcmp(p->aFrom[j].z+p->aFrom[j].indent,z,nw)==0 ) break;
    }
    if( j>=iE1 ) break;
  }
  return i<iEX;
}

/**
    Do a single step in the difference.  Compute a sequence of
    copy/delete/insert steps that will convert lines iS1 through iE1-1
    of the input into lines iS2 through iE2-1 of the output and write
    that sequence into the difference context.
   
    The algorithm is to find a block of common text near the middle of
    the two segments being diffed.  Then recursively compute
    differences on the blocks before and after that common segment.
    Special cases apply if either input segment is empty or if the two
    segments have no text in common.
 */
static int diff_step(fsl__diff_cx *p, int iS1, int iE1, int iS2, int iE2){
  int iSX, iEX, iSY, iEY;
  int rc = 0;
  if( iE1<=iS1 ){
    /* The first segment is empty */
    if( iE2>iS2 ){
      rc = appendTriple(p, 0, 0, iE2-iS2);
    }
    return rc;
  }
  if( iE2<=iS2 ){
    /* The second segment is empty */
    return appendTriple(p, 0, iE1-iS1, 0);
  }

  /* Find the longest matching segment between the two sequences */
  fsl__diff_lcs(p, iS1, iE1, iS2, iE2, &iSX, &iEX, &iSY, &iEY);
  if( iEX>iSX+5
      || (iEX>iSX && likelyNotIndentChngArtifact(p,iS1,iSX,iEX,iE1) )){
    /* A common segment has been found.
       Recursively diff either side of the matching segment */
    rc = diff_step(p, iS1, iSX, iS2, iSY);
    if(!rc){
      if(iEX>iSX){
        rc = appendTriple(p, iEX - iSX, 0, 0);
      }
      if(!rc) rc = diff_step(p, iEX, iE1, iEY, iE2);
    }
  }else{
    /* The two segments have nothing in common.  Delete the first then
       insert the second. */
    rc = appendTriple(p, 0, iE1-iS1, iE2-iS2);
  }
  return rc;
}

int fsl__diff_all(fsl__diff_cx * const p){
  int mnE, iS, iE1, iE2;
  int rc = 0;
  /* Carve off the common header and footer */
  iE1 = p->nFrom;
  iE2 = p->nTo;
  while( iE1>0 && iE2>0 && p->cmpLine(&p->aFrom[iE1-1], &p->aTo[iE2-1])==0 ){
    iE1--;
    iE2--;
  }
  mnE = iE1<iE2 ? iE1 : iE2;
  for(iS=0; iS<mnE && p->cmpLine(&p->aFrom[iS],&p->aTo[iS])==0; iS++){}

  /* do the difference */
  if( iS>0 ){
    rc = appendTriple(p, iS, 0, 0);
    if(rc) return rc;
  }
  rc = diff_step(p, iS, iE1, iS, iE2);
  //fsl__dump_triples(p, __FILE__, __LINE__);
  if(rc) return rc;
  else if( iE1<p->nFrom ){
    rc = appendTriple(p, p->nFrom - iE1, 0, 0);
    if(rc) return rc;
  }
  /* Terminate the COPY/DELETE/INSERT triples with three zeros */
  rc = fsl__diff_expand_edit(p, p->nEdit+3);
  if(0==rc){
    if(p->aEdit ){
      p->aEdit[p->nEdit++] = 0;
      p->aEdit[p->nEdit++] = 0;
      p->aEdit[p->nEdit++] = 0;
      //fsl__dump_triples(p, __FILE__, __LINE__);
    }
  }
  return rc;
}

void fsl__diff_optimize(fsl__diff_cx * const p){
  int r;       /* Index of current triple */
  int lnFrom;  /* Line number in p->aFrom */
  int lnTo;    /* Line number in p->aTo */
  int cpy, del, ins;

  //fsl__dump_triples(p, __FILE__, __LINE__);
  lnFrom = lnTo = 0;
  for(r=0; r<p->nEdit; r += 3){
    cpy = p->aEdit[r];
    del = p->aEdit[r+1];
    ins = p->aEdit[r+2];
    lnFrom += cpy;
    lnTo += cpy;

    /* Shift insertions toward the beginning of the file */
    while( cpy>0 && del==0 && ins>0 ){
      fsl_dline *pTop = &p->aFrom[lnFrom-1];  /* Line before start of insert */
      fsl_dline *pBtm = &p->aTo[lnTo+ins-1];  /* Last line inserted */
      if( p->cmpLine(pTop, pBtm) ) break;
      if( LENGTH(pTop+1)+LENGTH(pBtm)<=LENGTH(pTop)+LENGTH(pBtm-1) ) break;
      lnFrom--;
      lnTo--;
      p->aEdit[r]--;
      p->aEdit[r+3]++;
      cpy--;
    }

    /* Shift insertions toward the end of the file */
    while( r+3<p->nEdit && p->aEdit[r+3]>0 && del==0 && ins>0 ){
      fsl_dline *pTop = &p->aTo[lnTo];       /* First line inserted */
      fsl_dline *pBtm = &p->aTo[lnTo+ins];   /* First line past end of insert */
      if( p->cmpLine(pTop, pBtm) ) break;
      if( LENGTH(pTop)+LENGTH(pBtm-1)<=LENGTH(pTop+1)+LENGTH(pBtm) ) break;
      lnFrom++;
      lnTo++;
      p->aEdit[r]++;
      p->aEdit[r+3]--;
      cpy++;
    }

    /* Shift deletions toward the beginning of the file */
    while( cpy>0 && del>0 && ins==0 ){
      fsl_dline *pTop = &p->aFrom[lnFrom-1];     /* Line before start of delete */
      fsl_dline *pBtm = &p->aFrom[lnFrom+del-1]; /* Last line deleted */
      if( p->cmpLine(pTop, pBtm) ) break;
      if( LENGTH(pTop+1)+LENGTH(pBtm)<=LENGTH(pTop)+LENGTH(pBtm-1) ) break;
      lnFrom--;
      lnTo--;
      p->aEdit[r]--;
      p->aEdit[r+3]++;
      cpy--;
    }

    /* Shift deletions toward the end of the file */
    while( r+3<p->nEdit && p->aEdit[r+3]>0 && del>0 && ins==0 ){
      fsl_dline *pTop = &p->aFrom[lnFrom];     /* First line deleted */
      fsl_dline *pBtm = &p->aFrom[lnFrom+del]; /* First line past end of delete */
      if( p->cmpLine(pTop, pBtm) ) break;
      if( LENGTH(pTop)+LENGTH(pBtm-1)<=LENGTH(pTop)+LENGTH(pBtm) ) break;
      lnFrom++;
      lnTo++;
      p->aEdit[r]++;
      p->aEdit[r+3]--;
      cpy++;
    }

    lnFrom += del;
    lnTo += ins;
  }
  //fsl__dump_triples(p, __FILE__, __LINE__);
}


/**
   Counts the number of lines in the first n bytes of the given 
   string. If n<0 then fsl_strlen() is used to count it. 

   It includes the last line in the count even if it lacks the \n
   terminator. If an empty string is passed in, the number of lines
   is zero.

   For the purposes of this function, a string is considered empty if
   it contains no characters OR contains only NUL characters.

   If the input appears to be plain text it returns true and, if nOut
   is not NULL, writes the number of lines there. If the input appears
   to be binary, returns false and does not modify nOut.
*/
static bool fsl__count_lines(const char *z, fsl_int_t n, uint32_t * nOut ){
  uint32_t nLine;
  const char *zNL, *z2;
  if(n<0) n = (fsl_int_t)fsl_strlen(z);
  for(nLine=0, z2=z; (zNL = strchr(z2,'\n'))!=0; z2=zNL+1, nLine++){}
  if( z2[0]!='\0' ){
    nLine++;
    do{ z2++; }while( z2[0]!='\0' );
  }
  if( n!=(fsl_int_t)(z2-z) ) return false;
  if( nOut ) *nOut = nLine;
  return true;
}

int fsl_break_into_dlines(const char *z, fsl_int_t n,
                          uint32_t *pnLine,
                          fsl_dline **pOut, uint64_t diffFlags){
  uint32_t nLine, i, k, nn, s, x;
  uint64_t h, h2;
  fsl_dline *a = 0;
  const char *zNL;

  if(!z || !n){
    *pnLine = 0;
    *pOut = NULL;
    return 0;
  }
  if( !fsl__count_lines(z, n, &nLine) ){
    return FSL_RC_DIFF_BINARY;
  }
  assert( nLine>0 || z[0]=='\0' );
  if(nLine>0){
    a = fsl_malloc( (fsl_size_t)nLine * sizeof(a[0]) );
    if(!a) return FSL_RC_OOM;
    memset(a, 0, sizeof(a[0])*nLine);
  }else{
    *pnLine = 0;
    *pOut = a;
    return 0;
  }
  assert( a );
  i = 0;
  do{
    zNL = strchr(z,'\n');
    if( zNL==0 ) zNL = z+n;
    nn = (uint32_t)(zNL - z);
    if( nn>FSL__LINE_LENGTH_MASK ){
      fsl_free(a);
      return FSL_RC_DIFF_BINARY;
    }
    a[i].z = z;
    k = nn;
    if( diffFlags & FSL_DIFF2_STRIP_EOLCR ){
      if( k>0 && z[k-1]=='\r' ){ k--; }
    }
    a[i].n = k;
    if( diffFlags & FSL_DIFF2_IGNORE_EOLWS ){
      while( k>0 && diff_isspace(z[k-1]) ){ k--; }
    }
    if( (diffFlags & FSL_DIFF2_IGNORE_ALLWS)
        ==FSL_DIFF2_IGNORE_ALLWS ){
      uint32_t numws = 0;
      for(s=0; s<k && (unsigned char)z[s]<=' '; s++){}
      a[i].indent = s;
      a[i].nw = k - s;
      for(h=0, x=s; x<k; ++x){
        char c = z[x];
        if( diff_isspace(c) ){
          ++numws;
        }else{
          h = (h^c)*9000000000000000041LL;
        }
      }
      k -= numws;
    }else{
      uint32_t k2 = k & ~0x7;
      uint64_t m;
      for(h=x=s=0; x<k2; x += 8){
        memcpy(&m, z+x, 8);
        h = (h^m)*9000000000000000041LL;
      }
      m = 0;
      memcpy(&m, z+x, k-k2);
      h ^= m;
    }
    a[i].h = h = ((h%281474976710597LL)<<FSL__LINE_LENGTH_MASK_SZ) | (k-s);
    h2 = h % nLine;
    a[i].iNext = a[h2].iHash;
    a[h2].iHash = i+1;
    z += nn+1; n -= nn+1;
    i++;
  }while( zNL[0]!='\0' && zNL[1]!='\0' );
  assert( i==nLine );

  *pnLine = nLine;
  *pOut = a;
  return 0;
}

int fsl_dline_cmp(const fsl_dline * const pA,
                  const fsl_dline * const pB){
  if( pA->h!=pB->h ) return 1;
  return memcmp(pA->z,pB->z, pA->h&FSL__LINE_LENGTH_MASK);
}

int fsl_dline_cmp_ignore_ws(const fsl_dline * const pA,
                            const fsl_dline * const pB){
  if( pA->h==pB->h ){
    unsigned short a, b;
    if( memcmp(pA->z, pB->z, pA->h&FSL__LINE_LENGTH_MASK)==0 ) return 0;
    a = pA->indent;
    b = pB->indent;
    while( a<pA->n || b<pB->n ){
      if( a<pA->n && b<pB->n && pA->z[a++] != pB->z[b++] ) return 1;
      while( a<pA->n && diff_isspace(pA->z[a])) ++a;
      while( b<pB->n && diff_isspace(pB->z[b])) ++b;
    }
    return pA->n-a != pB->n-b;
  }
  return 1;
}

/*
** The two text segments zLeft and zRight are known to be different on
** both ends, but they might have  a common segment in the middle.  If
** they do not have a common segment, return 0.  If they do have a large
** common segment, return non-0 and before doing so set:
**
**   aLCS[0] = start of the common segment in zLeft
**   aLCS[1] = end of the common segment in zLeft
**   aLCS[2] = start of the common segment in zLeft
**   aLCS[3] = end of the common segment in zLeft
**
** This computation is for display purposes only and does not have to be
** optimal or exact.
*/
static int textLCS2(
  const char *zLeft,  uint32_t nA, /* String on the left */
  const char *zRight, uint32_t nB, /* String on the right */
  uint32_t *aLCS                   /* Identify bounds of LCS here */
){
  const unsigned char *zA = (const unsigned char*)zLeft;    /* left string */
  const unsigned char *zB = (const unsigned char*)zRight;   /* right string */
  uint32_t i, j, k;               /* Loop counters */
  uint32_t lenBest = 0;           /* Match length to beat */

  for(i=0; i<nA-lenBest; i++){
    unsigned char cA = zA[i];
    if( (cA&0xc0)==0x80 ) continue;
    for(j=0; j<nB-lenBest; j++ ){
      if( zB[j]==cA ){
        for(k=1; j+k<nB && i+k<nA && zB[j+k]==zA[i+k]; k++){}
        while( (zB[j+k]&0xc0)==0x80 ){ k--; }
        if( k>lenBest ){
          lenBest = k;
          aLCS[0] = i;
          aLCS[1] = i+k;
          aLCS[2] = j;
          aLCS[3] = j+k;
        }
      }
    }
  }
  return lenBest>0;
}

/*
** Find the smallest spans that are different between two text strings
** that are known to be different on both ends. Returns the number
** of entries in p->a which get populated.
*/
static unsigned short textLineChanges(
  const char *zLeft,  uint32_t nA, /* String on the left */
  const char *zRight, uint32_t nB, /* String on the right */
  fsl_dline_change * const p             /* Write results here */
){
  p->n = 1;
  p->a[0].iStart1 = 0;
  p->a[0].iLen1 = nA;
  p->a[0].iStart2 = 0;
  p->a[0].iLen2 = nB;
  p->a[0].isMin = 0;
  while( p->n<fsl_dline_change_max_spans-1 ){
    int mxi = -1;
    int mxLen = -1;
    int x, i;
    uint32_t aLCS[4] = {0,0,0,0};
    struct fsl_dline_change_span *a, *b;
    for(i=0; i<p->n; i++){
      if( p->a[i].isMin ) continue;
      x = p->a[i].iLen1;
      if( p->a[i].iLen2<x ) x = p->a[i].iLen2;
      if( x>mxLen ){
        mxLen = x;
        mxi = i;
      }
    }
    if( mxLen<6 ) break;
    x = textLCS2(zLeft + p->a[mxi].iStart1, p->a[mxi].iLen1,
                 zRight + p->a[mxi].iStart2, p->a[mxi].iLen2, aLCS);
    if( x==0 ){
      p->a[mxi].isMin = 1;
      continue;
    }
    a = p->a+mxi;
    b = a+1;
    if( mxi<p->n-1 ){
      memmove(b+1, b, sizeof(*b)*(p->n-mxi-1));
    }
    p->n++;
    b->iStart1 = a->iStart1 + aLCS[1];
    b->iLen1 = a->iLen1 - aLCS[1];
    a->iLen1 = aLCS[0];
    b->iStart2 = a->iStart2 + aLCS[3];
    b->iLen2 = a->iLen2 - aLCS[3];
    a->iLen2 = aLCS[2];
    b->isMin = 0;
  }
  return p->n;
}

/*
** Return true if the string starts with n spaces
*/
static int allSpaces(const char *z, int n){
  int i;
  for(i=0; i<n && diff_isspace(z[i]); ++i){}
  return i==n;
}

/*
** Try to improve the human-readability of the fsl_dline_change p.
**
** (1)  If the first change span shows a change of indentation, try to
**      move that indentation change to the left margin.
**
** (2)  Try to shift changes so that they begin or end with a space.
*/
static void improveReadability(
  const char *zA,  /* Left line of the change */
  const char *zB,  /* Right line of the change */
  fsl_dline_change * const p /* The fsl_dline_change to be adjusted */
){
  int j, n, len;
  if( p->n<1 ) return;

  /* (1) Attempt to move indentation changes to the left margin */
  if( p->a[0].iLen1==0
   && (len = p->a[0].iLen2)>0
   && (j = p->a[0].iStart2)>0
   && zB[0]==zB[j]
   && allSpaces(zB, j)
  ){
    for(n=1; n<len && n<j && zB[j]==zB[j+n]; n++){}
    if( n<len ){
      memmove(&p->a[1], &p->a[0], sizeof(p->a[0])*p->n);
      p->n++;
      p->a[0] = p->a[1];
      p->a[1].iStart2 += n;
      p->a[1].iLen2 -= n;
      p->a[0].iLen2 = n;
    }
    p->a[0].iStart1 = 0;
    p->a[0].iStart2 = 0;
  }else
  if( p->a[0].iLen2==0
   && (len = p->a[0].iLen1)>0
   && (j = p->a[0].iStart1)>0
   && zA[0]==zA[j]
   && allSpaces(zA, j)
  ){
    for(n=1; n<len && n<j && zA[j]==zA[j+n]; n++){}
    if( n<len ){
      memmove(&p->a[1], &p->a[0], sizeof(p->a[0])*p->n);
      p->n++;
      p->a[0] = p->a[1];
      p->a[1].iStart1 += n;
      p->a[1].iLen1 -= n;
      p->a[0].iLen1 = n;
    }
    p->a[0].iStart1 = 0;
    p->a[0].iStart2 = 0;
  }

  /* (2) Try to shift changes so that they begin or end with a
  ** space.  (TBD) */
}

void fsl_dline_change_spans(const fsl_dline *pLeft, const fsl_dline *pRight,
                            fsl_dline_change * const p){
  /* fossil(1) counterpart ==> diff.c oneLineChange() */
  int nLeft;           /* Length of left line in bytes */
  int nRight;          /* Length of right line in bytes */
  int nShort;          /* Shortest of left and right */
  int nPrefix;         /* Length of common prefix */
  int nSuffix;         /* Length of common suffix */
  int nCommon;         /* Total byte length of suffix and prefix */
  const char *zLeft;   /* Text of the left line */
  const char *zRight;  /* Text of the right line */
  int nLeftDiff;       /* nLeft - nPrefix - nSuffix */
  int nRightDiff;      /* nRight - nPrefix - nSuffix */

  nLeft = pLeft->n;
  zLeft = pLeft->z;
  nRight = pRight->n;
  zRight = pRight->z;
  nShort = nLeft<nRight ? nLeft : nRight;

  nPrefix = 0;
  while( nPrefix<nShort && zLeft[nPrefix]==zRight[nPrefix] ){
    nPrefix++;
  }
  if( nPrefix<nShort ){
    while( nPrefix>0 && (zLeft[nPrefix]&0xc0)==0x80 ) nPrefix--;
  }
  nSuffix = 0;
  if( nPrefix<nShort ){
    while( nSuffix<nShort
           && zLeft[nLeft-nSuffix-1]==zRight[nRight-nSuffix-1] ){
      nSuffix++;
    }
    if( nSuffix<nShort ){
      while( nSuffix>0 && (zLeft[nLeft-nSuffix]&0xc0)==0x80 ) nSuffix--;
    }
    if( nSuffix==nLeft || nSuffix==nRight ) nPrefix = 0;
  }
  nCommon = nPrefix + nSuffix;

  /* If the prefix and suffix overlap, that means that we are dealing with
  ** a pure insertion or deletion of text that can have multiple alignments.
  ** Try to find an alignment to begins and ends on whitespace, or on
  ** punctuation, rather than in the middle of a name or number.
  */
  if( nCommon > nShort ){
    int iBest = -1;
    int iBestVal = -1;
    int i;
    int nLong = nLeft<nRight ? nRight : nLeft;
    int nGap = nLong - nShort;
    for(i=nShort-nSuffix; i<=nPrefix; i++){
       int iVal = 0;
       char c = zLeft[i];
       if( diff_isspace(c) ){
         iVal += 5;
       }else if( !fsl_isalnum(c) ){
         iVal += 2;
       }
       c = zLeft[i+nGap-1];
       if( diff_isspace(c) ){
         iVal += 5;
       }else if( !fsl_isalnum(c) ){
         iVal += 2;
       }
       if( iVal>iBestVal ){
         iBestVal = iVal;
         iBest = i;
       }
    }
    nPrefix = iBest;
    nSuffix = nShort - nPrefix;
    nCommon = nPrefix + nSuffix;
  }

  /* A single chunk of text inserted */
  if( nCommon==nLeft ){
    p->n = 1;
    p->a[0].iStart1 = nPrefix;
    p->a[0].iLen1 = 0;
    p->a[0].iStart2 = nPrefix;
    p->a[0].iLen2 = nRight - nCommon;
    improveReadability(zLeft, zRight, p);
    return;
  }

  /* A single chunk of text deleted */
  if( nCommon==nRight ){
    p->n = 1;
    p->a[0].iStart1 = nPrefix;
    p->a[0].iLen1 = nLeft - nCommon;
    p->a[0].iStart2 = nPrefix;
    p->a[0].iLen2 = 0;
    improveReadability(zLeft, zRight, p);
    return;
  }

  /* At this point we know that there is a chunk of text that has
  ** changed between the left and the right.  Check to see if there
  ** is a large unchanged section in the middle of that changed block.
  */
  nLeftDiff = nLeft - nCommon;
  nRightDiff = nRight - nCommon;
  if( nLeftDiff >= 4
   && nRightDiff >= 4
   && textLineChanges(&zLeft[nPrefix], nLeftDiff,
                      &zRight[nPrefix], nRightDiff, p)>1
  ){
    int i;
    for(i=0; i<p->n; i++){
      p->a[i].iStart1 += nPrefix;
      p->a[i].iStart2 += nPrefix;
    }
    improveReadability(zLeft, zRight, p);
    return;
  }

  /* If all else fails, show a single big change between left and right */
  p->n = 1;
  p->a[0].iStart1 = nPrefix;
  p->a[0].iLen1 = nLeft - nCommon;
  p->a[0].iStart2 = nPrefix;
  p->a[0].iLen2 = nRight - nCommon;
  improveReadability(zLeft, zRight, p);
}


/*
** The threshold at which diffBlockAlignment transitions from the
** O(N*N) Wagner minimum-edit-distance algorithm to a less process
** O(NlogN) divide-and-conquer approach.
*/
#define DIFF_ALIGN_MX  1225

/**
   FSL_DIFF_SMALL_GAP=0 is a temporary(? as of 2022-01-04) patch for a
   cosmetic-only (but unsightly) quirk of the diff engine where it
   produces a pair of identical DELETE/INSERT lines. Richard's
   preliminary solution for it is to remove the "small gap merging,"
   but he notes (in fossil /chat) that he's not recommending this as
   "the" fix.

   PS: we colloquially know this as "the lineno diff" because it was first
   reported in a diff which resulted in:

```
-  int     lineno;
+  int     lineno;
```

   (No, there are no whitespace changes there.)

   To reiterate, though: this is not a "bug," in that it does not
   cause incorrect results when applying the resulting unfified-diff
   patches. It does, however, cause confusion for human users.


   Here are two inputs which, when diffed, expose the lineno behavior:

   #1:

```
struct fnc_diff_view_state {
  int     first_line_onscreen;
  int     last_line_onscreen;
  int     diff_flags;
  int     context;
  int     sbs;
  int     matched_line;
  int     current_line;
  int     lineno;
  size_t     ncols;
  size_t     nlines;
  off_t    *line_offsets;
  bool     eof;
  bool     colour;
  bool     showmeta;
  bool     showln;
};
```

   #2:

```
struct fnc_diff_view_state {
  int     first_line_onscreen;
  int     last_line_onscreen;
  int     diff_flags;
  int     context;
  int     sbs;
  int     matched_line;
  int     selected_line;
  int     lineno;
  int     gtl;
  size_t     ncols;
  size_t     nlines;
  off_t    *line_offsets;
  bool     eof;
  bool     colour;
  bool     showmeta;
  bool     showln;
};
```

   Result without this patch:

```
Index: X.0
==================================================================
--- X.0
+++ X.1
@@ -3,15 +3,16 @@
   int     last_line_onscreen;
   int     diff_flags;
   int     context;
   int     sbs;
   int     matched_line;
+  int     selected_line;
-  int     current_line;
-  int     lineno;
+  int     lineno;
+  int     gtl;
   size_t     ncols;
   size_t     nlines;
   off_t    *line_offsets;
   bool     eof;
   bool     colour;
   bool     showmeta;
   bool     showln;
 };
```

    And with the patch:

```
Index: X.0
==================================================================
--- X.0
+++ X.1
@@ -3,15 +3,16 @@
   int     last_line_onscreen;
   int     diff_flags;
   int     context;
   int     sbs;
   int     matched_line;
-  int     current_line;
+  int     selected_line;
   int     lineno;
+  int     gtl;
   size_t     ncols;
   size_t     nlines;
   off_t    *line_offsets;
   bool     eof;
   bool     colour;
   bool     showmeta;
   bool     showln;
 };
```

*/
#define FSL_DIFF_SMALL_GAP 0

#if FSL_DIFF_SMALL_GAP
/*
** R[] is an array of six integer, two COPY/DELETE/INSERT triples for a
** pair of adjacent differences.  Return true if the gap between these
** two differences is so small that they should be rendered as a single
** edit.
*/
static int smallGap2(const int *R, int ma, int mb){
  int m = R[3];
  ma += R[4] + m;
  mb += R[5] + m;
  if( ma*mb>DIFF_ALIGN_MX ) return 0;
  return m<=2 || m<=(R[1]+R[2]+R[4]+R[5])/8;
}
#endif

static unsigned short diff_opt_context_lines(fsl_dibu_opt const * opt){
  const unsigned short dflt = 5;
  unsigned short n = opt ? opt->contextLines : dflt;
  if( !n && (opt->diffFlags & FSL_DIFF2_CONTEXT_ZERO)==0 ){
    n = dflt;
  }
  return n;
}

/*
** Minimum of two values
*/
static int diffMin(int a, int b){ return a<b ? a : b; }

/****************************************************************************/
/*
** Return the number between 0 and 100 that is smaller the closer pA and
** pB match.  Return 0 for a perfect match.  Return 100 if pA and pB are
** completely different.
**
** The current algorithm is as follows:
**
** (1) Remove leading and trailing whitespace.
** (2) Truncate both strings to at most 250 characters
** (3) If the two strings have a common prefix, measure that prefix
** (4) Find the length of the longest common subsequence that is
**     at least 150% longer than the common prefix.
** (5) Longer common subsequences yield lower scores.
*/
static int match_dline2(fsl_dline * const pA, fsl_dline * const pB){
  const char *zA;            /* Left string */
  const char *zB;            /* right string */
  int nA;                    /* Bytes in zA[] */
  int nB;                    /* Bytes in zB[] */
  int nMin;
  int nPrefix;
  int avg;                   /* Average length of A and B */
  int i, j, k;               /* Loop counters */
  int best = 0;              /* Longest match found so far */
  int score;                 /* Final score.  0..100 */
  unsigned char c;           /* Character being examined */
  unsigned char aFirst[256]; /* aFirst[X] = index in zB[] of first char X */
  unsigned char aNext[252];  /* aNext[i] = index in zB[] of next zB[i] char */

  zA = pA->z;
  if( pA->nw==0 && pA->n ){
    for(i=0; i<pA->n && diff_isspace(zA[i]); i++){}
    pA->indent = i;
    for(j=pA->n-1; j>i && diff_isspace(zA[j]); j--){}
    pA->nw = j - i + 1;
  }
  zA += pA->indent;
  nA = pA->nw;

  zB = pB->z;
  if( pB->nw==0 && pB->n ){
    for(i=0; i<pB->n && diff_isspace(zB[i]); i++){}
    pB->indent = i;
    for(j=pB->n-1; j>i && diff_isspace(zB[j]); j--){}
    pB->nw = j - i + 1;
  }
  zB += pB->indent;
  nB = pB->nw;

  if( nA>250 ) nA = 250;
  if( nB>250 ) nB = 250;
  avg = (nA+nB)/2;
  if( avg==0 ) return 0;
  nMin = nA;
  if( nB<nMin ) nMin = nB;
  if( nMin==0 ) return 68;
  for(nPrefix=0; nPrefix<nMin && zA[nPrefix]==zB[nPrefix]; nPrefix++){}
  best = 0;
  if( nPrefix>5 && nPrefix>nMin/2 ){
    best = nPrefix*3/2;
    if( best>=avg - 2 ) best = avg - 2;
  }
  if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
  memset(aFirst, 0xff, sizeof(aFirst));
  zA--; zB--;   /* Make both zA[] and zB[] 1-indexed */
  for(i=nB; i>0; i--){
    c = (unsigned char)zB[i];
    aNext[i] = aFirst[c];
    aFirst[c] = i;
  }
  for(i=1; i<=nA-best; i++){
    c = (unsigned char)zA[i];
    for(j=aFirst[c]; j<nB-best && memcmp(&zA[i],&zB[j],best)==0; j = aNext[j]){
      int limit = diffMin(nA-i, nB-j);
      for(k=best; k<=limit && zA[k+i]==zB[k+j]; k++){}
      if( k>best ) best = k;
    }
  }
  score = 5 + ((best>=avg) ? 0 : (avg - best)*95/avg);

#if 0
  fprintf(stderr, "A: [%.*s]\nB: [%.*s]\nbest=%d avg=%d score=%d\n",
  nA, zA+1, nB, zB+1, best, avg, score);
#endif

  /* Return the result */
  return score;
}

// Forward decl for recursion's sake.
static int diffBlockAlignment(
  fsl_dline * const aLeft, int nLeft,
  fsl_dline * const aRight, int nRight,
  fsl_dibu_opt const * pOpt,
  unsigned char **pResult,
  unsigned *pNResult
);

/*
** Make a copy of a list of nLine fsl_dline objects from one array to
** another.  Hash the new array to ignore whitespace.
*/
static void diffDLineXfer(
  fsl_dline *aTo,
  const fsl_dline *aFrom,
  int nLine
){
  int i, j, k;
  uint64_t h, h2;
  for(i=0; i<nLine; i++) aTo[i].iHash = 0;
  for(i=0; i<nLine; i++){
    const char *z = aFrom[i].z;
    int n = aFrom[i].n;
    for(j=0; j<n && diff_isspace(z[j]); j++){}
    aTo[i].z = &z[j];
    for(k=aFrom[i].n; k>j && diff_isspace(z[k-1]); k--){}
    aTo[i].n = n = k-j;
    aTo[i].indent = 0;
    aTo[i].nw = 0;
    for(h=0; j<k; j++){
      char c = z[j];
      if( !diff_isspace(c) ){
        h = (h^c)*9000000000000000041LL;
      }
    }
    aTo[i].h = h = ((h%281474976710597LL)<<FSL__LINE_LENGTH_MASK_SZ) | n;
    h2 = h % nLine;
    aTo[i].iNext = aTo[h2].iHash;
    aTo[h2].iHash = i+1;
  }
}

/*
** For a difficult diff-block alignment that was originally for
** the default consider-all-whitespace algorithm, try to find the
** longest common subsequence between the two blocks that involves
** only whitespace changes.
**
** Result is stored in *pOut and must be eventually fsl_free()d.
** Returns 0 on success, setting *pOut to NULL if no good match is
** found. Returns FSL_RC_OOM on allocation error.
*/
static int diffBlockAlignmentIgnoreSpace(
  fsl_dline * const aLeft, int nLeft,     /* Text on the left */
  fsl_dline * const aRight, int nRight,   /* Text on the right */
  fsl_dibu_opt const *pOpt,            /* Configuration options */
  unsigned char ** pOut,          /* OUTPUT: Result */
  unsigned *pNResult                /* OUTPUT: length of result */
){
  fsl__diff_cx dc;
  int iSX, iEX;                /* Start and end of LCS on the left */
  int iSY, iEY;                /* Start and end of the LCS on the right */
  unsigned char *a1, *a2;
  int n1, n2, nLCS, rc = 0;

  dc.aEdit = 0;
  dc.nEdit = 0;
  dc.nEditAlloc = 0;
  dc.nFrom = nLeft;
  dc.nTo = nRight;
  dc.cmpLine = fsl_dline_cmp_ignore_ws;
  dc.aFrom = fsl_malloc( sizeof(fsl_dline)*(nLeft+nRight) );
  if(!dc.aFrom) return FSL_RC_OOM;
  dc.aTo = &dc.aFrom[dc.nFrom];
  diffDLineXfer(dc.aFrom, aLeft, nLeft);
  diffDLineXfer(dc.aTo, aRight, nRight);
  fsl__diff_lcs(&dc,0,nLeft,0,nRight,&iSX,&iEX,&iSY,&iEY);
  fsl_free(dc.aFrom);
  nLCS = iEX - iSX;
  if( nLCS<5 ){
    /* No good LCS was found */
    *pOut = NULL;
    *pNResult = 0;
    return 0;
  }
  rc = diffBlockAlignment(aLeft,iSX,aRight,iSY,
                          pOpt,&a1, (unsigned *)&n1);
  if(rc) return rc;
  rc = diffBlockAlignment(aLeft+iEX, nLeft-iEX,
                          aRight+iEY, nRight-iEY,
                          pOpt, &a2, (unsigned *)&n2);
  if(rc){
    fsl_free(a1);
    return rc;
  }else{
    unsigned char * x = (unsigned char *)fsl_realloc(a1, n1+nLCS+n2);
    if(NULL==x){
      fsl_free(a1);
      fsl_free(a2);
      return FSL_RC_OOM;
    }
    a1 = x;
  }
  memcpy(a1+n1+nLCS,a2,n2);
  memset(a1+n1,3,nLCS);
  fsl_free(a2);
  *pNResult = (unsigned)(n1+n2+nLCS);
  *pOut = a1;
  return 0;
}

/*
** This is a helper route for diffBlockAlignment().  In this case,
** a very large block is encountered that might be too expensive to
** use the O(N*N) Wagner edit distance algorithm.  So instead, this
** block implements a less-precise but faster O(N*logN) divide-and-conquer
** approach.
**
** Result is stored in *pOut and must be eventually fsl_free()d.
** Returns 0 on success. Returns FSL_RC_OOM on allocation error.
*/
static int diffBlockAlignmentDivideAndConquer(
  fsl_dline * const aLeft, int nLeft,     /* Text on the left */
  fsl_dline * const aRight, int nRight,   /* Text on the right */
  fsl_dibu_opt const *pOpt,            /* Configuration options */
  unsigned char ** pOut,       /* OUTPUT: result */
  unsigned *pNResult                /* OUTPUT: length of result */
){
  fsl_dline *aSmall;               /* The smaller of aLeft and aRight */
  fsl_dline *aBig;                 /* The larger of aLeft and aRight */
  int nSmall, nBig;            /* Size of aSmall and aBig.  nSmall<=nBig */
  int iDivSmall, iDivBig;      /* Divider point for aSmall and aBig */
  int iDivLeft, iDivRight;     /* Divider point for aLeft and aRight */
  unsigned char *a1 = 0, *a2 = 0; /* Results of the alignments on two halves */
  int n1, n2;                  /* Number of entries in a1 and a2 */
  int score, bestScore;        /* Score and best score seen so far */
  int i;                       /* Loop counter */
  int rc;

  if( nLeft>nRight ){
    aSmall = aRight;
    nSmall = nRight;
    aBig = aLeft;
    nBig = nLeft;
  }else{
    aSmall = aLeft;
    nSmall = nLeft;
    aBig = aRight;
    nBig = nRight;
  }
  iDivBig = nBig/2;
  iDivSmall = nSmall/2;
  bestScore = 10000;
  for(i=0; i<nSmall; i++){
    score = match_dline2(aBig+iDivBig, aSmall+i) + abs(i-nSmall/2)*2;
    if( score<bestScore ){
      bestScore = score;
      iDivSmall = i;
    }
  }
  if( aSmall==aRight ){
    iDivRight = iDivSmall;
    iDivLeft = iDivBig;
  }else{
    iDivRight = iDivBig;
    iDivLeft = iDivSmall;
  }
  rc = diffBlockAlignment(aLeft,iDivLeft,aRight,iDivRight,
                          pOpt,&a1, (unsigned*)&n1);
  if(!rc){
    rc = diffBlockAlignment(aLeft+iDivLeft, nLeft-iDivLeft,
                            aRight+iDivRight, nRight-iDivRight,
                            pOpt, &a2, (unsigned*)&n2);
  }
  if(rc){
    fsl_free(a1);
    fsl_free(a2);
  }else{
    unsigned char * x = (unsigned char *)fsl_realloc(a1, n1+n2);
    if(!x) rc = FSL_RC_OOM;
    else{
      a1 = x;
      memcpy(a1+n1,a2,n2);
      *pNResult = (unsigned)(n1+n2);
      *pOut = a1;
    }
    fsl_free(a2);
  }
  return rc;
}


/*
** There is a change block in which nLeft lines of text on the left are
** converted into nRight lines of text on the right.  This routine computes
** how the lines on the left line up with the lines on the right.
**
** The return value is a buffer of unsigned characters, obtained from
** fsl_malloc().  (The caller needs to free the `*pResult` value using
** fsl_free().)  Entries in the returned array have values as follows:
**
**    1.  Delete the next line of pLeft.
**    2.  Insert the next line of pRight.
**    3.  The next line of pLeft changes into the next line of pRight.
**    4.  Delete one line from pLeft and add one line to pRight.
**
** The length of the returned array will be at most nLeft+nRight bytes.
** If the first bytes is 4, that means we could not compute reasonable
** alignment between the two blocks.
**
** Algorithm:  Wagner's minimum edit-distance algorithm, modified by
** adding a cost to each match based on how well the two rows match
** each other.  Insertion and deletion costs are 50.  Match costs
** are between 0 and 100 where 0 is a perfect match 100 is a complete
** mismatch.
*/
int diffBlockAlignment(
  fsl_dline * const aLeft, int nLeft,     /* Text on the left */
  fsl_dline * const aRight, int nRight,   /* Text on the right */
  fsl_dibu_opt const * pOpt,             /* Configuration options */
  unsigned char **pResult,         /* Raw result */
  unsigned *pNResult               /* OUTPUT: length of result */
){
  int i, j, k;                 /* Loop counters */
  int *a = 0;                  /* One row of the Wagner matrix */
  int *pToFree = 0;            /* Space that needs to be freed */
  unsigned char *aM = 0;       /* Wagner result matrix */
  int aBuf[100];               /* Stack space for a[] if nRight not to big */
  int rc = 0;

  if( nLeft==0 ){
    aM = fsl_malloc( nRight + 2 );
    if(!aM) return FSL_RC_OOM;
    memset(aM, 2, nRight);
    *pNResult = nRight;
    *pResult = aM;
    return 0;
  }
  if( nRight==0 ){
    aM = fsl_malloc( nLeft + 2 );
    if(!aM) return FSL_RC_OOM;
    memset(aM, 1, nLeft);
    *pNResult = nLeft;
    *pResult = aM;
    return 0;
  }

  /* For large alignments, try to use alternative algorithms that are
  ** faster than the O(N*N) Wagner edit distance. */
  if( (int64_t)nLeft*(int64_t)nRight>DIFF_ALIGN_MX
      && ((pOpt->diffFlags & FSL_DIFF2_SLOW_SBS)==0
          /* The Wagner matrix below is indexed, and its costs summed,
             in int. */
          || ((int64_t)nLeft+1)*((int64_t)nRight+1) > INT_MAX
          || ((int64_t)nLeft+nRight+1)*50 > INT_MAX) ){
    if( (pOpt->diffFlags & FSL_DIFF2_IGNORE_ALLWS)==0 ){
      *pResult = NULL;
      rc = diffBlockAlignmentIgnoreSpace(aLeft, nLeft,aRight,nRight,
                                         pOpt, pResult, pNResult);
      if(rc || *pResult) return rc;
    }
    return diffBlockAlignmentDivideAndConquer(aLeft, nLeft,aRight, nRight,
                                              pOpt, pResult, pNResult);
  }

  /* If we reach this point, we will be doing an O(N*N) Wagner minimum
  ** edit distance to compute the alignment.
  */
  if( nRight < (int)(sizeof(aBuf)/sizeof(aBuf[0]))-1 ){
    pToFree = 0;
    a = aBuf;
  }else{
    a = pToFree = fsl_malloc( sizeof(a[0])*(nRight+1) );
    if(!a){
      rc = FSL_RC_OOM;
      goto end;
    }
  }
  aM = fsl_malloc( (nLeft+1)*(nRight+1) );
  if(!aM){
    rc = FSL_RC_OOM;
    goto end;
  }

  /* Compute the best alignment */
  for(i=0; i<=nRight; i++){
    aM[i] = 2;
    a[i] = i*50;
  }
  aM[0] = 0;
  for(j=1; j<=nLeft; j++){
    int p = a[0];
    a[0] = p+50;
    aM[j*(nRight+1)] = 1;
    for(i=1; i<=nRight; i++){
      int m = a[i-1]+50;
      int d = 2;
      if( m>a[i]+50 ){
        m = a[i]+50;
        d = 1;
      }
      if( m>p ){
        int const score =
          match_dline2(&aLeft[j-1], &aRight[i-1]);
        if( (score<=90 || (i<j+1 && i>j-1)) && m>p+score ){
          m = p+score;
          d = 3 | score*4;
        }
      }
      p = a[i];
      a[i] = m;
      aM[j*(nRight+1)+i] = d;
    }
  }

  /* Compute the lowest-cost path back through the matrix */
  i = nRight;
  j = nLeft;
  k = (nRight+1)*(nLeft+1)-1;
  while( i+j>0 ){
    unsigned char c = aM[k];
    if( c>=3 ){
      assert( i>0 && j>0 );
      i--;
      j--;
      aM[k] = 3;
    }else if( c==2 ){
      assert( i>0 );
      i--;
    }else{
      assert( j>0 );
      j--;
    }
    k--;
    aM[k] = aM[j*(nRight+1)+i];
  }
  k++;
  i = (nRight+1)*(nLeft+1) - k;
  memmove(aM, &aM[k], i);
  *pNResult = i;
  *pResult = aM;

  end:
  fsl_free(pToFree);
  return rc;
}


/*
** Format a diff using a fsl_dibu object
*/
static int fdb__format(
  fsl__diff_cx * const cx,
  fsl_dibu * const pBuilder
){
  fsl_dline *A;        /* Left side of the diff */
  fsl_dline *B;        /* Right side of the diff */
  fsl_dibu_opt const * pOpt = pBuilder->opt;
  const int *R;          /* Array of COPY/DELETE/INSERT triples */
  unsigned int a;    /* Index of next line in A[] */
  unsigned int b;    /* Index of next line in B[] */
  unsigned int r;        /* Index into R[] */
  unsigned int nr;       /* Number of COPY/DELETE/INSERT triples to process */
  unsigned int mxr;      /* Maximum value for r */
  unsigned int na, nb;   /* Number of lines shown from A and B */
  unsigned int i, j;     /* Loop counters */
  unsigned int m, ma, mb;/* Number of lines to output */
  signed int skip;   /* Number of lines to skip */
  unsigned int contextLines; /* Lines of context above and below each change */
  unsigned short passNumber = 0;
  int rc = 0;
  
#define RC if(rc) goto end
#define METRIC(M) if(1==passNumber) ++pBuilder->metrics.M
  pass_again:
  contextLines = diff_opt_context_lines(pOpt);
  skip = 0;
  a = b = 0;
  A = cx->aFrom;
  B = cx->aTo;
  R = cx->aEdit;
  mxr = cx->nEdit;
  //MARKER(("contextLines=%u, nEdit = %d, mxr=%u\n", contextLines, cx->nEdit, mxr));
  while( mxr>2 && R[mxr-1]==0 && R[mxr-2]==0 ){ mxr -= 3; }

  pBuilder->lnLHS = pBuilder->lnRHS = 0;
  ++passNumber;
  if(pBuilder->start){
    pBuilder->passNumber = passNumber;
    rc = pBuilder->start(pBuilder);
    RC;
  }
  for(r=0; r<mxr; r += 3*nr){
    /* Figure out how many triples to show in a single block */
    for(nr=1; 3*nr<mxr && R[r+nr*3]>0 && R[r+nr*3]<(int)contextLines*2; nr++){}

#if 0
    /* MISSING: this "should" be replaced by a stateful predicate
       function, probably in the fsl_dibu_opt class. */
    /* If there is a regex, skip this block (generate no diff output)
    ** if the regex matches or does not match both insert and delete.
    ** Only display the block if one side matches but the other side does
    ** not.
    */
    if( pOpt->pRe ){
      int hideBlock = 1;
      int xa = a, xb = b;
      for(i=0; hideBlock && i<nr; i++){
        int c1, c2;
        xa += R[r+i*3];
        xb += R[r+i*3];
        c1 = re_dline_match(pOpt->pRe, &A[xa], R[r+i*3+1]);
        c2 = re_dline_match(pOpt->pRe, &B[xb], R[r+i*3+2]);
        hideBlock = c1==c2;
        xa += R[r+i*3+1];
        xb += R[r+i*3+2];
      }
      if( hideBlock ){
        a = xa;
        b = xb;
        continue;
      }
    }
#endif

    /* Figure out how many lines of A and B are to be displayed
    ** for this change block.
    */
    if( R[r]>(int)contextLines ){
      na = nb = contextLines;
      skip = R[r] - contextLines;
    }else{
      na = nb = R[r];
      skip = 0;
    }
    for(i=0; i<nr; i++){
      na += R[r+i*3+1];
      nb += R[r+i*3+2];
    }
    if( R[r+nr*3]>(int)contextLines ){
      na += contextLines;
      nb += contextLines;
    }else{
      na += R[r+nr*3];
      nb += R[r+nr*3];
    }
    for(i=1; i<nr; i++){
      na += R[r+i*3];
      nb += R[r+i*3];
    }

    //MARKER(("Chunk header... a=%u, b=%u, na=%u, nb=%u, skip=%d\n", a, b, na, nb, skip));
    if(pBuilder->chunkHeader
       /* The following bit is a kludge to keep from injecting a chunk
          header between chunks which are directly adjacent.

          The problem, however, is that we cannot skip _reliably_
          without also knowing how the next chunk aligns. If we skip
          it here, the _previous_ chunk header may well be telling
          the user a lie with regards to line numbers.

          Fossil itself does not have this issue because it generates
          these chunk headers directly in this routine, instead of in
          the diff builder, depending on a specific flag being set in
          builder->opt. Also (related), in that implementation, fossil
          will collapse chunks which are separated by less than the
          context distance into contiguous chunks (see below). Because
          we farm out the chunkHeader lines to the builder, we cannot
          reliably do that here.
       */
#if 0
       && !skip
#endif
       ){
      rc = pBuilder->chunkHeader(pBuilder,
                                 (uint32_t)(na ? a+skip+1 : a+skip),
                                 (uint32_t)na,
                                 (uint32_t)(nb ? b+skip+1 : b+skip),
                                 (uint32_t)nb);
      RC;
    }

    /* Show the initial common area */
    a += skip;
    b += skip;
    m = R[r] - skip;
    if( r ) skip -= contextLines;

    //MARKER(("Show the initial common... a=%u, b=%u, m=%u, r=%u, skip=%d\n", a, b, m, r, skip));
    if( skip>0 ){
      if( NULL==pBuilder->chunkHeader && skip<(int)contextLines ){
        /* 2021-09-27: BUG: this is incompatible with unified diff
           format. The generated header lines say we're skipping X
           lines but we then end up including lines which that header
           says to skip. As a workaround, we'll only run this when
           pBuilder->chunkHeader is NULL, noting that fossil's diff
           builder interface does not have that method (and thus
           doesn't have this issue, instead generating chunk headers
           directly in this algorithm).

           Without this block, our "utxt" diff builder can mimic
           fossil's non-diff builder unified diff format, except that
           we add Index lines (feature or bug?). With this block,
           the header values output above are wrong.
        */
        /* If the amount to skip is less that the context band, then
        ** go ahead and show the skip band as it is not worth eliding */
        //MARKER(("skip %d < contextLines %d\n", skip, contextLines));
        /* from fossil(1) from formatDiff() */
        for(j=0; 0==rc && j<(unsigned)skip; j++){
          //MARKER(("(A) COMMON\n"));
          rc = pBuilder->common(pBuilder, &A[a+j-skip]);
        }
      }else{
        rc = pBuilder->skip(pBuilder, skip);
      }
      RC;
    }
    for(j=0; 0==rc && j<m; j++){
      //MARKER(("(B) COMMON\n"));
      rc = pBuilder->common(pBuilder, &A[a+j]);
    }
    RC;
    a += m;
    b += m;
    //MARKER(("Show the differences... a=%d, b=%d, m=%d\n", a, b, m));

    /* Show the differences */
    for(i=0; i<nr; i++){
      unsigned int nAlign;
      unsigned char *alignment = 0;
      ma = R[r+i*3+1];   /* Lines on left but not on right */
      mb = R[r+i*3+2];   /* Lines on right but not on left */

#if FSL_DIFF_SMALL_GAP
  /* Try merging the current block with subsequent blocks, if the
      ** subsequent blocks are nearby and their result isn't too big.
      */
      while( i<nr-1 && smallGap2(&R[r+i*3],ma,mb) ){
        i++;
        m = R[r+i*3];
        ma += R[r+i*3+1] + m;
        mb += R[r+i*3+2] + m;
      }
#endif

      /* Try to find an alignment for the lines within this one block */
      rc = diffBlockAlignment(&A[a], ma, &B[b], mb, pOpt,
                              &alignment, &nAlign);
      RC;
      for(j=0; ma+mb>0; j++){
        assert( j<nAlign );
        switch( alignment[j] ){
          case 1: {
            /* Delete one line from the left */
            METRIC(deletions);
            rc = pBuilder->deletion(pBuilder, &A[a]);
            if(rc) goto bail;
            ma--;
            a++;
            break;
          }
          case 2: {
            /* Insert one line on the right */
            METRIC(insertions);
            rc = pBuilder->insertion(pBuilder, &B[b]);
            if(rc) goto bail;
            assert( mb>0 );
            mb--;
            b++;
            break;
          }
          case 3: {
            /* The left line is changed into the right line */
            if( 0==cx->cmpLine(&A[a], &B[b]) ){
              rc = pBuilder->common(pBuilder, &A[a]);
            }else{
              METRIC(edits);
              rc = pBuilder->edit(pBuilder, &A[a], &B[b]);
            }
            if(rc) goto bail;
            assert( ma>0 && mb>0 );
            ma--;
            mb--;
            a++;
            b++;
            break;
          }
          case 4: {
            /* Delete from left then separately insert on the right */
            METRIC(replacements);
            rc = pBuilder->replacement(pBuilder, &A[a], &B[b]);
            if(rc) goto bail;
            ma--;
            a++;
            mb--;
            b++;
            break;
          }
        }
      }
      assert( nAlign==j );
      fsl_free(alignment);
      if( i<nr-1 ){
        m = R[r+i*3+3];
        for(j=0; 0==rc && j<m; j++){
          //MARKER(("D common\n"));
          rc = pBuilder->common(pBuilder, &A[a+j]);
        }
        RC;
        b += m;
        a += m;
      }
      continue;
      bail:
      assert(rc);
      fsl_free(alignment);
      goto end;
    }

    /* Show the final common area */
    assert( nr==i );
    m = R[r+nr*3];
    if( m>contextLines ) m = contextLines;
    for(j=0; 0==rc && j<m && j<contextLines; j++){
      //MARKER(("E common\n"));
      rc = pBuilder->common(pBuilder, &A[a+j]);
    }
    RC;
  }
  if( R[r]>(int)contextLines ){
    rc = pBuilder->skip(pBuilder, R[r] - contextLines);
  }
  end:
#undef RC
#undef METRIC
  if(0==rc){
    if(pBuilder->finish) rc = pBuilder->finish(pBuilder);
    if(0==rc && pBuilder->twoPass && 1==passNumber){
      goto pass_again;
    }
  }
  return rc;
}

/**
   Like fossil(1), diff text as UTF-8 with no byte-order mark. If *pp
   starts with a BOM, copies it into conv, converts the copy with
   fsl_b_to_utf8_no_bom() and points *pp at it, leaving the caller's
   buffer unchanged. Returns 0 or FSL_RC_OOM.
*/
static int fsl__diff_input_utf8(fsl_b const ** pp, fsl_b * conv){
  int rc;
  if(!fsl_b_has_bom(*pp)) return 0;
  rc = fsl_b_append(conv, (*pp)->mem, (*pp)->used);
  if(!rc) rc = fsl_b_to_utf8_no_bom(conv);
  if(!rc) *pp = conv;
  return rc;
}

/**
   Performs a diff of version 1 (pA) and version 2 (pB). ONE of
   pBuilder or outRaw must be non-NULL. If pBuilder is not NULL, all
   output for the diff is emitted via pBuilder. If outRaw is not NULL
   then on success *outRaw is set to the array of diff triples,
   transfering ownership to the caller, who must eventually fsl_free()
   it. On error, *outRaw is not modified but pBuilder may have emitted
   partial output. That is not knowable for the general
   case. Ownership of pBuilder is not changed. If pBuilder is not NULL
   then pBuilder->opt must be non-NULL.
*/
static int fsl_diff2_text_impl(fsl_b const *pA,
                               fsl_b const *pB,
                               fsl_dibu * const pBuilder,
                               fsl_dibu_opt const * const opt_,
                               int ** outRaw){
  int rc = 0;
  fsl__diff_cx c = fsl__diff_cx_empty;
  bool ignoreWs = false;
  int ansiOptCount = 0;
  fsl_b convA = fsl_b_empty, convB = fsl_b_empty;
  fsl_dibu_opt opt = *opt_
    /*we need a copy for the sake of the FSL_DIFF2_INVERT flag*/;
  if(!pA || !pB || (pBuilder && outRaw)) return FSL_RC_MISUSE;

  rc = fsl__diff_input_utf8(&pA, &convA);
  if(!rc) rc = fsl__diff_input_utf8(&pB, &convB);
  if(rc) goto end;

  if( opt.diffFlags & FSL_DIFF2_INVERT ){
    char const * z;
    fsl_b const *pTemp = pA;
    pA = pB;
    pB = pTemp;
    z = opt.hashRHS; opt.hashRHS = opt.hashLHS; opt.hashLHS = z;
    z = opt.nameRHS; opt.nameRHS = opt.nameLHS; opt.nameLHS = z;
  }
#define AOPT(OPT) \
  if(opt.ansiColor.OPT) ansiOptCount += (*opt.ansiColor.OPT) ? 1 : 0; \
  else opt.ansiColor.OPT = ""
  AOPT(insertion);
  AOPT(edit);
  AOPT(deletion);
#undef AOPT
  if(0==ansiOptCount){
    opt.ansiColor.reset = "";
  }else if(!opt.ansiColor.reset || !*opt.ansiColor.reset){
    opt.ansiColor.reset = "\x1b[0m";
  }
  ignoreWs = (opt.diffFlags & FSL_DIFF2_IGNORE_ALLWS)!=0;
  if(FSL_DIFF2_IGNORE_ALLWS==(opt.diffFlags & FSL_DIFF2_IGNORE_ALLWS)){
    c.cmpLine = fsl_dline_cmp_ignore_ws;
  }else{
    c.cmpLine = fsl_dline_cmp;
  }

  rc = fsl_break_into_dlines(fsl_b_cstr(pA), (fsl_int_t)pA->used,
                             (uint32_t*)&c.nFrom, &c.aFrom, opt.diffFlags);
  if(rc) goto end;
  rc = fsl_break_into_dlines(fsl_b_cstr(pB), (fsl_int_t)pB->used,
                             (uint32_t*)&c.nTo, &c.aTo, opt.diffFlags);
  if(rc) goto end;

  /* Compute the difference */
  rc = fsl__diff_all(&c);
  if(rc) goto end;
  if( ignoreWs && c.nEdit==6 && c.aEdit[1]==0 && c.aEdit[2]==0 ){
    rc = FSL_RC_DIFF_WS_ONLY;
    goto end;
  }
  if( (opt.diffFlags & FSL_DIFF2_NOTTOOBIG)!=0 ){
    int i, m, n;
    int const * const a = c.aEdit;
    int const mx = c.nEdit;
    for(i=m=n=0; i<mx; i+=3){ m += a[i]; n += a[i+1]+a[i+2]; }
    if( n>10000 ){
      rc = FSL_RC_RANGE;
      /* diff_errmsg(pOut, DIFF_TOO_MANY_CHANGES, diffFlags); */
      goto end;
    }
  }
  //fsl__dump_triples(&c, __FILE__, __LINE__);
  if( (opt.diffFlags & FSL_DIFF2_NOOPT)==0 ){
    fsl__diff_optimize(&c);
  }
  //fsl__dump_triples(&c, __FILE__, __LINE__);

  /**
     Reference:

     https://fossil-scm.org/home/file?ci=cae7036bb7f07c1b&name=src/diff.c&ln=2749-2804

     Noting that:

     - That function's return value is this one's *outRaw

     - DIFF_NUMSTAT flag is not implemented. For that matter,
     flags which result in output going anywhere except for
     pBuilder->out are not implemented here, e.g. DIFF_RAW.

     That last point makes this impl tiny compared to the original!
  */
  if(pBuilder){
    fsl_dibu_opt const * oldOpt = pBuilder->opt;
    pBuilder->opt = &opt;
    rc = fdb__format(&c, pBuilder);
    pBuilder->opt = oldOpt;
  }
  end:
  if(0==rc && outRaw){
    *outRaw = c.aEdit;
    c.aEdit = 0;
  }
  fsl__diff_cx_clean(&c);
  fsl_b_clear(&convA);
  fsl_b_clear(&convB);
  return rc;
}

int fsl_diff_v2(fsl_b const * pv1,
                fsl_b const * pv2,
                fsl_dibu * const pBuilder){
  return fsl_diff2_text_impl(pv1, pv2, pBuilder, pBuilder->opt, NULL);
}

int fsl_diff_v2_raw(fsl_b const * pv1,
                    fsl_b const * pv2,
                    fsl_dibu_opt const * const opt,
                    int **outRaw ){
  return fsl_diff2_text_impl(pv1, pv2, NULL,
                             opt ? opt : &fsl_dibu_opt_empty,
                             outRaw);
}


#undef DIFF_ALIGN_MX
#undef FSL_DIFF_SMALL_GAP
#undef diff_isspace
#undef LENGTH
/* end of file src/diff.c */
/* start of file src/encode.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**************************************************************************
  This file houses some encoding/decoding API routines.
*/
#include <assert.h>
#include <string.h>

/* Only for debugging */
#include <stdio.h>

/*
   An array for translating single base-16 characters into a value.
   Disallowed input characters have a value of 64.
*/
static const char zDecode[] = {
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
   0,  1,  2,  3,  4,  5,  6,  7,   8,  9, 64, 64, 64, 64, 64, 64,
  64, 10, 11, 12, 13, 14, 15, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 10, 11, 12, 13, 14, 15, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64
};

/* Randomness used for XOR-ing by the obscure() and unobscure() routines */
static const unsigned char aObscurer[16] = {
  0xa7, 0x21, 0x31, 0xe3, 0x2a, 0x50, 0x2c, 0x86,
  0x4c, 0xa4, 0x52, 0x25, 0xff, 0x49, 0x35, 0x85
};

char *fsl_unobscure(const char *zIn){
  fsl_size_t n, i; unsigned char salt; char *zOut;
  if( zIn==0 ) return 0;
  n = fsl_strlen(zIn);
  zOut = fsl_malloc( n + 1 );
  if( !zOut ) return 0;
  if( n<2
    || fsl_decode16((unsigned char const*)zIn, &salt, 2)
    || fsl_decode16((unsigned char const*)&zIn[2], (unsigned char*)zOut, n-2) ){
      memcpy(zOut, zIn, n+1);
  }else{
    n = n/2 - 1;
    for(i=0; i<n; i++) zOut[i] = zOut[i] ^ aObscurer[i&0x0f] ^ salt;
    zOut[n] = 0;
  }
  return zOut;
}

int fsl_decode16(const unsigned char *zIn, unsigned char *pOut,
                 fsl_size_t N){
  fsl_int_t i, j;
  if( (N&1)!=0 ) return FSL_RC_RANGE;
  for(i=j=0; i<(fsl_int_t)N; i += 2, j++){
    fsl_int_t v1, v2, a;
    a = zIn[i];
    if( (a & 0x80)!=0 || (v1 = zDecode[a])==64 ) return FSL_RC_RANGE;
    a = zIn[i+1];
    if( (a & 0x80)!=0 || (v2 = zDecode[a])==64 ) return FSL_RC_RANGE;
    pOut[j] = (v1<<4) + v2;
  }
  return 0;
}


bool fsl_validate16(const char *zIn, fsl_size_t nIn){
  fsl_size_t i;
  for(i=0; i<nIn; i++, zIn++){
    if( zDecode[zIn[0]&0xff]>63 ){
      return zIn[0]==0 ? true : false;
    }
  }
  return true;
}

/*
   The array used for encoding
*/                           /* 123456789 12345  */
static const char zEncode[] = "0123456789abcdef"; 

int fsl_encode16(const unsigned char *pIn, unsigned char *zOut, fsl_size_t N){
  fsl_size_t i;
  if(!pIn || !zOut) return FSL_RC_MISUSE;
  for(i=0; i<N; i++){
    *(zOut++) = zEncode[pIn[i]>>4];
    *(zOut++) = zEncode[pIn[i]&0xf];
  }
  *zOut = 0;
  return 0;
}

void fsl_canonical16(char *z, fsl_size_t n){
  while( *z && n-- ){
    *z = zEncode[zDecode[(*z)&0x7f]&0x1f];
    ++z;
  }
}

void fsl_bytes_defossilize( unsigned char * z, fsl_size_t * resultLen ){
  fsl_size_t i, j, c;
  for(i=0; (c=z[i])!=0 && c!='\\'; i++){}
  if( c==0 ) {
    if(resultLen) *resultLen = i;
    return;
  }
  for(j=i; (c=z[i])!=0; i++){
    if( c=='\\' && z[i+1] ){
      i++;
      switch( z[i] ){
        case 'n':  c = '\n';  break;
        case 's':  c = ' ';   break;
        case 't':  c = '\t';  break;
        case 'r':  c = '\r';  break;
        case 'v':  c = '\v';  break;
        case 'f':  c = '\f';  break;
        case '0':  c = 0;     break;
        case '\\': c = '\\';  break;
        default:   c = z[i];  break;
      }
    }
    z[j++] = c;
  }
  if( z[j] ) z[j] = 0;
  if(resultLen) *resultLen = j;
}

int fsl_bytes_fossilize( unsigned char const * inp,
                         fsl_int_t nIn,
                         fsl_b * out ){
  fsl_size_t n, i, j, c;
  unsigned char *zOut;
  int rc;
  fsl_size_t oldUsed;
  fsl_size_t inSz;
  if(!inp || !out) return FSL_RC_MISUSE;
  else if( inp && (nIn<0) ) nIn = (fsl_int_t)fsl_strlen((char const *)inp);
  out->used = 0;
  if(!nIn) return 0;
  inSz = (fsl_size_t)nIn;
  /* Figure out how much space we'll need... */
  for(i=n=0; i<inSz; ++i){
    c = inp[i];
    if( c==0 || c==' ' || c=='\n' || c=='\t' || c=='\r' || c=='\f' || c=='\v'
        || c=='\\') ++n;
  }
  /* Reserve memory... */
  n += nIn;
  oldUsed = out->used;
  rc = fsl_b_reserve( out, oldUsed + (fsl_size_t)(n+1));
  if(rc) return rc;
  zOut = out->mem + oldUsed;
  /* Encode it... */
  for(i=j=0; i<(fsl_size_t)nIn; i++){
    unsigned char c = (unsigned char)inp[i];
    if( c==0 ){
      zOut[j++] = '\\';
      zOut[j++] = '0';
    }else if( c=='\\' ){
      zOut[j++] = '\\';
      zOut[j++] = '\\';
    }else if( fsl_isspace(c) ){
      zOut[j++] = '\\';
      switch( c ){
        case '\n':  c = 'n'; break;
        case ' ':   c = 's'; break;
        case '\t':  c = 't'; break;
        case '\r':  c = 'r'; break;
        case '\v':  c = 'v'; break;
        case '\f':  c = 'f'; break;
      }
      zOut[j++] = c;
    }else{
      zOut[j++] = c;
    }
  }
  zOut[j] = 0;
  out->used += j;
  return 0;
}


fsl_size_t fsl_str_to_size(char const * str){
  fsl_size_t size, oldsize, c;
  if(!str) return -1;
  for(oldsize=size=0; (c = str[0])>='0' && c<='9'; str++){
    if( oldsize > ((fsl_size_t)-1 - (c - '0'))/10 ) return -1;
    size = oldsize*10 + c - '0';
    oldsize = size;
  }
  return size;
}

fsl_int_t fsl_str_to_int(char const * str, fsl_int_t dflt){
  fsl_size_t size, oldsize
    /* We use fsl_size_t for the calculation
       so that we can detect overflow (which is undefined
       for signed types).
    */;
  char c;
  fsl_int_t mult = 1;
  fsl_int_t rc;
  if(!str) return dflt;
  else switch(*str){
    case '+': ++str; break;
    case '-': ++str; mult = -1; break;
  };
  for(oldsize=size=0; (c = str[0])>='0' && c<='9'; str++){
    if( oldsize > ((fsl_size_t)-1 - (fsl_size_t)(c - '0'))/10 )
      /* overflow */ return dflt;
    size = oldsize*10 + c - '0';
    oldsize = size;
  }
  if( size > (fsl_size_t)INT64_MAX ) return dflt /* result is too big */;
  rc = (fsl_int_t)size;
  return rc * mult;
}

fsl_size_t fsl_htmlize_xlate(int c, char const ** xlate){
  switch( c ){
    case '<': *xlate = "&lt;"; return 4;
    case '>': *xlate = "&gt;"; return 4;
    case '&': *xlate = "&amp;";  return 5;
    case '"': *xlate = "&quot;";  return 6;
    default: *xlate = NULL; return 1;
  }
}

int fsl_htmlize(fsl_output_f out, void * oState,
                const char *zIn, fsl_int_t n){
  int rc = 0;
  int c, len;
  fsl_int_t i, j;
  char const * xlate;
  if(!out || !zIn) return FSL_RC_MISUSE;
  else if( n<0 ) n = fsl_strlen(zIn);
  for(i=j=0; !rc && (i<n); ++i){
    c = zIn[i];
    len = fsl_htmlize_xlate(c, &xlate);
    if(len>1){
      if( j<i ) rc = out(oState, zIn+j, i-j);
      if(!rc) rc = out(oState, xlate, len);
      j = i+1;
    }
  }
  if( !rc && j<i ) rc = out(oState, zIn+j, i-j);
  return rc;
}


int fsl_htmlize_to_buffer(fsl_b *p, const char *zIn, fsl_int_t n){
  int rc = 0;
  int c;
  fsl_int_t i = 0;
  fsl_size_t count = 0;
  char const * xl = NULL;
  if(!p || !zIn) return FSL_RC_MISUSE;
  else if( n<0 ) n = fsl_strlen(zIn);
  if(0==n) return 0;
  /* Count how many bytes we need, to avoid reallocs and the
     associated error checking... */
  for( ; i<n && (c = zIn[i])!=0; ++i ){
    count += fsl_htmlize_xlate(c, &xl);
  }
  if(count){
    rc = fsl_b_reserve(p, p->used + count + 1);
    if(!rc){
      /* Now none of the fsl_b_append()s can fail. */
      rc = fsl_htmlize(fsl_output_f_b, p, zIn, n);
    }
  }
  return rc;
}

char *fsl_htmlize_str(const char *zIn, fsl_int_t n){
  int rc;
  fsl_b b = fsl_b_empty;
  rc = fsl_htmlize_to_buffer(&b, zIn, n);
  if(!rc){
    return (char *)b.mem /* transfer ownership */;
  }else{
    fsl_b_clear(&b);
    return NULL;
  }
}
/* end of file src/encode.c */
/* start of file src/event.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/************************************************************************
  This file implements technote (formerly known as event)-related
  parts of the library.
*/
#include <assert.h>


/**
   Fetches all "technote" (formerly "event") IDs from the repository
   and appends each one to the given list in the form of a
   (`char*`). This function relies on the `event-` tag prefix being
   reserved for technotes and that the technote IDS are all exactly 40
   bytes long.

   Returns 0 on success, FSL_RC_NOT_A_REPO if f has no repository db
   opened, FSL_RC_OOM if allocation of a new list entry fails, or
   propagates db-related code on any other error. Results are
   undefined if either argument is NULL.

   TODO? Reformulate this to be like fsl_tkt_id_to_rids(), returning
   the list as RIDs?
*/
/*FSL_EXPORT*/ int fsl_technote_ids_get(fsl_cx * const f, fsl_list * const tgt );

int fsl_technote_ids_get( fsl_cx * const f, fsl_list * const tgt ){
  fsl_db * const db = fsl_needs_repo(f);
  if(!db) return FSL_RC_NOT_A_REPO;
  int rc = fsl_db_select_slist( db, tgt,
                                "SELECT substr(tagname,7) AS n "
                                "FROM {{dbname.repo}}.tag "
                                "WHERE tagname GLOB 'event-*' "
                                "AND length(tagname)=46 "
                                "ORDER BY n");
  if(rc && db->error.code && !f->error.code){
    fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}
/* end of file src/event.c */
/* start of file src/foci.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
 * Copyright 2022 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt
 *
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 * SPDX-FileCopyrightText: 2021 The Libfossil Authors
 * SPDX-FileType: Code
 *
 * Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
 */

/*
 * This file implements the files-of-checkin (foci) API used to construct a
 * SQLite3 virtual table via a table-valued function to aggregate all files
 * pertaining to a specific check-in. This table is used in repository
 * queries such as listing all files belonging to a specific version.
 *
 * Usage (from fossil(1) /src/foci.c:24):
 *
 *    SELECT * FROM fsl_foci('trunk');
 *
 * temp.foci table schema:
 *
 *     CREATE TABLE fsl_foci(
 *       checkinID    INTEGER,    -- RID for the check-in manifest
 *       filename     TEXT,       -- Name of a file
 *       uuid         TEXT,       -- hash of the file
 *       previousName TEXT,       -- Name of the file in previous check-in
 *       perm         TEXT,       -- Permissions on the file
 *       symname      TEXT HIDDEN -- Symbolic name of the check-in.
 *     );
 *
 * The hidden symname column is (optionally) used as a query parameter to
 * identify the particular check-in to parse.  The checkinID parameter
 * (such is a unique numeric RID rather than symbolic name) can also be used
 * to identify the check-in.  Example:
 *
 *    SELECT * FROM fsl_foci
 *     WHERE checkinID=fsl_sym2rid('trunk');
 *
 */
#include <string.h>/*memset()*/
#include <assert.h>

/* Only for debugging */
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

enum {
FOCI_CHECKINID = 0,
FOCI_FILENAME = 1,
FOCI_UUID = 2,
FOCI_PREVNAME = 3,
FOCI_PERM = 4,
FOCI_SYMNAME = 5
};

typedef struct FociCursor FociCursor;
struct FociCursor {
  sqlite3_vtab_cursor base; /* Base class - must be first */
  fsl_deck d;           /* Current manifest */
  const fsl_card_F *cf;  /* Current file */
  int idx;                /* File index */
};

typedef struct FociTable FociTable;
struct FociTable {
  sqlite3_vtab base;        /* Base class - must be first */
  sqlite3 * db;             /* Its db connection. The fsl_cx is
                               looked up from it, as for the UDFs
                               in udf.c. */
};

/*
 * The schema for the virtual table:
 */
static const char zFociSchema[] =
  " CREATE TABLE fsl_foci("
  "  checkinID    INTEGER,    -- RID for the check-in manifest\n"
  "  filename     TEXT,       -- Name of a file\n"
  "  uuid         TEXT,       -- hash of the file\n"
  "  previousName TEXT,       -- Name of the file in previous check-in\n"
  "  perm         TEXT,       -- Permissions on the file\n"
  "  symname      TEXT HIDDEN -- Symbolic name of the check-in\n"
  " );";

/*
 * Connect to or create a foci virtual table.
 */
static int fociConnect(
  sqlite3 *db,
  void *pAux /*unused: the context comes from fsl__cx_for_dbh()*/,
  int argc fsl__unused,
  const char * const * argv fsl__unused,
  sqlite3_vtab **ppVtab,
  char **pzErr fsl__unused
){
  FociTable *pTab;
  int rc = SQLITE_OK;

  (void)argc;
  (void)argv;
  (void)pzErr;
  pTab = (FociTable *)sqlite3_malloc(sizeof(FociTable));
  if( !pTab ){
    return SQLITE_NOMEM;
  }
  memset(pTab, 0, sizeof(FociTable));
  rc = sqlite3_declare_vtab(db, zFociSchema);
  if( rc==SQLITE_OK ){
    (void)pAux;
    pTab->db = db;
    *ppVtab = &pTab->base;
  }else{
    sqlite3_free(pTab);
  }
  return rc;
}

/*
 * Disconnect from or destroy a focivfs virtual table.
 */
static int fociDisconnect(sqlite3_vtab *pVtab){
  sqlite3_free(pVtab);
  return SQLITE_OK;
}

/*
 * Available scan methods:
 *
 *   (0)     A full scan.  Visit every manifest in the repo.  (Slow)
 *   (1)     checkinID=?.  visit only the single manifest specified.
 *   (2)     symName=?     visit only the single manifest specified.
 */
static int fociBestIndex(
  sqlite3_vtab *tab fsl__unused,
  sqlite3_index_info *pIdxInfo
){
  int i;

  (void)tab;
  pIdxInfo->estimatedCost = 1000000000.0;
  for( i=0; i<pIdxInfo->nConstraint; i++ ){
    if( !pIdxInfo->aConstraint[i].usable ) continue;
    if( pIdxInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
     && (pIdxInfo->aConstraint[i].iColumn==FOCI_CHECKINID
            || pIdxInfo->aConstraint[i].iColumn==FOCI_SYMNAME)
    ){
      if( pIdxInfo->aConstraint[i].iColumn==FOCI_CHECKINID ){
        pIdxInfo->idxNum = 1;
      }else{
        pIdxInfo->idxNum = 2;
      }
      pIdxInfo->estimatedCost = 100.0;
      pIdxInfo->aConstraintUsage[i].argvIndex = 1;
      pIdxInfo->aConstraintUsage[i].omit = 1;
      break;
    }
  }
  return SQLITE_OK;
}

/*
 * Open a new focivfs cursor.
 */
static int fociOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  FociCursor *pCsr;
  pCsr = (FociCursor *)sqlite3_malloc(sizeof(FociCursor));
  if( !pCsr ){
    return SQLITE_NOMEM;
  }
  memset(pCsr, 0, sizeof(FociCursor));
  pCsr->d = fsl_deck_empty;
  pCsr->base.pVtab = pVTab;
  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  return SQLITE_OK;
}

/*
 * Close a focivfs cursor.
 */
static int fociClose(sqlite3_vtab_cursor *pCursor){
  FociCursor *pCsr = (FociCursor *)pCursor;
  fsl_deck_finalize(&pCsr->d);
  sqlite3_free(pCsr);
  return SQLITE_OK;
}

/*
 * Move a focivfs cursor to the next F card entry in the deck. If this
 * fails, return the failing result code. SQLite still closes the
 * cursor with fociClose(), so it must not be closed here.
 */
static int fociNext(sqlite3_vtab_cursor *pCursor){
  int rc = SQLITE_OK;

  FociCursor *pCsr = (FociCursor *)pCursor;
  rc = fsl_deck_F_next(&pCsr->d, &pCsr->cf);
  if( !rc ){
    pCsr->idx++;
  }else{
    pCsr->cf = 0;
  }
  return rc;
}

static int fociEof(sqlite3_vtab_cursor *pCursor){
  FociCursor *pCsr = (FociCursor *)pCursor;
  return pCsr->cf==0;
}

static int fociFilter(
  sqlite3_vtab_cursor *pCursor,
  int idxNum, const char *idxStr fsl__unused,
  int argc fsl__unused, sqlite3_value **argv
){
  int rc = SQLITE_OK;
  FociCursor *const pCur = (FociCursor *)pCursor;
  fsl_cx * const f = fsl__cx_for_dbh(((FociTable*)pCur->base.pVtab)->db);

  (void)idxStr;
  (void)argc;
  if( !f ){
    sqlite3_vtab * const pTab = pCur->base.pVtab;
    sqlite3_free(pTab->zErrMsg);
    pTab->zErrMsg = sqlite3_mprintf("No libfossil context is bound "
                                    "to this db connection.");
    return SQLITE_ERROR;
  }
  fsl__cx_host_rollback_check(f);
  fsl_deck_finalize(&pCur->d);
  pCur->cf = 0 /* pointed into the deck just finalized */;
  if( idxNum ){
    fsl_id_t rid;
    if( idxNum==1 ){
      rid = (fsl_id_t)sqlite3_value_int64(argv[0]);
    }else{
      rc = fsl_sym_to_rid(f, (const char *)sqlite3_value_text(argv[0]),
       FSL_SATYPE_CHECKIN, &rid);
      if( rc ){
        goto end;
      }
    }
    rc = fsl_deck_load_rid(f, &pCur->d, rid, FSL_SATYPE_CHECKIN);
    if( rc ){
      goto end;
    }
    if( pCur->d.rid ){
      rc = fsl_deck_F_rewind(&pCur->d);
      if( !rc ){
        rc = fsl_deck_F_next(&pCur->d, &pCur->cf);
      }
      if( rc ){
        goto end;
      }
    }
  }
  pCur->idx = 0;
end:
  if( rc ){
    fsl_deck_finalize(&pCur->d);
    pCur->cf = 0;
  }
  return rc;
}

static int fociColumn(
  sqlite3_vtab_cursor *pCursor,
  sqlite3_context *ctx,
  int i
){
  FociCursor *pCsr = (FociCursor *)pCursor;
  switch( i ){
    case FOCI_CHECKINID:
      sqlite3_result_int64(ctx, pCsr->d.rid);
      break;
    case FOCI_FILENAME:
      sqlite3_result_text(ctx, pCsr->cf->name, -1, SQLITE_TRANSIENT);
      break;
    case FOCI_UUID:
      sqlite3_result_text(ctx, pCsr->cf->uuid, -1, SQLITE_TRANSIENT);
      break;
    case FOCI_PREVNAME:
      sqlite3_result_text(ctx, pCsr->cf->priorName, -1, SQLITE_TRANSIENT);
      break;
    case FOCI_PERM: {
      char *perm[3] = {"l", "w", "x"};
      int i = 1;
      switch( pCsr->cf->perm ){
        case FSL_FILE_PERM_LINK:
          i = 0; break;
        case FSL_FILE_PERM_EXE:
          i = 2; break;
        default:
          break;
      }
      sqlite3_result_text(ctx, perm[i], 1, SQLITE_TRANSIENT);
      break;
    }
    case FOCI_SYMNAME:
      break;
  }
  return SQLITE_OK;
}

static int fociRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  FociCursor *pCsr = (FociCursor *)pCursor;
  *pRowid = pCsr->idx;
  return SQLITE_OK;
}

int fsl__foci_register(fsl_cx * const f, fsl_db * const db){
  static sqlite3_module foci_module = {
    0,                            /* iVersion */
    fociConnect,                  /* xCreate */
    fociConnect,                  /* xConnect */
    fociBestIndex,                /* xBestIndex */
    fociDisconnect,               /* xDisconnect */
    fociDisconnect,               /* xDestroy */
    fociOpen,                     /* xOpen - open a cursor */
    fociClose,                    /* xClose - close a cursor */
    fociFilter,                   /* xFilter - configure scan constraints */
    fociNext,                     /* xNext - advance a cursor */
    fociEof,                      /* xEof - check for end of scan */
    fociColumn,                   /* xColumn - read data */
    fociRowid,                    /* xRowid - read data */
    0,                            /* xUpdate */
    0,                            /* xBegin */
    0,                            /* xSync */
    0,                            /* xCommit */
    0,                            /* xRollback */
    0,                            /* xFindMethod */
    0,                            /* xRename */
    0,                            /* xSavepoint */
    0,                            /* xRelease */
    0,                            /* xRollbackTo */
    0,                            /* xShadowName */
    0                             /* xIntegrity */
  };
  assert(f);
  assert(db);
  (void)f;
  int rc = sqlite3_create_module(db->dbh, "fsl_foci",
                                 &foci_module, NULL);
  /* fsl__db_errcode() takes 0 to mean "use sqlite3_errcode()", which
     can hold an older error, e.g. from fsl__cx_init_db()'s unchecked
     sqlite3_create_function() calls failing on a host's connection
     after fsl_close(). */
  return rc ? fsl__db_errcode(db, rc) : 0;
}

#undef MARKER
/* end of file src/foci.c */
/* start of file src/fs.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2013-25 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
#ifdef _WIN32
# undef __STRICT_ANSI__ /* Needed for _wfopen */
#endif

#include <assert.h>
#include <string.h> /* strlen() */
#include <stddef.h> /* NULL on linux */
#include <errno.h>
#if FSL_PLATFORM_IS_WINDOWS
# if !defined(ELOOP)
#  define ELOOP 114 /* Missing in MinGW */
# endif
# include <sys/utime.h> /* _utimbuf, _wutime() */
#else
# include <unistd.h> /* access(2), readlink(2) */
# include <sys/types.h>
# include <sys/time.h>
#endif
#include <sys/stat.h>
#include <stdlib.h> /* getenv() */

const fsl_path_splitter fsl_path_splitter_empty = fsl_path_splitter_empty_m;

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

FILE *fsl_fopen(const char *zName, const char *zMode){
  FILE *f;
  if(zName && ('-'==*zName && !zName[1])){
    f = (strchr(zMode, 'w') || strchr(zMode,'+'))
      ? stdout
      : stdin
      ;
  }else{
#ifdef _WIN32
    wchar_t *uMode = (wchar_t *)fsl_utf8_to_unicode(zMode);
    wchar_t *uName = (wchar_t *)fsl_utf8_to_filename(zName);
    f = _wfopen(uName, uMode);
    fsl_os_str_free(uName);
    fsl_unicode_free(uMode);
#else
    f = fopen(zName, zMode);
#endif
  }
  return f;
}


void fsl_fclose( FILE * f ){
  if(f && (stdin!=f) && (stdout!=f) && (stderr!=f)){
    fclose(f);
  }
}

/*
   Wrapper around the access() system call.
*/
int fsl_file_access(const char *zFilename, int flags){
  /* FIXME: port in fossil(1) win32_access() */
#ifdef _WIN32
  wchar_t *zMbcs = (wchar_t *)fsl_utf8_to_filename(zFilename);
#define ACC _waccess
#else
  char *zMbcs = (char*)fsl_utf8_to_filename(zFilename);
#define ACC access
#endif
  int rc = zMbcs ? ACC(zMbcs, flags) : FSL_RC_OOM;
  if(zMbcs) fsl_os_str_free(zMbcs);
  return rc;
#undef ACC
}


int fsl_getcwd(char *zBuf, fsl_size_t nBuf, fsl_size_t * outLen){
#ifdef _WIN32
  /* FIXME: port in fossil(1) win32_getcwd() */
  char *zPwdUtf8;
  fsl_size_t nPwd;
  fsl_size_t i;
  wchar_t zPwd[2000];
  if(!zBuf) return FSL_RC_MISUSE;
  else if(!nBuf) return FSL_RC_RANGE;
  /*
    https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx

    It says:

    Note File I/O functions in the Windows API convert "/" to "\" as
    part of converting the name to an NT-style name, except when using
    the "\\?\" prefix as detailed in the following sections.

    So the path-demangling bits below might do more damage they
    fix?
  */
  else if( _wgetcwd(zPwd, sizeof(zPwd)/sizeof(zPwd[0])-1)==0 ){
    /* FIXME: how to determine if FSL_RC_RANGE is a better
       return value?
    */
    return FSL_RC_IO;
  }
  zPwdUtf8 = fsl_filename_to_utf8(zPwd);
  if(!zPwdUtf8) return FSL_RC_OOM;
  nPwd = strlen(zPwdUtf8);
  if( nPwd > nBuf-1 ){
    fsl_os_str_free(zPwdUtf8);
    return FSL_RC_RANGE;
  }
  for(i=0; zPwdUtf8[i]; i++) if( zPwdUtf8[i]=='\\' ) zPwdUtf8[i] = '/';
  memcpy(zBuf, zPwdUtf8, nPwd+1);
  fsl_os_str_free(zPwdUtf8);
  if(outLen) *outLen = nPwd;
  return 0;
#else
  if(!zBuf) return FSL_RC_MISUSE;
  else if(!nBuf) return FSL_RC_RANGE;
  else if( NULL==getcwd(zBuf,nBuf) ){
    return fsl_errno_to_rc(errno, FSL_RC_IO);
  }else{
    if(outLen) *outLen = fsl_strlen(zBuf);
    return 0;
  }
#endif
}

/*
   The file status information from the most recent stat() call.

   Use _stati64 rather than stat on windows, in order to handle files
   larger than 2GB.
*/
#if defined(_WIN32) && (defined(__MSVCRT__) || defined(_MSC_VER))
# undef stat
# define stat _stati64
#endif
/*
   On Windows S_ISLNK always returns FALSE.
*/
#if !defined(S_ISLNK)
# define S_ISLNK(x) (0)
#endif

/* Reminder: the semantics of the 3rd parameter are
   reversed from v1's fossil_stat().
*/
int fsl_stat(const char *zFilename, fsl_fstat * fst,
             bool derefSymlinks){
  /* FIXME: port in fossil(1) win32_stat() */
#if FSL_API_ARMOR
  if(!zFilename) return FSL_RC_MISUSE;
  else if(!*zFilename) return FSL_RC_RANGE;
#endif
  int rc;
  struct stat buf;
#if !defined(_WIN32)
  char *zMbcs = (char *)fsl_utf8_to_filename(zFilename);
  if(!zMbcs) rc = FSL_RC_OOM;
  else{
    if( derefSymlinks ){
      rc = stat(zMbcs, &buf);
    }else{
      rc = lstat(zMbcs, &buf);
    }
    if(rc) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
  }
#else
  wchar_t *zMbcs = (wchar_t *)fsl_utf8_to_filename(zFilename);
  /*trailing pathseps are forbidden in Windows stat fxns, as per doc; sigh*/
  int nzmbcslen = wcslen ( zMbcs );
  while ( nzmbcslen > 0 && ( L'\\' == zMbcs[nzmbcslen-1] ||
                             L'/' == zMbcs[nzmbcslen-1] ) ) {
    zMbcs[nzmbcslen-1] = 0;
    --nzmbcslen;
  }
  rc = zMbcs
    ? (_wstati64(zMbcs, &buf) ? fsl_errno_to_rc(errno, FSL_RC_IO) : 0)
    : FSL_RC_OOM;
#endif
  if(zMbcs) fsl_os_str_free(zMbcs);
  if(fst && (0==rc)){
    *fst = fsl_fstat_empty;
    fst->ctime = (fsl_time_t)buf.st_ctime;
    fst->mtime = (fsl_time_t)buf.st_mtime;
    fst->size = (fsl_size_t)buf.st_size;
    if(S_ISDIR(buf.st_mode)) fst->type = FSL_FSTAT_TYPE_DIR;
#if !defined(_WIN32)
    else if(S_ISLNK(buf.st_mode)) fst->type = FSL_FSTAT_TYPE_LINK;
#endif
    else /* if(S_ISREG(buf.st_mode)) */{
      fst->type = FSL_FSTAT_TYPE_FILE;
#if defined(_WIN32)
#  ifndef S_IXUSR
#    define S_IXUSR  _S_IEXEC
#  endif
      if(((S_IXUSR)&buf.st_mode)!=0){
        fst->perm |= FSL_FSTAT_PERM_EXE;
      }
#else
      if( ((S_IXUSR|S_IXGRP|S_IXOTH)&buf.st_mode)!=0 ){
        fst->perm |= FSL_FSTAT_PERM_EXE;
      }
#if 0
      /* Porting artifact: something to consider... */
      else if( g.allowSymlinks && S_ISLNK(buf.st_mode) )
        return PERM_LNK;
#endif
#endif
    }
  }
  return rc;
}

fsl_int_t fsl_file_size(const char *zFilename){
  fsl_fstat fst;
  return (0 == fsl_stat(zFilename, &fst, 1))
    ? (fsl_int_t)fst.size
    : -1;
}

fsl_time_t fsl_file_mtime(const char *zFilename){
  fsl_fstat fst;
  return (0==fsl_stat(zFilename, &fst, 1))
    ? (fsl_time_t)fst.mtime
    : -1;
}


bool fsl_is_file(const char *zFilename){
  fsl_fstat fst;
  return (0==fsl_stat(zFilename, &fst, 1))
    ? (FSL_FSTAT_TYPE_FILE == fst.type)
    : false;
}

bool fsl_is_symlink(const char *zFilename){
#if FSL_PLATFORM_IS_WINDOWS
  (void)zFilename;
  return false;
#else
  fsl_fstat fst;
  return (0 == fsl_stat(zFilename, &fst, 0))
    ? (FSL_FSTAT_TYPE_LINK == fst.type)
    : false;
#endif
}

bool fsl_is_absolute_path(const char *zPath){
  if( zPath && ((zPath[0]=='/')
#if defined(_WIN32) || defined(__CYGWIN__)
      || (zPath[0]=='\\')
      || (fsl_isalpha(zPath[0]) && zPath[1]==':'
          && (zPath[2]=='\\' || zPath[2]=='/'))
#endif
    )
  ){
    return true;
  }else{
    return false;
  }
}

bool fsl_is_simple_pathname(const char *z, bool bStrictUtf8){
  int i;
  unsigned char c = (unsigned char) z[0];
  char maskNonAscii = bStrictUtf8 ? 0x80 : 0x00;
  if( c=='/' || c==0 ) return 0;
  if( c=='.' ){ /* Common cases: ./ and ../ */
    if( z[1]=='/' || z[1]==0 ) return 0;
    if( z[1]=='.' && (z[2]=='/' || z[2]==0) ) return 0;
  }
  for(i=0; (c=(unsigned char)z[i])!=0; i++){
    if( c & maskNonAscii ){
      if( (z[++i]&0xc0)!=0x80 ){
        /* Invalid first continuation byte */
        return 0;
      }
      if( c<0xc2 ){
        /* Invalid 1-byte UTF-8 sequence, or 2-byte overlong form. */
        return 0;
      }else if( (c&0xe0)==0xe0 ){
        /* 3-byte or more */
        int unicode;
        if( c&0x10 ){
          /* Unicode characters > U+FFFF are not supported.
           * Windows XP and earlier cannot handle them.
           */
          return 0;
        }
        /* This is a 3-byte UTF-8 character */
        unicode = ((c&0x0f)<<12) + ((z[i]&0x3f)<<6) + (z[i+1]&0x3f);
        if( unicode <= 0x07ff ){
          /* overlong form */
          return 0;
        }else if( unicode>=0xe000 ){
          /* U+E000..U+FFFF */
          if( (unicode<=0xf8ff) || (unicode>=0xfffe) ){
            /* U+E000..U+F8FF are for private use.
             * U+FFFE..U+FFFF are noncharacters. */
            return 0;
          } else if( (unicode>=0xfdd0) && (unicode<=0xfdef) ){
            /* U+FDD0..U+FDEF are noncharacters. */
            return 0;
          }
        }else if( (unicode>=0xd800) && (unicode<=0xdfff) ){
          /* U+D800..U+DFFF are for surrogate pairs. */
          return 0;
        }
        if( (z[++i]&0xc0)!=0x80 ){
          /* Invalid second continuation byte */
          return 0;
        }
      }
    }else if( bStrictUtf8 && (c=='\\') ){
      return 0;
    }
    if( c=='/' ){
      if( z[i+1]=='/' ) return 0;
      if( z[i+1]=='.' ){
        if( z[i+2]=='/' || z[i+2]==0 ) return 0;
        if( z[i+2]=='.' && (z[i+3]=='/' || z[i+3]==0) ) return 0;
      }
    }
  }
  if( z[i-1]=='/' ) return 0;
  return 1;
}


/*
   If the last component of the pathname in z[0]..z[j-1] is something
   other than ".." then back it out and return true.  If the last
   component is empty or if it is ".." then return false.
*/
static bool fsl_backup_dir(const char *z, fsl_int_t *pJ){
  fsl_int_t j = *pJ;
  fsl_int_t i;
  if( !j ) return 0;
  for(i=j-1; i>0 && z[i-1]!='/'; i--){}
  if( z[i]=='.' && i==j-2 && z[i+1]=='.' ) return 0;
  *pJ = i-1;
  return 1;
}



fsl_size_t fsl_file_simplify_name(char *z, fsl_int_t n_, bool slash){
  fsl_size_t i;
  fsl_size_t n = (n_<0) ? fsl_strlen(z) : (fsl_size_t)n_;
  fsl_int_t j;
  bool const hadSlash = n && (z[n-1]=='/');
  /* On windows and cygwin convert all \ characters to / */
#if defined(_WIN32) || defined(__CYGWIN__)
  for(i=0; i<n; i++){
    if( z[i]=='\\' ) z[i] = '/';
  }
#endif
  /* Removing trailing "/" characters */
  while( n>1 && z[n-1]=='/' ){--n;}

  /* Remove duplicate '/' characters.  Except, two // at the beginning
     of a pathname is allowed since this is important on windows. */
  for(i=j=1; i<n; i++){
    z[j++] = z[i];
    while( z[i]=='/' && i<n-1 && z[i+1]=='/' ) i++;
  }
  n = j;
  /* Skip over zero or more initial "./" sequences */
  for(i=0; i<n-1 && z[i]=='.' && z[i+1]=='/'; i+=2){}

  /* Begin copying from z[i] back to z[j]... */
  for(j=0; i<n; i++){
    if( z[i]=='/' ){
      /* Skip over internal "/." directory components */
      if( z[i+1]=='.' && (i+2==n || z[i+2]=='/') ){
        i += 1;
        continue;
      }

      /* If this is a "/.." directory component then back out the
         previous term of the directory if it is something other than ".."
         or "."
      */
      if( z[i+1]=='.' && i+2<n && z[i+2]=='.' && (i+3==n || z[i+3]=='/')
       && fsl_backup_dir(z, &j)
      ){
        i += 2;
        continue;
      }
    }
    if( j>=0 ) z[j] = z[i];
    j++;
  }
  if( j==0 ) z[j++] = '.';
  if(slash && hadSlash && '/'!=z[j-1]) z[j++] = '/';
  z[j] = 0;
  return (fsl_size_t)j;
}

int fsl_file_canonical_name2(const char *zRoot,
                             const char *zOrigName,
                             fsl_b * const pOut, bool slash){
  int rc;
  if(!zOrigName || !pOut) return FSL_RC_MISUSE;
  else if( fsl_is_absolute_path(zOrigName) || (zRoot && !*zRoot)){
    rc = fsl_b_append( pOut, zOrigName, -1 );
#if defined(_WIN32) || defined(__CYGWIN__)
    if(!rc){
      char *zOut;
      /*
         On Windows/cygwin, normalize the drive letter to upper case.
      */
      zOut = fsl_b_str(pOut);
      if( fsl_islower(zOut[0]) && zOut[1]==':' ){
        zOut[0] = fsl_toupper(zOut[0]);
      }
    }
#endif
  }else if(!zRoot){
    char zPwd[2000];
    fsl_size_t nOrig = fsl_strlen(zOrigName);
    assert(nOrig < sizeof(zPwd));
    rc = fsl_getcwd(zPwd, sizeof(zPwd)-nOrig, NULL);
    if(!rc){
#if defined(_WIN32)
      /*
         On Windows, normalize the drive letter to upper case.
      */
      if( !rc && fsl_islower(zPwd[0]) && zPwd[1]==':' ){
        zPwd[0] = fsl_toupper(zPwd[0]);
      }
#endif
      rc = fsl_b_appendf(pOut, "%//%/", zPwd, zOrigName);
    }
  }else{
    rc = fsl_b_appendf(pOut, "%/%s%/", zRoot,
                            *zRoot ? "/" : "",
                            zOrigName);
  }
  if(!rc){
    fsl_size_t const newLen = fsl_file_simplify_name(fsl_b_str(pOut),
                                                     (int)pOut->used, slash);
    /* Reminder to self: do NOT resize pOut to the new,
       post-simplification length because pOut is almost always a
       fsl_cx::scratchpad buffer and doing so forces all sorts of
       downstream reallocs. */
    pOut->used = newLen;
  }
  return rc;
}


int fsl_file_canonical_name(const char *zOrigName,
                            fsl_b * const pOut,
                            bool slash){
  return fsl_file_canonical_name2(NULL, zOrigName, pOut, slash);
}

int fsl_file_dirpart(char const * zFilename,
                     fsl_int_t nLen,
                     fsl_b * const pOut,
                     bool leaveSlash){
  if(!zFilename || !*zFilename || !pOut) return FSL_RC_MISUSE;
  else if(!nLen) return FSL_RC_RANGE;
  else{
    fsl_size_t n = (nLen>0) ? (fsl_size_t)nLen : fsl_strlen(zFilename);
    char const * z = zFilename + n;
    char doBreak = 0;
    if(!n) return FSL_RC_RANGE;
    else while( !doBreak && (--z >= zFilename) ){
      switch(*z){
#if defined(_WIN32)
        case '\\':
#endif
        case '/':
          if(!leaveSlash) --z;
          doBreak = 1;
          break;
      }
    }
    if(z<=zFilename){
      return (doBreak && leaveSlash)
        ? fsl_b_append(pOut, zFilename, 1)
        : fsl_b_append(pOut, "", 0) /* ensure a NUL terminator */;
    }else{
      return fsl_b_append(pOut, zFilename, z-zFilename + 1);
    }
  }
}

const char *fsl_file_tail(const char *z){
  const char *zTail = z;
  if( !zTail ) return 0;
  while( z[0] ){
    if( '/'==z[0] || '\\'==z[0] ) zTail = &z[1];
    z++;
  }
  return zTail;
}


int fsl_find_home_dir( fsl_b * const tgt, bool requireWriteAccess ){
  char * zHome = NULL;
  int rc = 0;
  fsl_b_reuse(tgt);
#if defined(_WIN32) || defined(__CYGWIN__)
  zHome = fsl_getenv("LOCALAPPDATA");
  if( zHome==0 ){
    zHome = fsl_getenv("APPDATA");
    if( zHome==0 ){
      char *zDrive = fsl_getenv("HOMEDRIVE");
      zHome = fsl_getenv("HOMEPATH");
      if( zDrive && zHome ){
        tgt->used = 0;
        rc = fsl_b_appendf(tgt, "%s", zDrive);
        fsl_os_str_free(zDrive);
        if(rc){
          fsl_os_str_free(zHome);
          return rc;
        }
      }
    }
  }
  if(NULL==zHome){
    rc = fsl_b_append(tgt,
                           "Cannot locate home directory - "
                           "please set the LOCALAPPDATA or "
                           "APPDATA or HOMEPATH "
                           "environment variables.",
                           -1);
    return rc ? rc : FSL_RC_NOT_FOUND;
  }
  rc = fsl_b_appendf( tgt, "%/", zHome );
#else
  /* Unix... */
  zHome = fsl_getenv("HOME");
  if( zHome==0 ){
    rc = fsl_b_append(tgt,
                           "Cannot locate home directory - "
                           "please set the HOME environment "
                           "variable.",
                           -1);
    return rc ? rc : FSL_RC_NOT_FOUND;
  }
  rc = fsl_b_appendf( tgt, "%s", zHome );
#endif

  fsl_os_str_free(zHome);
  if(rc) return rc;
  assert(0<tgt->used);
  zHome = fsl_b_str(tgt);

  if( fsl_dir_check(zHome)<1 ){
    /* assert(0==tgt->used); */
    fsl_b tmp = fsl_b_empty;
    rc = fsl_b_appendf(&tmp,
                            "Invalid home directory: %s",
                            zHome);
    fsl_b_swap_free(&tmp, tgt, -1);
    return rc ? rc : FSL_RC_TYPE;
  }

#if !(defined(_WIN32) || defined(__CYGWIN__))
  /* Not sure why, but the is-writable check is historically only done
     on Unix platforms?

     TODO: this was subsequently changed in fossil(1) to only require
     that the global db dir be writable. Port the newer logic in.
  */
  if( requireWriteAccess &&
      (0 != fsl_file_access(zHome, W_OK)) ){
    fsl_b tmp = fsl_b_empty;
    rc = fsl_b_appendf(&tmp,
                            "Home directory [%s] must "
                            "be writeable.",
                            zHome);
    fsl_b_swap_free(&tmp, tgt, -1);
    return rc ? rc : FSL_RC_ACCESS;
  }
#endif

  return rc;
}

int fsl_errno_to_rc(int errNo, int dflt){
  switch(errNo){
    /* Plese expand on this as tests/use cases call for it... */
    case 0:
      return 0;
    case EINVAL:
      return FSL_RC_MISUSE;
    case ENOMEM:
      return FSL_RC_OOM;
    case EROFS:
    case EACCES:
    case EBUSY:
    case EPERM:
#if defined(EDQUOT)
    case EDQUOT:
#endif
    case EAGAIN:
    case ETXTBSY:
      return FSL_RC_ACCESS;
    case EISDIR:
    case ENOTDIR:
      return FSL_RC_TYPE;
    case ENAMETOOLONG:
    case ELOOP:
    case ERANGE:
      return FSL_RC_RANGE;
    case ENOENT:
    case ESRCH:
      return FSL_RC_NOT_FOUND;
    case EEXIST:
    case ENOTEMPTY:
      return FSL_RC_ALREADY_EXISTS;
    case EIO:
      return FSL_RC_IO;
    default:
      return dflt;
  }
}

int fsl_file_unlink(const char *zFilename){
  int rc;
#ifdef _WIN32
  wchar_t *z = (wchar_t*)fsl_utf8_to_filename(zFilename);
  if(!z) return FSL_RC_OOM;
  rc = _wunlink(z) ? fsl_errno_to_rc(errno, FSL_RC_IO) : 0;
#else
  char *z = (char *)fsl_utf8_to_filename(zFilename);
  if(!z) return FSL_RC_OOM;
  rc = unlink(z) ? fsl_errno_to_rc(errno, FSL_RC_IO) : 0;
#endif
  fsl_os_str_free(z);
  return rc;
}

int fsl_mkdir(const char *zName, bool forceFlag){
  int rc =
    /*file_wd_dir_check(zName)*/
    fsl_dir_check(zName)
    ;
  if( rc<0 ){
    if( !forceFlag ) return FSL_RC_TYPE;
    rc = fsl_file_unlink(zName);
    if(rc) return rc;
  }else if( 0==rc ){
#if defined(_WIN32)
    typedef wchar_t char_t;
#define mkdir(F,P) _wmkdir(F)
#else
    typedef char char_t;
#endif
    char_t *zMbcs = (char_t*)fsl_utf8_to_filename(zName);
    if(!zMbcs) return FSL_RC_OOM;
    rc = mkdir(zMbcs, 0755) ? fsl_errno_to_rc(errno, FSL_RC_IO) : 0;
    fsl_os_str_free(zMbcs);
    return rc;
#if defined(_WIN32)
#undef mkdir
#endif
  }
  return 0;
}

int fsl_mkdir_for_file(char const *zName, bool forceFlag){
  int rc;
  fsl_b b = fsl_b_empty /* we copy zName to
                                     simplify traversal */;
  fsl_size_t n = fsl_strlen(zName);
  fsl_size_t i;
  char * zCan;
  if(n==0) return FSL_RC_RANGE;
  else if(n<2) return 0/*no dir part*/;
#if 1
  /* This variant does more work (checks dirs we know already
     exist) but transforms the path into something platform-neutral.
     If we use fsl_file_simplify_name() instead then we end up
     having to do the trailing-slash logic here.
  */
  rc = fsl_file_canonical_name(zName, &b, true);
#else
  rc = fsl_b_append(&b, zName, n);
#endif
  zCan = fsl_b_str(&b);
  n = b.used;
  for( i = 1; 0==rc && i<n; ++i ){
    if( '/'==zCan[i] ){
      zCan[i] = 0;
#if defined(_WIN32) || defined(__CYGWIN__)
      /*
         On Windows, local path looks like: C:/develop/project/file.txt
         The if stops us from trying to create a directory of a drive letter
         C: in this example.
      */
      if( !(i==2 && zCan[1]==':') ){
#endif
        rc = fsl_dir_check(zCan);
#if 0
        if(rc<0){
          if(forceFlag) rc = fsl_file_unlink(zCan);
          else rc = FSL_RC_TYPE;
        }
#endif
        /* MARKER(("dir_check rc=%d, zCan=%s\n", rc, zCan)); */
        if(0>=rc){
          rc = fsl_mkdir(zCan, forceFlag);
          /* MARKER(("mkdir(%s) rc=%s\n", zCan, fsl_rc_cstr(rc))); */
        }else{
          rc = 0;
          /* Nothing to do. */
        }
#if defined(_WIN32) || defined(__CYGWIN__)
      }
#endif
      zCan[i] = '/';
    }
  }
  fsl_b_clear(&b);
  return rc;
}

#if defined(_WIN32)
/* Taken verbatim from fossil(1), just renamed */
/*
** Returns non-zero if the specified name represents a real directory, i.e.
** not a junction or symbolic link.  This is important for some operations,
** e.g. removing directories via _wrmdir(), because its detection of empty
** directories will (apparently) not work right for junctions and symbolic
** links, etc.
*/
static int w32_file_is_normal_dir(wchar_t *zName){
  /*
  ** Mask off attributes, applicable to directories, that are harmless for
  ** our purposes.  This may need to be updated if other attributes should
  ** be ignored by this function.
  */
  DWORD dwAttributes = GetFileAttributesW(zName);
  if( dwAttributes==INVALID_FILE_ATTRIBUTES ) return 0;
  dwAttributes &= ~(
    FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_COMPRESSED |
    FILE_ATTRIBUTE_ENCRYPTED | FILE_ATTRIBUTE_NORMAL |
    FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
  );
  return dwAttributes==FILE_ATTRIBUTE_DIRECTORY;
}
#endif


bool fsl_file_isexec(const char *zFilename){
  fsl_fstat st = fsl_fstat_empty;
  int const s = fsl_stat(zFilename, &st, true);
  return 0==s ? (st.perm & FSL_FSTAT_PERM_EXE) : false;
}

int fsl_rmdir(const char *zFilename){
  int rc = fsl_dir_check(zFilename);
  if(rc<1) return rc ? FSL_RC_TYPE : FSL_RC_NOT_FOUND;
#ifdef _WIN32
  wchar_t *z = (wchar_t*)fsl_utf8_to_filename(zFilename);
  if(w32_file_is_normal_dir(z)){
    rc = _wunlink(z) ? errno : 0;
  }else{
    rc = ENOTDIR;
  }
#else
  char *z = (char *)fsl_utf8_to_filename(zFilename);
  rc = rmdir(zFilename) ? errno : 0;
#endif
  fsl_os_str_free(z);
  if(rc){
    /* rc holds the errno value saved before fsl_os_str_free(). */
    switch(rc){
      /* ENOENT normally maps to FSL_RC_NOT_FOUND,
         but in this case that's ambiguous. */
      case ENOENT: rc = FSL_RC_ACCESS; break;
      default: rc = fsl_errno_to_rc(rc, FSL_RC_IO);
        break;
    }
  }
  return rc;
}

int fsl_dir_check(const char *zFilename){
  fsl_fstat fst;
  int rc;
  if( zFilename ){
#if 1
    rc = fsl_stat(zFilename, &fst, 1);
#else
    char *zFN = fsl_strdup(zFilename);
    if(!zFN) rc = FSL_RC_OOM;
    else{
      fsl_file_simplify_name(zFN, -1, 0);
      rc = fsl_stat(zFN, &fst, 1);
      fsl_free(zFN);
    }
#endif
  }else{
    rc = -1 /*fsl_stat(zFilename, &fst, 1) historic: used static stat cache*/;
  }
  return rc ? 0 : ((FSL_FSTAT_TYPE_DIR == fst.type) ? 1 : -1);
}

int fsl_chdir(const char *zChDir){
  int rc;
#ifdef _WIN32
  wchar_t *zPath = fsl_utf8_to_filename(zChDir);
  errno = 0;
  rc = (int)!SetCurrentDirectoryW(zPath);
  fsl_os_str_free(zPath);
  if(rc) rc = FSL_RC_IO;
#else
  char *zPath = fsl_utf8_to_filename(zChDir);
  if(!zPath) return FSL_RC_OOM;
  errno = 0;
  rc = chdir(zPath) ? fsl_errno_to_rc(errno, FSL_RC_IO) : 0;
  fsl_os_str_free(zPath);
#endif
  return rc;
}

#if 0
/*
  The family of 'wd' functions is historical in nature and not really
  needed(???) at the library level. 'wd' == 'working directory'
  (i.e. checkout).  Ideally the library won't have to do any _direct_
  manipulation of directory trees, e.g. checkouts. That is essentially
  app-level logic, though we'll need some level of infrastructure for
  the apps to build off of.  When that comes, the "wd" family of
  functions (or something similar) might come back into play.

  [Edit much later: the library most definintely needs to manipulate
  the checkout on behalf of apps, but we've so far never needed the wd
  variants to do any of that.]
*/
/*
   Same as dir_check(), but takes into account symlinks.
*/
int file_wd_dir_check(const char *zFilename){
  if(!zFilename || !*zFilename) return FSL_RC_MISUSE;
  else{
    int rc;
    fsl_fstat fst = fsl_fstat_empty;
    char *zFN = fsl_strdup(zFilename);
    if(!zFN) rc = FSL_RC_OOM;
    else{
      fsl_file_simplify_name(zFN, -1, 0);
      rc = fsl_stat(zFN, &fst, 0);
      fsl_free(zFN);
    }
    return rc ? 0 : ((FSL_FSTAT_TYPE_DIR == fst.type) ? 1 : 2);
  }
}
#endif

#if 0
/* This block requires permissions flags from v1's manifest.c. */

/*
   Return TRUE if the named file is an executable.  Return false
   for directories, devices, fifos, symlinks, etc.
*/
int fsl_wd_isexe(const char *zFilename){
  return fsl_wd_perm(zFilename)==PERM_EXE;
}

/*
   Return TRUE if the named file is a symlink and symlinks are allowed.
   Return false for all other cases.

   On Windows, always return False.
*/
int file_wd_islink(const char *zFilename){
  return file_wd_perm(zFilename)==PERM_LNK;
}
#endif

#if 0
/**
    Same as fsl_is_file(), but takes into account symlinks.
 */
bool fsl_wd_isfile(const char *zFilename);
bool fsl_wd_isfile(const char *zFilename){
  fsl_fstat fst;
  return ( 0 != fsl_stat(zFilename, &fst, 0) )
    ? 0
    : (FSL_FSTAT_TYPE_FILE == fst.type);
}
#endif
#if 0
/**
    Same as fsl_file_mtime(), but takes into account symlinks.
 */
fsl_time_t fsl_wd_mtime(const char *zFilename);
fsl_time_t fsl_wd_mtime(const char *zFilename){
  fsl_fstat fst;
  return ( 0 != fsl_stat(zFilename, &fst, 0) )
    ? -1
    : (fsl_time_t)fst.mtime;
}

bool fsl_wd_isfile_or_link(const char *zFilename){
  fsl_fstat fst;
  return ( 0 != fsl_stat(zFilename, &fst, 0) )
    ? 0
    : ((FSL_FSTAT_TYPE_LINK == fst.type)
       || (FSL_FSTAT_TYPE_FILE == fst.type))
    ;
}
#endif

#if 0
/**
    Same as fsl_file_size(), but takes into account symlinks.
 */
fsl_size_t fsl_wd_size(const char *zFilename);
fsl_size_t fsl_wd_size(const char *zFilename){
  fsl_fstat fst;
  return ( 0 != fsl_stat(zFilename, &fst, 0) )
    ? -1
    : fst.size;
}
#endif

int fsl_file_mtime_set(const char *zFilename, fsl_time_t newMTime){
  if(!zFilename || !*zFilename) return FSL_RC_MISUSE;
  else{
    int rc;
    void * zMbcs;
#if !defined(_WIN32)
    struct timeval tv[2];
    if(newMTime < 0) newMTime = (fsl_time_t)time(0);
    zMbcs = fsl_utf8_to_filename(zFilename);
    if(!zMbcs) return FSL_RC_OOM;
    memset(tv, 0, sizeof(tv[0])*2);
    tv[0].tv_sec = newMTime;
    tv[1].tv_sec = newMTime;
    rc = utimes((char const *)zMbcs, tv)
      ? fsl_errno_to_rc(errno, FSL_RC_IO) : 0;
#else
    struct _utimbuf tb;
    if(newMTime < 0) newMTime = (fsl_time_t)time(0);
    zMbcs = fsl_utf8_to_filename(zFilename);
    if(!zMbcs) return FSL_RC_OOM;
    tb.actime = newMTime;
    tb.modtime = newMTime;
    rc = _wutime((wchar_t const *)zMbcs, &tb)
      ? fsl_errno_to_rc(errno, FSL_RC_IO) : 0;
#endif
    fsl_os_str_free(zMbcs);
    return rc;
  }
}



void fsl_pathfinder_clear(fsl_pathfinder * const pf){
  if(pf){
    fsl_list_visit_free(&pf->ext, 1);
    fsl_list_visit_free(&pf->dirs, 1);
    fsl_b_clear(&pf->buf);
    *pf = fsl_pathfinder_empty;
  }
}

static int fsl__pathfinder_add_impl(fsl_list * const li, char const * str,
                                   fsl_int_t strLen){
  char * cp = fsl_strndup(str, strLen);
  int rc;
  if(!cp) rc = FSL_RC_OOM;
  else{
    rc = fsl_list_append(li, cp);
    if(rc) fsl_free(cp);
  }
  return rc;
}

int fsl_pathfinder_dir_add(fsl_pathfinder * const pf, char const * const dir){
  return dir
    ? fsl__pathfinder_add_impl(&pf->dirs, dir, -1)
    : FSL_RC_MISUSE;
}

int fsl_pathfinder_dir_add2(fsl_pathfinder * const pf, char const * const dir,
                            fsl_int_t strLen){
  return dir
    ? fsl__pathfinder_add_impl(&pf->dirs, dir, strLen)
    : FSL_RC_MISUSE;
}

int fsl_pathfinder_ext_add(fsl_pathfinder * const pf, char const * const ext){
  return (pf && ext)
    ? fsl__pathfinder_add_impl(&pf->ext, ext, -1)
    : FSL_RC_MISUSE;
}

int fsl_pathfinder_ext_add2(fsl_pathfinder * const pf, char const * const ext,
                           fsl_int_t strLen){
  return (pf && ext)
    ? fsl__pathfinder_add_impl(&pf->ext, ext, strLen)
    : FSL_RC_MISUSE;
}

int fsl_pathfinder_search(fsl_pathfinder * const pf,
                          char const * const base,
                          char const ** pOut,
                          fsl_size_t * const outLen ){
  fsl_b * const buf = &pf->buf;
  fsl_list * ext;
  fsl_list * dirs;
  int rc = 0;
  fsl_size_t d, x, nD, nX, resetLen = 0;
  fsl_size_t baseLen;
  static char const pathSep =
#if defined(_WIN32)
    '\\' /* TODO: confirm whether we can always use '/', and do so if
            we can. */
#else
    '/'
#endif
    ;
  if(!base || !*base) return FSL_RC_MISUSE;
  else if(0==fsl_file_access( base, 0 )){
    /* Special case: if base is found as-is, without a path search,
       use it. */
    if(pOut) *pOut = base;
    if(outLen) *outLen = fsl_strlen(base);
    return 0;
  }
  baseLen = fsl_strlen(base);
  ext = &pf->ext;
  dirs = &pf->dirs;
  nD = dirs->used;
  nX = ext->used;
  for( d = 0; !rc && (d < nD); ++d ){
    char const * vD = (char const *)dirs->list[d];
    /*
      Search breadth-first for a file/directory named by vD/base
    */
    buf->used = 0;
    if(vD){
      fsl_size_t const used = buf->used;
      rc = fsl_b_append(buf, vD, -1);
      if(rc) return rc;
      if(used != buf->used){
        /* Only append separator if vD is non-empty. */
        rc = fsl_b_append(buf, &pathSep, 1);
        if(rc) return rc;
      }
    }
    rc = fsl_b_append(buf, base, (fsl_int_t)baseLen);
    if(rc) return rc;
    if(0==fsl_file_access( (char const *)buf->mem, 0 )) goto gotone;
    resetLen = buf->used;
    for( x = 0; !rc && (x < nX); ++x ){
      char const * vX = (char const *)ext->list[x];
      if(vX){
        buf->used = resetLen;
        rc = fsl_b_append(buf, vX, -1);
        if(rc) return rc;
      }
      assert(buf->used < buf->capacity);
      buf->mem[buf->used] = 0;
      if(0==fsl_file_access( (char const *)buf->mem, 0 )){
        goto gotone;
      }
    }
  }
  return FSL_RC_NOT_FOUND;
  gotone:
  if(outLen) *outLen = buf->used;
  if(pOut) *pOut = (char const *)buf->mem;
  return 0;
}

void fsl_path_splitter_init( fsl_path_splitter * pt, char const * path, fsl_int_t len ){
  *pt = fsl_path_splitter_empty;
  pt->pos = pt->begin = path;
  pt->end = pt->begin + ((len>=0) ? (fsl_size_t)len : fsl_strlen(path));
}

int fsl_path_splitter_next( fsl_path_splitter * const pt, char const ** token,
                            fsl_size_t * const len ){
  if(!pt->pos || pt->pos>=pt->end) return FSL_RC_RANGE;
  else if(!pt->separators || !*pt->separators) return FSL_RC_MISUSE;
  else{
    char const * pos = pt->pos;
    char const * t;
    char const * sep;
    for( sep = pt->separators; *sep; ++sep){
      if(*sep & 0x80) return FSL_RC_MISUSE;
      /* non-ASCII */
    }
    for( ; pos<pt->end; ){
      /*skip leading separators*/
      for( sep = pt->separators;
           *sep && *pos!=*sep; ++sep ){
      }
      if(*pos == *sep) ++pos;
      else break;
    }
    t = pos;
    for( ; pos<pt->end; ){
      /*skip until the next separator*/
      for( sep = pt->separators;
           *sep && *pos!=*sep; ++sep ){
      }
      if(*pos == *sep) break;
      else ++pos;
    }
    pt->pos = pos;
    if(pos>t){
      *token = t;
      *len = (fsl_size_t)(pos - t);
      return 0;
    }
    return FSL_RC_NOT_FOUND;
  }
}

int fsl_pathfinder_split( fsl_pathfinder * const tgt,
                          bool isDirs,
                          char const * path,
                          fsl_int_t pathLen ){
  int rc = 0;
  char const * t = 0;
  fsl_size_t tLen = 0;
  fsl_path_splitter pt = fsl_path_splitter_empty;
  fsl_path_splitter_init(&pt, path, pathLen);
  while(0==rc && 0==fsl_path_splitter_next(&pt, &t, &tLen)){
    rc = isDirs
      ? fsl_pathfinder_dir_add2(tgt, t, (fsl_int_t)tLen)
      : fsl_pathfinder_ext_add2(tgt, t, (fsl_int_t)tLen);
  }
  return rc;
}

char * fsl__file_without_drive_letter(char * zIn){
#ifdef _WIN32
  if( zIn && fsl_isalpha(zIn[0]) && zIn[1]==':' ) zIn += 2;
#endif
  return zIn;
}

int fsl_dir_is_empty(const char *path){
  struct dirent *ent;
  int            retval = 0;
  DIR *d = opendir(path);
  if(!d){
    return -1;
  }
  while((ent = readdir(d))) {
    const char * z = ent->d_name;
    if('.'==*z &&
       (!z[1] || ('.'==z[1] && !z[2]))){
      // Skip "." and ".." entries
      continue;
    }
    retval = 1;
    break;
  }
  closedir(d);
  return retval;
}

int fsl_file_exec_set(const char *zFilename, bool isExe){
#if FSL_PLATFORM_IS_WINDOWS
  return 0;
#else
  int rc = 0, err;
  struct stat sb;
  err = stat(zFilename, &sb);
  if(0==err){
    if(!S_ISREG(sb.st_mode)) return 0;
    else if(isExe){
      if( 0==(sb.st_mode & 0100) ){
        int const mode = (sb.st_mode & 0444)>>2
          /* This impl is from fossil, which is known to work, but...
             what is the >>2 for?*/;
        err = chmod(zFilename, (mode_t)(sb.st_mode | mode));
      }
    }else if( 0!=(sb.st_mode & 0100) ){
      err = chmod(zFilename, sb.st_mode & ~0111);
    }
  }
  if(err) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
  return rc;
#endif
}

/**
   fsl_dircrawl() part for handling a single directory. fst must be
   valid state from a freshly-fsl_stat()'d DIRECTORY and this
   function will re-use it for its own stat()ing.
*/
/*
   The UTF-8 form of a name returned by readdir(), freed with
   fsl__dirent_utf8_free(). fsl_filename_to_utf8() turns the decomposed
   names HFS+ returns on macOS into precomposed form, as fossil(1)'s
   directory scan does, so that they compare equal to the names stored
   in a repository; on Cygwin it maps private-use characters back to
   ASCII; elsewhere on Unix it returns its argument. On Windows the name
   is used as it is, because fsl_filename_to_utf8() expects a wide
   string there but the readdir() of xdirent.h returns a narrow one.
*/
#if defined(_WIN32)
#  define fsl__dirent_utf8(Z) ((char *)(Z))
#  define fsl__dirent_utf8_free(Z) ((void)(Z))
#else
#  define fsl__dirent_utf8(Z) fsl_filename_to_utf8(Z)
#  define fsl__dirent_utf8_free(Z) fsl_os_str_free(Z)
#endif

static int fsl_dircrawl_impl(fsl_b * const dbuf, fsl_fstat * const fst,
                             fsl_dircrawl_f cb,
                             fsl_dircrawl_state * const dst,
                             unsigned int depth){
  int rc = 0;
  DIR *dir;
  struct dirent * dent = 0;
  fsl_size_t const dPos = dbuf->used;
  if(depth>20/*arbitrary limit to try to avoid stack overflow*/){
    return FSL_RC_RANGE;
  }
  dir = opendir(fsl_b_cstr(dbuf));
  if(!dir){
    return fsl_errno_to_rc(errno, FSL_RC_IO);
  }
  while(!rc && (dent = readdir(dir))){
    char * zUtf8;
    const char * z = dent->d_name;
    if('.'==*z &&
       (!z[1] || ('.'==z[1] && !z[2]))){
      // Skip "." and ".." entries
      continue;
    }
    zUtf8 = fsl__dirent_utf8(z);
    if(!zUtf8){
      rc = FSL_RC_OOM;
      break;
    }
    z = zUtf8;
    dbuf->used = dPos;
    rc = fsl_b_appendf(dbuf, "/%s", z);
    if(rc){
      fsl__dirent_utf8_free(zUtf8);
      break;
    }
    fsl_size_t const newLen = dbuf->used;
    if(fsl_stat((char const *)dbuf->mem, fst, false)){
      // Simply skip stat errors. i was once bitten by an app which did
      // not do so. Scarred for life. Too soon.
      fsl__dirent_utf8_free(zUtf8);
      continue;
    }
    switch(fst->type){
      case FSL_FSTAT_TYPE_LINK:
      case FSL_FSTAT_TYPE_DIR:
      case FSL_FSTAT_TYPE_FILE:
        break;
      default:
        fsl__dirent_utf8_free(zUtf8);
        continue;
    }
    dbuf->mem[dbuf->used = dPos] = 0;
    dst->absoluteDir = (char const *)dbuf->mem;
    dst->entryName = z;
    dst->entryType = fst->type;
    dst->depth = depth;
    rc = cb( dst );
    if(!rc){
      dbuf->mem[dbuf->used] = '/';
      dbuf->used = newLen;
      if(FSL_FSTAT_TYPE_DIR==fst->type){
        rc = fsl_dircrawl_impl( dbuf, fst, cb, dst, depth+1 );
      }
    }else if(FSL_RC_NOOP == rc){
      rc = 0;
    }
    fsl__dirent_utf8_free(zUtf8);
  }
  closedir(dir);
  return rc;
}

int fsl_dircrawl(char const * dirName, fsl_dircrawl_f callback,
                 void * cbState){
  fsl_b dbuf = fsl_b_empty;
  fsl_fstat fst = fsl_fstat_empty;
  int rc = fsl_file_canonical_name(dirName, &dbuf, false);
  fsl_dircrawl_state dst;
  if(!rc && '/' == dbuf.mem[dbuf.used-1]){
    dbuf.mem[--dbuf.used] = 0;
  }
  memset(&dst, 0, sizeof(dst));
  dst.callbackState = cbState;
  while(!rc){
    rc = fsl_stat((char const *)dbuf.mem, &fst, false);
    if(rc) break;
    else if(FSL_FSTAT_TYPE_DIR!=fst.type){
      rc = FSL_RC_TYPE;
      break;
    }
    rc = fsl_dircrawl_impl(&dbuf, &fst, callback, &dst, 1);
    if(FSL_RC_BREAK==rc) rc = 0;
    break;
  }
  fsl_b_clear(&dbuf);
  return rc;
}

bool fsl_is_file_or_link(const char *zFilename){
  fsl_fstat fst = fsl_fstat_empty;
  return fsl_stat(zFilename, &fst, false)
    ? false
    : (fst.type==FSL_FSTAT_TYPE_FILE
       || fst.type==FSL_FSTAT_TYPE_LINK);
}

fsl_size_t fsl_strip_trailing_slashes(char * name, fsl_int_t nameLen){
  fsl_size_t rc = 0;
  if(nameLen < 0) nameLen = (fsl_int_t)fsl_strlen(name);
  if(nameLen){
    char * z = name + nameLen - 1;
    for( ; (z>=name) && ('/'==*z); --z){
      *z = 0;
      ++rc;
    }
  }
  return rc;
}

void fsl_b_strip_slashes(fsl_b * const b){
  if( 0==fsl_b_materialize(b) ){
    b->used -= fsl_strip_trailing_slashes((char *)b->mem,
                                          (fsl_int_t)b->used);
  }
}

int fsl_file_rename(const char *zFrom, const char *zTo){
  int rc;
#if defined(_WIN32)
  /** 2021-03-24: fossil's impl of this routine has 2 additional
      params (bool isFromDir, bool isToDir), which are passed on to
      fsl_utf8_to_filename(), only used on Windows platforms, and are
      only to allow for 12 bytes of edge case in MAX_PATH handling.
      We don't need them. */
  wchar_t *zMbcsFrom = fsl_utf8_to_filename(zFrom);
  wchar_t *zMbcsTo = zMbcsFrom ? fsl_utf8_to_filename(zTo) : 0;
  rc = zMbcsTo ? _wrename(zMbcsFrom, zMbcsTo) : FSL_RC_OOM;
#else
  char *zMbcsFrom = fsl_utf8_to_filename(zFrom);
  char *zMbcsTo = zMbcsFrom ? fsl_utf8_to_filename(zTo) : 0;
  rc = zMbcsTo ? rename(zMbcsFrom, zMbcsTo) : FSL_RC_OOM;
#endif
  fsl_os_str_free(zMbcsTo);
  fsl_os_str_free(zMbcsFrom);
  return -1==rc ? fsl_errno_to_rc(errno, FSL_RC_IO) : rc;
}

char ** fsl_temp_dirs_get(void){
#if FSL_PLATFORM_IS_WINDOWS
  const char *azDirs[] = {
     ".",
     NULL
  };
  unsigned int const nDirs = 4
    /* GetTempPath(), $TEMP, $TMP, azDirs */;
#else
  const char *azDirs[] = {
     "/var/tmp",
     "/usr/tmp",
     "/tmp",
     "/temp",
     ".", NULL
  };
  unsigned int const nDirs = 6
    /* $TMPDIR, azDirs */;
#endif
  char *z;
  char const *zC;
  char ** zDirs = NULL;
  unsigned int i, n = 0;

  zDirs = (char **)fsl_malloc(sizeof(char*) * (nDirs + 1));
  if(!zDirs) return NULL;
  for(i = 0; i<=nDirs; ++i) zDirs[i] = NULL;
#define DOZ \
  if(z && fsl_dir_check(z)>0) zDirs[n++] = z;   \
  else if(z) fsl_os_str_free(z)

#if FSL_PLATFORM_IS_WINDOWS
  wchar_t zTmpPath[MAX_PATH];

  if( GetTempPathW(MAX_PATH, zTmpPath) ){
    z = fsl_filename_to_utf8(zTmpPath);
    DOZ;
  }
  z = fsl_getenv("TEMP");
  DOZ;
  z = fsl_getenv("TMP");
  DOZ;
#else /* Unix-like */
  z = fsl_getenv("TMPDIR");
  DOZ;
#endif
  for( i = 0; (zC = azDirs[i]); ++i ){
    z = fsl_filename_to_utf8(azDirs[i]);
    DOZ;
  }
#undef DOZ
  /* Strip any trailing slashes unless the only character is a
     slash. Note that we ignore the root-dir case on Windows here,
     mainly because this developer can't test it and secondarily
     because it's a highly unlikely case. */
  for(i = 0; i < n; ++i ){
    fsl_size_t len;
    z = zDirs[i];
    len = fsl_strlen(z);
    while(len>1 && (z[len-1]=='/' || z[len-1]=='\\')){
      z[--len] = 0;
    }
  }
  return zDirs;
}

void fsl_temp_dirs_free(char **aDirs){
  if(aDirs){
    char * z;
    for(unsigned i = 0; (z = aDirs[i]); ++i){
      fsl_os_str_free(z);
      aDirs[i] = NULL;
    }
    fsl_free(aDirs);
  }
}

int fsl_file_tempname(fsl_b * const tgt, char const *zPrefix,
                      char * const * const dirs){
  int rc = 0;
  unsigned int tries = 0;
  const unsigned char zChars[] =
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789_-";
  enum { RandSize = 16 };
  char zRand[RandSize + 1];
  int i;
  char const * zDir = "";

  if( tgt->errCode ) return tgt->errCode;
  if(dirs){
    for(i = 0; (zDir=dirs[i++]); ){
      /* We repeat this check, performed in fsl_temp_dirs_get(), for the
         sake of long-lived apps where a given temp dir might disappear
         at some point. */
      if(fsl_dir_check(zDir)>0) break;
    }
    if(!zDir) return FSL_RC_NOT_FOUND;
  }
  if(!zPrefix) zPrefix = "libfossil";
  /* Pre-fill buffer to allocate it in advance and remember the length
     of the base filename part so that we don't have to re-write the
     prefix each iteration below. */
  rc = fsl_b_appendf(tgt, "%/%s%s%s%.*cZ",
                          zDir, *zDir ? "/" : "",
                          zPrefix, *zPrefix ? "~" : "",
                          (int)RandSize, 'X');
  fsl_size_t const baseLen = rc ? 0 : (tgt->used - RandSize - 1);
  do{
    if(++tries == 20){
      rc = FSL_RC_RANGE;
      break;
    }
    fsl_randomness(RandSize, zRand);
    for( i=0; i < RandSize; ++i ){
      zRand[i] = (char)zChars[ ((unsigned char)zRand[i])%(sizeof(zChars)-1) ];
    }
    zRand[RandSize] = 0;
    tgt->used = baseLen;
    rc = fsl_b_append(tgt, zRand, (fsl_int_t)RandSize);
    assert(0==rc && "We pre-allocated the buffer above.");
  }while(0==rc && fsl_file_size(fsl_b_cstr(tgt)) >= 0);
  return rc;
}

int fsl_file_copy(char const *zFrom, char const *zTo){
  FILE * in = 0, *out = 0;
  int rc;
  in = fsl_fopen(zFrom, "rb");
  if(!in) return fsl_errno_to_rc(errno, FSL_RC_IO);
  rc = fsl_mkdir_for_file(zTo, false);
  if(rc) goto end;
  out = fsl_fopen(zTo, "wb");
  rc = out
    ? fsl_stream(fsl_input_f_FILE, in, fsl_output_f_FILE, out)
    : fsl_errno_to_rc(errno, FSL_RC_IO);
  end:
  if(in) fsl_fclose(in);
  if(out && 0!=fclose(out) && 0==rc){
    /* A write error may surface only when the buffered output is
       flushed. */
    rc = fsl_errno_to_rc(errno, FSL_RC_IO);
  }
  if(0==rc && fsl_file_isexec(zFrom)){
    fsl_file_exec_set(zTo, true);
  }
  return rc;
}

int fsl_symlink_read(fsl_b * const tgt, char const * zFilename){
#if FSL_PLATFORM_IS_WINDOWS
  fsl_b_reuse(tgt);
  return 0;
#else
  enum { BufLen = 1024 * 2 };
  char buf[BufLen];
  int rc;
  ssize_t const len = readlink(zFilename, buf, BufLen-1);
  if(len<0) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
  else{
    fsl_b_reuse(tgt);
    rc = fsl_b_append(tgt, buf, (fsl_size_t)len);
  }
  return rc;
#endif
}

int fsl_symlink_create(const char *zTargetFile, const char *zLinkFile,
                       bool realLink){
  int rc;
#if FSL_PLATFORM_IS_WINDOWS
  (void)realLink;
#else
  if( realLink ){
    char *zName;
    char zBuf[1024 * 2];
    fsl_size_t nName = fsl_strlen(zLinkFile);
    if( nName>=sizeof(zBuf) ){
      zName = fsl_mprintf("%s", zLinkFile);
      if(!zName) return FSL_RC_OOM;
    }else{
      zName = zBuf;
      memcpy(zName, zLinkFile, nName+1);
    }
    nName = fsl_file_simplify_name(zName, (fsl_int_t)nName, false);
    rc = fsl_mkdir_for_file(zName, false);
    if(0==rc && 0!=symlink(zTargetFile, zName) ){
      rc = fsl_errno_to_rc(errno, FSL_RC_IO);
    }
    if( zName!=zBuf ) fsl_free(zName);
  }else
#endif
  {
    rc = fsl_mkdir_for_file(zLinkFile, false);
    if(0==rc){
      fsl_b content = fsl_b_empty;
      fsl_b_external(&content, zTargetFile, -1);
      fsl_file_unlink(zLinkFile)
        /* in case it's already a symlink, we don't want the following
           to overwrite the symlinked-to file */;
      rc = fsl_b_to_filename(&content, zLinkFile);
    }
  }
  return rc;
}

int fsl_symlink_copy(char const *zFrom, char const *zTo, bool realLink){
  int rc;
  fsl_b b = fsl_b_empty;
  rc = fsl_symlink_read(&b, zFrom);
  if(0==rc){
    rc = fsl_symlink_create(fsl_b_cstr(&b), zTo, realLink);
  }
  fsl_b_clear(&b);
  return rc;
}

char const * fsl_last_path_sep(char const * str, fsl_int_t slen ){
  if(slen<0) slen = (fsl_int_t)fsl_strlen(str);
  unsigned char const * pos = (unsigned char const *)str + slen;
  while( --pos >= (unsigned char const *)str ){
    if('/'==*pos || '\\'==*pos){
      return (char const *)pos;
    }
  }
  return NULL;
}

int fsl_filename_preferred_case(bool isCaseSensitive, const char *zDir,
                                const char *zPath, char **zOut){
  /* Adapted from: https://fossil-scm.org/home/timeline?r=preserve-case-on-add */
  /* 2024-10-15: Florian added a Windows-specific variant of that:
     https://fossil-scm.org/home/info/9919dfbbaa2019e7eb7b
     but we'll need a Windows-using developer to integrate that here.
  */
  DIR *d = 0;
  int i;
  char *zResult = 0;
  void *zNative = 0;
  int rc = 0;
  struct dirent *pEntry;

  if( isCaseSensitive ){
    if( (zResult = fsl_strdup(zPath))!=0 ) *zOut = zResult;
    else rc = FSL_RC_OOM;
    return rc;
  }
  for( i = 0; zPath[i] && zPath[i]!='/' && zPath[i]!='\\'; ++i){}
  /* potential TODO: reimplement this using fsl_dircrawl().

     alternative potential TODO: add an outer loop which adjusts zDir
     and zPath on each iteration instead of recursing.
  */
#define CKERR(P,RC) if( !(P) ){ rc = RC; goto end_err; }(void)0
#define CKOOM(P) CKERR(P,FSL_RC_OOM)
  zNative = fsl_utf8_to_unicode(zDir);
  CKOOM(zNative);
  d = opendir(zNative);
  if( !d ){
    rc = fsl_errno_to_rc(errno, FSL_RC_IO);
    goto end_err;
  }
  while( (pEntry = readdir(d)) != 0 ){
    char *zUtf8 = fsl__dirent_utf8(pEntry->d_name);
    CKOOM(zUtf8);
    if( fsl_strnicmp(zUtf8, zPath, i)==0 && zUtf8[i]==0 ){
      if( zPath[i]==0 ){
        zResult = fsl_strdup(zUtf8);
        if( !zResult ) rc = FSL_RC_OOM;
      }else{
        char *zSubDir = fsl_mprintf("%s/%s", zDir, zUtf8);
        char *zSubPath = 0;
        rc = zSubDir
          ? fsl_filename_preferred_case(false, zSubDir, &zPath[i+1], &zSubPath)
          : FSL_RC_OOM;
        zResult = rc ? 0 : fsl_mprintf("%s/%s", zUtf8, zSubPath);
        if( !rc && !zResult ) rc = FSL_RC_OOM;
        fsl_free(zSubPath);
        fsl_free(zSubDir);
      }
      fsl__dirent_utf8_free(zUtf8);
      if( rc ) goto end_err;
      break;
    }
    fsl__dirent_utf8_free(zUtf8);
  }
  closedir(d);
  d = 0;
  if( !zResult ){
    zResult = fsl_strdup(zPath);
    CKOOM(zResult);
  }
  fsl_free(zNative);
  *zOut = zResult;
  return 0;
#undef CKOOM
#undef CKERR
end_err:
  if(d) closedir(d);
  fsl_free(zNative);
  fsl_free(zResult);
  return rc;
}

int fsl_chdir2(const char *zTo, char * zCurrent, fsl_size_t nCurrent){
  int rc = fsl_getcwd(zCurrent, nCurrent, NULL);
  if( 0==rc ){
    rc = fsl_chdir(zTo);
  }
  return rc;
}

int fsl__find_bin( char const *zPath, char const *zBinName, char **zOut ){
  fsl_pathfinder pf = fsl_pathfinder_empty;
  int rc = 0;
  if( !zPath ) zPath = getenv("PATH");
  if( !zPath ){
#if FSL_PLATFORM_IS_UNIX
    zPath = "/usr/local/bin:/usr/bin";
#else
    return FSL_RC_NOT_FOUND;
#endif
  }
  rc = fsl_pathfinder_split(&pf, true, zPath, -1);
  if( rc ) goto end;
#if FSL_PLATFORM_IS_WINDOWS
  rc = fsl_pathfinder_ext_add2(&pf, ".exe", 4);
  if( rc ) goto end;
#endif
  fsl_size_t nGot = 0;
  char const * got = 0;
  rc = fsl_pathfinder_search(&pf, zBinName, &got, &nGot);
  if( got ){
    *zOut = fsl_strndup(got, (fsl_int_t)nGot);
    if( !*zOut ){
      rc = FSL_RC_OOM;
    }
  }
end:
  fsl_pathfinder_clear(&pf);
  return rc;
}

#if 0
int fsl_file_relative_name( char const * zRoot, char const * zPath,
                            fsl_b * pOut, char retainSlash ){
  int rc = FSL_RC_NYI;
  char * zPath;
  fsl_size_t rootLen;
  fsl_size_t pathLen;
  if(!zPath || !*zPath || !pOut) return FSL_RC_MISUSE;

  return rc;
}
#endif

int fsl__dir_list(char const * zDir,
                  int (*cb)(void * cbState, char const * zEntry),
                  void * cbState){
  /* As fsl_dircrawl_impl() reads a directory, for one level. */
  int rc = 0;
  struct dirent * dent;
  DIR * const dir = opendir(zDir);
  if(!dir) return fsl_errno_to_rc(errno, FSL_RC_IO);
  while(!rc && (dent = readdir(dir))){
    char const * z = dent->d_name;
    char * zUtf8;
    if('.'==*z && (!z[1] || ('.'==z[1] && !z[2]))) continue;
    zUtf8 = fsl__dirent_utf8(z);
    if(!zUtf8){
      rc = FSL_RC_OOM;
      break;
    }
    rc = cb(cbState, zUtf8);
    fsl__dirent_utf8_free(zUtf8);
  }
  closedir(dir);
  return rc;
}

#undef fsl__dirent_utf8
#undef fsl__dirent_utf8_free
#undef MARKER
#ifdef _WIN32
#  undef DIR
#  undef dirent
#  undef opendir
#  undef readdir
#  undef closedir
#endif
/* end of file src/fs.c */
/* start of file src/forum.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/***************************************************************************
  This file houses the code for forum-level APIS.
*/
#include <assert.h>


/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

int fsl_repo_install_schema_forum(fsl_cx *f){
  int rc;
  fsl_db * db = fsl_needs_repo(f);
  if(!db) return FSL_RC_NOT_A_REPO;
  if(fsl_db_table_exists(db, FSL_DBROLE_REPO, "forumpost")){
    return 0;
  }
  rc = fsl_db_exec_multi(db, fsl_schema_forum())
    /* the format string, so that its schema placeholders expand */;
  if(rc){
    rc = fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}



#undef MARKER
/* end of file src/forum.c */
/* start of file src/glob.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*************************************************************************
  This file contains some of the APIs dealing with globs.
*/
#include <assert.h>

bool fsl_str_glob(const char *zGlob, const char *z){
#if 1
  return (zGlob && z)
    ? (sqlite3_strglob(zGlob,z) ? 0 : 1)
    : 0;
#else
  int c, c2;
  int invert;
  int seen;
  while( (c = (*(zGlob++)))!=0 ){
    if( c=='*' ){
      while( (c=(*(zGlob++))) == '*' || c=='?' ){
        if( c=='?' && (*(z++))==0 ) return 0;
      }
      if( c==0 ){
        return 1;
      }else if( c=='[' ){
        while( *z && fsl_str_glob(zGlob-1,z)==0 ){
          z++;
        }
        return (*z)!=0;
      }
      while( (c2 = (*(z++)))!=0 ){
        while( c2!=c ){
          c2 = *(z++);
          if( c2==0 ) return 0;
        }
        if( fsl_str_glob(zGlob,z) ) return 1;
      }
      return 0;
    }else if( c=='?' ){
      if( (*(z++))==0 ) return 0;
    }else if( c=='[' ){
      int prior_c = 0;
      seen = 0;
      invert = 0;
      c = *(z++);
      if( c==0 ) return 0;
      c2 = *(zGlob++);
      if( c2=='^' ){
        invert = 1;
        c2 = *(zGlob++);
      }
      if( c2==']' ){
        if( c==']' ) seen = 1;
        c2 = *(zGlob++);
      }
      while( c2 && c2!=']' ){
        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
          c2 = *(zGlob++);
          if( c>=prior_c && c<=c2 ) seen = 1;
          prior_c = 0;
        }else{
          if( c==c2 ){
            seen = 1;
          }
          prior_c = c2;
        }
        c2 = *(zGlob++);
      }
      if( c2==0 || (seen ^ invert)==0 ) return 0;
    }else{
      if( c!=(*(z++)) ) return 0;
    }
  }
  return *z==0;
#endif
}


int fsl_glob_list_parse( fsl_list * const tgt, char const * zPatternList ){
  fsl_size_t i;             /* Loop counter */
  char const *z = zPatternList;
  char * cp;
  char delimiter;    /* '\'' or '\"' or 0 */
  int rc = 0;
  char const * end;
  if( !tgt || !zPatternList ) return FSL_RC_MISUSE;
  else if(!*zPatternList) return 0;
  end = zPatternList + fsl_strlen(zPatternList);
  while( (z<end) && z[0] ){
    while( fsl_isspace(z[0]) || z[0]==',' ){
      ++z;  /* Skip leading commas, spaces, and newlines */
    }
    if( z[0]==0 ) break;
    if( z[0]=='\'' || z[0]=='"' ){
      delimiter = z[0];
      ++z;
    }else{
      delimiter = ',';
    }
    /* Find the next delimter (or the end of the string). */
    for(i=0; z[i] && z[i]!=delimiter; i++){
      if( delimiter!=',' ) continue; /* If quoted, keep going. */
      if( fsl_isspace(z[i]) ) break; /* If space, stop. */
    }
    if( !i ) break;
    cp = fsl_strndup(z, (fsl_int_t)i);
    if(!cp) return FSL_RC_OOM;
    else{
      rc = fsl_list_append(tgt, cp);
      if(rc){
        fsl_free(cp);
        break;
      }
      cp[i]=0;
    }
    z += i+1;
  }
  return rc;
}


char const * fsl_glob_list_matches( fsl_list const * const globList,
                                    char const * zNeedle ){
  if(!zNeedle || !*zNeedle || !globList->used) return NULL;
  else{
    char const * glob;
    fsl_size_t i = 0;
    for( ; i < globList->used; ++i){
      glob = (char const *)globList->list[i];
      if( fsl_str_glob( glob, zNeedle ) ) return glob;
    }
    return NULL;
  }
}

int fsl_glob_list_append( fsl_list * const tgt, char const * zGlob ){
  if(!tgt || !zGlob || !*zGlob) return FSL_RC_MISUSE;
  else{
    char * cp = fsl_strdup(zGlob);
    int rc = cp ? 0 : FSL_RC_OOM;
    if(!rc){
      rc = fsl_list_append(tgt, cp);
      if(rc) fsl_free(cp);
    }
    return rc;
  }
}


void fsl_glob_list_clear( fsl_list * const globList ){
  if(globList) fsl_list_visit_free(globList, 1);
}

/* end of file src/glob.c */
/* start of file src/io.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*************************************************************************
  This file implements the generic i/o-related parts of the library.
*/
#include <assert.h>
#include <errno.h>
#include <string.h> /* memcmp() */

#if FSL_PLATFORM_IS_UNIX
#  include <unistd.h>
#elif FSL_PLATFORM_IS_WINDOWS
#  include <io.h> /* read() */
#else
#  error "don't know which #include to use for read(2)."
#endif

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

/**
    fsl_appendf_f() impl which sends its output to fsl_output(). state
    must be a (fsl_cx*).
 */
static int fsl_output_f_fsl_output( void * state, void const * s,
                                    fsl_size_t n ){
  return fsl_output( (fsl_cx *)state, s, n );
}


int fsl_outputfv( fsl_cx * const f, char const * fmt, va_list args ){
#if FSL_API_ARMOR
  if(!f || !fmt) return FSL_RC_MISUSE;
  else if(!*fmt) return FSL_RC_RANGE;
#endif
  return fsl_cx_formatv( f, fsl_output_f_fsl_output, f, fmt, args );
}

int fsl_outputf( fsl_cx * const f, char const * fmt, ... ){
#if FSL_API_ARMOR
  if(!f || !fmt) return FSL_RC_MISUSE;
  else if(!*fmt) return FSL_RC_RANGE;
#endif
  int rc;
  va_list args;
  va_start(args,fmt);
  rc = fsl_outputfv( f, fmt, args );
  va_end(args);
  return rc;
}

int fsl_output( fsl_cx * const cx, void const * const src, fsl_size_t n ){
  if(!n || !cx->output.out) return 0;
  else return cx->output.out( cx->output.state, src, n );
}

int fsl_flush( fsl_cx * const f ){
  return f->output.flush
       ? f->output.flush(f->output.state)
       : 0;
}


int fsl_flush_f_FILE(void * _FILE){
  return fflush((FILE*)_FILE) ? fsl_errno_to_rc(errno, FSL_RC_IO) : 0;
}

int fsl_output_f_FILE( void * state,
                       void const * src, fsl_size_t n ){
  if(!n) return 0;
  else if(1 == fwrite(src, n, 1, state ? (FILE*)state : stdout)){
    return 0;
  }else{
    int const eno = errno;
    return eno ? fsl_errno_to_rc(eno, FSL_RC_IO) : FSL_RC_IO;
  }
}


int fsl_output_f_fd( void * state, void const * src, fsl_size_t n ){
  if( !n ) return 0;
#if FSL_API_ARMOR
  else if( !state ) return FSL_RC_MISUSE;
#endif
  int const fd = *((int*)state);
  while( n ){
    fsl_int_t const wn = write(fd, src, n);
    if( wn<0 ){
      if( EINTR==errno ) continue;
      return fsl_errno_to_rc(errno, FSL_RC_IO);
    }else if( 0==wn ){
      return FSL_RC_IO;
    }
    src = (unsigned char const *)src + wn;
    n -= (fsl_size_t)wn;
  }
  return 0;
}


int fsl_input_f_FILE( void * state, void * dest, fsl_size_t * n ){
  if( !*n ) return FSL_RC_RANGE;
  FILE * f = (FILE*) state;
  fsl_size_t const rn = *n;
  *n = (size_t)fread( dest, 1, rn, f );
  if(*n==rn || feof(f)) return 0;
  else{
    int const eno = errno;
    return eno ? fsl_errno_to_rc(eno, FSL_RC_IO) : FSL_RC_IO;
  }
}

int fsl_input_f_fd( void * state, void * dest, fsl_size_t * n ){
  if( !*n ) return FSL_RC_RANGE;
  int const fd = *((int*)state);
  fsl_size_t got = 0;
  /* Fill *n bytes unless the input ends first, as fread() does for
     fsl_input_f_FILE(): fsl_stream() and fsl_b_fill_from() take a
     short read as the end, and a pipe returns only what is
     available so far. */
  while( got < *n ){
    fsl_int_t const rn = read( fd, (unsigned char *)dest + got, *n - got );
    if( rn<0 ){
      if( EINTR==errno ) continue;
      return fsl_errno_to_rc(errno, FSL_RC_IO);
    }
    if( 0==rn ) break;
    got += (fsl_size_t)rn;
  }
  *n = got;
  return 0;
}

void fsl_finalizer_f_FILE( void * state fsl__unused, void * mem ){
  (void)state;
  if(mem){
    fsl_fclose((FILE*)mem);
  }
}

int fsl_stream( fsl_input_f inF, void * inState,
                fsl_output_f outF, void * outState ){
#if FSL_API_ARMOR
  if(!inF || !outF) return FSL_RC_MISUSE;
#endif
  int rc = 0;
  enum { BufSize = 1024 * 4 };
  unsigned char buf[BufSize];
  fsl_size_t rn = BufSize;
  while( 0==rc
         && (rn==BufSize)
         && (0==(rc=inF(inState, buf, &rn))) ){
    if(rn) rc = outF(outState, buf, rn);
  }
  return rc;
}

int fsl_stream_compare( fsl_input_f in1, void * in1State,
                        fsl_input_f in2, void * in2State ){
  enum { BufSize = 1024 * 2 };
  unsigned char buf1[BufSize];
  unsigned char buf2[BufSize];
  fsl_size_t rn1 = BufSize;
  fsl_size_t rn2 = BufSize;
  int rc;
  while(1){
    rc = in1(in1State, buf1, &rn1);
    if(rc) return -1;
    rc = in2(in2State, buf2, &rn2);
    if(rc) return 1;
    else if(rn1!=rn2){
      rc = (rn1<rn2) ? -1 : 1;
      break;
    }
    else if(0==rn1 && 0==rn2) return 0;
    rc = memcmp( buf1, buf2, rn1 );
    if(rc) break;
    rn1 = rn2 = BufSize;
  }
  return rc;
}

#undef MARKER
/* end of file src/io.c */
/* start of file src/leaf.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/************************************************************************
  This file houses some of the "leaf"-related APIs.
*/
#include <assert.h>


/* Only for debugging */
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

int fsl_repo_leaves_rebuild(fsl_cx * const f){
  char const * zMainBranch = 0;
  int rc = fsl_branch_main(f, &zMainBranch, false);
  if( rc ) return rc;
#if 0
  /* Historical variant plus its long-missing tagtype>0 check */
  return fsl_cx_exec_multi(
    f,
    "DELETE FROM {{dbname.repo}}.leaf;"
    "INSERT OR IGNORE INTO {{dbname.repo}}.leaf"
    "  SELECT cid FROM {{dbname.repo}}.plink AS plink"
    "  EXCEPT"
    "  SELECT pid FROM {{dbname.repo}}.plink AS plink"
    "   WHERE coalesce((SELECT value FROM {{dbname.repo}}.tagxref"
    "     WHERE tagid=%d AND rid=plink.pid"
    "     AND tagtype>0),%Q)"
    "   == coalesce((SELECT value FROM {{dbname.repo}}.tagxref"
    "     WHERE tagid=%d AND rid=plink.cid"
    "     AND tagtype>0),%Q)",
    FSL_TAGID_BRANCH, zMainBranch,
    FSL_TAGID_BRANCH, zMainBranch
  );
#else
  /*
    2026-09-25 variant suggested by an LLM via analysis by Dan
    Shearer.

    The problem this solves over the prior impl is that it directly
    filters out non-checkins, whereas a few other constructs
    participate in plink. Granted, those won't have branch tags unless
    someone actively intervenes to add some, so would be filtered out
    anyway, but filtering them out this way seems like a nice
    improvement.

    2026-10-13: the candidates are limited to those which incremental
    leaf tracking ever looks at: check-ins with a branch tag of any
    type, plus their parents (see fsl__leaf_eventually_check()). An
    untagged check-in which is not the parent of a tagged one is
    never a leaf, even if it has no children. This makes the result
    match what crosslinking every check-in in one batch (as
    fsl_repo_rebuild() does) produces.
  */
  return fsl_cx_exec_multi(
    f,
    "DELETE FROM {{dbname.repo}}.leaf;"
    "INSERT OR IGNORE INTO {{dbname.repo}}.leaf(rid) "
    "SELECT e.objid "
    "FROM {{dbname.repo}}.event AS e "
    "WHERE e.type = 'ci' "
    "AND e.objid IN ("
    "  SELECT rid FROM {{dbname.repo}}.tagxref WHERE tagid = %d"
    "  UNION"
    "  SELECT pid FROM {{dbname.repo}}.plink"
    "   WHERE cid IN (SELECT rid FROM {{dbname.repo}}.tagxref WHERE tagid = %d)"
    ") "
    "AND NOT EXISTS ("
    "  SELECT 1"
    "  FROM {{dbname.repo}}.plink AS p"
    "  WHERE p.pid = e.objid"
    "  AND coalesce("
    "    (SELECT value"
    "     FROM {{dbname.repo}}.tagxref"
    "     WHERE tagid = %d"
    "     AND rid = p.pid"
    "     AND tagtype > 0),%Q)"
    "     == coalesce("
    "       (SELECT value"
    "        FROM {{dbname.repo}}.tagxref"
    "        WHERE tagid = %d"
    "        AND rid = p.cid"
    "        AND tagtype > 0),%Q)"
    ")",
    FSL_TAGID_BRANCH, FSL_TAGID_BRANCH,
    FSL_TAGID_BRANCH, zMainBranch,
    FSL_TAGID_BRANCH, zMainBranch
  );
#endif
}

fsl_int_t fsl_count_nonbranch_children(fsl_cx * const f, fsl_id_t rid){
  int32_t rv = 0;
  fsl_db * const db = fsl_cx_db_repo(f);
  char const * zMainBranch = 0;
  int rc;
  if(!db || !db->dbh || (rid<=0)) return -1;
  rc = fsl_branch_main(f, &zMainBranch, false);
  if( 0==rc ){
    rc = fsl_db_get_int32(db, &rv,
                          "SELECT count(*) FROM {{dbname.repo}}.plink AS plink "
                          "WHERE pid=%"FSL_ID_T_PFMT" "
                          "AND isprim "
                          "AND coalesce((SELECT value FROM {{dbname.repo}}.tagxref "
                          "WHERE tagid=%d AND rid=plink.pid"
                          " AND tagtype>0), %Q)"
                          "=coalesce((SELECT value FROM {{dbname.repo}}.tagxref "
                          "WHERE tagid=%d AND rid=plink.cid"
                          " AND tagtype>0), %Q)",
                          rid, FSL_TAGID_BRANCH, zMainBranch,
                          FSL_TAGID_BRANCH, zMainBranch);
    if( rc ) fsl_cx_uplift_db_error2(f, db, rc);
  }
  return rc ? -2 : rv;
}

bool fsl_rid_is_leaf(fsl_cx * const f, fsl_id_t rid){
  if( rid<0 || !fsl_cx_db_repo(f) ) return false;
  fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_ridIsLeaf);
  bool rv = false;
  if( q ){
    char const * zMainBranch = 0;
    int rc = fsl_branch_main(f, &zMainBranch, false);
    if( 0==rc ){
      rc = fsl_stmt_bind_step_v2(q, "Rs", rid, zMainBranch);
      switch( rc ){
        case FSL_RC_STEP_DONE: rv = true; break;
        case FSL_RC_STEP_ROW: fsl_stmt_reset(q); break;
        default:
          fsl_cx_uplift_db_error2(f, q->db, rc);
          break;
      }
    }
    fsl__cx_stmt_yield(f, q);
  }
  return rv;
}

/** @internal

    Check to see if checkin "rid" is a leaf and either add it to the LEAF
    table if it is, or remove it if it is not.

    Returns 0 on success, FSL_RC_MISUSE if !f or f has no repo db
    opened, FSL_RC_RANGE if pid is <=0. Other errors
    (e.g. FSL_RC_DB) may indicate that db is not a repo. On error
    db's error state may be updated.
*/
static int fsl__leaf_check(fsl_cx * const f, fsl_id_t rid){
  if(rid<=0) return FSL_RC_RANGE;
  else {
    int rc = 0;
    bool isLeaf;
    fsl_cx_err_reset(f);
    isLeaf = fsl_rid_is_leaf(f, rid);
    if( f->error.code ){
      /* fsl_rid_is_leaf() failed. */
      return f->error.code;
    }
    fsl_stmt * const q = fsl__cx_stmt( f, isLeaf
                                       ? fsl__cx_stmt_e_leafInsert
                                       : fsl__cx_stmt_e_leafDelete );
    if( !q ) rc = f->error.code;
    else{
      rc = fsl_stmt_bind_step_v2(q, "R", rid);
      rc = (FSL_RC_STEP_DONE==rc)
        /* Reminder to self (2025-08-13): if we ever add (RETURNING
           rid) to leafInsert we'll need to handle FSL_RC_STEP_ROW
           here. */
        ? 0
        : fsl_cx_uplift_db_error2(f, q->db, rc);
      fsl__cx_stmt_yield(f, q);
    }
    return rc;
  }
}

int fsl__leaf_do_pending_checks(fsl_cx * const f){
  fsl_id_t rid;
  int rc = 0;
  fsl_id_bag * const bLeaf = fsl__cx_ptl_bag(f, fsl__ptl_e_leafCheck);
  for(rid=fsl_id_bag_first(bLeaf);
      !rc && rid; rid=fsl_id_bag_next(bLeaf,rid)){
    rc = fsl__leaf_check(f, rid);
  }
  fsl_id_bag_reuse(bLeaf);
  return rc;
}

int fsl__leaf_eventually_check( fsl_cx * const f, fsl_id_t rid){
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  if(!f) return FSL_RC_MISUSE;
  else if(rid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid rid %" FSL_ID_T_PFMT
                          " for a leaf check.", rid);
  }
  else if(!db){
    fsl_needs_repo(f);
    return FSL_RC_NOT_A_REPO;
  }
  else {
    fsl_id_bag * const bLeaf = fsl__cx_ptl_bag(f, fsl__ptl_e_leafCheck);
    fsl_stmt * q = fsl__cx_stmt(f, fsl__cx_stmt_e_parentsOf);
    int rc = q ? 0 : f->error.code;
    if( 0==rc ){
      assert( q );
      rc = fsl_stmt_bind_id(q, 1, rid);
      if( 0==rc ){
        rc = fsl_id_bag_insert(bLeaf, rid);
        while( !rc && (FSL_RC_STEP_ROW==(rc = fsl_stmt_step(q))) ){
          rc = fsl_id_bag_insert(bLeaf, fsl_stmt_g_id(q, 0));
        }
        if( FSL_RC_STEP_DONE==rc ) rc = 0;
      }
      if( rc ) rc = fsl_cx_uplift_db_error2(f, q->db, rc);
      fsl__cx_stmt_yield(f,q);
    }
    return rc;
  }
}


int fsl_leaves_compute(fsl_cx * const f, fsl_id_t vid,
                       fsl_leaves_compute_e closeMode){
  fsl_db * const db = fsl_needs_repo(f);
  if(!db) return FSL_RC_NOT_A_REPO;
  int rc = 0;

  /* Create the LEAVES table if it does not already exist.  Make sure
  ** it is empty.
  */
  rc = fsl_db_exec_multi(db,
    "CREATE TEMP TABLE IF NOT EXISTS {{temp.leaves}}("
    "  rid INTEGER PRIMARY KEY"
    ");"
    "DELETE FROM {{temp.leaves}};"
  );
  if(rc) goto dberr;
  if( vid <= 0 ){
    rc = fsl_db_exec_multi(db,
      "INSERT INTO {{temp.leaves}} SELECT leaf.rid FROM {{dbname.repo}}.leaf AS leaf"
    );
    if(rc) goto dberr;
  }else{
    fsl_id_bag seen = fsl_id_bag_empty;     /* Descendants seen */
    fsl_id_bag pending = fsl_id_bag_empty;  /* Unpropagated descendants */
    fsl_stmt q1 = fsl_stmt_empty;      /* Query to find children of a check-in */
    fsl_stmt isBr = fsl_stmt_empty;    /* Query to check if a check-in starts a new branch */
    fsl_stmt * const qIns = fsl__cx_stmt(f, fsl__cx_stmt_e_leavesInsert);
    char const * zMainBranch = 0;
    if( !qIns ){
      rc = f->error.code;
      goto end;
    }

    rc = fsl_branch_main(f, &zMainBranch, false);
    if( rc ) goto cleanup;

    /* Initialize the bags. */
    rc = fsl_id_bag_insert(&pending, vid);
    if(rc) goto cleanup;

    /* This query returns all non-branch-merge children of check-in
    ** RID (?1).
    **
    ** If a child is a merge of a fork within the same branch (?2), it
    ** is returned. Only merge children in different branches are
    ** excluded.
    */
    rc = fsl_db_prepare(db, &q1,
                        "SELECT cid FROM {{dbname.repo}}.plink AS plink"
                        " WHERE pid=?1"
                        " AND (isprim"
                        "      OR coalesce("
                        "(SELECT value FROM {{dbname.repo}}.tagxref"
                        " WHERE tagid=%d AND rid=plink.pid"
                        " AND tagtype>0), ?2"
                        ")=coalesce("
                        "(SELECT value FROM {{dbname.repo}}.tagxref"
                        "   WHERE tagid=%d AND rid=plink.cid"
                        " AND tagtype>0), ?2)"
                        ")",
                        FSL_TAGID_BRANCH, FSL_TAGID_BRANCH
    );
    if(rc) goto cleanup;
    /* This query returns a single row if check-in RID (?1) is the
    ** first check-in of a new branch. */
    rc = fsl_db_prepare(db, &isBr,
       "SELECT 1 FROM {{dbname.repo}}.tagxref"
       " WHERE rid=?1 AND tagid=%d AND tagtype=%d"
       "   AND srcid>0",
       FSL_TAGID_BRANCH, FSL_TAGTYPE_PROPAGATING
    );
    if(rc) goto cleanup;

    while( fsl_id_bag_count(&pending) ){
      fsl_id_t const rid = fsl_id_bag_first(&pending);
      unsigned cnt = 0;
      fsl_id_bag_remove(&pending, rid);
      rc = fsl_stmt_bind_fmt(&q1, "Rs", rid, zMainBranch);
      if( rc ) goto cleanup;
      while( FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q1)) ){
        fsl_id_t const cid = fsl_stmt_g_id(&q1, 0);
        rc = fsl_id_bag_insert(&seen, cid);
        if(rc) break;
        rc = fsl_id_bag_insert(&pending, cid);
        if(rc) break;
        fsl_stmt_bind_id(&isBr, 1, cid);
        if( FSL_RC_STEP_DONE==fsl_stmt_step(&isBr) ){
          ++cnt;
        }
        fsl_stmt_reset(&isBr);
      }
      if(FSL_RC_STEP_DONE==rc) rc = 0;
      else if(rc) break;
      fsl_stmt_reset(&q1);
      if( cnt==0 && !fsl_rid_is_leaf(f, rid) ){
        ++cnt;
      }
      if( cnt==0 ){
        fsl_stmt_bind_id(qIns, 1, rid);
        rc = fsl_stmt_step(qIns);
        if(FSL_RC_STEP_DONE!=rc) break;
        rc = 0;
        fsl_stmt_reset(qIns);
      }
    }
    cleanup:
    fsl__cx_stmt_yield(f,qIns);
    fsl_stmt_finalize(&isBr);
    fsl_stmt_finalize(&q1);
    fsl_id_bag_clear(&pending);
    fsl_id_bag_clear(&seen);
    if(rc) goto dberr;
  }
  assert(!rc);
  switch(closeMode){
    case FSL_LEAVES_COMPUTE_CLOSED:
    case FSL_LEAVES_COMPUTE_OPEN:
      rc =
        fsl_db_exec(db,
                    "DELETE FROM {{temp.leaves}} WHERE rid %s IN"
                    "  (SELECT leaves.rid FROM {{temp.leaves}} AS leaves, {{dbname.repo}}.tagxref AS tagxref"
                    "    WHERE tagxref.rid=leaves.rid "
                    "      AND tagxref.tagid=%d /*FSL_TAGID_CLOSED*/"
                    "      AND tagxref.tagtype>0)",
                    FSL_LEAVES_COMPUTE_CLOSED==closeMode ? "NOT " : "",
                    FSL_TAGID_CLOSED);
      if(rc) goto dberr;
      break;
    default: break;
  }

  end:
  return rc;
  dberr:
  assert(rc);
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  goto end;
}

bool fsl_leaves_computed_has(fsl_cx * const f){
  return fsl_db_exists(fsl_cx_db_repo(f),
                       "SELECT 1 FROM {{temp.leaves}}");
}

fsl_int_t fsl_leaves_computed_count(fsl_cx * const f){
  int32_t rv = -1;
  fsl_db * const db = fsl_cx_db_repo(f);
  int const rc = fsl_db_get_int32(db, &rv,
                                 "SELECT COUNT(*) FROM {{temp.leaves}}");
  if(rc){
    fsl_cx_uplift_db_error2(f, db, rc);
    assert(-1==rv);
  }else{
    assert(rv>=0);
  }
  return rv;
}

fsl_id_t fsl_leaves_computed_latest(fsl_cx * const f){
  fsl_id_t rv = 0;
  fsl_db * const db = fsl_cx_db_repo(f);
  int const rc =
    fsl_db_get_id(db, &rv,
                  "SELECT rid FROM {{temp.leaves}} AS leaves, {{dbname.repo}}.event AS event"
                  " WHERE event.objid=leaves.rid"
                  " ORDER BY event.mtime DESC");
  if(rc){
    fsl_cx_uplift_db_error2(f, db, rc);
    assert(!rv);
  }else{
    assert(rv>=0);
  }
  return rv;
}

void fsl_leaves_computed_cleanup(fsl_cx * const f){
  fsl__db_temp_drop(fsl_cx_db(f), "leaves");
}

#undef MARKER
/* end of file src/leaf.c */
/* start of file src/list.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/************************************************************************
  This file houses the implementations for the fsl_list routines.
*/

#include <assert.h>
#include <stdlib.h> /* malloc() and friends, qsort() */
#include <memory.h> /* memset() */
int fsl_list_reserve( fsl_list * const self, fsl_size_t n )
{
  if( !self ) return FSL_RC_MISUSE;
  else if(0 == n){
    if(0 == self->capacity) return 0;
    fsl_free(self->list);
    *self = fsl_list_empty;
    return 0;
  }
  else if( self->capacity >= n ){
    return 0;
  }
  else{
    if(n > (fsl_size_t)SIZE_MAX / sizeof(void*)){
      return FSL_RC_OOM;
    }
    fsl_size_t const sz = sizeof(void*) * n;
    void* * m = (void**)fsl_realloc( self->list, sz );
    if( !m ) return FSL_RC_OOM;
    memset( m + self->capacity, 0, (sizeof(void*)*(n-self->capacity)));
    self->capacity = n;
    self->list = m;
    return 0;
  }
}

void fsl_list_swap( fsl_list * const lhs, fsl_list * const rhs ){
  fsl_list tmp = *lhs;
  *lhs = *rhs;
  *rhs = tmp;
}

int fsl_list_append( fsl_list * const self, void* cp ){
  if( !self ) return FSL_RC_MISUSE;
  assert(self->used <= self->capacity);
  if(self->used == self->capacity){
    int rc;
    fsl_size_t const cap = self->capacity
      ? (self->capacity * 2)
      : 10;
    rc = fsl_list_reserve(self, cap);
    if(rc) return rc;
  }
  self->list[self->used++] = cp;
  if(self->used<self->capacity) self->list[self->used]=NULL;
  return 0;
}

int fsl_list_v_fsl_free(void * obj, void * visitorState fsl__unused){
  fsl_free( obj );
  (void)visitorState;
  return 0;
}

int fsl_list_clear( fsl_list * const self, fsl_list_visitor_f childFinalizer,
                    void * finalizerState ){
  /*
    TODO: manually traverse the list and set each list entry for which
    the finalizer succeeds to NULL, so that we can provide
    well-defined behaviour if childFinalizer() fails and we abort the
    loop.
   */
  int rc = fsl_list_visit(self, 0, childFinalizer, finalizerState );
  if(!rc) fsl_list_reserve(self, 0);
  return rc;
}

void fsl_list_visit_free( fsl_list * const self, bool freeListMem ){
  fsl_list_visit(self, 0, fsl_list_v_fsl_free, NULL );
  if(freeListMem) fsl_list_reserve(self, 0);
  else self->used = 0;
}


int fsl_list_visit( fsl_list const * self, int order,
                    fsl_list_visitor_f visitor,
                    void * visitorState ){
  int rc = FSL_RC_OK;
  if( self && self->used && visitor ){
    fsl_int_t i = 0;
    fsl_int_t pos = (order<0) ? self->used-1 : 0;
    fsl_int_t step = (order<0) ? -1 : 1;
    for( rc = 0; (i < (fsl_int_t)self->used)
           && (0 == rc); ++i, pos+=step ){
      void* obj = self->list[pos];
      if(obj) rc = visitor( obj, visitorState );
      if( obj != self->list[pos] ){
        --i;
        if(order>=0) pos -= step;
      }
    }
  }
  return rc;
}


int fsl_list_visit_p( fsl_list * const self, int order,
                      bool shiftIfNulled,
                      fsl_list_visitor_f visitor, void * visitorState )
{
  int rc = FSL_RC_OK;
  if( self && self->used && visitor ){
    fsl_int_t i = 0;
    fsl_int_t pos = (order<0) ? self->used-1 : 0;
    fsl_int_t step = (order<0) ? -1 : 1;
    for( rc = 0; (i < (fsl_int_t)self->used)
           && (0 == rc); ++i, pos+=step ){
      void* obj = self->list[pos];
      if(obj) {
        assert((order<0) && "TEST THAT THIS WORKS WITH IN-ORDER!");
        rc = visitor( &self->list[pos], visitorState );
        if( shiftIfNulled && !self->list[pos]){
          fsl_int_t x = pos;
          fsl_int_t const to = (fsl_int_t)self->used - 1;

          assert( to < (fsl_int_t) self->capacity );
          for( ; x < to; ++x ) self->list[x] = self->list[x+1];
          if( x < (fsl_int_t)self->capacity ) self->list[x] = 0;
          --i;
          --self->used;
          if(order>=0) pos -= step;
        }
      }
    }
  }
  return rc;
}

void fsl_list_sort( fsl_list * const li,
                    fsl_generic_cmp_f cmp){
  if(li && li->used>1){
    qsort( li->list, li->used, sizeof(void*), cmp );
  }
}



fsl_int_t fsl_list_index_of( fsl_list const * li,
                             void const * key,
                             fsl_generic_cmp_f cmpf ){
  fsl_size_t i;
  void const * p;
  for(i = 0; i < li->used; ++i){
    p = li->list[i];
    if(!p){
      if(!key) return (fsl_int_t)i;
      else continue;
    }else if((p==key) ||
            (0==cmpf( key, p )) ){
      return (fsl_int_t)i;
    }
  }
  return -1;
}


fsl_int_t fsl_list_index_of_cstr( fsl_list const * li,
                                  char const * key ){
  return fsl_list_index_of(li, key, fsl_strcmp_cmp);
}
/* end of file src/list.c */
/* start of file src/lookslike.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

#include <string.h> /* memcmp() */


/* definitions for various UTF-8 sequence lengths, encoded as start value
 * and size of each valid range belonging to some lead byte*/
#define US2A  0x80, 0x01 /* for lead byte 0xC0 */
#define US2B  0x80, 0x40 /* for lead bytes 0xC2-0xDF */
#define US3A  0xA0, 0x20 /* for lead byte 0xE0 */
#define US3B  0x80, 0x40 /* for lead bytes 0xE1-0xEF */
#define US4A  0x90, 0x30 /* for lead byte 0xF0 */
#define US4B  0x80, 0x40 /* for lead bytes 0xF1-0xF3 */
#define US4C  0x80, 0x10 /* for lead byte 0xF4 */
#define US0A  0x00, 0x00 /* for any other lead byte */

/* a table used for quick lookup of the definition that goes with a
 * particular lead byte */
static const unsigned char lb_tab[] = {
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US2A, US0A, US2B, US2B, US2B, US2B, US2B, US2B,
  US2B, US2B, US2B, US2B, US2B, US2B, US2B, US2B,
  US2B, US2B, US2B, US2B, US2B, US2B, US2B, US2B,
  US2B, US2B, US2B, US2B, US2B, US2B, US2B, US2B,
  US3A, US3B, US3B, US3B, US3B, US3B, US3B, US3B,
  US3B, US3B, US3B, US3B, US3B, US3B, US3B, US3B,
  US4A, US4B, US4B, US4B, US4C, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A
};

#undef US2A
#undef US2B
#undef US3A
#undef US3B
#undef US4A
#undef US4B
#undef US4C
#undef US0A

bool fsl_looks_like_binary(fsl_b const * const b){
  return (fsl_looks_like_utf8(b, FSL_LOOKSLIKE_BINARY) & FSL_LOOKSLIKE_BINARY)
    != FSL_LOOKSLIKE_NONE;
}

int fsl_looks_like_utf8(fsl_b const * const b, int stopFlags){
  fsl_size_t n = 0;
  const char *z = fsl_b_cstr2(b, &n);
  int j, c, flags = FSL_LOOKSLIKE_NONE;  /* Assume UTF-8 text, prove otherwise */

  if( n==0 ) return flags;  /* Empty file -> text */
  c = *z;
  if( c==0 ){
    flags |= FSL_LOOKSLIKE_NUL;  /* NUL character in a file -> binary */
  }else if( c=='\r' ){
    flags |= FSL_LOOKSLIKE_CR;
    if( n<=1 || z[1]!='\n' ){
      flags |= FSL_LOOKSLIKE_LONE_CR;  /* Not enough chars or next char not LF */
    }
  }
  j = (c!='\n');
  if( !j ) flags |= (FSL_LOOKSLIKE_LF | FSL_LOOKSLIKE_LONE_LF);  /* Found LF as first char */
  while( !(flags&stopFlags) && --n>0 ){
    int c2 = c;
    c = *++z; ++j;
    if( c==0 ){
      flags |= FSL_LOOKSLIKE_NUL;  /* NUL character in a file -> binary */
    }else if( c=='\n' ){
      flags |= FSL_LOOKSLIKE_LF;
      if( c2=='\r' ){
        flags |= (FSL_LOOKSLIKE_CR | FSL_LOOKSLIKE_CRLF);  /* Found LF preceded by CR */
      }else{
        flags |= FSL_LOOKSLIKE_LONE_LF;
      }
      if( j>FSL__LINE_LENGTH_MASK ){
        flags |= FSL_LOOKSLIKE_LONG;  /* Very long line -> binary */
      }
      j = 0;
    }else if( c=='\r' ){
      flags |= FSL_LOOKSLIKE_CR;
      if( n<=1 || z[1]!='\n' ){
        flags |= FSL_LOOKSLIKE_LONE_CR;  /* Not enough chars or next char not LF */
      }
    }
  }
  if( n ){
    flags |= FSL_LOOKSLIKE_SHORT;  /* The whole blob was not examined */
  }
  if( j>FSL__LINE_LENGTH_MASK ){
    flags |= FSL_LOOKSLIKE_LONG;  /* Very long line -> binary */
  }
  return flags;
}

unsigned char const *fsl_utf8_bom(unsigned int *pnByte){
  static const unsigned char bom[] = {
    0xef, 0xbb, 0xbf, 0x00, 0x00, 0x00
  };
  if( pnByte ) *pnByte = 3;
  return bom;
}

bool fsl_starts_with_bom_utf8(fsl_b const * const b,
                              unsigned int *pBomSize){
  unsigned int bomSize;
  const char * const z = fsl_b_cstr(b);
  const unsigned char * const bom = fsl_utf8_bom(&bomSize);
  if( pBomSize ) *pBomSize = bomSize;
  return fsl_b_size(b)<bomSize
    ? false
    : memcmp(z, bom, bomSize)==0;
}

bool fsl_b_has_bom(fsl_b const * const b){
  unsigned char const * const z = b->mem;
  fsl_size_t const n = b->used;
  if(n>=3 && z[0]==0xef && z[1]==0xbb && z[2]==0xbf) return true;
  return n>=2 && ((z[0]==0xff && z[1]==0xfe) || (z[0]==0xfe && z[1]==0xff));
}

/** Appends the UTF-8 encoding of c to the n bytes at z, returning the
    new byte count. */
static fsl_size_t fsl__utf8_put(unsigned char * z, fsl_size_t n,
                                unsigned int c){
  if(c<0x80){
    z[n++] = (unsigned char)c;
  }else if(c<0x800){
    z[n++] = (unsigned char)(0xc0 | (c>>6));
    z[n++] = (unsigned char)(0x80 | (c&0x3f));
  }else if(c<0x10000){
    z[n++] = (unsigned char)(0xe0 | (c>>12));
    z[n++] = (unsigned char)(0x80 | ((c>>6)&0x3f));
    z[n++] = (unsigned char)(0x80 | (c&0x3f));
  }else{
    z[n++] = (unsigned char)(0xf0 | (c>>18));
    z[n++] = (unsigned char)(0x80 | ((c>>12)&0x3f));
    z[n++] = (unsigned char)(0x80 | ((c>>6)&0x3f));
    z[n++] = (unsigned char)(0x80 | (c&0x3f));
  }
  return n;
}

int fsl_b_to_utf8_no_bom(fsl_b * const b){
  unsigned char const * const z = b->mem;
  fsl_size_t const n = b->used;
  if(n>=3 && z[0]==0xef && z[1]==0xbb && z[2]==0xbf){
    memmove(b->mem, b->mem+3, n-3);
    b->used = n-3;
    b->mem[b->used] = 0;
    return 0;
  }
  if(n>=2 && ((z[0]==0xff && z[1]==0xfe) || (z[0]==0xfe && z[1]==0xff))){
    bool const le = z[0]==0xff;
    fsl_b out = fsl_b_empty;
    fsl_size_t i, nOut = 0;
    /* Each 2-byte unit becomes at most 3 bytes; a 4-byte pair, 4. */
    int const rc = fsl_b_reserve(&out, n/2*3 + 1);
    if(rc) return rc;
    for(i=2; i+1<n; i+=2){
      unsigned int c = le ? (z[i] | (z[i+1]<<8)) : ((z[i]<<8) | z[i+1]);
      if(c>=0xd800 && c<=0xdbff && i+3<n){
        unsigned int const c2 = le
          ? (z[i+2] | (z[i+3]<<8)) : ((z[i+2]<<8) | z[i+3]);
        if(c2>=0xdc00 && c2<=0xdfff){
          c = 0x10000 + ((c-0xd800)<<10) + (c2-0xdc00);
          i += 2;
        }else{
          c = 0xfffd;
        }
      }else if(c>=0xd800 && c<=0xdfff){
        c = 0xfffd;
      }
      nOut = fsl__utf8_put(out.mem, nOut, c);
    }
    out.used = nOut;
    out.mem[nOut] = 0;
    fsl_b_swap(b, &out);
    fsl_b_clear(&out);
  }
  return 0;
}

bool fsl_invalid_utf8(fsl_b const * const b){
  fsl_size_t n = 0;
  const unsigned char *z = (unsigned char *) fsl_b_cstr2(b, &n);
  unsigned char c; /* lead byte to be handled. */
  if( n==0 ) return false;  /* Empty file -> OK */
  c = *z;
  while( --n>0 ){
    if( c>=0x80 ){
      const unsigned char *def; /* pointer to range table*/
      c <<= 1; /* multiply by 2 and get rid of highest bit */
      def = &lb_tab[c]; /* search fb's valid range in table */
      if( (unsigned int)(*++z-def[0])>=def[1] ){
        return true/*FSL_LOOKSLIKE_INVALID*/;
      }
      c = (c>=0xC0) ? (c|3) : ' '; /* determine next lead byte */
    } else {
      c = *++z;
    }
  }
  return c>=0x80 /* Final lead byte must be ASCII. */;
}
/* end of file src/lookslike.c */
/* start of file src/md5.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
   The code is modified for use in fossil (then libfossil).  The
   original header comment follows:
*/
/*
 * This code implements the MD5 message-digest algorithm.
 * The algorithm is due to Ron Rivest.  This code was
 * written by Colin Plumb in 1993, no copyright is claimed.
 * This code is in the public domain; do with it what you wish.
 *
 * Equivalent code is available from RSA Data Security, Inc.
 * This code has been tested against that, and is equivalent,
 * except that you don't need to include two pages of legalese
 * with every copy.
 *
 * To compute the message digest of a chunk of bytes, declare an
 * MD5Context structure, pass it to MD5Init, call MD5Update as
 * needed on buffers full of bytes, and then call MD5Final, which
 * will fill a supplied 16-byte array with the digest.
 */
#include <string.h>
#include <stdio.h>
#include <errno.h>

#if defined(__i386__) || defined(__x86_64__) || defined(_WIN32)
# define byteReverse(A,B)
#else
/*
 * Convert an array of integers to little-endian.
 * Note: this code is a no-op on little-endian machines.
 */
static void byteReverse (unsigned char *buf, unsigned longs){
    uint32_t t;
    do {
        t = (uint32_t)((unsigned)buf[3]<<8 | buf[2]) << 16 |
            ((unsigned)buf[1]<<8 | buf[0]);
        memcpy(buf, &t, 4);
        buf += 4;
    } while (--longs);
}
#endif

/* The four core functions - F1 is optimized somewhat */

/* #define F1(x, y, z) (x & y | ~x & z) */
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))

/* This is the central step in the MD5 algorithm. */
#define MD5STEP(f, w, x, y, z, data, s)                         \
    ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )

/*
 * The core of the MD5 algorithm, this alters an existing MD5 hash to
 * reflect the addition of 16 longwords of new data.  MD5Update blocks
 * the data and converts bytes into longwords for this routine.
 */
static void MD5Transform(uint32_t buf[4], const unsigned char inBytes[64]){
    register uint32_t a, b, c, d;
    uint32_t in[16];

    memcpy(in, inBytes, 64);
    a = buf[0];
    b = buf[1];
    c = buf[2];
    d = buf[3];

    MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
    MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
    MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
    MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
    MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
    MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
    MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
    MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
    MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
    MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
    MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
    MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
    MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
    MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
    MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
    MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);

    MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
    MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
    MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
    MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
    MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
    MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
    MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
    MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
    MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
    MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
    MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
    MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
    MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
    MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
    MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
    MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);

    MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
    MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
    MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
    MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
    MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
    MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
    MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
    MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
    MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
    MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
    MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
    MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
    MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
    MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
    MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
    MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);

    MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
    MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
    MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
    MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
    MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
    MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
    MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
    MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
    MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
    MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
    MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
    MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
    MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
    MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
    MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
    MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);

    buf[0] += a;
    buf[1] += b;
    buf[2] += c;
    buf[3] += d;
}

const fsl_md5_cx fsl_md5_cx_empty = fsl_md5_cx_empty_m;
/*
 * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
 * initialization constants.
 */
void fsl_md5_init(fsl_md5_cx *ctx){
    *ctx = fsl_md5_cx_empty;
}

/*
 * Update context to reflect the concatenation of another buffer full
 * of bytes.
 */
void fsl_md5_update(fsl_md5_cx *ctx, void const * buf_, fsl_size_t len){
  const unsigned char * buf = (const unsigned char *)buf_;
  uint32_t t;

  /* Update bitcount */

  t = ctx->bits[0];
  if ((ctx->bits[0] = t + ((uint32_t)len << 3)) < t)
    ctx->bits[1]++; /* Carry from low to high */
  ctx->bits[1] += len >> 29;

  t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */

  /* Handle any leading odd-sized chunks */

  if ( t ) {
    unsigned char *p = (unsigned char *)ctx->in + t;

    t = 64-t;
    if (len < t) {
      memcpy(p, buf, len);
      return;
    }
    memcpy(p, buf, t);
    byteReverse(ctx->in, 16);
    MD5Transform(ctx->buf, ctx->in);
    buf += t;
    len -= t;
  }

  /* Process data in 64-byte chunks */

  while (len >= 64) {
    memcpy(ctx->in, buf, 64);
    byteReverse(ctx->in, 16);
    MD5Transform(ctx->buf, ctx->in);
    buf += 64;
    len -= 64;
  }

  /* Handle any remaining bytes of data. */

  memcpy(ctx->in, buf, len);
}

/*
 * Final wrapup - pad to 64-byte boundary with the bit pattern
 * 1 0* (64-bit count of bits processed, MSB-first)
 */
void fsl_md5_final(fsl_md5_cx * ctx, unsigned char * digest){
  unsigned count;
  unsigned char *p;

  /* Compute number of bytes mod 64 */
  count = (ctx->bits[0] >> 3) & 0x3F;

  /* Set the first char of padding to 0x80.  This is safe since there is
     always at least one byte free */
  p = ctx->in + count;
  *p++ = 0x80;

  /* Bytes of padding needed to make 64 bytes */
  count = 64 - 1 - count;

  /* Pad out to 56 mod 64 */
  if (count < 8) {
    /* Two lots of padding:  Pad the first block to 64 bytes */
    memset(p, 0, count);
    byteReverse(ctx->in, 16);
    MD5Transform(ctx->buf, ctx->in);

    /* Now fill the next block with 56 bytes */
    memset(ctx->in, 0, 56);
  } else {
    /* Pad block to 56 bytes */
    memset(p, 0, count-8);
  }
  byteReverse(ctx->in, 14);

  /* Append length in bits and transform */
  memcpy(&ctx->in[14*sizeof(uint32_t)], ctx->bits, 2*sizeof(uint32_t));

  MD5Transform(ctx->buf, ctx->in);
  byteReverse((unsigned char *)ctx->buf, 4);
  memcpy(digest, ctx->buf, 16);
  memset(ctx, 0, sizeof(*ctx));    /* In case it's sensitive */
}

void fsl_md5_digest_to_base16(unsigned char const *digest, char *zBuf){
  static char const zEncode[] = "0123456789abcdef";
  fsl_size_t i, j;
  for(j=i=0; i<16; i++){
    zBuf[j++] = zEncode[(*digest>>4)&0xf];
    zBuf[j++] = zEncode[*digest++ & 0xf];
  }
  zBuf[j] = 0;
}

#if 0
/* The symlink-hashing code here may be needed at some point... */
int fsl_md5sum_file(const char *zFilename, fsl_b *pCksum){
  if(!zFilename || !pCksum) return FSL_RC_MISUSE;
  else{
    /* Requires v1 code which has not yet been ported in. */
    FILE *in;
    fsl_md5_cx ctx;
    unsigned char zResult[20];
    char zBuf[10240];

    if( fsl_wd_islink(zFilename) ){
      /* Instead of file content, return md5 of link destination path */
      Blob destinationPath;
      int rc;
      blob_read_link(&destinationPath, zFilename);
      rc = sha1sum_blob(&destinationPath, pCksum);
      blob_reset(&destinationPath);
      return rc;
    }

    in = fossil_fopen(zFilename,"rb");
    if( in==0 ){
      return 1;
    }
    fsl_sha1_init(&ctx);
    for(;;){
      int n;
      n = fread(zBuf, 1, sizeof(zBuf), in);
      if( n<=0 ) break;
      fsl_sha1_update(&ctx, (unsigned char*)zBuf, (unsigned)n);
    }
    fsl_fclose(in);
    blob_zero(pCksum);
    blob_resize(pCksum, 40);
    fsl_sha1_final(&ctx, zResult);
    fsl_sha1_digest_to_base16(zResult, blob_buffer(pCksum));
    return 0;
  }
}
#endif

int fsl_md5sum_buffer(fsl_b const *pIn, fsl_b *pCksum){
  if(!pIn || !pCksum) return FSL_RC_MISUSE;
  else{
    fsl_md5_cx ctx = fsl_md5_cx_empty;
    unsigned char zResult[20];
    int rc;
    fsl_md5_update(&ctx, pIn->mem, pIn->used);
    fsl_b_reuse(pCksum);
    rc = fsl_b_resize(pCksum, FSL_STRLEN_MD5/*resize() adds 1 for NUL*/);
    if(!rc){
      fsl_md5_final(&ctx, zResult);
      fsl_md5_digest_to_base16(zResult, fsl_b_str(pCksum));
    }
    return rc;
  }
}

char *fsl_md5sum_cstr(const char *zIn, fsl_int_t len){
  if(!zIn || !len) return NULL;
  else{
    fsl_md5_cx ctx;
    unsigned char zResult[20];
    char * zDigest = (char *)fsl_malloc(FSL_STRLEN_MD5+1);
    if(!zDigest) return NULL;
    fsl_md5_init(&ctx);
    fsl_md5_update(&ctx, zIn,
                   (len<0) ? fsl_strlen(zIn) : (fsl_size_t)len);
    fsl_md5_final(&ctx, zResult);
    fsl_md5_digest_to_base16(zResult, zDigest);
    return zDigest;
  }
}

int fsl_md5sum_stream(fsl_input_f src, void * srcState, fsl_b *pCksum){
  fsl_md5_cx ctx;
  int rc;
  unsigned char zResult[20];
  enum { BufSize = 1024 * 4 };
  unsigned char zBuf[BufSize];
  if(!src || !pCksum) return FSL_RC_MISUSE;
  fsl_md5_init(&ctx);
  for(;;){
    fsl_size_t read = (fsl_size_t)BufSize;
    rc = src(srcState, zBuf, &read);
    if(rc) return rc;
    else if(read) fsl_md5_update(&ctx, (unsigned char*)zBuf, read);
    if(read < (fsl_size_t)BufSize) break;
  }
  fsl_b_reuse(pCksum);
  rc = fsl_b_resize(pCksum, FSL_STRLEN_MD5);
  if(!rc){
    fsl_md5_final(&ctx, zResult);
    fsl_md5_digest_to_base16(zResult, fsl_b_str(pCksum));
  }
  return rc;
}



#if 0
void fsl_md5_to_base16(fsl_md5_cx const * cx, char *zBuf){
  static char const zEncode[] = "0123456789abcdef";
  int i, j;

  for(j=i=0; i<16; i++){
    int a = digest[i];
    zBuf[j++] = zEncode[(a>>4)&0xf];
    zBuf[j++] = zEncode[a & 0xf];
  }
  zBuf[j] = 0;
}
#endif


#if 0
/*
  Add the content of a blob to the incremental MD5 checksum.
*/
void md5sum_step_blob(Blob *p){
  md5sum_step_text(blob_buffer(p), blob_size(p));
}
#endif

int fsl_md5sum_filename(const char *zFilename, fsl_b *pCksum){
  if(!zFilename || !pCksum) return FSL_RC_MISUSE;
  else{
    int rc;
    FILE *in = fsl_fopen(zFilename, "rb");
    if(!in) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
    else{
      rc = fsl_md5sum_stream(fsl_input_f_FILE, in, pCksum);
      fsl_fclose(in);
    }
    return rc;
  }
}

void fsl_md5_update_buffer(fsl_md5_cx *cx, fsl_b const * b){
  if(b->used) fsl_md5_update(cx, b->mem, b->used);
}

void fsl_md5_update_cstr(fsl_md5_cx *cx, char const * str, fsl_int_t len){
  if(len<0) len = fsl_strlen(str);
  if(len>0) fsl_md5_update(cx, str, (fsl_size_t)len);
}

int fsl_md5_update_stream(fsl_md5_cx *ctx,
                          fsl_input_f src, void * srcState){
  int rc;
  enum { BufSize = 1024 * 4 };
  unsigned char zBuf[BufSize];
  if(!ctx || !src) return FSL_RC_MISUSE;
  for(;;){
    fsl_size_t read = (fsl_size_t)BufSize;
    rc = src(srcState, zBuf, &read);
    if(rc) return rc;
    else if(read) fsl_md5_update(ctx, (unsigned char*)zBuf, read);
    if(read < (fsl_size_t)BufSize) break;
  }
  return 0;
}

int fsl_md5_update_filename(fsl_md5_cx *cx, char const * fname){
  if(!cx || !fname) return FSL_RC_MISUSE;
  else{
    int rc;
    FILE *in = fsl_fopen(fname, "rb");
    if(!in) rc = fsl_errno_to_rc(errno,FSL_RC_IO);
    else {
      rc = fsl_md5_update_stream(cx, fsl_input_f_FILE, in);
      fsl_fclose(in);
    }
    return rc;
  }
}


#undef F1
#undef F2
#undef F3
#undef F4
#undef MD5STEP
#undef byteReverse
/* end of file src/md5.c */
/* start of file src/merge.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
#include <assert.h>
#include <memory.h>
#include <stdlib.h>
#include <string.h> /* memmove()/strlen() */

#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

/* TEMP tables, as {{temp.NAME}} placeholders: their names are a
   context's own (see fsl__db_schema_token()). */
#define FSL__TABLE_PIVOT "{{temp.aqueue}}"

/**
   Sets the primary version of a merge.  The primary version is
   one of the two files that have a common ancestor.  The other file
   is the secondary.  There can be multiple secondaries but only a
   single primary.  The primary must be set first.

   In the merge algorithm, the file being merged in is the primary.
   The current check-out or other files that have been merged into
   the current checkout are the secondaries.

   The act of setting the primary resets the pivot-finding algorithm.

   Returns 0 on success, non-0 on serious error.

   This works using a TEMP db, so does not strictly require
   a repo or checkout.

   @see fsl__pivot_add_secondary()
   @see fsl__pivot_find()
*/
static int fsl__pivot_set_primary(fsl_cx * const f, fsl_id_t rid){
  /* Set up table used to do the search */
  int rc = fsl_cx_exec_multi(f,
    "CREATE TEMP TABLE IF NOT EXISTS " FSL__TABLE_PIVOT "("
    "  rid INTEGER,"              /* The record id for this version */
    "  mtime REAL,"               /* Time when this version was created */
    "  pending BOOLEAN,"          /* True if we have not check this one yet */
    "  src BOOLEAN,"              /* 1 for primary.  0 for others */
    "  PRIMARY KEY(rid,src)"
    ") WITHOUT ROWID;"
    "DELETE FROM " FSL__TABLE_PIVOT ";"
    "CREATE INDEX IF NOT EXISTS {{temp.aqueue_idx1}}"
    " ON {{bare.temp.aqueue}}(pending, mtime);"
  );
  if(0==rc){
    /* Insert the primary record */
    rc = fsl_cx_exec(f,
      "INSERT INTO " FSL__TABLE_PIVOT "(rid, mtime, pending, src)"
      "  SELECT %" FSL_ID_T_PFMT ", mtime, 1, 1 "
      "  FROM {{dbname.repo}}.event WHERE objid=%" FSL_ID_T_PFMT
      " AND type='ci' LIMIT 1",
      rid, rid );
  }
  return rc;
}

/**
   Set a secondary file of a merge. The primary file must be set
   first. There must be at least one secondary but there can be more
   than one if desired.

   Returns 0 on success, non-0 on db error.

   @see fsl__pivot_set_primary()
   @see fsl__pivot_find()
*/
static int fsl__pivot_add_secondary(fsl_cx * const f, fsl_id_t rid){
  return fsl_cx_exec(f,
    "INSERT OR IGNORE INTO " FSL__TABLE_PIVOT "(rid, mtime, pending, src)"
    "  SELECT %" FSL_ID_T_PFMT ", mtime, 1, 0 "
    "FROM {{dbname.repo}}.event WHERE objid=%" FSL_ID_T_PFMT " AND type='ci'",
    rid, rid
  );
}


/**
   Searches for the most recent common ancestor of the primary and one of
   the secondaries in a merge.

   On success, *outRid is set to its value and 0 is returned. If no
   match is found, *outRid is set to 0 and 0 is returned. Returns
   non-0 on error, indicating either a lower-level db error or an
   allocation error.

   If ignoreMerges is true, it follows only "primary" parent links.

   @see fsl__pivot_set_primary()
   @see fsl__pivot_add_secondary()
*/
static int fsl__pivot_find(fsl_cx * const f, bool ignoreMerges, fsl_id_t *outRid){
  fsl_db * const db = fsl_cx_db(f);
  int rc;
  fsl_stmt q1 = fsl_stmt_empty, q2 = fsl_stmt_empty,
    u1 = fsl_stmt_empty, i1 = fsl_stmt_empty;
  fsl_id_t rid = 0;
  if(fsl_db_g_int32(db, 0, "SELECT COUNT(distinct src) FROM " FSL__TABLE_PIVOT "")<2){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Pivot list [aqueue] lacks either a "
                          "primary or a secondary entry.");
  }
  /* Prepare queries we will be needing
  **
  ** The first query finds the oldest pending version on the
  ** FSL__TABLE_PIVOT. This will be next one searched.
  */
  rc = fsl_cx_prepare(f, &q1,
                      "SELECT rid FROM " FSL__TABLE_PIVOT " WHERE pending"
                      " ORDER BY pending DESC, mtime DESC");
  if(rc) goto end;

  /* Check to see if the record :rid is a common ancestor.  The result
  ** set contains one or more rows if it is and is the empty set if it
  ** is not.
  */
  rc = fsl_cx_prepare(f, &q2,
    "SELECT 1 FROM " FSL__TABLE_PIVOT " A, {{dbname.repo}}.plink AS plink, " FSL__TABLE_PIVOT " B"
    " WHERE plink.pid=?1"
    "   AND plink.cid=B.rid"
    "   AND A.rid=?1"
    "   AND A.src!=B.src %s",
    ignoreMerges ? "AND plink.isprim" : ""
  );
  if(rc) goto end;

  /* Mark the :rid record has having been checked.  It is not the
  ** common ancestor.
  */
  rc = fsl_cx_prepare(f, &u1,
    "UPDATE " FSL__TABLE_PIVOT " SET pending=0 WHERE rid=?1"
  );
  if(rc) goto end;

  /* Add to the queue all ancestors of :rid.
  */
  rc = fsl_cx_prepare(f, &i1,
    "REPLACE INTO " FSL__TABLE_PIVOT " "
    "SELECT plink.pid,"
    " coalesce((SELECT mtime FROM {{dbname.repo}}.event X WHERE X.objid=plink.pid), 0.0),"
    " 1,"
    " " FSL__TABLE_PIVOT ".src "
    "  FROM {{dbname.repo}}.plink AS plink, " FSL__TABLE_PIVOT
    " WHERE plink.cid=?1"
    "   AND " FSL__TABLE_PIVOT ".rid=?1 %s",
    ignoreMerges ? "AND plink.isprim" : ""
  );
  if(rc) goto end;
  while(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q1))){
    rid = fsl_stmt_g_id(&q1, 0);
    fsl_stmt_reset(&q1);
    rc = fsl_stmt_bind_step(&q2, "R", rid);
    if(rc) break/*error or found match*/;
    rc = fsl_stmt_bind_step(&i1, "R", rid);
    assert(FSL_RC_STEP_ROW!=rc);
    if(0==rc) rc = fsl_stmt_bind_step(&u1, "R", rid);
    if(rc) break;
    assert(FSL_RC_STEP_ROW!=rc);
    rid = 0;
  }
  switch(rc){
    case 0: break;
    case FSL_RC_STEP_ROW:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default:
      rc = fsl_cx_uplift_db_error2(f, NULL, rc);
      break;
  }
  end:
  fsl_stmt_finalize(&q1);
  fsl_stmt_finalize(&q2);
  fsl_stmt_finalize(&u1);
  fsl_stmt_finalize(&i1);
  if(0==rc  && rid) *outRid = rid;
  return rc;
}

#if 0
// not currently used anywhere in libfossil.
/**
   Searches f's current repository for the nearest fork related to
   version vid.

   More specifically: this looks for the most recent leaf that is (1)
   not equal to vid and (2) has not already been merged into vid and
   (3) the leaf is not closed and (4) the leaf is in the same branch
   as vid.

   If checkVmerge is true then the current checkout
   database is also checked (via the vmerge table), in which case a
   checkout must be opened.

   On success, returns 0 and assigns *outRid to the resulting RID.

   On error:

   - FSL_RC_NOT_A_REPO or FSL_RC_NOT_A_CKOUT if called when no repo or
     (if checkVmerge is true) no checkout.

   - FSL_RC_NOT_FOUND: no closest merge was found.

   - FSL_RC_OOM: on allocation error

   - Any number of potential other errors from the db layer.

   f's error state will contain more information about errors reported
   here.
*/
static int fsl__find_nearest_fork(fsl_cx * const f,
                                  fsl_id_t vid, bool checkVmerge,
                                  fsl_id_t * outRid){
  fsl_db * const db = checkVmerge
    ? fsl_needs_ckout(f) : fsl_needs_repo(f);
  fsl_b * const sql = fsl__cx_scratchpad(f);
  fsl_stmt q;
  if(!db){
    return checkVmerge ? FSL_RC_NOT_A_CKOUT : FSL_RC_NOT_A_REPO;
  }
  q = fsl_stmt_empty;
  int rc = fsl__db_appendf(db, sql,
    "SELECT leaf.rid"
    "  FROM {{dbname.repo}}.leaf AS leaf, {{dbname.repo}}.event AS event"
    " WHERE leaf.rid=event.objid"
    "   AND leaf.rid!=%" FSL_ID_T_PFMT,  /* Constraint (1) */
    vid
  );
  if(rc) goto end;
  if( checkVmerge ){
    rc = fsl__db_appendf(db, sql,
      "   AND leaf.rid NOT IN (SELECT merge FROM {{dbname.ckout}}.vmerge)"
      /* Constraint (2) */ );
    if(rc) goto end;
  }
  rc = fsl__db_appendf(db, sql,
    "   AND NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.tagxref" /* Constraint (3) */
                  "     WHERE rid=leaf.rid"
                  "       AND tagid=%d"
                  "       AND tagtype>0)"
    "   AND (SELECT value FROM {{dbname.repo}}.tagxref"      /* Constraint (4) */
          "  WHERE tagid=%d AND rid=%" FSL_ID_T_PFMT " AND tagtype>0) ="
          " (SELECT value FROM {{dbname.repo}}.tagxref"
          "  WHERE tagid=%d AND rid=leaf.rid AND tagtype>0)"
    " ORDER BY event.mtime DESC LIMIT 1",
                         FSL_TAGID_CLOSED,
                         FSL_TAGID_BRANCH,
                         vid, FSL_TAGID_BRANCH
  );
  if(rc) goto end;
  rc = fsl_db_prepare(db, &q, "%b", sql);
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, db, rc);
    goto end;
  }
  rc = fsl_stmt_step(&q);
  switch(rc){
    case FSL_RC_STEP_ROW:
      rc = 0;
      *outRid = fsl_stmt_g_id(&q, 0);
      assert(*outRid>0);
      break;
    case FSL_RC_STEP_DONE:
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Cannot find nearest fork of RID #%"
                          FSL_ID_T_PFMT ".", vid);
      break;
    default:
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      break;
  }
  end:
  fsl_stmt_finalize(&q);
  fsl__cx_scratchpad_yield(f, sql);
  return rc;
}
#endif /* fsl__find_nearest_fork() */

/**
   Name for the merge algo's version of the fv table, noting that it
   differs enough from the update algo's version that they do not
   map 1-to-1 without some degree of pain which might make sense
   once merge is in the library and working.
*/
#define FSL__TABLE_FVM "{{temp.fvm}}"

static int fsl__renames_init(fsl_cx * const f){
  char const * const coll = fsl_cx_filename_collation(f);
  return fsl_cx_exec_multi(f,
    "CREATE TEMP TABLE IF NOT EXISTS " FSL__TABLE_FVM "(\n"
    "  fn TEXT UNIQUE %s,\n"       /* The filename */
    "  idv INTEGER DEFAULT 0,\n"   /* VFILE entry for current version */
    "  idp INTEGER DEFAULT 0,\n"   /* VFILE entry for the pivot */
    "  idm INTEGER DEFAULT 0,\n"   /* VFILE entry for version merging in */
    "  chnged BOOLEAN,\n"          /* True if current version has been edited */
    "  ridv INTEGER DEFAULT 0,\n"  /* Record ID for current version */
    "  ridp INTEGER DEFAULT 0,\n"  /* Record ID for pivot */
    "  ridm INTEGER DEFAULT 0,\n"  /* Record ID for merge */
    "  isexe BOOLEAN,\n"           /* Execute permission enabled */
    "  fnp TEXT UNIQUE %s,\n"      /* The filename in the pivot */
    "  fnm TEXT UNIQUE %s,\n"      /* The filename in the merged version */
    "  fnn TEXT UNIQUE %s,\n"      /* The filename in the name pivot */
    "  islinkv BOOLEAN,\n"         /* True if current version is a symlink */
    "  islinkm BOOLEAN\n"          /* True if merged version in is a symlink */
    ");"
    "DELETE FROM " FSL__TABLE_FVM ";",
    coll, coll, coll, coll);
}

static int fsl__renames_finalize(fsl_cx * const f){
  return fsl_cx_exec(f,
                     //"DROP TABLE IF EXISTS " FSL__TABLE_FVM
                     "DELETE FROM " FSL__TABLE_FVM);
}

static int fsl__renames_add(fsl_cx * const f,
                            char const * zFnCol,
                            fsl_id_t vid, fsl_id_t nid,
                            bool reverseOk){
  int rc;
  uint32_t i; /* loop counter */
  uint32_t nChng; /* # of entries in aChng */
  fsl_id_t * aChng = 0; /* Array of filename changes */
  fsl_stmt q1 = fsl_stmt_empty, q2 = fsl_stmt_empty;
  fsl_db * const db = fsl_cx_db_repo(f);
  rc = fsl__find_filename_changes(f, nid, vid, reverseOk, &nChng, &aChng);
  if(rc) goto end;
  else if(0==nChng) return 0;
  rc = fsl_cx_prepare(f, &q1,
                      "SELECT name FROM {{dbname.repo}}.filename WHERE fnid=?1");
  if(0==rc){
    rc = fsl_cx_prepare(f, &q2,
                        "SELECT name FROM {{dbname.repo}}.filename WHERE fnid=?1");
  }
  for(i=0; 0==rc && i < nChng; ++i){
    char const *zN;
    char const *zV;
    rc = fsl_stmt_bind_step(&q1, "R", aChng[i*2]);
    if(FSL_RC_STEP_ROW==rc){
      rc = fsl_stmt_bind_step(&q2, "R", aChng[i*2+1]);
      if(FSL_RC_STEP_ROW==rc) rc = 0;
    }
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, NULL, rc);
      break;
    }
    rc = fsl_stmt_get_text(&q1, 0, &zN, NULL);
    if(0==rc) rc = fsl_stmt_get_text(&q2, 0, &zV, NULL);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      break;
    }
    rc = fsl_cx_exec(f,"INSERT OR IGNORE INTO " FSL__TABLE_FVM
                     "(%s,fnn) VALUES(%Q,%Q)",
                     zFnCol, zV, zN);
    if(0==rc && 0==fsl_db_changes_recent(db)){
      rc = fsl_cx_exec_multi(f, "UPDATE " FSL__TABLE_FVM
                             " SET %s=%Q WHERE fnn=%Q",
                             zFnCol, zV, zN);
    }
  }
  end:
  fsl_stmt_finalize(&q1);
  fsl_stmt_finalize(&q2);
  fsl_free(aChng);
  return rc;
}

/**
   Part of fsl_ckout_merge() related to collecting filenames and
   setting up renames. Returns 0 on success.
*/
static int fsl__renames_tweak(fsl_cx * const f, fsl_id_t mid,
                              fsl_id_t pid, fsl_id_t vid,
                              fsl_id_t nid,
                              fsl_merge_opt const * const mOpt){
  int rc = 0;
  char vAncestor = 'p'; /* If P is an ancestor of V then 'p', else 'n' */

  rc = fsl__renames_init(f);
  if(0==rc) rc = fsl__renames_add(f, "fn", vid, nid, false);
  if(0==rc) rc = fsl__renames_add(f, "fnp", pid, nid, false);
  if(0==rc) rc = fsl__renames_add(f, "fnm", mid, nid,
                                  FSL_MERGE_TYPE_BACKOUT==mOpt->mergeType);
  /*
    It goes without saying that all of the SQL wizardry which follows
    was implemented by D. Richard Hipp. Its usage here does not imply
    any real understanding of it on the fossil-to-libfossil porter's
    part.
  */
  if(rc) goto end;
  else if(nid!=pid){
    /* See forum thread https://fossil-scm.org/forum/forumpost/549700437b
    **
    ** If a filename changes between nid and one of the other check-ins
    ** pid, vid, or mid, then it might not have changed for all of them.
    ** try to fill in the appropriate filename in all slots where the
    ** name is missing.
    **
    ** This does not work if
    **   (1) The filename changes more than once in between nid and vid/mid
    **   (2) Two or more filenames swap places - for example if A is renamed
    **       to B and B is renamed to A.
    ** The Fossil merge algorithm breaks down in those cases.  It will need
    ** to be completely rewritten to handle such complex cases.  Such cases
    ** appear to be rare, and also confusing to humans.
    */
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fnp=vfile.pathname FROM {{dbname.ckout}}.vfile AS vfile"
      " WHERE fnp IS NULL"
      " AND vfile.pathname = " FSL__TABLE_FVM ".fnn"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      pid
    );
    if(rc) goto end;
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fn=vfile.pathname FROM {{dbname.ckout}}.vfile AS vfile"
      " WHERE fn IS NULL"
      " AND vfile.pathname = "
      "   coalesce(" FSL__TABLE_FVM ".fnp," FSL__TABLE_FVM ".fnn)"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      vid
    );
    if(rc) goto end;
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fnm=vfile.pathname FROM {{dbname.ckout}}.vfile AS vfile"
      " WHERE fnm IS NULL"
      " AND vfile.pathname ="
      "  coalesce(" FSL__TABLE_FVM ".fnp," FSL__TABLE_FVM ".fnn)"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      mid
    );
    if(rc) goto end;
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fnp=vfile.pathname FROM {{dbname.ckout}}.vfile AS vfile"
      " WHERE fnp IS NULL"
      " AND vfile.pathname"
      "   IN (" FSL__TABLE_FVM ".fnm," FSL__TABLE_FVM ".fn)"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      pid
    );
    if(rc) goto end;
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fn=vfile.pathname FROM {{dbname.ckout}}.vfile AS vfile"
      " WHERE fn IS NULL"
      " AND vfile.pathname = " FSL__TABLE_FVM ".fnm"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      vid
    );
    if(rc) goto end;
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fnm=vfile.pathname FROM {{dbname.ckout}}.vfile AS vfile"
      " WHERE fnm IS NULL"
      " AND vfile.pathname = " FSL__TABLE_FVM ".fn"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      mid
    );
    if(rc) goto end;
  }
  assert(0==rc);
  if(mOpt->baselineRid>0){
    fsl_db * const db = fsl_cx_db_repo(f);
    fsl_db_err_reset(db);
    vAncestor = fsl_db_exists(db,
      "WITH RECURSIVE ancestor(id) AS ("
      "  VALUES(%" FSL_ID_T_PFMT ")"
      "  UNION"
      "  SELECT pid FROM {{dbname.repo}}.plink, ancestor"
      "   WHERE cid=ancestor.id"
      "   AND pid!=%" FSL_ID_T_PFMT
      "   AND cid!=%" FSL_ID_T_PFMT ")"
      "SELECT 1 FROM ancestor"
      "  WHERE id=%" FSL_ID_T_PFMT " LIMIT 1",
      vid, nid, pid, pid
    ) ? 'p' : 'n';
    assert(0==fsl_db_err_get(db, NULL, NULL));
  }

  /*
  ** Add files found in V
  */
  rc = fsl_cx_exec_multi(f,
    "UPDATE OR IGNORE " FSL__TABLE_FVM
    " SET fn=coalesce(fn%c,fnn) WHERE fn IS NULL;"
    "REPLACE INTO "
    FSL__TABLE_FVM "(fn,fnp,fnm,fnn,idv,ridv,islinkv,isexe,chnged)"
    " SELECT pathname, fnp, fnm, fnn, id, rid, islink, vf.isexe, vf.chnged"
    "   FROM {{dbname.ckout}}.vfile vf"
    "   LEFT JOIN " FSL__TABLE_FVM " ON fn=coalesce(origname,pathname)"
    "    AND rid>0 AND vf.chnged NOT IN (3,5)"
    "  WHERE vid=%" FSL_ID_T_PFMT ";",
    vAncestor, vid
  );
  if(rc) goto end;
  /*
  ** Add files found in P
  */
  rc = fsl_cx_exec_multi(f,
    "UPDATE OR IGNORE " FSL__TABLE_FVM " SET fnp=coalesce(fnn,"
    "   (SELECT coalesce(origname,pathname) FROM {{dbname.ckout}}.vfile WHERE id=idv))"
    " WHERE fnp IS NULL;"
    "INSERT OR IGNORE INTO " FSL__TABLE_FVM "(fnp)"
    " SELECT coalesce(origname,pathname) FROM {{dbname.ckout}}.vfile WHERE vid=%" FSL_ID_T_PFMT ";",
    pid
  );
  if(rc) goto end;

  /*
  ** Add files found in M
  */
  rc = fsl_cx_exec_multi(f,
    "UPDATE OR IGNORE " FSL__TABLE_FVM " SET fnm=fnp WHERE fnm IS NULL;"
    "INSERT OR IGNORE INTO " FSL__TABLE_FVM "(fnm)"
    " SELECT pathname FROM {{dbname.ckout}}.vfile WHERE vid=%" FSL_ID_T_PFMT ";",
    mid
  );
  if(rc) goto end;

  /*
  ** Compute the file version ids for P and M
  */
  if( pid==vid ){
    rc = fsl_cx_exec_multi(f,
      "UPDATE " FSL__TABLE_FVM " SET idp=idv, ridp=ridv"
      " WHERE ridv>0 AND chnged NOT IN (3,5)"
    );
  }else{
    rc = fsl_cx_exec_multi(f,
      "UPDATE " FSL__TABLE_FVM
      " SET idp=coalesce(vfile.id,0), ridp=coalesce(vfile.rid,0)"
      " FROM {{dbname.ckout}}.vfile AS vfile"
      " WHERE vfile.vid=%" FSL_ID_T_PFMT
      " AND " FSL__TABLE_FVM ".fnp=vfile.pathname",
      pid
    );
  }
  if(rc) goto end;
  rc = fsl_cx_exec_multi(f,
    "UPDATE " FSL__TABLE_FVM " SET"
    " idm=coalesce(vfile.id,0),"
    " ridm=coalesce(vfile.rid,0),"
    " islinkm=coalesce(vfile.islink,0),"
    " isexe=coalesce(vfile.isexe," FSL__TABLE_FVM ".isexe)"
    " FROM {{dbname.ckout}}.vfile AS vfile"
    " WHERE vid=%" FSL_ID_T_PFMT " AND fnm=pathname",
    mid
  );
  if(rc) goto end;

  /*
  ** Update the execute bit on files where it's changed from P->M but
  ** not P->V
  */
  if(!mOpt->dryRun){
    fsl_stmt q = fsl_stmt_empty;
    rc = fsl_cx_prepare(f, &q,
      "SELECT idv, fn, " FSL__TABLE_FVM ".isexe "
      "FROM " FSL__TABLE_FVM ", {{dbname.ckout}}.vfile p,"
      " {{dbname.ckout}}.vfile v"
      " WHERE p.id=idp AND v.id=idv AND " FSL__TABLE_FVM ".isexe!=p.isexe"
      " AND v.isexe=p.isexe"
    );
    if(rc) goto end;
    fsl_b * const fnAbs =
      fsl__cx_scratchpad(f)/*absolute filenames*/;
    rc = fsl_b_reserve(fnAbs, f->db.ckout.dirLen + 256);
    if(0==rc){
      rc = fsl_b_append(fnAbs, f->db.ckout.dir, f->db.ckout.dirLen);
    }
    while( 0==rc && fsl__cx_stmt_step_each(f, &q, &rc) ){
      fsl_id_t const idv = fsl_stmt_g_id(&q, 0);
      int const isExe = fsl_stmt_g_int32(&q, 2);
      fsl_size_t nName = 0;
      const char *zName = 0;
      rc = fsl_stmt_get_text(&q, 1, &zName, &nName);
      if(rc){
        rc = fsl_cx_uplift_db_error2(f, NULL, rc);
        break;
      }
      fnAbs->mem[f->db.ckout.dirLen] = 0;
      fnAbs->used = f->db.ckout.dirLen;
      rc = fsl_b_append(fnAbs, zName, (fsl_int_t)nName);
      if(rc) break;
      fsl__cfs_exec_set(f, fsl_b_cstr(fnAbs), !!isExe )
        /* Ignoring error */;
      rc = fsl_cx_exec(f, "UPDATE {{dbname.ckout}}.vfile SET isexe=%d "
                       "WHERE id=%" FSL_ID_T_PFMT,
                       isExe, idv);
    }
    fsl__cx_scratchpad_yield(f, fnAbs);
    fsl_stmt_finalize(&q);
  }
  end:
  return rc;
}/*fsl__renames_tweak()*/

/**
   Adds an an entry in the vmerge table for the given id and rid.
   Returns 0 on success, uplifts any db error into f's error state.
*/
static int fsl__vmerge_insert(fsl_cx * const f, fsl_id_t id, fsl_id_t rid){
  return fsl_cx_exec(f,
    "INSERT OR IGNORE INTO {{dbname.ckout}}.vmerge(id,merge,mhash)"
    "VALUES(%" FSL_ID_T_PFMT ",%" FSL_ID_T_PFMT
    ",(SELECT uuid FROM {{dbname.repo}}.blob WHERE rid=%" FSL_ID_T_PFMT "))",
    id, rid, rid
  );
}

#define fsl_merge_state_empty_m {        \
  NULL/*f*/,                             \
  NULL/*opt*/,                           \
  NULL/*filename*/,                      \
  NULL/*priorName*/,                     \
  FSL_MERGE_FCHANGE_NONE/*fileChangeType*/,\
  FSL_CKUP_RM_NOT/* fileRmInfo */        \
}
/**
   Initialized-with-defaults fsl_merge_state instance,
   intended for use in non-const copy initialization.
*/
const fsl_merge_state fsl_merge_state_empty = fsl_merge_state_empty_m;

static int fsl__ckout_merge_impl(fsl_cx * const f,
                                 fsl_merge_opt const * const opt){
  /**
     Notation:

     V (vid)  The current checkout
     M (mid)  The version being merged in
     P (pid)  The "pivot" - the most recent common ancestor of V and M.
     N (nid)  The "name pivot" - for detecting renames

     What follows was initially based on:

     https://fossil-scm.org/home/file/src/merge.c?ci=e340af58a249dc09&ln=331-1065
  */
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return FSL_RC_NOT_A_CKOUT;
  int rc = 0;
  bool inTrans = false;
  fsl_id_t const vid = f->db.ckout.rid /* current checkout (V) */;
  fsl_id_t pid = 0 /* pivot RID (P): most recent common ancestor of V and M*/;
  fsl_id_t mid = opt->mergeRid /* merge-in version (M) */;
  fsl_id_t nid = 0 /* "name pivot" version (N) */;
  bool doIntegrate = FSL_MERGE_TYPE_INTEGRATE==opt->mergeType;
  fsl_stmt q = fsl_stmt_empty;
  fsl_b * const absPath = fsl__cx_scratchpad(f);
  fsl_merge_state mState = fsl_merge_state_empty;
  fsl_b * const m = fsl_cx_b_borrow(f);
  fsl_b * const p = m ? fsl_cx_b_borrow(f) : 0;
  fsl_b * const r = p ? fsl_cx_b_borrow(f) : 0;
  if( !r ){
    rc = FSL_RC_OOM;
    goto end;
  }
  else if(0==vid){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                        "Cannot merge into empty top-level checkin.");
  }else if(FSL_MERGE_TYPE_CHERRYPICK==opt->mergeType
           && opt->baselineRid>0){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot use the baselineRid option "
                          "with a cherry-pick merge.");
  }
  if(!rc) rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) goto end;
  inTrans = true;
  if((pid = opt->baselineRid)>0){
    if(!fsl_rid_is_a_checkin(f, pid)){
      rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                          "Baseline RID #%" FSL_ID_T_PFMT
                          " does not refer to a checkin version.",
                          pid);
      goto end;
    }
  }
  if(FSL_MERGE_TYPE_CHERRYPICK==opt->mergeType
     || FSL_MERGE_TYPE_BACKOUT==opt->mergeType){
    pid = fsl_db_g_id(db, 0, "SELECT pid FROM {{dbname.repo}}.plink WHERE cid=%"
                           FSL_ID_T_PFMT " AND isprim",
                           mid);
    if(0==pid){
      char * const zMid = fsl_rid_to_uuid(f, mid);
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "Cannot find an ancestor "
                          "for to-merge version [%S] (RID #%"
                          FSL_ID_T_PFMT ").", zMid, mid);
      fsl_free(zMid);
      goto end;
    }
  }else{
    if(opt->baselineRid<=0){
      fsl_stmt q = fsl_stmt_empty;
      rc = fsl__pivot_set_primary(f, mid);
      if(0==rc) rc = fsl__pivot_add_secondary(f, vid);
      if(rc) goto end;
      rc = fsl_cx_prepare(f, &q, "SELECT merge FROM {{dbname.ckout}}.vmerge WHERE id=0");
      while( 0==rc && fsl__cx_stmt_step_each(f, &q, &rc) ){
        rc = fsl__pivot_add_secondary(f, fsl_stmt_g_id(&q, 0));
      }
      fsl_stmt_finalize(&q);
      if(0==rc) rc = fsl__pivot_find(f, false, &pid);
      if(rc) goto end;
      else if( pid<=0 ){
        char * const zMid = fsl_rid_to_uuid(f, mid);
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Cannot find a common ancestor between "
                            "the current checkout [%S] and [%S] "
                            "(RID #%" FSL_ID_T_PFMT ").",
                            f->db.ckout.uuid, zMid, mid);
        fsl_free(zMid);
        goto end;
      }
    }
    rc = fsl__pivot_set_primary(f, mid);
    if(0==rc) rc = fsl__pivot_add_secondary(f, vid);
    if(0==rc) rc = fsl__pivot_find(f, true, &nid);
    if(rc) goto end;
    else if( nid!=pid ){
      rc = fsl__pivot_set_primary(f, nid);
      if(0==rc) rc = fsl__pivot_add_secondary(f, pid);
      if(0==rc) rc = fsl__pivot_find(f, true, &nid);
      if(rc) goto end;
    }
    /* ^^^ the above block is a great example of how much error
       checking intrudes on the library API compared to fossil(1). */
  }
  if( FSL_MERGE_TYPE_BACKOUT == opt->mergeType ){
    fsl_id_t const t = pid;
    pid = mid;
    mid = t;
  }
  if(0==nid) nid = pid;
  if(opt->debug){
    MARKER(("pid=%" FSL_ID_T_PFMT
            ", mid=%" FSL_ID_T_PFMT
            ", nid=%" FSL_ID_T_PFMT
            ", vid=%" FSL_ID_T_PFMT
            " integrate=%d\n",
            pid, mid, nid, vid, doIntegrate));
  }
  if(mid == pid){
    char * const zMid = fsl_rid_to_uuid(f, mid);
    rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Cowardly refusing to perform "
                        "no-op merge from/to version [%S] (RID #%"
                        FSL_ID_T_PFMT ").", zMid, mid);
    fsl_free(zMid);
    goto end;
  }else if(mid == vid){
    rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Cowardly refusing to merge "
                        "version [%S] into itself.", f->db.ckout.uuid);
    goto end;
  }else if(!fsl_rid_is_a_checkin(f, pid)){
    rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                        "RID #%" FSL_ID_T_PFMT " does not refer "
                        "to a checkin version.", pid);
    goto end;
  }else{
    uint32_t missing = 0;
    fsl_id_t missingIn = mid;
    rc = fsl_vfile_load(f, mid, false, &missing);
    if(0==rc && 0==missing){
      missingIn = pid;
      rc = fsl_vfile_load(f, pid, false, &missing);
    }
    if(0==rc && missing){
      char * const zMissing = fsl_rid_to_uuid(f, missingIn);
      rc = fsl_cx_err_set(f, FSL_RC_PHANTOM,
                          "Cannot merge due to missing content in "
                          "%" PRIu32 " blob(s) of %s version [%S].",
                          missing, missingIn==mid ? "to-merge" : "pivot",
                          zMissing);
      fsl_free(zMissing);
    }
    if(rc) goto end;
  }
  if( doIntegrate && (fsl_content_is_private(f, mid)
                      || !fsl_rid_is_leaf(f, mid)) ){
    doIntegrate = false;
  }
  if(opt->scanForChanges){
    rc = fsl_vfile_changes_scan(f, vid, FSL_VFILE_CKSIG_ENOTFILE);
    if(rc) goto end;
  }
  rc = fsl__renames_tweak(f, mid, pid, vid, nid, opt);
  if(rc) goto end;
  if(opt->debug){
    MARKER(("pid=%" FSL_ID_T_PFMT
            ", mid=%" FSL_ID_T_PFMT
            ", nid=%" FSL_ID_T_PFMT
            ", vid=%" FSL_ID_T_PFMT
            " integrate=%d\n",
            pid, mid, nid, vid, doIntegrate));
    MARKER(("Contents of " FSL__TABLE_FVM ":\n"));
    if(1==opt->debug){
      fsl_db_each(db, fsl_stmt_each_f_dump, f,
                  "SELECT fn,fnp,fnm,chnged,ridv,ridp,ridm, "
                  " isexe,islinkv islinkm, fnn "
                  " FROM " FSL__TABLE_FVM
                  " WHERE chnged OR (ridv!=ridm AND ridm!=ridp)"
                  " ORDER BY fn, fnp, fnm ");
    }else{
      fsl_db_each(db, fsl_stmt_each_f_dump, f,
                  "SELECT * FROM " FSL__TABLE_FVM
                  " ORDER BY fn, fnp, fnm");
    }
    MARKER(("Contents of " FSL__TABLE_PIVOT ":\n"));
    fsl_db_each(db, fsl_stmt_each_f_dump, f,
                "SELECT * FROM " FSL__TABLE_PIVOT
                " ORDER BY src DESC, rid, pending, src");
    MARKER(("Contents of [vmerge]:\n"));
    fsl_db_each(db, fsl_stmt_each_f_dump, f,
                "SELECT * FROM {{dbname.ckout}}.vmerge order by merge");
  }
  mState.f = f;
  mState.opt = opt;
#define MCB(FCT,RMI,FN) \
  assert(opt->callback); \
  mState.fileChangeType = FCT; \
  mState.fileRmInfo = RMI; \
  mState.filename = FN; \
  rc = opt->callback(&mState); \
  if(rc && !f->error.code && FSL_RC_OOM!=rc){ \
    rc = fsl_cx_err_set(f, rc, "Error %R returned from merge " \
                        "callback for file: %s", rc, FN); \
  } \
  mState.priorName = NULL
#define MCB2(FCT,FN) MCB(FCT,FSL_CKUP_RM_NOT,FN)
  /************************************************************************
  ** All of the information needed to do the merge is now contained in the
  ** FV table.  Starting here, we begin to actually carry out the merge.
  **
  ** First, find files that have changed from P->M but not P->V.  Copy
  ** the M content over into V.
  */
  rc = fsl_cx_prepare(f, &q,
    "SELECT idv, ridm, fn, islinkm FROM " FSL__TABLE_FVM
    " WHERE idp>0 AND idv>0 AND idm>0"
    "   AND ridm!=ridp AND ridv=ridp AND NOT chnged"
  );
  if(rc) goto end;
  while( 0==rc && (fsl__cx_stmt_step_each(f, &q, &rc)) ){
    fsl_id_t const idv = fsl_stmt_g_id(&q, 0);
    fsl_id_t const ridm = fsl_stmt_g_id(&q, 1);
    int const islinkm = fsl_stmt_g_int32(&q, 3);
    /* Copy content from idm over into idv.  Overwrite idv. */
    if(opt->debug){
      const char *zName = fsl_stmt_g_text(&q, 2, NULL);
      MARKER(("COPIED (M)=>(V) %s\n", zName));
    }
    if( !opt->dryRun ){
      //undo_save(zName);
      rc = fsl_cx_exec(f,
        "UPDATE {{dbname.ckout}}.vfile SET mtime=0, mrid=%" FSL_ID_T_PFMT
        ", chnged=%d, islink=%d,"
        " mhash=CASE WHEN rid<>%" FSL_ID_T_PFMT
        " THEN (SELECT uuid FROM {{dbname.repo}}.blob AS blob WHERE blob.rid=%" FSL_ID_T_PFMT ") END"
        " WHERE id=%" FSL_ID_T_PFMT,
        ridm, doIntegrate ? 4 : 2, islinkm, ridm, ridm, idv
      );
      if(0==rc) rc = fsl__vfile_to_ckout(f, idv, NULL);
    }
    if(0==rc && opt->callback){
      const char *zName = 0;
      rc = fsl_stmt_get_text(&q, 2, &zName, NULL);
      if(0==rc){
        MCB2(FSL_MERGE_FCHANGE_COPIED,zName);
      }else{
        rc = fsl_cx_uplift_db_error2(f, NULL, rc);
      }
    }
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }

  /*
  ** Do a three-way merge on files that have changes on both P->M and P->V.
  **
  ** Proceed even if the file doesn't exist on P, as if the common
  ** ancestor of M and V is an empty file. In this case, merge
  ** conflict marks will be added to the file and the user will be
  ** forced to handle them like any other conflict. The alternative is
  ** that we warn the user via opt->callback and let them decide on
  ** whether to keep the copy from P->V (historical default behavior)
  ** or error out.  As of 2023-04, fossil treats this as a normal
  ** merge conflict with an empty common ancestor version, so we'll do
  ** the same.
  */
  rc = fsl_cx_prepare(f, &q,
    "SELECT ridm, idv, ridp, ridv,"
    " FSL_GLOB('binary-glob'," FSL__TABLE_FVM ".fn),"
    " fn, isexe, islinkv, islinkm FROM " FSL__TABLE_FVM
    " WHERE /*idp>0 AND*/ idv>0 AND idm>0"
    /* -----^^^^^^^^^^^^^ https://fossil-scm.org/home/info/7c75e47b3c130ff1
       With that clause, entries with no common ancestor are filtered out. */
    "   AND ridm!=ridp AND (ridv!=ridp OR chnged)"
  );
  if(0==rc){
    rc = fsl_b_append( absPath, f->db.ckout.dir, (fsl_int_t)f->db.ckout.dirLen);
  }
  while( 0==rc && (fsl__cx_stmt_step_each(f, &q, &rc)) ){
    fsl_id_t const ridm = fsl_stmt_g_id(&q, 0);
    fsl_id_t const idv = fsl_stmt_g_id(&q, 1);
    fsl_id_t const ridp = fsl_stmt_g_id(&q, 2);
    fsl_id_t const  ridv = fsl_stmt_g_id(&q, 3);
    int32_t isBinary = fsl_stmt_g_int32(&q, 4);
    int32_t const isExe = fsl_stmt_g_int32(&q, 6);
    int32_t const islinkv = fsl_stmt_g_int32(&q, 7);
    int32_t const islinkm = fsl_stmt_g_int32(&q, 8);
    char const *zFullPath;
    const char *zName = NULL;
    fsl_size_t nName = 0;
    rc = fsl_stmt_get_text(&q, 5, &zName, &nName);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, NULL, rc);
      break;
    }
    /* Do a 3-way merge of idp->idm into idp->idv.  The results go into idv. */
    if(opt->debug){
      MARKER(("MERGE %s  (pivot=%"FSL_ID_T_PFMT
              " v1=%"FSL_ID_T_PFMT" v2=%"FSL_ID_T_PFMT")\n",
              zName, ridp, ridm, ridv));
    }
    if( islinkv || islinkm ){
      //MARKER(("***** Cannot merge symlink %s\n", zName));
      if(opt->callback){
        MCB2(FSL_MERGE_FCHANGE_CONFLICT_SYMLINK,zName);
      }
    }else if(isBinary){
      if(opt->callback){
        MCB2(FSL_MERGE_FCHANGE_CONFLICT_BINARY,zName);
      }
    }else{
      //if( !dryRunFlag ) undo_save(zName);
      fsl_b_reuse(m);
      fsl_b_reuse(p);
      fsl_b_reuse(r);
      if(opt->debug){
        MARKER(("Merge: %s\n", zName));
      }
      absPath->used = f->db.ckout.dirLen;
      rc = fsl_b_append(absPath, zName, (fsl_int_t)nName);
      if(rc) break;
      zFullPath = fsl_b_cstr(absPath);
      if(ridp) rc = fsl_content_get(f, ridp, p);
      if(0==rc) rc = fsl_content_get(f, ridm, m);
      if(rc && !f->error.code && FSL_RC_OOM!=rc){
        rc = fsl_cx_err_set(f, rc, "Error %R loading content of %s "
                            "(blob RIDs %" FSL_ID_T_PFMT " and %"
                            FSL_ID_T_PFMT ") for merging.",
                            rc, zName, ridp, ridm);
      }
      if(0==rc){
        //unsigned mergeFlags = dryRunFlag ? MERGE_DRYRUN : 0;
        //if(keepMergeFlag!=0) mergeFlags |= MERGE_KEEP_FILES;
        //rc = merge_3way(p, zFullPath, m, r, mergeFlags);
        unsigned int nConflict = 0;
        fsl_b * const contentLocal = fsl__cx_content_buffer(f);
        rc = fsl__cfs_read(f, contentLocal, zFullPath);
        if(rc){
          rc = fsl_cx_err_set(f, rc, "Error %R reading file: %s",
                              rc, zFullPath);
        }else{
          rc = fsl_b_merge3( p, contentLocal, m, r, &nConflict );
          switch(rc){
            case 0:
              if(opt->debug){
                MARKER(("%swriting merged file w/ %u conflict(s): %s\n",
                        opt->dryRun ? "Not " : "", nConflict, zName));
              }
              if(!opt->dryRun){
                rc = fsl__cfs_write(f, r, zFullPath);
                if(rc){
                  rc = fsl_cx_err_set(f, rc, "Error %R writing to "
                                      "file: %s", rc, zFullPath);
                }else{
                  fsl__cfs_exec_set(f, zFullPath, !!isExe);
                }
              }
              break;
            case FSL_RC_DIFF_BINARY:
            case FSL_RC_TYPE:
              /* fsl_b_merge3() reports binary input as
                 FSL_RC_DIFF_BINARY. FSL_RC_TYPE is accepted for
                 compatibility with its older documentation. */
              rc = 0; isBinary = 1;
              break;
            default: break;
          }
        }
        fsl__cx_content_buffer_yield(f);
        if(0==rc && !isBinary){
          rc = fsl_cx_exec(f, "UPDATE {{dbname.ckout}}.vfile "
                           "SET mtime=0 WHERE id=%" FSL_ID_T_PFMT, idv);
        }
        if(0==rc && opt->callback){
          fsl_merge_fchange_e const fce =
            isBinary
            ? FSL_MERGE_FCHANGE_CONFLICT_BINARY
            : (nConflict
               ? FSL_MERGE_FCHANGE_CONFLICT_MERGED
               : FSL_MERGE_FCHANGE_MERGED);
          MCB2(fce,zName);
        }
      }
    }
    if(0==rc) rc = fsl__vmerge_insert(f, idv, ridm);
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }

  /*
  ** Drop files that are in P and V but not in M
  */
  rc = fsl_cx_prepare(f, &q,
    "SELECT idv, fn, chnged FROM " FSL__TABLE_FVM
    " WHERE idp>0 AND idv>0 AND idm=0"
  );
  while( 0==rc && FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&q)) ){
    fsl_id_t const idv = fsl_stmt_g_id(&q, 0);
    int32_t const chnged = fsl_stmt_g_int32(&q, 2);
    const char *zName;
    fsl_size_t nName = 0;
    rc = fsl_stmt_get_text(&q, 1, &zName, &nName);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, NULL, rc);
      break;
    }
    /* Delete the file idv */
    if(opt->debug){
      MARKER(("DELETE %s\n", zName));
    }
    if( chnged ){
      if(opt->debug){
        MARKER(("WARNING: local edits lost for %s", zName));
      }
    }
    //if( !dryRunFlag ) undo_save(zName);
    rc = fsl_cx_exec(f,
      "UPDATE {{dbname.ckout}}.vfile SET deleted=1 WHERE id=%" FSL_ID_T_PFMT, idv
    );
    if(rc) break;
    if(!chnged && !opt->dryRun ){
      /* ^^^ this differs from fossil(1), which always deletes the
         local file regardless of whether it has local changes. */
      absPath->used = f->db.ckout.dirLen;
      rc = fsl_b_append(absPath, zName, (fsl_int_t)nName);
      if(0==rc) fsl__cfs_unlink(f, fsl_b_cstr(absPath));
    }
    if(opt->callback){
      fsl_ckup_rm_state_e const rme =
        chnged ? FSL_CKUP_RM_KEPT : FSL_CKUP_RM;
      MCB(FSL_MERGE_FCHANGE_RM,rme,zName);
    }
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }

  /* For certain sets of renames (e.g. A -> B and B -> A), a file that is
  ** being renamed must first be moved to a temporary location to avoid
  ** being overwritten by another rename operation. A row is added to the
  ** TMPRN table for each of these temporary renames.
  */
  rc = fsl_cx_exec_multi(f,
    "CREATE TEMP TABLE IF NOT EXISTS {{temp.tmprn}}(fn UNIQUE, tmpfn);"
    "DELETE FROM {{temp.tmprn}};"
  );
  if(rc) goto end;

  /*
  ** Rename files that have taken a rename on P->M but which keep the same
  ** name on P->V.  If a file is renamed on P->V only or on both P->V and
  ** P->M then we retain the V name of the file.
  */
  rc = fsl_cx_prepare(f, &q,
    "SELECT idv, fnp, fnm, isexe FROM " FSL__TABLE_FVM
    " WHERE idv>0 AND idp>0 AND idm>0 AND fnp=fn AND fnm!=fnp"
  );
  while( 0==rc && FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&q)) ){
    fsl_id_t const idv = fsl_stmt_g_id(&q, 0);
    int32_t const isExe = fsl_stmt_g_int32(&q, 3);
    const char *zOldName;
    const char *zNewName;
    rc = fsl_stmt_get_text(&q, 1, &zOldName, NULL);
    if(0==rc) rc = fsl_stmt_get_text(&q, 2, &zNewName, NULL);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, NULL, rc);
      break;
    }
    if(opt->debug){
      MARKER(("RENAME %s -> %s\n", zOldName, zNewName));
    }
    //if( !dryRunFlag ) undo_save(zOldName);
    //if( !dryRunFlag ) undo_save(zNewName);
    rc = fsl_cx_exec_multi(f,
      "UPDATE {{dbname.ckout}}.vfile SET pathname=NULL, origname=pathname"
      " WHERE vid=%" FSL_ID_T_PFMT " AND pathname=%Q;"
      "UPDATE {{dbname.ckout}}.vfile SET pathname=%Q, origname=coalesce(origname,pathname)"
      " WHERE id=%" FSL_ID_T_PFMT ";",
      vid, zNewName, zNewName, idv
    );
    if(rc) break;
    if( !opt->dryRun ){
      fsl_b * const bFullOld = fsl__cx_scratchpad(f);
      fsl_b * const bFullNew = fsl__cx_scratchpad(f);
      fsl_b * const bTmp = fsl__cx_scratchpad(f);
      char const *zFullOldPath;
      char const *zFullNewPath;
      bool const realSymlinks = fsl_cx_allows_symlinks(f, false);
      rc = fsl_db_get_buffer(db, bFullOld, false,
                             "SELECT tmpfn FROM {{temp.tmprn}} WHERE fn=%Q", zOldName);
      if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
      else if(!bFullOld->used){
        rc = fsl_b_appendf(bFullOld, "%s%s", f->db.ckout.dir, zOldName);
      }
      if(0==rc) rc = fsl_b_appendf(bFullNew, "%s%s", f->db.ckout.dir, zNewName);
      if(rc) goto merge_rename_end;
      zFullOldPath = fsl_b_cstr(bFullOld);
      zFullNewPath = fsl_b_cstr(bFullNew);
      if( fsl__cfs_size(f, zFullNewPath)>=0 ){
        assert(!bTmp->used);
        /* The copy goes in the checkout's directory, through the
           checkout's storage, rather than in the current directory. */
        rc = fsl_b_append(bTmp, f->db.ckout.dir,
                          (fsl_int_t)f->db.ckout.dirLen);
        if(0==rc) rc = fsl_file_tempname(bTmp, "merge-rename", NULL);
        if(rc){
          rc = fsl_cx_err_set(f, rc, "Error %R generating a temporary "
                              "name for renaming %s to %s.",
                              rc, zOldName, zNewName);
          goto merge_rename_end;
        }
        rc = fsl_cx_exec(f, "INSERT INTO {{temp.tmprn}}(fn,tmpfn) VALUES(%Q,%B)",
                         zNewName, bTmp);
        if(rc) goto merge_rename_end;
        rc = fsl__cfs_is_symlink(f, zFullNewPath)
          ? fsl__cfs_symlink_copy(f, zFullNewPath, fsl_b_cstr(bTmp),
                                  realSymlinks)
          : fsl__cfs_copy(f, zFullNewPath, fsl_b_cstr(bTmp));
        if(rc){
          rc = fsl_cx_err_set(f, rc, "Error %R copying file [%s] "
                              "to [%b].", rc, zFullNewPath, bTmp);
        }
        if(rc) goto merge_rename_end;
      }
      rc = fsl__cfs_is_symlink(f, zFullOldPath)
        ? fsl__cfs_symlink_copy(f, zFullOldPath, zFullNewPath, realSymlinks)
        : fsl__cfs_copy(f, zFullOldPath, zFullNewPath);
      if(rc){
        rc = fsl_cx_err_set(f, rc, "Error %R copying file [%s] to [%s].",
                            rc, zFullOldPath, zFullNewPath);
      }else{
        fsl__cfs_exec_set(f, zFullNewPath, !!isExe);
        fsl__cfs_unlink(f, zFullOldPath);
        /* ^^^ Ignore errors: not critical here */
      }
      merge_rename_end:
      fsl__cx_scratchpad_yield(f, bFullOld);
      fsl__cx_scratchpad_yield(f, bFullNew);
      fsl__cx_scratchpad_yield(f, bTmp);
    }
    if(0==rc && opt->callback){
      mState.priorName = zOldName;
      MCB2(FSL_MERGE_FCHANGE_RENAMED,zNewName);
    }
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }
  /* Remove the temporary copies the above loop made. Most were
     already moved into place; fossil(1) leaves the rest behind. */
  rc = fsl_cx_prepare(f, &q, "SELECT tmpfn FROM {{temp.tmprn}}");
  if(rc) goto end;
  while( FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
    char const * const zTmp = fsl_stmt_g_text(&q, 0, NULL);
    if( zTmp ) fsl__cfs_unlink(f, zTmp) /* ignore errors */;
  }
  fsl_stmt_finalize(&q);
  /* A file that has been deleted and replaced by a renamed file will have a
  ** NULL pathname. Change it to something that makes the output of "status"
  ** and similar commands make sense for such files and that will (most likely)
  ** not be an actual existing pathname.
  */
  rc = fsl_cx_exec(f,
    "UPDATE {{dbname.ckout}}.vfile SET pathname=origname || ' (overwritten by rename)'"
    " WHERE pathname IS NULL"
  );
  if(rc) goto end;
  /*
  ** Insert into V any files that are not in V or P but are in M.
  */
  rc = fsl_cx_prepare(f, &q,
    "SELECT idm, fnm FROM " FSL__TABLE_FVM
    " WHERE idp=0 AND idv=0 AND idm>0"
  );
  while( 0==rc && FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&q)) ){
    fsl_id_t const idm = fsl_stmt_g_id(&q, 0);
    const char *zName;
    fsl_b * const bFullName = fsl__cx_scratchpad(f);
    fsl_merge_fchange_e fchange = FSL_MERGE_FCHANGE_NONE
      /* this initialization is bogus, but some gcc versions
         incorrectly report that it may be used uninitialized */;
    rc = fsl_cx_exec(f,
      "REPLACE INTO {{dbname.ckout}}.vfile(vid,chnged,deleted,rid,mrid,"
                         "isexe,islink,pathname,mhash)"
      "  SELECT %" FSL_ID_T_PFMT ",%d,0,rid,mrid,isexe,islink,pathname,"
            "CASE WHEN rid<>mrid"
            " THEN (SELECT uuid FROM {{dbname.repo}}.blob AS blob WHERE blob.rid=vfile.mrid) END "
            "FROM {{dbname.ckout}}.vfile AS vfile WHERE id=%" FSL_ID_T_PFMT,
      vid, doIntegrate
           ? FSL_VFILE_CHANGE_INTEGRATE_MOD
           : FSL_VFILE_CHANGE_MERGE_ADD,
      idm);
    if(0==rc){
      rc = fsl_stmt_get_text(&q, 1, &zName, NULL);
      if(rc) rc = fsl_cx_uplift_db_error2(f, NULL, rc);
    }
    if(0==rc) rc = fsl_b_appendf(bFullName, "%s%s", f->db.ckout.dir, zName);
    if(rc) goto merge_add_end;
    if( fsl__cfs_is_file_or_link(f, fsl_b_cstr(bFullName))
        && !fsl_db_exists(db, "SELECT 1 FROM " FSL__TABLE_FVM
                          " WHERE fn=%Q", zName) ){
      if(opt->debug){
        MARKER(("ADDED %s (overwrites an unmanaged file)\n", zName));
      }
      fchange = FSL_MERGE_FCHANGE_CONFLICT_ADDED_UNMANAGED;
    }else{
      if(opt->debug){
        MARKER(("ADDED %s\n", zName));
      }
      fchange = FSL_MERGE_FCHANGE_ADDED;
    }
    if( !opt->dryRun ){
      //undo_save(zName);
      rc = fsl__vfile_to_ckout(f, idm, NULL);
    }
    merge_add_end:
    fsl__cx_scratchpad_yield(f, bFullName);
    if(0==rc && opt->callback){
      assert(FSL_MERGE_FCHANGE_CONFLICT_ADDED_UNMANAGED==fchange
             || FSL_MERGE_FCHANGE_ADDED==fchange);
      MCB2(fchange,zName);
    }
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }

  fsl_id_t vmergeWho = 0;
  switch(opt->mergeType){
    case FSL_MERGE_TYPE_CHERRYPICK:
      vmergeWho = mid;
      /* For a cherry-pick merge, make the default check-in comment the same
      ** as the check-in comment on the check-in that is being merged in. */
      if(0==rc){
        rc = fsl_cx_exec(f,
               "REPLACE INTO {{dbname.ckout}}.vvar(name,value)"
               " SELECT 'ci-comment', coalesce(ecomment,comment) FROM {{dbname.repo}}.event"
               "  WHERE type='ci' AND objid=%" FSL_ID_T_PFMT,
               mid);
      }
      break;
    case FSL_MERGE_TYPE_BACKOUT:
      vmergeWho = pid;
      break;
    case FSL_MERGE_TYPE_INTEGRATE:
    case FSL_MERGE_TYPE_NORMAL:
      vmergeWho = mid;
      break;
  }
  if(0==rc){
    rc = fsl__vmerge_insert(f, (int)opt->mergeType, vmergeWho);
  }
#undef MCB
#undef MCB2
  end:
  fsl_cx_b_return(f, r);
  fsl_cx_b_return(f, p);
  fsl_cx_b_return(f, m);
  if(opt->debug){
    MARKER(("fsl_ckout_merge() made it to the end with rc %s.\n",
            fsl_rc_cstr(rc)));
  }
  fsl__cx_scratchpad_yield(f, absPath);
  if(0==rc){
    fsl__renames_finalize(f);
  }
  fsl_stmt_finalize(&q);
  if(inTrans){
    if(0==rc){
      rc = fsl_vfile_unload_except(f, vid);
      // ^^^ not strictly needed unless we're NOT rolling back
    }
    int const rc2 = fsl_cx_txn_end_v2(f, 0==rc && !opt->dryRun, 0!=rc);
    if(rc2 && 0==rc) rc = rc2;
  }
  return rc;
}

#undef FSL__TABLE_PIVOT
#undef FSL__TABLE_FVM

#undef MARKER

int fsl_ckout_merge(fsl_cx * const f, fsl_merge_opt const * const opt){
  bool undoOwner = false;
  int rc = opt->dryRun ? 0 : fsl__undo_begin(f, "merge", &undoOwner);
  if(!rc) rc = fsl__ckout_merge_impl(f, opt);
  return fsl__undo_end(f, rc, undoOwner);
}
/* end of file src/merge.c */
/* start of file src/merge3.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
#include <assert.h>
#include <memory.h>
#include <stdlib.h>
#include <string.h> /* memmove()/strlen() */

#if 0
#define FDEBUG(X)  X
#define ISFDEBUG 1
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)
#else
#define FDEBUG(X)
#define ISFDEBUG 0
#define MARKER(pfexp) (void)0
#endif

// Only for testing/debugging..

/* The minimum of two integers */
#define mymin(A,B)  ((A)<(B)?(A):(B))

/**
   Compare N lines of text from pV1 and pV2. If the lines are the
   same, return true. Return false if one or more of the N lines are
   different.

   The cursors on both pV1 and pV2 is unchanged by this comparison.
*/
static
bool sameLines(fsl_b const * const pV1,
               fsl_b const * const pV2,
               int N){
  unsigned char const *z1;
  unsigned char const *z2;
  fsl_size_t i;
  unsigned char c;
  if( !N ) return true;
  z1 = pV1->mem + pV1->cursor;
  z2 = pV2->mem + pV2->cursor;
  for(i=0; (c=z1[i])==z2[i]; ++i){
    if( c=='\n' || !c ){
      --N;
      if( !N || !c ) return true;
    }
  }
  return false;
}

/**
   Look at the next edit triple in both aC1 and aC2.  (An "edit triple" is
   three integers describing the number of copies, deletes, and inserts in
   moving from the original to the edited copy of the file.) If the three
   integers of the edit triples describe an identical edit, then return 1.
   If the edits are different, return 0.

   aC1 = the array of edit integers for pV1.

   aC2 = the array of edit integers for pV2.
*/
static
bool sameEdit(int const * const aC1, int const * const aC2,
              fsl_b const * const pV1,
              fsl_b const * const pV2){
#if 0
  if( aC1[0]!=aC2[0] ) return 0;
  if( aC1[1]!=aC2[1] ) return 0;
  if( aC1[2]!=aC2[2] ) return 0;
  if( sameLines(pV1, pV2, aC1[2]) ) return 1;
  return 0;
#else
  if( aC1[0]!=aC2[0]
      || aC1[1]!=aC2[1]
      || aC1[2]!=aC2[2] ) return false;
  return sameLines(pV1, pV2, aC1[2]);
#endif
}


/**
   The aC[] array contains triples of integers. Within each triple,
   the elements are:

   (0)  The number of lines to copy
   (1)  The number of lines to delete
   (2)  The number of lines to insert

   Suppose we want to advance over sz lines of the original file.
   This routine returns true if that advance would land us on a copy
   operation. It returns false if the advance would end on a delete.
*/
static
bool ends_at_CPY(int const * aC, int sz){
  while( sz>0 && (aC[0]>0 || aC[1]>0 || aC[2]>0) ){
    if( aC[0]>=sz ) return true;
    sz -= aC[0];
    if( aC[1]>sz ) return false;
    sz -= aC[1];
    aC += 3;
  }
  return true;
}

/**
   pSrc contains an edited file where aC[] describes the edit,
   starting at index i. Part of pSrc has already been output. This
   routine outputs additional lines of pSrc - lines that correspond to
   the next sz lines of the original unedited file.

   Note that sz counts the number of lines of text in the original
   file, but text is output from the edited file, so the number of
   lines transfer to pOut might be different from sz. Fewer lines
   appear in pOut if there are deletes. More lines appear if there
   are inserts.

   The aC[] array is updated and the new index into aC[] is returned
   via the newIndex. The running line number count is updated via
   pLn.

   Returns 0 on success, FSL_RC_OOM on allocation error.
*/
static
int output_one_side(fsl_b * const pOut,
                    fsl_b * const pSrc,
                    int * const aC,
                    int i,
                    int sz,
                    int * const newIndex,
                    int * const pLn){
  int rc = 0;
  while( sz>0 ){
    if( aC[i]==0 && aC[i+1]==0 && aC[i+2]==0 ) break;
    if( aC[i]>=sz ){
      rc = fsl_b_copy_lines(pOut, pSrc, sz);
      *pLn += sz;
      if(rc) break;
      aC[i] -= sz;
      break;
    }
    rc = fsl_b_copy_lines(pOut, pSrc, aC[i]);
    *pLn += aC[i];
    if(!rc){
      rc = fsl_b_copy_lines(pOut, pSrc, aC[i+2]);
      *pLn += aC[i+2];
    }
    if(rc) break;
    sz -= aC[i] + aC[i+1];
    i += 3;
  }
  if(!rc) *newIndex = i;
  return rc;
}

/**
   Return true if the input blob contains any CR/LF pairs on the first
   ten lines. This should be enough to detect files that use mainly
   CR/LF line endings without causing a performance impact for LF only
   files.
*/
static
bool contains_crlf(fsl_b const * const p){
  fsl_size_t i;
  fsl_size_t j = 0;
  const uint16_t maxL = 10; //Max lines to check
  unsigned const char *z = p->mem;
  fsl_size_t const n = p->used+1;
  for(i=1; i<n; ){
    if( z[i-1]=='\r' && z[i]=='\n' ) return true;
    while( i<n && z[i]!='\n' ){ ++i; }
    ++j;
    if( j>maxL ) break;
  }
  return false;
}

/**
   Ensure that the text in p, if not empty, ends with a new line. If
   useCrLf is true adds "\r\n" otherwise "\n".  Returns 0 on success
   or p is empty, and FSL_RC_OOM on OOM.
*/
static int ensure_line_end(fsl_b * const p, bool useCrLf){
  int rc = 0;
  if( !p->used ) return 0;
  if( p->mem[p->used-1]!='\n' ){
    rc = fsl_b_append(p, useCrLf ? "\r\n" : "\n", useCrLf ? 2 : 1);
  }
  return rc;
}

/**
   Returns an array of bytes representing the byte-order-mark for
   UTF-8. If pnByte is not NULL, the number of bytes in the BOM (3)
   is written there.
*/
static
const unsigned char *get_utf8_bom(unsigned int * const pnByte){
  static const unsigned char bom[] = {
    0xef, 0xbb, 0xbf, 0x00, 0x00, 0x00
  };
  if( pnByte ) *pnByte = 3;
  return bom;
}

/**
   Returns true if given blob starts with a UTF-8 byte-order-mark
   (BOM). n is as document for get_utf8_bom()'s one argument.
*/
static
bool starts_with_utf8_bom(fsl_b const * const p, unsigned int *n){
  unsigned const char *z = p->mem;
  unsigned int bomSize = 0;
  const unsigned char *bom = get_utf8_bom(&bomSize);
  if( n ) *n = bomSize;
  return (p->used<bomSize)
    ? false
    : memcmp(z, bom, bomSize)==0;
}

/**
   Text of boundary markers for merge conflicts.

   NEVER, EVER change these. They MUST match the ones used
   by fossil.
*/
static
const char *const mergeMarker[] = {
 /*123456789 123456789 123456789 123456789 123456789 123456789 123456789*/
  "<<<<<<< BEGIN MERGE CONFLICT: local copy shown first <<<<<<<<<<<<",
  "||||||| COMMON ANCESTOR content follows |||||||||||||||||||||||||",
  "======= MERGED IN content follows ===============================",
  ">>>>>>> END MERGE CONFLICT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
};
enum {
/* strlen() of each mergeMarker entry. */
MEMA_LENGTH = 65
};
/**
   Asserts, the first time it is called, that all mergeMarker entries
   are of the same length and returns that length.
*/
#if defined(NDEBUG)
#  define assert_mema_lengths() MEMA_LENGTH
#else
static inline fsl_int_t assert_mema_lengths(void){
  static bool once = true;
  if(once){
    once = false;
    assert(sizeof(mergeMarker)/sizeof(mergeMarker[0]) == 4);
    assert((fsl_int_t)fsl_strlen(mergeMarker[0])==MEMA_LENGTH);
    assert((fsl_int_t)fsl_strlen(mergeMarker[1])==MEMA_LENGTH);
    assert((fsl_int_t)fsl_strlen(mergeMarker[2])==MEMA_LENGTH);
    assert((fsl_int_t)fsl_strlen(mergeMarker[3])==MEMA_LENGTH);
  }
  return MEMA_LENGTH;
}
#endif
/*
** Write out mergeMarker[iMark] to pOut, along with the given line
** number (if>0). Returns 0 on success, FSL_RC_OOM on allocation
** error.
*/
static int append_merge_mark(fsl_b * const pOut, int iMark,
                             int ln, bool useCrLf){
  int rc = ensure_line_end(pOut, useCrLf);
  if(0==rc){
    rc = fsl_b_append(pOut, mergeMarker[iMark], MEMA_LENGTH);
    if( 0==rc && ln>0 ) rc = fsl_b_appendf(pOut, " (line %d)", ln);
    if(0==rc) rc = ensure_line_end(pOut, useCrLf);
  }
  return rc;
}

int fsl_b_merge3(fsl_b * const pPivot,
                      fsl_b * const pV1,
                      fsl_b * const pV2,
                      fsl_b * const pOut,
                      unsigned int * const conflictCount){
  int *aC1 = 0;          /* Changes from pPivot to pV1 */
  int *aC2 = 0;          /* Changes from pPivot to pV2 */
  int i1, i2;            /* Index into aC1[] and aC2[] */
  int nCpy, nDel, nIns;  /* Number of lines to copy, delete, or insert */
  int limit1, limit2;    /* Sizes of aC1[] and aC2[] */
  int rc = 0;
  unsigned int nConflict = 0;     /* Number of merge conflicts seen so far */
  bool useCrLf = false;
  int ln1, ln2, lnPivot; /* Line numbers for all files */
  (void)assert_mema_lengths();

#define RC if(rc) { \
    MARKER(("rc=%s\n", fsl_rc_cstr(rc))); goto end; } (void)0
  fsl_b_reuse(pOut);         /* Merge results stored in pOut */

  /* If both pV1 and pV2 start with a UTF-8 byte-order-mark (BOM),
  ** keep it in the output. This should be secure enough not to cause
  ** unintended changes to the merged file and consistent with what
  ** users are using in their source files.
  */
  if( starts_with_utf8_bom(pV1, 0) && starts_with_utf8_bom(pV2, 0) ){
    rc = fsl_b_append(pOut, get_utf8_bom(0), 3);
    RC;
  }

  /* Check once to see if both pV1 and pV2 contains CR/LF endings.
  ** If true, CR/LF pair will be used later to append the
  ** boundary markers for merge conflicts.
  */
  if( contains_crlf(pV1) && contains_crlf(pV2) ){
    useCrLf = true;
  }

  /* Compute the edits that occur from pPivot => pV1 (into aC1)
  ** and pPivot => pV2 (into aC2).  Each of the aC1 and aC2 arrays is
  ** an array of integer triples.  Within each triple, the first integer
  ** is the number of lines of text to copy directly from the pivot,
  ** the second integer is the number of lines of text to omit from the
  ** pivot, and the third integer is the number of lines of text that are
  ** inserted.  The edit array ends with a triple of 0,0,0.
  */
  rc = fsl_diff_v2_raw(pPivot, pV1, NULL, &aC1);
  if(!rc) rc = fsl_diff_v2_raw(pPivot, pV2, NULL, &aC2);
  RC;
  assert(aC1 && aC2);

  /* Rewind inputs:  Needed to reconstruct output */
  fsl_b_rewind(pV1);
  fsl_b_rewind(pV2);
  fsl_b_rewind(pPivot);

  /* Determine the length of the aC1[] and aC2[] change vectors */
  for(i1=0; aC1[i1] || aC1[i1+1] || aC1[i1+2]; i1+=3){}
  limit1 = i1;
  for(i2=0; aC2[i2] || aC2[i2+1] || aC2[i2+2]; i2+=3){}
  limit2 = i2;

  FDEBUG(
    for(i1=0; i1<limit1; i1+=3){
      printf("c1: %4d %4d %4d\n", aC1[i1], aC1[i1+1], aC1[i1+2]);
    }
    for(i2=0; i2<limit2; i2+=3){
      printf("c2: %4d %4d %4d\n", aC2[i2], aC2[i2+1], aC2[i2+2]);
    }
  )

  /* Loop over the two edit vectors and use them to compute merged text
  ** which is written into pOut.  i1 and i2 are multiples of 3 which are
  ** indices into aC1[] and aC2[] to the edit triple currently being
  ** processed
  */
  i1 = i2 = 0;
  ln1 = ln2 = lnPivot = 1;
  while( i1<limit1 && i2<limit2 ){
    FDEBUG( printf("%d: %2d %2d %2d   %d: %2d %2d %2d\n",
           i1/3, aC1[i1], aC1[i1+1], aC1[i1+2],
           i2/3, aC2[i2], aC2[i2+1], aC2[i2+2]); )

    if( aC1[i1]>0 && aC2[i2]>0 ){
      /* Output text that is unchanged in both V1 and V2 */
      nCpy = mymin(aC1[i1], aC2[i2]);
      FDEBUG( printf("COPY %d\n", nCpy); )
      rc = fsl_b_copy_lines(pOut, pPivot, (fsl_size_t)nCpy);
      lnPivot += nCpy;
      if(!rc) rc = fsl_b_copy_lines(0, pV1, (fsl_size_t)nCpy);
      ln1 += nCpy;
      if(!rc) rc = fsl_b_copy_lines(0, pV2, (fsl_size_t)nCpy);
      ln2 += nCpy;
      RC;
      aC1[i1] -= nCpy;
      aC2[i2] -= nCpy;
    }else
    if( aC1[i1] >= aC2[i2+1] && aC1[i1]>0 && aC2[i2+1]+aC2[i2+2]>0 ){
      /* Output edits to V2 that occurs within unchanged regions of V1 */
      nDel = aC2[i2+1];
      nIns = aC2[i2+2];
      FDEBUG( printf("EDIT -%d+%d left\n", nDel, nIns); )
      rc = fsl_b_copy_lines(0, pPivot, (fsl_size_t)nDel);
      lnPivot += nDel;
      if(!rc) rc = fsl_b_copy_lines(0, pV1, (fsl_size_t)nDel);
      ln1 += nDel;
      if(!rc) rc = fsl_b_copy_lines(pOut, pV2, (fsl_size_t)nIns);
      ln2 += nIns;
      RC;
      aC1[i1] -= nDel;
      i2 += 3;
    }else
    if( aC2[i2] >= aC1[i1+1] && aC2[i2]>0 && aC1[i1+1]+aC1[i1+2]>0 ){
      /* Output edits to V1 that occur within unchanged regions of V2 */
      nDel = aC1[i1+1];
      nIns = aC1[i1+2];
      FDEBUG( printf("EDIT -%d+%d right\n", nDel, nIns); )
      rc = fsl_b_copy_lines(0, pPivot, (fsl_size_t)nDel);
      lnPivot += nDel;
      if(!rc) fsl_b_copy_lines(0, pV2, (fsl_size_t)nDel);
      ln2 += nDel;
      if(!rc) fsl_b_copy_lines(pOut, pV1, (fsl_size_t)nIns);
      ln1 += nIns;
      aC2[i2] -= nDel;
      i1 += 3;
    }else
    if( sameEdit(&aC1[i1], &aC2[i2], pV1, pV2) ){
      /* Output edits that are identical in both V1 and V2. */
      assert( aC1[i1]==0 );
      nDel = aC1[i1+1];
      nIns = aC1[i1+2];
      FDEBUG( printf("EDIT -%d+%d both\n", nDel, nIns); )
      rc = fsl_b_copy_lines(0, pPivot, (fsl_size_t)nDel);
      lnPivot += nDel;
      if(!rc) fsl_b_copy_lines(pOut, pV1, (fsl_size_t)nIns);
      ln1 += nIns;
      if(!rc) fsl_b_copy_lines(0, pV2, (fsl_size_t)nIns);
      ln2 += nIns;
      i1 += 3;
      i2 += 3;
    }else{
      /* We have found a region where different edits to V1 and V2 overlap.
      ** This is a merge conflict.  Find the size of the conflict, then
      ** output both possible edits separated by distinctive marks.
      */
      int sz = 1;    /* Size of the conflict in lines */
      ++nConflict;
      while( !ends_at_CPY(&aC1[i1], sz) || !ends_at_CPY(&aC2[i2], sz) ){
        ++sz;
      }
      FDEBUG( printf("CONFLICT %d\n", sz); )
      rc = append_merge_mark(pOut, 0, ln1, useCrLf);
      if(!rc) rc = output_one_side(pOut, pV1, aC1, i1, sz, &i1, &ln1);
      RC;

      rc = append_merge_mark(pOut, 1, lnPivot, useCrLf);
      if(!rc) rc = fsl_b_copy_lines(pOut, pPivot, sz);
      lnPivot += sz;
      RC;

      rc = append_merge_mark(pOut, 2, ln2, useCrLf);
      if(!rc) rc = output_one_side(pOut, pV2, aC2, i2, sz, &i2, &ln2);
      if(!rc) rc = append_merge_mark(pOut, 3, -1, useCrLf);
      RC;
    }

    /* If we are finished with an edit triple, advance to the next
    ** triple.
    */
    if( i1<limit1 && aC1[i1]==0 && aC1[i1+1]==0 && aC1[i1+2]==0 ) i1+=3;
    if( i2<limit2 && aC2[i2]==0 && aC2[i2+1]==0 && aC2[i2+2]==0 ) i2+=3;
  }

  /* When one of the two edit vectors reaches its end, there might still
  ** be an insert in the other edit vector.  Output this remaining
  ** insert.
  */
  FDEBUG( printf("%d: %2d %2d %2d   %d: %2d %2d %2d\n",
         i1/3, aC1[i1], aC1[i1+1], aC1[i1+2],
         i2/3, aC2[i2], aC2[i2+1], aC2[i2+2]); )
  if( i1<limit1 && aC1[i1+2]>0 ){
    FDEBUG( printf("INSERT +%d left\n", aC1[i1+2]); )
    rc = fsl_b_copy_lines(pOut, pV1, aC1[i1+2]);
  }else if( i2<limit2 && aC2[i2+2]>0 ){
    FDEBUG( printf("INSERT +%d right\n", aC2[i2+2]); )
    rc = fsl_b_copy_lines(pOut, pV2, aC2[i2+2]);
  }

  end:
  fsl_free(aC1);
  fsl_free(aC2);
  if(!rc && conflictCount) *conflictCount = nConflict;
  return rc;
#undef RC
}

bool fsl_b_contains_merge_marker(fsl_b const * const p){
  fsl_size_t i;
  fsl_size_t const len = (fsl_size_t)assert_mema_lengths();
  if(p->used <= len) return false;
  fsl_size_t j;
  const char * const z = (const char *)p->mem;
  fsl_size_t const n = p->used - len + 1;
  for(i=0; i<n; ){
    for(j=0; j<4; ++j){
      if( 0==memcmp(&z[i], mergeMarker[j], len) ){
        return true;
      }
    }
    while( i<n && z[i]!='\n' ){ ++i; }
    while( i<n && (z[i]=='\n' || z[i]=='\r') ){ ++i; }
  }
  return false;
}

#undef mymin
#undef FDEBUG
#undef ISFDEBUG
#undef MARKER
#if defined(NDEBUG)
#undef assert_mema_lengths
#endif
/* end of file src/merge3.c */
/* start of file src/msg.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2025 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2025 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**
  This file contains the fsl_msg pieces of the API.
*/
#include <assert.h>

const fsl_msg fsl_msg_empty = fsl_msg_empty_m;

const fsl_msg_listener fsl_msg_listener_empty =
  fsl_msg_listener_empty_m;

char const * fsl_msg_type_cstr(fsl_msg_e e){
  switch(e){
#define E(N,V,D) case FSL_MSG_ ## N: return "FSL_MSG_" # N;
    fsl_msg_map(E)
#undef E
  }
  return NULL;
}

int fsl_msg_emit(fsl_msg const * msg,
                 fsl_msg_listener const * where){
  if( where && where->callback ){
    return where->callback(msg, where->state);
  }
  return 0;
}

int fsl_cx_emit(fsl_cx * const f, fsl_msg_e type, void const * p){
  if( f->cxConfig.listener.callback ){
    const fsl_msg msg = {
      .type = type, .payload = p, .f = f
    };
    return f->cxConfig.listener.callback(
      &msg, f->cxConfig.listener.state
    );
  }
  return 0;
}

static inline void const * fsl__msg_strbuf(fsl_msg_e type,
                                              fsl_b const * const b){
  switch( type & FSL_MSG_mask_type ){
    case FSL_MSG_type_string: return fsl_b_cstr(b);
    case FSL_MSG_type_buffer: return b;
    default: return 0;
  }
}

int fsl_cx_emitfv(fsl_cx *f, fsl_msg_e type, char const * zFmt, va_list args){
  int rc = 0;
  if( f->cxConfig.listener.callback ){
    switch( type & FSL_MSG_mask_type ){
      case FSL_MSG_type_string:
      case FSL_MSG_type_buffer: {
        fsl_b * const b = fsl_b_reuse(&f->scratchpads.emit);
        rc = fsl_b_appendfv(b, zFmt, args);
        if( 0==rc ){
          fsl_msg const m = {
            .type = type, .payload = fsl__msg_strbuf(type,b), .f = f
          };
          rc = f->cxConfig.listener.callback(&m, f->cxConfig.listener.state);
        }
        break;
      }
      default:
        assert(!"invalid message type id");
        fsl__fatal(FSL_RC_TYPE, "Invalid message type 0x%08x for %s(). "
                   "Must have type FSL_MSG_type_string|buffer",
                   type, __func__);
        break;
    }
  }
  return rc;
}

int fsl_cx_emitf(fsl_cx *f, fsl_msg_e type, char const * zFmt, ...){
  int rc = 0;
  if( f->cxConfig.listener.callback ){
    va_list args;
    va_start(args, zFmt);
    rc = fsl_cx_emitfv(f, type, zFmt, args);
    va_end(args);
  }
  return rc;
}

void fsl_cx_listener_replace(fsl_cx * f, fsl_msg_listener const *pNew,
                             fsl_msg_listener * pOld){
  if( pOld ){
    *pOld = f->cxConfig.listener;
  }
  f->cxConfig.listener = *pNew;
}
/* end of file src/msg.c */
/* start of file src/popen.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
** Copyright (c) 2010 D. Richard Hipp
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
** known as the "2-Clause License" or "FreeBSD License".)
**
** This program is distributed in the hope that it will be useful,
** but without any warranty; without even the implied warranty of
** merchantability or fitness for a particular purpose.
**
** Author contact information:
**   [email protected]
**   http://www.hwaci.com/drh/
**
*******************************************************************************
**
** This file contains an implementation of a bi-directional popen().
*/
/*************************************************************************
  This copy has been modified slightly for use in the libfossil project.
*/
#undef __STRICT_ANSI__
#include <errno.h>

#if FSL_PLATFORM_IS_WINDOWS
#include <windows.h>
#include <fcntl.h>
#include <io.h> /* _open_osfhandle(), close() */
#else
#include <fcntl.h> /* open() */
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#endif

#if FSL_PLATFORM_IS_WINDOWS
/*
   On Windows, create a child process running the command line zCmd
   directly (no shell), with the given standard handles. On success
   *phProcess is the child's process handle, which the caller must
   close. Returns 0 on success, non-0 on error.
*/
static int win32_create_child_process(
  wchar_t *zCmd,       /* The command line the child process will run */
  HANDLE hIn,          /* Standard input */
  HANDLE hOut,         /* Standard output */
  HANDLE hErr,         /* Standard error */
  HANDLE *phProcess    /* OUT: Child process handle */
){
  STARTUPINFOW si;
  PROCESS_INFORMATION pi;
  BOOL rc;

  memset(&si, 0, sizeof(si));
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESTDHANDLES;
  SetHandleInformation(hIn, HANDLE_FLAG_INHERIT, TRUE);
  si.hStdInput  = hIn;
  SetHandleInformation(hOut, HANDLE_FLAG_INHERIT, TRUE);
  si.hStdOutput = hOut;
  SetHandleInformation(hErr, HANDLE_FLAG_INHERIT, TRUE);
  si.hStdError  = hErr;
  rc = CreateProcessW(
     NULL,  /* Application Name */
     zCmd,  /* Command-line */
     NULL,  /* Process attributes */
     NULL,  /* Thread attributes */
     TRUE,  /* Inherit Handles */
     0,     /* Create flags  */
     NULL,  /* Environment */
     NULL,  /* Current directory */
     &si,   /* Startup Info */
     &pi    /* Process Info */
  );
  if( !rc ) return 1;
  CloseHandle( pi.hThread );
  *phProcess = pi.hProcess;
  return 0;
}
#endif

/**
   Create a child process running command "zCmd". *pfdIn gets
   assigned to the stdout from the child process. (The caller reads
   from *pfdIn in order to receive input from the child.) Note that
   *pfdIn is an unbuffered file descriptor, not a FILE.

   If zStdinFile is not NULL, the child reads its standard input from
   that file and *ppOut is set to NULL. Otherwise *ppOut gets assigned
   to a FILE that becomes the standard input of the child process.
   (The caller writes to *ppOut in order to send text to the child.)

   On Unix zCmd runs through /bin/sh. On Windows it is run directly
   by CreateProcessW() as a command line, so it may not use shell
   features such as redirections.

   *pChildPid identifies the child for fsl__pclose2(): on Unix it is
   the process id, on Windows the process handle, which Windows
   guarantees fits in 32 bits.

   On success the values returned via *pfdIn, *ppOut, and *pChildPid
   must be passed to fsl__pclose2() to properly clean up.

   Return 0 on success, non-0 on error.
*/
int fsl__popen2(const char *zCmd, const char *zStdinFile,
                int *pfdIn, FILE **ppOut, int *pChildPid){
#if FSL_PLATFORM_IS_WINDOWS
  HANDLE hStdinRd = INVALID_HANDLE_VALUE, hStdinWr = INVALID_HANDLE_VALUE;
  HANDLE hStdoutRd, hStdoutWr, hStderr, hProcess = NULL;
  SECURITY_ATTRIBUTES saAttr;
  wchar_t * zW = NULL;
  int fd, rc = 0;

  *pfdIn = -1;
  *ppOut = NULL;
  *pChildPid = 0;
  saAttr.nLength = sizeof(saAttr);
  saAttr.bInheritHandle = TRUE;
  saAttr.lpSecurityDescriptor = NULL;
  hStderr = GetStdHandle(STD_ERROR_HANDLE);
  if( zStdinFile ){
    wchar_t * const zF = fsl_utf8_to_unicode(zStdinFile);
    if( !zF ) return FSL_RC_OOM;
    hStdinRd = CreateFileW(zF, GENERIC_READ,
                           FILE_SHARE_READ | FILE_SHARE_WRITE
                           | FILE_SHARE_DELETE,
                           &saAttr, OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL, NULL);
    fsl_free(zF);
    if( INVALID_HANDLE_VALUE==hStdinRd ) return FSL_RC_IO;
  }else if( !CreatePipe(&hStdinRd, &hStdinWr, &saAttr, 4096) ){
    return FSL_RC_IO;
  }else{
    SetHandleInformation( hStdinWr, HANDLE_FLAG_INHERIT, FALSE);
  }
  if( !CreatePipe(&hStdoutRd, &hStdoutWr, &saAttr, 4096) ){
    CloseHandle(hStdinRd);
    if( INVALID_HANDLE_VALUE!=hStdinWr ) CloseHandle(hStdinWr);
    return FSL_RC_IO;
  }
  SetHandleInformation( hStdoutRd, HANDLE_FLAG_INHERIT, FALSE);
  zW = fsl_utf8_to_unicode(zCmd);
  if( !zW ) rc = FSL_RC_OOM;
  else if( win32_create_child_process(zW, hStdinRd, hStdoutWr, hStderr,
                                      &hProcess) ){
    rc = FSL_RC_ERROR;
  }
  fsl_free(zW);
  CloseHandle(hStdinRd);
  CloseHandle(hStdoutWr);
  if( rc ){
    CloseHandle(hStdoutRd);
    if( INVALID_HANDLE_VALUE!=hStdinWr ) CloseHandle(hStdinWr);
    return rc;
  }
  *pChildPid = (int)(intptr_t)hProcess;
  *pfdIn = _open_osfhandle((intptr_t)hStdoutRd, 0);
  if( INVALID_HANDLE_VALUE!=hStdinWr ){
    fd = _open_osfhandle((intptr_t)hStdinWr, 0);
    *ppOut = _fdopen(fd, "w");
  }
  return 0;
#else
  int rc;
  int pin[2], pout[2] = {-1, -1};
  int fdStdin = -1;
  *pfdIn = -1;
  *ppOut = 0;
  *pChildPid = 0;

  if( zStdinFile ){
    fdStdin = open(zStdinFile, O_RDONLY);
    if( fdStdin<0 ) return fsl_errno_to_rc(errno, FSL_RC_IO);
  }
  if( pipe(pin)<0 ){
    rc = fsl_errno_to_rc(errno, FSL_RC_ERROR);
    if( fdStdin>=0 ) close(fdStdin);
    return rc;
  }
  if( fdStdin<0 && pipe(pout)<0 ){
    rc = fsl_errno_to_rc(errno, FSL_RC_ERROR);
    close(pin[0]);
    close(pin[1]);
    return rc;
  }
  *pChildPid = fork();
  if( *pChildPid<0 ){
    rc = fsl_errno_to_rc(errno, FSL_RC_ERROR);
    close(pin[0]);
    close(pin[1]);
    if( fdStdin>=0 ) close(fdStdin);
    else{
      close(pout[0]);
      close(pout[1]);
    }
    *pChildPid = 0;
    return rc;
  }
  if( *pChildPid==0 ){
    int fd;
    /* This is the child process */
    close(0);
    if( fdStdin>=0 ){
      fd = dup(fdStdin);
      close(fdStdin);
    }else{
      fd = dup(pout[0]);
      close(pout[0]);
      close(pout[1]);
    }
    if( fd!=0 ) { /* nop */ };
    close(1);
    fd = dup(pin[1]);
    if( fd!=1 ) { /* nop */ };
    close(pin[0]);
    close(pin[1]);
    execl("/bin/sh", "/bin/sh", "-c", zCmd, (char*)0)
      /* doesn't return on success */;
    /* Returning here would run the caller's code in the child. Exit
       with the shell's "command not found" status, which the parent
       sees via fsl__pclose2(). */
    _exit(127);
  }else{
    /* This is the parent process */
    close(pin[1]);
    *pfdIn = pin[0];
    if( fdStdin>=0 ){
      close(fdStdin);
    }else{
      close(pout[0]);
      *ppOut = fdopen(pout[1], "w");
    }
    return 0;
  }
#endif
}

/**
   Close the connection to a child process previously created using
   fsl__popen2(). All 3 arguments are assumed to values returned via
   fsl__popen2()'s output parameters: the input file descriptor,
   output FILE handle (may be NULL), and the child's id.

   This blocks until the child exits, and returns its exit status, or
   (on Unix) the negated number of the signal that ended the child.
   It returns 0 if the child's status cannot be determined. This used
   to kill the child but in the normal case that is never needed.
   Consider extending this function to request a kill if child
   appears to have a network hang.
*/
int fsl__pclose2(int fdIn, FILE *pOut, int childPid){
#if FSL_PLATFORM_IS_WINDOWS
  /* childPid is the process handle from fsl__popen2(). */
  HANDLE const hProcess = (HANDLE)(intptr_t)childPid;
  DWORD code = 0;
  close(fdIn);
  if(pOut) fclose(pOut);
  if( hProcess ){
    WaitForSingleObject(hProcess, INFINITE);
    if( !GetExitCodeProcess(hProcess, &code) ) code = 0;
    CloseHandle(hProcess);
  }
  return (int)code;
#elif 1
  int wp, rc = 0;
  close(fdIn);
  if( pOut ) fclose(pOut);
  /* Block until the child exits. Its output may go to a file:// given
     on its command line instead of to fdIn, in which case EOF on fdIn
     says nothing about whether the child has finished writing. */
  do{
    wp = waitpid((pid_t)childPid, &rc, 0);
  } while( wp<0 && EINTR==errno );
  if( wp>0 ){
    if( WIFEXITED(rc) ){
      rc = WEXITSTATUS(rc);
    }else if( WIFSIGNALED(rc) ){
      rc = -WTERMSIG(rc);
    }else{
      rc = 0/*???*/;
    }
  }else{
    rc = 0;
  }
  return rc;
#endif
}

/* end of file src/popen.c */
/* start of file src/pq.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/************************************************************************
  This file houses the priority queue class.
*/
#include <assert.h>


void fsl__pq_clear(fsl__pq *p){
  fsl_free(p->list);
  *p = fsl__pq_empty;
}

/*
   Change the size of the queue so that it contains N slots
*/
static int fsl__pq_resize(fsl__pq *p, fsl_size_t N){
  void * re = fsl_realloc(p->list, sizeof(fsl__pq_entry)*N);
  if(!re) return FSL_RC_OOM;
  else{
    p->list = (fsl__pq_entry*)re;
    p->capacity = N;
    return 0;
  }
}

/**
   Insert element e into the queue.
*/
int fsl__pq_insert(fsl__pq *p, fsl_id_t e,
                  double v, void *pData){
  fsl_size_t i, j;
  if( p->used+1>p->capacity ){
    int const rc = fsl__pq_resize(p, p->used+5);
    if(rc) return rc;
  }
  for(i=0; i<p->used; ++i){
    if( p->list[i].priority>v ){
      for(j=p->used; j>i; --j){
        p->list[j] = p->list[j-1];
      }
      break;
    }
  }
  p->list[i].id = e;
  p->list[i].data = pData;
  p->list[i].priority = v;
  ++p->used;
  return 0;
}

fsl_id_t fsl__pq_extract(fsl__pq *p, void **pp){
  fsl_id_t e, i;
  if( p->used==0 ){
    if( pp ) *pp = 0;
    return 0;
  }
  e = p->list[0].id;
  if( pp ) *pp = p->list[0].data;
  for(i=0; i<((fsl_id_t)p->used-1); ++i){
    p->list[i] = p->list[i+1];
  }
  --p->used;
  return e;
}
/* end of file src/pq.c */
/* start of file src/repo.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/***********************************************************************
  This file implements most of the fsl_repo_xxx() APIs.
*/
#include <assert.h>
#include <memory.h> /* memcpy() */
#include <time.h> /* time() */
#include <errno.h>

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

/**
   Calculate the youngest ancestor of the given blob.rid value that is a member of
   branch zBranch.

   Returns the blob.id value of the matching record, 0 if not found,
   or a negative value on error.

   Potential TODO: do we need this in the public API?
*/
static fsl_id_t fsl__youngest_ancestor_in_branch(fsl_cx * f, fsl_id_t rid,
                                                 const char *zBranch){
  fsl_db * const db = fsl_needs_repo(f);
  if(!db) return (fsl_id_t)-1;
  return fsl_db_g_id(db, 0,
    "WITH RECURSIVE "
    "  ancestor(rid, mtime) AS ("
    "    SELECT %"FSL_ID_T_PFMT", "
    "      mtime FROM {{dbname.repo}}.event AS event WHERE objid=%"FSL_ID_T_PFMT
    "    UNION "
    "    SELECT plink.pid, event.mtime"
    "      FROM ancestor, {{dbname.repo}}.plink AS plink, {{dbname.repo}}.event AS event"
    "     WHERE plink.cid=ancestor.rid"
    "       AND event.objid=plink.pid"
    "     ORDER BY mtime DESC"
    "  )"
    "  SELECT ancestor.rid FROM ancestor"
    "   WHERE EXISTS(SELECT 1 FROM {{dbname.repo}}.tagxref AS tagxref"
                    " WHERE tagid=%d AND tagxref.rid=ancestor.rid"
                    "   AND value=%Q AND tagtype>0)"
    "  ORDER BY mtime DESC"
    "  LIMIT 1",
    rid, rid, FSL_TAGID_BRANCH, zBranch
  );
}

int fsl_branch_of_rid(fsl_cx * const f, fsl_id_t rid,
                      bool doFallback, char ** zOut ){
  char *zBr = 0;
  if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_branchOfRid);
  if( !q ) return f->error.code;
  int rc = fsl_stmt_bind_step_v2(q, "R", rid);
  if( FSL_RC_STEP_ROW==rc ){
    fsl_size_t nz = 0;
    char const * zz = fsl_stmt_g_text(q, 0, &nz);
    rc = 0;
    if( zz ){
      zBr = fsl_strndup(zz, nz);
      if( !zBr ){
        rc = FSL_RC_OOM;
      }
    }
  }else if( FSL_RC_STEP_DONE==rc ){
    rc = 0;
  }else{
    rc = fsl_cx_uplift_db_error2(f, q->db, rc);
  }
  fsl__cx_stmt_yield(f, q);
  if( !rc ){
    if( zBr==0 && doFallback ){
      zBr = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", 0);
      if(!zBr){
        fsl_cx_err_reset(f)/* assume FSL_RC_NOT_FOUND */;
        zBr = fsl_strdup("trunk");
        if(!zBr) rc = FSL_RC_OOM;
      }
    }
    if(0==rc) *zOut = zBr;
  }
  return rc;
}

/**
   mrewt ==> most recent event with tag

   Comments from original fossil implementation:

   Find the RID of the most recent object with symbolic tag zTag and
   having a type that matches zType.

   Return 0 if there are no matches.

   This is a tricky query to do efficiently.  If the tag is very
   common (ex: "trunk") then we want to use the query identified below
   as Q1 - which searching the most recent EVENT table entries for the
   most recent with the tag.  But if the tag is relatively scarce
   (anything other than "trunk", basically) then we want to do the
   indexed search show below as Q2.
*/
static fsl_id_t fsl__mrewt(fsl_cx * const f, const char *zTag, fsl_satype_e type){
  char const * zType = fsl_satype_event_cstr(type);
  return fsl_db_g_id(fsl_cx_db_repo(f), 0,
    "SELECT objid FROM ("
      /* Q1:  Begin by looking for the tag in the 30 most recent events */
      "SELECT objid"
       " FROM (SELECT * FROM {{dbname.repo}}.event ORDER BY mtime DESC LIMIT 30) AS ex"
      " WHERE type GLOB '%q'"
        " AND EXISTS(SELECT 1 FROM {{dbname.repo}}.tagxref AS tagxref, {{dbname.repo}}.tag AS tag"
                     " WHERE tag.tagname='sym-%q'"
                       " AND tagxref.tagid=tag.tagid"
                       " AND tagxref.tagtype>0"
                       " AND tagxref.rid=ex.objid)"
      " ORDER BY mtime DESC LIMIT 1"
    ") UNION ALL SELECT * FROM ("
      /* Q2: If the tag is not found in the 30 most recent events, then using
      ** the tagxref table to index for the tag */
      "SELECT event.objid"
       " FROM {{dbname.repo}}.tag AS tag, {{dbname.repo}}.tagxref AS tagxref, {{dbname.repo}}.event AS event"
      " WHERE tag.tagname='sym-%q'"
        " AND tagxref.tagid=tag.tagid"
        " AND tagxref.tagtype>0"
        " AND event.objid=tagxref.rid"
        " AND event.type GLOB '%q'"
      " ORDER BY event.mtime DESC LIMIT 1"
    ") LIMIT 1;",
    zType, zTag, zTag, zType
  );
}

/**
   Modes for fsl__start_of_branch().

   These values are hard-coded and must retain these values,
   else queries will break.
*/
enum fsl__stobr_type {
/**
   The check-in of the parent branch off of which
   the branch containing RID originally diverged.
*/
FSL__STOBR_ORIGIN = 0,
/**
   The first check-in of the branch that contains RID.
*/
FSL__STOBR_FIRST_CI = 1,
/**
   The youngest ancestor of RID that is on the branch from which the
   branch containing RID diverged.
*/
FSL__STOBR_YOAN = 2
};

/*
** Return the RID that is the "root" of the branch that contains
** check-in "rid".  Details depending on eType. If not found, rid is
** returned.
*/
static fsl_id_t fsl__start_of_branch(fsl_cx * const f, fsl_id_t rid,
                                     enum fsl__stobr_type eType){
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  fsl_id_t ans = rid;
  char * zBr = 0;
  rc = fsl_branch_of_rid(f, rid, true, &zBr);
  if(rc) return -1;
  rc = fsl_cx_prepare(f, &q,
    "WITH RECURSIVE"
    "  par(pid, ex, cnt) as ("
    "    SELECT pid, EXISTS(SELECT 1 FROM {{dbname.repo}}.tagxref"
    "                        WHERE tagid=%d AND tagtype>0"
    "                          AND value=%Q AND rid=plink.pid), 1"
    "    FROM {{dbname.repo}}.plink AS plink WHERE cid=%"FSL_ID_T_PFMT" AND isprim"
    "    UNION ALL "
    "    SELECT plink.pid, EXISTS(SELECT 1 FROM {{dbname.repo}}.tagxref "
    "                              WHERE tagid=%d AND tagtype>0"
    "                                AND value=%Q AND rid=plink.pid),"
    "           1+par.cnt"
    "      FROM {{dbname.repo}}.plink AS plink, par"
    "     WHERE cid=par.pid AND isprim AND par.ex "
    "     LIMIT 100000 "
    "  )"
    " SELECT pid FROM par WHERE ex>=%d ORDER BY cnt DESC LIMIT 1",
    FSL_TAGID_BRANCH, zBr, ans, FSL_TAGID_BRANCH, zBr, eType%2
  );
  fsl_free(zBr);
  zBr = 0;
  if(rc){
    ans = -2;
    MARKER(("Internal error: fsl_db_prepare() says: %s\n", fsl_rc_cstr(rc)));
    goto end;
  }
  if( FSL_RC_STEP_ROW == fsl_stmt_step(&q) ) {
    ans = fsl_stmt_g_id(&q, 0);
  }
  fsl_stmt_finalize(&q);
  end:
  if( ans>0 && eType==FSL__STOBR_YOAN ){
    rc = fsl_branch_of_rid(f, ans, true, &zBr);
    if(rc) goto oom;
    else{
      ans = fsl__youngest_ancestor_in_branch(f, rid, zBr);
      fsl_free(zBr);
    }
  }
  return ans;
  oom:
  if(!f->error.code){
    fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  }/* Else assume the OOM is really a misleading
      side-effect of another failure. */
  return -1;
}

int fsl_sym_to_rid( fsl_cx * const f, char const * sym,
                    fsl_satype_e type, fsl_id_t * const rv ){
  fsl_id_t rid = 0;
  fsl_id_t vid;
  fsl_size_t symLen;
  /* fsl_int_t i; */
  fsl_db * const dbR = fsl_cx_db_repo(f);
  fsl_db * const dbC = fsl_cx_db_ckout(f);
  bool startOfBranch = 0;
  int rc = 0;

  if(!rv) return FSL_RC_MISUSE;
  else if(!sym || !*sym){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Empty symbolic name.");
  }else if(!dbR){
    fsl_needs_repo(f);
    return FSL_RC_NOT_A_REPO;
  }

  if(FSL_SATYPE_BRANCH_START==type){
    /* The original implementation takes a (char const *) for the
       type, and treats "b" (branch?) as a special case of
       FSL_SATYPE_CHECKIN, resets the type to "ci", then sets
       startOfBranch to 1. We introduced the FSL_SATYPE_BRANCH
       pseudo-type for that purpose. That said: the original code
       base does not, as of this writing (2021-02-15) appear to actually
       use this feature anywhere. */
    type = FSL_SATYPE_CHECKIN;
    startOfBranch = 1;
  }

  /* special keyword: "tip" */
  if( 0==fsl_strcmp(sym,"tip")
      && (FSL_SATYPE_ANY==type || FSL_SATYPE_CHECKIN==type)){
    rid = fsl_db_g_id(dbR, 0,
                      "SELECT objid FROM {{dbname.repo}}.event AS event"
                      " WHERE type='ci'"
                      " ORDER BY event.mtime DESC"
                      " LIMIT 1");
    if(rid>0) goto gotit;
  }
  /* special keywords: "prev", "previous", "current", and "next".
     These require a checkout.
  */
  vid = dbC ? f->db.ckout.rid : 0;
  //MARKER(("has vid=%"FSL_ID_T_PFMT"\n", vid));
  if( vid>0){
    if( 0==fsl_strcmp(sym, "current") ){
      rid = vid;
    }
    else if( 0==fsl_strcmp(sym, "prev")
             || 0==fsl_strcmp(sym, "previous") ){
      rid = fsl_db_g_id(dbR, 0,
                        "SELECT pid FROM {{dbname.repo}}.plink WHERE "
                        "cid=%"FSL_ID_T_PFMT" AND isprim",
                        (fsl_id_t)vid);
    }
    else if( 0==fsl_strcmp(sym, "next") ){
      rid = fsl_db_g_id(dbR, 0,
                        "SELECT cid FROM {{dbname.repo}}.plink WHERE "
                        "pid=%"FSL_ID_T_PFMT
                        " ORDER BY isprim DESC, mtime DESC",
                        (fsl_id_t)vid);
    }
    if(rid>0) goto gotit;
  }

  /* Date and times */
  if( 0==strncmp(sym, "date:", 5) ){
    rid = fsl_db_g_id(dbR, 0,
                      "SELECT objid FROM {{dbname.repo}}.event"
                      " WHERE mtime<=julianday(%Q,'utc')"
                      " AND type GLOB '%q'"
                      " ORDER BY mtime DESC LIMIT 1",
                      sym+5, fsl_satype_event_cstr(type));
    goto gotit;
  }
  if( fsl_str_is_date(sym) ){
    rid = fsl_db_g_id(dbR, 0,
                      "SELECT objid FROM {{dbname.repo}}.event"
                      " WHERE mtime<=julianday(%Q,'utc')"
                      " AND type GLOB '%q'"
                      " ORDER BY mtime DESC LIMIT 1",
                      sym, fsl_satype_event_cstr(type));
    if(rid>0) goto gotit;
  }

  /* Deprecated time formats elided: local:..., utc:... */

  /* "tag:" + symbolic-name */
  if( strncmp(sym, "tag:", 4)==0 ){
    rid = fsl__mrewt(f, sym+4, type);
    if(rid>0 && startOfBranch){
      rid = fsl__start_of_branch(f, rid, FSL__STOBR_FIRST_CI);
    }
    goto gotit;
  }

  /* root:TAG -> The origin of the branch */
  if( strncmp(sym, "root:", 5)==0 ){
    rc = fsl_sym_to_rid(f, sym+5, type, &rid);
    if(!rc && rid>0){
      rid = fsl__start_of_branch(f, rid, FSL__STOBR_ORIGIN);
    }
    goto gotit;
  }

  /* start:TAG -> The first check-in on branch named TAG */
  if( strncmp(sym, "start:", 6)==0 ){
    rc = fsl_sym_to_rid(f, sym+6, type, &rid);
    if(!rc && rid>0){
      rid = fsl__start_of_branch(f, rid, FSL__STOBR_FIRST_CI);
    }
    goto gotit;
  }

  /* merge-in:TAG -> Most recent merge-in for the branch */
  if( strncmp(sym, "merge-in:", 9)==0 ){
    rc = fsl_sym_to_rid(f, sym+9, type, &rid);
    if(!rc){
      rid = fsl__start_of_branch(f, rid, FSL__STOBR_YOAN);
    }
    goto gotit;
  }

  symLen = fsl_strlen(sym);
  /* SHA1/SHA3 hash or prefix */
  if( symLen>=4
      && symLen<=FSL_STRLEN_K256
      && fsl_validate16(sym, symLen) ){
    fsl_stmt q = fsl_stmt_empty;
    char zUuid[FSL_STRLEN_K256+1];
    memcpy(zUuid, sym, symLen);
    zUuid[symLen] = 0;
    fsl_canonical16(zUuid, symLen);
    rid = 0;
    /* Reminder to self: caching these queries would be cool. */
    if( FSL_SATYPE_ANY==type ){
      rc = fsl_cx_prepare(f, &q,
                          "SELECT rid FROM {{dbname.repo}}.blob WHERE uuid GLOB '%s*'",
                          zUuid);
    }else{
      rc = fsl_cx_prepare(f, &q,
                          "SELECT blob.rid"
                          "  FROM {{dbname.repo}}.blob AS blob, {{dbname.repo}}.event AS event"
                          " WHERE blob.uuid GLOB '%s*'"
                          "   AND event.objid=blob.rid"
                          "   AND event.type GLOB '%q'",
                          zUuid, fsl_satype_event_cstr(type) );
    }
    if( rc ) return rc;
    if( fsl_stmt_step(&q)==FSL_RC_STEP_ROW ){
      int64_t r64 = 0;
      fsl_stmt_get_int64(&q, 0, &r64);
      if( fsl_stmt_step(&q)==FSL_RC_STEP_ROW ) rid = -1
        /* Ambiguous results */
        ;
      else rid = (fsl_id_t)r64;
    }
    fsl_stmt_finalize(&q);
    if(rid<0){
      fsl_cx_err_set(f, FSL_RC_AMBIGUOUS,
                     "Symbolic name is ambiguous: %s",
                     sym);
    }
    goto gotit
      /* None of the further checks against the sym can pass. */
      ;
  }

  if(FSL_SATYPE_WIKI==type){
    rid = fsl_db_g_id(dbR, 0,
                    "SELECT event.objid, max(event.mtime)"
                    "  FROM {{dbname.repo}}.tag AS tag, {{dbname.repo}}.tagxref AS tagxref, {{dbname.repo}}.event AS event"
                    " WHERE tag.tagname='sym-%q' "
                    "   AND tagxref.tagid=tag.tagid AND tagxref.tagtype>0 "
                    "   AND event.objid=tagxref.rid "
                    "   AND event.type GLOB '%q'",
                    sym, fsl_satype_event_cstr(type)
    );
  }else{
    rid = fsl__mrewt(f, sym, type);
    //MARKER(("mrewt(%s,%s) == %d\n", sym, fsl_satype_cstr(type), (int)rid));
  }

  if( rid>0 ){
    if(startOfBranch) rid = fsl__start_of_branch(f, rid,
                                                 FSL__STOBR_FIRST_CI);
    goto gotit;
  }

  /* Undocumented: rid:### ==> validate that ### is a known rid */
  if(symLen>4 && 0==fsl_strncmp("rid:",sym,4)){
    int i;
    char const * oldSym = sym;
    sym += 4;
    for(i=0; fsl_isdigit(sym[i]); i++){}
    if( sym[i]==0 ){
      /* It's an integer. */
      if( FSL_SATYPE_ANY==type ){
        rid = fsl_db_g_id(dbR, 0,
                          "SELECT rid"
                          "  FROM {{dbname.repo}}.blob"
                          " WHERE rid=%s",
                          sym);
      }else{
        rid = fsl_db_g_id(dbR, 0,
                          "SELECT event.objid"
                          "  FROM {{dbname.repo}}.event AS event"
                          " WHERE event.objid=%s"
                          "   AND event.type GLOB '%q'",
                          sym, fsl_satype_event_cstr(type));
      }
      if( rid>0 ) goto gotit;
    }
    sym = oldSym;
  }

  gotit:
  if(rid<=0){
    return f->error.code
      ? f->error.code
      : fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                       "Could not resolve symbolic name '%s'%s%s.",
                       sym,
                       FSL_SATYPE_ANY==type ? "" : " as type ",
                       FSL_SATYPE_ANY==type ? "" : fsl_satype_cstr(type));
  }
  assert(0==rc);
  *rv = rid;
  return rc;
}

fsl_id_t fsl__uuid_to_rid2(fsl_cx * const f, fsl_uuid_cstr uuid,
                           fsl__phantom_e mode){
    if(!f) return -1;
    else if(!fsl_is_uuid(uuid)){
      fsl_cx_err_set(f, FSL_RC_MISUSE,
                     "fsl__uuid_to_rid2() requires a "
                     "full UUID. Got: %s", uuid);
      return -2;
    }else{
      fsl_id_t rv = fsl_uuid_to_rid(f, uuid);
      if((0==rv) && (FSL_PHANTOM_NONE!=mode)
         && 0!=fsl__phantom_new(f, uuid,
                                (FSL_PHANTOM_PRIVATE==mode),
                                &rv)){
        assert(f->error.code);
        rv = -3;
      }
      return rv;
    }
}

int fsl_sym_to_uuid( fsl_cx * const f, char const * sym, fsl_satype_e type,
                     fsl_uuid_str * const rv, fsl_id_t * const rvId ){
  fsl_id_t rid = 0;
  fsl_db * dbR = fsl_needs_repo(f);
  fsl_uuid_str rvv = NULL;
  int rc = dbR
    ? fsl_sym_to_rid(f, sym, type, &rid)
    : FSL_RC_NOT_A_REPO;
  if(!rc){
    if(rvId) *rvId = rid;
    rvv = fsl_rid_to_uuid(f, rid)
      /* TODO: use a cached "exists" check if !rv, to avoid allocating
         rvv if we don't need it.
      */;
    if(!rvv){
      rc = f->error.code
        ? f->error.code
        : fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                         "Cannot find UUID for RID %"FSL_ID_T_PFMT".",
                         rid);
    }
    else if(rv){
      *rv = rvv;
    }else{
      fsl_free( rvv );
    }
  }
  return rc;
}

fsl_id_t fsl_uuid_to_rid( fsl_cx * const f, char const * uuid ){
  fsl_db * const db = fsl_needs_repo(f);
  fsl_size_t const uuidLen = (uuid && db) ? fsl_strlen(uuid) : 0;
  if(!db){
    /* f's error state has already been set */
    assert(FSL_RC_NOT_A_REPO == f->error.code);
    return -2;
  }else if(!uuid || !uuidLen){
    fsl_cx_err_set(f, FSL_RC_RANGE, "Empty UUID (prefix).");
    return -1;
  }else if(!fsl_validate16(uuid, uuidLen)){
    fsl_cx_err_set(f, FSL_RC_RANGE, "Invalid UUID (prefix): %s", uuid);
    return -3;
  }else if(uuidLen>FSL_STRLEN_K256){
    fsl_cx_err_set(f, FSL_RC_RANGE, "UUID is too long: %s", uuid);
    return -4;
  }else{
    fsl_id_t rid = -5;
    fsl_stmt qGlob = fsl_stmt_empty;
    fsl_stmt * q = NULL;
    int rc = 0;
    bool const isGlob = !fsl_is_uuid_len((int)uuidLen);
    if(isGlob){
      q = &qGlob;
      /* Maintenance reminder: rumor has it that GLOB '%q*' is more
         efficient than GLOB %Q || '*', the latter, rumor says,
         requiring a full table scan in some cases which the former
         does not. i.e. don't cache this in f->stmt with the latter
         formulation. */
      rc = fsl_cx_prepare(f, q, "SELECT rid FROM {{dbname.repo}}.blob"
                          " WHERE uuid GLOB '%q*' /*%s()*/",
                          uuid, __func__);
    }else{
      /* Optimization for the common internally-used case.*/
      q = fsl__cx_stmt(f, fsl__cx_stmt_e_uuidToRid);
      if( !q ) rc = f->error.code;
    }
    if(rc){
      rid = -10;
      goto end;
    }
    rc = (&qGlob==q)
      ? fsl_stmt_step(q)
      : fsl_stmt_bind_step_v2(q, "s", uuid);
    switch(rc){
      case FSL_RC_STEP_ROW:
        rc = 0;
        rid = fsl_stmt_g_id(q, 0);
        if(isGlob){
          /* Check for an ambiguous result. We don't need this for
             the !isGlob case because that one does an exact match
             on a unique key. */
          rc = fsl_stmt_step(q);
          switch(rc){
            case FSL_RC_STEP_ROW:
              rc = 0;
              fsl_cx_err_set(f, FSL_RC_AMBIGUOUS,
                             "UUID prefix is ambiguous: %s",
                             uuid);
              rid = -6;
              break;
            case FSL_RC_STEP_DONE:
              /* Unambiguous UUID */
              rc = 0;
              break;
            default:
              assert(q->db->error.code);
              rid = -7;
              break;
          }
        }
        break;
      case FSL_RC_STEP_DONE:
        rid = 0;
        rc = 0;
        break;
      default:
        assert(q->db->error.code);
        rid = -7;
        break;
    }
    if(rc && q->db->error.code && !f->error.code){
      fsl_cx_uplift_db_error(f, q->db);
    }
  end:
    if( &qGlob != q ) fsl__cx_stmt_yield(f, q);
    fsl_stmt_finalize(&qGlob);
    return rid;
  }
}

fsl_id_t fsl_repo_filename_fnid( fsl_cx * f, char const * fn ){
  fsl_id_t rv = 0;
  int const rc = fsl__repo_filename_fnid2(f, fn, &rv, false);
  return rv>=0 ? rv : (rc>0 ? -rc : rc);
}

int fsl__repo_filename_fnid2( fsl_cx * f, char const * fn, fsl_id_t * rv, bool createNew ){
  fsl_db * db = fsl_cx_db_repo(f);
  fsl_id_t fnid = 0;
  fsl_stmt * qSel = NULL;
  int rc;
  assert(f);
  assert(db);
  assert(rv);
  /* Names here come from existing artifacts, which may hold names that
     the strict check refuses for new files (for example, names written
     by older versions of fossil(1) or brought in by an import), so apply
     only the structural check, as fossil(1)'s manifest parser does. */
  if(!fn || !fsl_is_simple_pathname(fn, false)){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Filename is not a \"simple\" path: %s",
                          fn);
  }
  *rv = 0;
  rc = fsl_db_prepare_cached(db, &qSel,
                             "SELECT fnid FROM {{dbname.repo}}.filename "
                             "WHERE name=? "
                             "/*%s()*/",__func__);
  if(rc){
      fsl_cx_uplift_db_error(f, db);
      return rc;
  }
  rc = fsl_stmt_bind_text(qSel, 1, fn, -1, 0);
  if(rc){
    fsl_stmt_cached_yield(qSel);
  }else{
    rc = fsl_stmt_step(qSel);
    if( FSL_RC_STEP_ROW == rc ){
      rc = 0;
      fnid = fsl_stmt_g_id(qSel, 0);
      assert(fnid>0);
    }else if(FSL_RC_STEP_DONE == rc){
      rc = 0;
    }
    fsl_stmt_cached_yield(qSel);
    if(!rc && (fnid==0) && createNew){
      fsl_stmt * qIns = NULL;
      rc = fsl_db_prepare_cached(db, &qIns,
                                 "INSERT INTO {{dbname.repo}}.filename(name) "
                                 "VALUES(?) /*%s()*/",__func__);
      if(!rc){
        rc = fsl_stmt_bind_text(qIns, 1, fn, -1, 0);
        if(!rc){
          rc = fsl_stmt_step(qIns);
          if(FSL_RC_STEP_DONE==rc){
            rc = 0;
            fnid = fsl_db_last_insert_id(db);
          }
        }
        fsl_stmt_cached_yield(qIns);
      }
    }
  }
  if(!rc){
    assert(!createNew || (fnid>0));
    *rv = fnid;
  }else if(db->error.code){
    fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}

static int fsl__delta_id(fsl_cx * const f, fsl_stmt * const q,
                         fsl_id_t theId, fsl_id_t * const pOther){
  int rc;
  assert( pOther );
  if( !q ) return f->error.code;
#if FSL_API_ARMOR
  if(theId<=0){
    fsl__cx_stmt_yield(f, q);
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid rid %" FSL_ID_T_PFMT
                          " for a delta lookup.", theId);
  }
#endif
  rc = fsl_stmt_bind_step_v2(q, "R", theId);
  switch(rc){
    case FSL_RC_STEP_ROW:
      rc = 0;
      *pOther = fsl_stmt_g_id(q, 0);
      fsl_stmt_reset(q);
      break;
    case FSL_RC_STEP_DONE:
      rc = 0;
      *pOther = 0;
      break;
    default:
      fsl_cx_uplift_db_error2(f, q->db, rc);
      break;
  }
  fsl__cx_stmt_yield(f, q);
  fsl_check_oom_rc(rc);
  return rc;
}

int fsl_delta_s2r( fsl_cx * const f, fsl_id_t deltaId,
                   fsl_id_t * const rv ){
  return fsl__delta_id(f, fsl__cx_stmt(f, fsl__cx_stmt_e_deltaS2R),
                       deltaId, rv);
}

int fsl_delta_r2s( fsl_cx * const f, fsl_id_t deltaId,
                   fsl_id_t * const rv ){
  return fsl__delta_id(f, fsl__cx_stmt(f, fsl__cx_stmt_e_deltaR2S),
                       deltaId, rv);
}

int fsl__delta_replace(fsl_cx * const f, fsl_id_t rid,
                       fsl_id_t srcid){
  fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_replaceDelta);
  assert( rid>0 );
  assert( srcid>0 );
  assert( srcid!=rid );
  assert( fsl_cx_txn_level(f) );
  if( !q ) return f->error.code;
  int const rc = fsl_stmt_bind_step_v2(q, "RR", rid, srcid);
  fsl__cx_stmt_yield(f, q);
  return (FSL_RC_STEP_DONE==rc)
    ? 0
    : fsl_cx_uplift_db_error2(f, q->db, rc);
}

int fsl__repo_verify_before_commit( fsl_cx * const f, fsl_id_t rid ){
  if(0){
    /*
       v1 adds a commit hook here on the first entry, but it only
       seems to ever use one commit hook, so the infrastructure seems
       like overkill here. Thus this final verification is called from
       the commit (that's where v1 calls the hook).

       If we eventually add commit hooks, this is the place to do it.
    */
  }
  assert( fsl_cx_db_repo(f)->impl.txn.level > 0 );
  assert(rid>0);
  return rid>0
    ? fsl__cx_ptl_insert(f, fsl__ptl_e_toVerify, rid)
    : fsl_cx_err_set(f, FSL_RC_RANGE, "Cannot queue invalid rid %"
                     FSL_ID_T_PFMT " for verification.", rid);
}

void fsl__repo_verify_cancel( fsl_cx * const f ){
  fsl_id_bag_reuse( fsl__cx_ptl_bag(f, fsl__ptl_e_toVerify) );
}

int fsl_rid_to_uuid2(fsl_cx * const f, fsl_id_t rid, fsl_b *uuid){
  int rc;
  fsl_db * const db = f ? fsl_needs_repo(f) : NULL;
  if( !db ){
    rc = FSL_RC_NOT_A_REPO;
  }else if( rid<=0 ){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                        "fsl_rid_to_uuid2() requires "
                        "a positive RID value. rid=%" FSL_ID_T_PFMT,
                        rid);
  }else{
    fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_ridToUuid);
    if( q ){
      rc = fsl_stmt_bind_id(q, 1, rid);
      if(!rc){
        rc = fsl_stmt_step(q);
        if(FSL_RC_STEP_ROW==rc){
          fsl_size_t len = 0;
          char const * x = fsl_stmt_g_text(q, 0, &len);
          fsl_b_reuse(uuid);
          rc = fsl_b_append(uuid, x, (fsl_int_t)len);
        }else if(FSL_RC_STEP_DONE==rc){
          rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                              "No blob found for rid %" FSL_ID_T_PFMT ".",
                              rid);
        }
      }
      fsl__cx_stmt_yield(f, q);
      if(rc && !f->error.code){
        if(q->db->error.code){
          fsl_cx_uplift_db_error(f, q->db);
        }else{
          fsl_cx_err_set(f, rc, NULL);
        }
      }
    }else{
      rc = f->error.code;
    }
    fsl_stmt_reset(q);
  }
  return rc;
}

fsl_uuid_str fsl_rid_to_uuid(fsl_cx * const f, fsl_id_t rid){
  fsl_b uuid = fsl_b_empty;
  fsl_rid_to_uuid2(f, rid, &uuid);
  return fsl_b_take(&uuid);
}

fsl_uuid_str fsl_rid_to_artifact_uuid(fsl_cx * const f, fsl_id_t rid, fsl_satype_e type){
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  if(!f || !db || (rid<=0)) return NULL;
  else{
    char * rv = NULL;
    fsl_stmt * st = NULL;
    int rc;
    rc = fsl_db_prepare_cached(db, &st,
                               "SELECT uuid FROM {{dbname.repo}}.blob "
                               "WHERE rid=?1 AND EXISTS "
                               "(SELECT 1 FROM {{dbname.repo}}.event AS event"
                               " WHERE event.objid=?1 "
                               " AND event.type GLOB %Q)"
                               "/*%s()*/",
                               fsl_satype_event_cstr(type),
                               __func__);
    if(!rc){
      rc = fsl_stmt_bind_id(st, 1, rid);
      if(!rc){
        rc = fsl_stmt_step(st);
        if(FSL_RC_STEP_ROW==rc){
          fsl_size_t len = 0;
          char const * x = fsl_stmt_g_text(st, 0, &len);
          rv = x ? fsl_strndup(x, (fsl_int_t)len ) : NULL;
          if(x && !rv){
            fsl_cx_err_set(f, FSL_RC_OOM, NULL);
          }
        }else if(FSL_RC_STEP_DONE==rc){
          fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                         "No %s artifact found with rid %"FSL_ID_T_PFMT".",
                         fsl_satype_cstr(type), (fsl_id_t) rid);
        }
      }
      fsl_stmt_cached_yield(st);
      if(rc && !f->error.code){
        fsl_cx_uplift_db_error(f, db);
      }
    }
    return rv;
  }
}

/**
   Hashes content, which must be the full content of rid, and compares
   the result with uuid, rid's blob.uuid value. Returns 0 if they
   match. On a mismatch it updates f's error state and returns
   FSL_RC_CONSISTENCY. Any other non-0 result is from hashing.
*/
static int fsl__repo_check_hash(fsl_cx * const f, fsl_id_t rid,
                                char const * uuid,
                                fsl_b const * content){
  int rc;
  fsl_b * const hash = fsl_cx_b_borrow(f);
  if( !hash ) return f->error.code;
  int const uuidLen = fsl_is_uuid(uuid);
  /* This test can fail for artifacts which have an SHA1 hash in a
     repo with an SHA3 policy. A test case from the main fossil
     repo: c7dd1de9f9539a5a859c2b41fe4560604a774476

     This test hashes it (in that repo) as SHA3. As a workaround,
     if the hash is an SHA1 the we will temporarily force the hash
     policy to SHA1, and similarly for SHA3. Lame, but nothing
     better currently comes to mind.

     TODO: change the signature of fsl_cx_hash_buffer() to
     optionally take a forced policy, or supply a similar function
     which does what we're doing below.

     2025-08-05: what was this even for?
  */
  fsl_hashpolicy_e const oldHashP = f->cxConfig.hashPolicy;
  f->cxConfig.hashPolicy = (uuidLen==FSL_STRLEN_SHA1)
    ? FSL_HPOLICY_SHA1 : FSL_HPOLICY_SHA3;
  rc = fsl_cx_hash_buffer(f, 0, content, hash);
  f->cxConfig.hashPolicy = oldHashP;
  if( !rc && 0!=fsl_uuidcmp(uuid, fsl_b_cstr(hash)) ){
    fsl__bprc(rc);
    rc = fsl_cx_err_set(f, FSL_RC_CONSISTENCY,
                        "Hash (%b) of rid %" FSL_ID_T_PFMT
                        " does not match its uuid (%s)",
                        hash, rid, uuid);
  }
  fsl_cx_b_return(f, hash);
  return rc;
}

/**
   Load the record identified by rid. Make sure we can reproduce it
   without error.

   Return non-0 and set f's error state if anything goes wrong.  If
   this procedure returns 0 it means that everything looks OK.
 */
int fsl__repo_verify_rid(fsl_cx * f, fsl_id_t rid){
  fsl_uuid_str uuid = NULL;
  fsl_b content = fsl_b_empty;
  int rc;
  fsl_db * db;
  if( fsl_content_size(f, rid)<0 ){
    return 0 /* No way to verify phantoms */;
  }
  db = fsl_cx_db_repo(f);
  assert(db);
  uuid = fsl_rid_to_uuid(f, rid);
  if(!uuid){
    rc = f->error.code
      ? f->error.code
      : fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                       "Could not find blob record for "
                       "rid #%"FSL_ID_T_PFMT".",
                       rid);
  }else{
    int const uuidLen = fsl_is_uuid(uuid);
    fsl__bccache_remove(&f->cache.blobContent, rid)
      /* Evict this rid so we verify what is actually stored rather
         than a cached copy. Cached ancestors are fine to use: the
         cache is only ever populated by fsl_content_get() from stored
         content, and every incoming rid gets this same evict-and-verify
         treatment, so corruption anywhere in a chain still fails the
         commit. Disabling the cache outright (the old approach) cost a
         full delta-chain expansion per verified artifact, which made
         verify-at-commit unusably slow on large clones. */;
    if(!uuidLen){
      rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid uuid for rid #%"FSL_ID_T_PFMT": %s",
                          (fsl_id_t)rid, uuid);
    }else if( 0==(rc=fsl_content_get(f, rid, &content)) ){
      rc = fsl__repo_check_hash(f, rid, uuid, &content);
    }else if( FSL_RC_NOT_FOUND==rc || FSL_RC_PHANTOM==rc ){
      /* The delta chain runs through content we don't have (e.g. it
         was shunned on the remote, or its source has not arrived), so
         this artifact cannot be reconstructed, thus cannot be
         verified yet. fsl_content_get() reports NOT_FOUND when the
         cache knows the chain is incomplete and PHANTOM when it finds
         out by reaching the phantom, e.g. for content another
         connection stored. fossil(1) skips this case too: its
         verify_rid() only treats a hash mismatch of retrievable
         content as fatal. */
      rc = 0;
      fsl_cx_err_reset(f);
    }
  }
  fsl_free(uuid);
  fsl_b_clear(&content);
  return rc;
}


/**
   fsl__repo_verify_at_commit() emits FSL_MSG_VERIFY after every this
   many artifacts, and only when it has at least this many to check,
   so ordinary small commits stay quiet.

   These are also emitted during clone.
*/
#define FSL__VERIFY_PROGRESS_EVERY 100

int fsl__repo_verify_at_commit( fsl_cx * const f ){
  fsl_id_t rid;
  int rc = 0;
  fsl_id_bag * const bag = fsl__cx_ptl_bag(f, fsl__ptl_e_toVerify);
  fsl_id_bag * const debag = fsl__cx_ptl_bag(f, fsl__ptl_e_dephantomize);

  assert( f->cache.ptl.level>0 );

  if( debag->entryCount ){
    rid = fsl_id_bag_first(debag);
    for( ; !rc && rid>0; rid = fsl_id_bag_next(debag, rid) ){
      rc = fsl__after_dephantomize(f, rid, false);
    }
    fsl_id_bag_reuse(debag);
    if( rc ) return rc;
  }

  if( !bag->entryCount ) return 0;
  //fsl__id_bag_dump(&f->cache.toVerify, NULL, __func__);
  //assert(!"here");

  assert( f->dbMain );
  rid = fsl_id_bag_first(bag);
  if( rid>0 ){
    assert( !f->cache.inFinalVerify );
    f->cache.inFinalVerify = 1;
    if( f->cxConfig.traceSql ){
      fsl_db_exec(f->dbMain,
                  "SELECT 'Starting verify-at-commit.'");
    }
    fsl_size_t nLeft = bag->entryCount;
    bool const progress = nLeft >= FSL__VERIFY_PROGRESS_EVERY;
    while( !rc && rid>0 ){
#if 0
      MARKER(("verifying RID %d at txn level %d\n", (int)rid,
              f->cache.ptl.level));
#endif
      rc = fsl__repo_verify_rid(f, rid);
      if(progress && !rc){
        --nLeft;
        if( 0==nLeft % FSL__VERIFY_PROGRESS_EVERY ){
          rc = fsl_cx_emit(f, FSL_MSG_VERIFY, &nLeft);
        }
      }
      if(!rc) rid = fsl_id_bag_next(bag, rid);
    }
    if( 0!=rc ){
      fsl__cx_content_caches_clear(f)
        /* This is unfortunate but we don't yet have a way to
           cherry-pick failed items from that cache and this failure
           may have just invalidated some. */;
    }
    fsl_id_bag_reuse(bag);
    if( f->cxConfig.traceSql ){
      fsl_db_exec(f->dbMain,
                  "SELECT 'Ending verify-at-commit. rc=%R'", rc);
    }
    assert( 1==f->cache.inFinalVerify );
    if( rc && !f->error.code ){
      fsl_cx_err_set(f, rc,
                     "Error %R in %s() for rid %" FSL_ID_T_PFMT,
                     rc, __func__, rid);
    }
    f->cache.inFinalVerify = 0;
  }
  return rc;
}


static int fsl__repo_create_default_users(fsl_db * db, bool addOnlyUser,
                                          char const * defaultUser ){
  int rc = fsl_db_exec(db,
                       "INSERT OR IGNORE INTO {{dbname.repo}}.user(login, info) "
                       "VALUES(%Q,'')", defaultUser);
  if(!rc){
    rc = fsl_db_exec(db,
                     "UPDATE {{dbname.repo}}.user SET cap='s', pw=lower(hex(randomblob(3)))"
                     " WHERE login=%Q", defaultUser);
    if( !rc && !addOnlyUser ){
      rc = fsl_db_exec_multi(db,
                        "INSERT OR IGNORE INTO {{dbname.repo}}.user(login,pw,cap,info)"
                        "   VALUES('anonymous',hex(randomblob(8)),'hz',"
                        "          'Anon');"
                        "INSERT OR IGNORE INTO {{dbname.repo}}.user(login,pw,cap,info)"
                        "   VALUES('nobody','','gjor','Nobody');"
                        "INSERT OR IGNORE INTO {{dbname.repo}}.user(login,pw,cap,info)"
                        "   VALUES('developer','','dei','Dev');"
                        "INSERT OR IGNORE INTO {{dbname.repo}}.user(login,pw,cap,info)"
                        "   VALUES('reader','','kptw','Reader');"
                        );
    }
  }
  return rc;
}

/**
   For creating or importing repository tables with prefix zPre in the
   main db of db's connection: checks that the prefix overlaps no
   recorded one (fsl__host_prefix_recorded_check()) and that main has
   no table, index, trigger or view whose name starts with it, ignoring
   case, so that no object of the host's, or of another repository or
   working copy, is adopted or dropped. Returns 0 or an error code,
   with f's error state set.
*/
int fsl__repo_host_free_check(fsl_cx * const f, fsl_db * const db,
                              char const * zPre){
  char * zList;
  int rc = fsl__host_prefix_recorded_check(f, db, FSL_DBROLE_REPO, zPre);
  if(rc) return rc;
  zList = fsl_db_g_text(db, NULL,
    /* The first few, and how many. */
    "WITH o(name) AS (SELECT name FROM main.sqlite_schema"
    "  WHERE lower(substr(name, 1, %d))=lower(%Q))"
    " SELECT (SELECT count(*) FROM o)||' ('||(SELECT group_concat(name,"
    "  ', ') FROM (SELECT name FROM o ORDER BY name LIMIT 5))"
    "  ||CASE WHEN (SELECT count(*) FROM o)>5 THEN ', ...' ELSE '' END"
    "  ||')' WHERE EXISTS(SELECT 1 FROM o)",
    (int)fsl_strlen(zPre), zPre);
  if(db->error.code) rc = fsl_cx_uplift_db_error(f, db);
  else if(zList && *zList){
    rc = fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                        "The host db already has objects whose names "
                        "start with repository table prefix %s: %s",
                        zPre, zList);
  }
  fsl_free(zList);
  return rc;
}

/**
   fsl__repo_host_free_check() on f's db in the transaction which must
   be open on it, after taking the main db's write lock, so that no
   other connection can write in between.
*/
static int fsl__repo_host_claim(fsl_cx * const f, char const * zPre){
  fsl_db * const db = f->dbMain;
  int const rc = fsl__db_main_write_lock(db);
  return rc ? fsl_cx_uplift_db_error2(f, db, rc)
    : fsl__repo_host_free_check(f, db, zPre);
}

int fsl_repo_create(fsl_cx * f, fsl_repo_create_opt const * opt ){
  fsl_db * db = 0;
  fsl_cx F = fsl__cx_empty /* used if !f */;
  int rc = 0;
  char const * userName = 0;
  fsl_time_t const unixNow = (fsl_time_t)time(0);
  bool fileExists;
  bool inTrans = 0;
  char const * const zPre = opt ? opt->hostTablePrefix : NULL;
  if(!opt || !(opt->filename || zPre)){
    return f
      ? fsl_cx_err_set(f, FSL_RC_MISUSE, "no repository file name "
                       "given to fsl_repo_create()")
      : FSL_RC_MISUSE;
  }else if(zPre && (!f || opt->allowOverwrite)){
    return f
      ? fsl_cx_err_set(f, FSL_RC_MISUSE, "allowOverwrite is not for "
                       "prefixed repository tables: drop the tables "
                       "instead.")
      : FSL_RC_MISUSE;
  }
  fileExists = !zPre && 0 == fsl_file_access(opt->filename,0);
  if(fileExists && !opt->allowOverwrite){
    return f
      ? fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                       "File already exists and "
                       "allowOverwrite is false: %s",
                       opt->filename)
      : FSL_RC_ALREADY_EXISTS;
  }
  if(f){
    rc = fsl_close_scm_dbs(f)
      /* Will fail if a transaction is active! */;
    switch(rc){
      case 0:
        break;
      default:
        return rc;
    }
  }else{
    f = &F;
    rc = fsl_cx_init( &f, NULL );
    if(rc){
      fsl_cx_finalize(f);
      return rc;
    }
  }
  /* We probably should truncate/unlink the file here
     before continuing, to ensure a clean slate.
  */
  if(fileExists){
    rc = fsl_file_unlink(opt->filename);
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Cannot unlink existing repo file: %s",
                          opt->filename);
      goto end2;
    }
  }
  rc = zPre
    ? fsl__cx_attach_repo_prefixed(f, zPre)
    : fsl__cx_attach_role(f, opt->filename, FSL_DBROLE_REPO, true);
  //MARKER(("attach role rc=%s\n", fsl_rc_cstr(rc)));
  if(rc){
    goto end2;
  }
  db = fsl_cx_db(f);
  if(!f->db.repo.user){
    f->db.repo.user = fsl_user_name_guess()
      /* Ignore OOM error here - we'll use 'root'
         by default (but if we're really OOM here then
         the next op will fail).
      */;
  }
  userName = opt->username;

  rc = fsl_cx_txn_begin(f);
  if(rc) goto end1;
  inTrans = 1;
  if(zPre){
    rc = fsl__repo_host_claim(f, zPre);
    if(rc) goto end1;
  }
  /* Install the schemas... */
  /* The repository schemas are format strings, so that their schema
     placeholders expand. The ticket schema is data (it may be a
     repository's own, see fsl_cx_schema_ticket()), so its object names
     get the schema name instead. */
  rc = fsl_db_exec_multi(db, fsl_schema_repo1());
  if(0==rc && !zPre){
    /* The application ID helps the unix "file" command to identify the
       database as a fossil repository. Not for repository tables in a
       host's main db, which is the host's. */
    rc = fsl_db_exec(db, "PRAGMA {{dbname.repo}}.application_id"
                     "=252006673;");
  }
  if(0==rc) rc = fsl_db_exec_multi(db, fsl_schema_repo2());
  if(0==rc) rc = fsl__ticket_schema_install(f, fsl_schema_ticket());
  if(0==rc) rc = fsl_db_exec_multi(db, fsl_schema_ticket_reports());
  if(rc) goto end1;

  if(1){
    /*
      Set up server-code and project-code...

      in fossil this is optional, so we will presumably eventually
      have to make it so here as well. Not yet sure where this routine
      is used in fossil (i.e. whether the option is actually
      exercised).
    */
    rc = fsl_db_exec_multi(db,
                           "INSERT OR IGNORE INTO {{dbname.repo}}.config (name,value,mtime) "
                           "VALUES ('server-code',"
                           "lower(hex(randomblob(20))),"
                           "%"PRIi64");",
                           (int64_t)unixNow);
    if( 0==rc && !opt->elideProjectCode ){
      rc = fsl_db_exec_multi(db,
                           "INSERT OR IGNORE INTO {{dbname.repo}}.config (name,value,mtime) "
                           "VALUES ('project-code',"
                           "lower(hex(randomblob(20))),"
                           "%"PRIi64");",
                           (int64_t)unixNow);
    }
    if(rc) goto end1;
  }

  /* Set some config vars ... */
  {
    fsl_stmt st = fsl_stmt_empty;
    rc = fsl_db_prepare(db, &st,
                        "INSERT INTO {{dbname.repo}}.config (name,value,mtime) "
                        "VALUES (?,?,%"PRIi64")",
                        (int64_t)unixNow);
    if(!rc){
#define DBSET_STEP \
      if(0==rc){                                       \
        rc = fsl_stmt_step(&st);                       \
        if(FSL_RC_STEP_DONE==rc) rc = 0;               \
      }                                                \
      fsl_stmt_reset(&st)
#define DBSET_STR(KEY,VAL) \
      if(0==rc) rc = fsl_stmt_bind_text(&st, 1, KEY, -1, 0); \
      if(0==rc) rc = fsl_stmt_bind_text(&st, 2, VAL, -1, 0); \
      DBSET_STEP
      DBSET_STR("content-schema",FSL_CONTENT_SCHEMA);
      DBSET_STR("aux-schema",FSL_AUX_SCHEMA);
#undef DBSET_STR

#define DBSET_INT(KEY,VAL) \
      if(0==rc) rc = fsl_stmt_bind_text(&st, 1, KEY, -1, 0 ); \
      if(0==rc) rc = fsl_stmt_bind_int32(&st, 2, VAL); \
      DBSET_STEP

      /* Every name seeded here gets stamped with unixNow. Any name
      ** which is ALSO wire-syncable via a /config card would
      ** permanently out-rank any older, real incoming value forever,
      ** since fsl__config_receive()'s overwrite guard is
      ** `mtime<incoming` (this bit libfossil once, for
      ** "timeline-plaintext" -- fixed 2026-07-22). The assert below
      ** enforces that invariant at every repo creation, not just in
      ** whatever tests happen to be run, so a future addition here
      ** cannot silently reintroduce the same bug. */
#if !defined(NDEBUG)
#define DBSET_INT_GUARD(KEY) assert(0==fsl__config_name_mask(KEY) \
        && KEY " must not be wire-syncable: see fsl_repo_create() comment")
#else
#define DBSET_INT_GUARD(KEY)
#endif
      DBSET_INT_GUARD("autosync"); DBSET_INT("autosync",1);
      DBSET_INT_GUARD("localauth"); DBSET_INT("localauth",0);
#undef DBSET_INT_GUARD
#undef DBSET_INT
#undef DBSET_STEP
      fsl_stmt_finalize(&st);
    }
    if(rc) goto end1;
  }

  rc = fsl__repo_create_default_users(
    db, false,
    (userName && *userName) ? userName
    : (fsl_cx_user_get(f) ? fsl_cx_user_get(f) : "root"));
  if(rc) goto end1;

  end1:
  if(rc && FSL_RC_OOM!=rc && !f->error.code){
    rc = fsl_cx_err_set(f, rc, "cannot create repository %s%s: %s",
                        zPre ? "with table prefix " : "",
                        zPre ? zPre : opt->filename, rc==db->error.code
                        ? fsl_b_cstr(&db->error.msg) : fsl_rc_cstr(rc));
    if(rc==db->error.code) fsl_error_reset(&db->error);
  }
  if(inTrans){
    if( 0==rc ) rc = fsl_cx_txn_end_v2(f, true, false);
    else fsl_cx_txn_end_v2(f, false, false);
    inTrans = 0;
  }
  fsl_close_scm_dbs(f);
  db = 0;
  if(rc) goto end2;

  /**
      In order for injection of the first commit to go through
      cleanly (==without any ugly kludging of f->dbMain), we
      need to now open the new db so that it gets connected
      to f properly...
   */
  rc = zPre ? fsl_repo_open_host(f, zPre) : fsl_repo_open(f, opt->filename);
  if(rc) goto end2;
  db = fsl_cx_db_repo(f);
  assert(db);
  assert(db == f->dbMain);

  if(!userName || !*userName){
    userName = fsl_cx_user_get(f);
    if(!userName || !*userName){
      userName = "root" /* historical value */;
    }
  }

  /*
    Copy config...

    This is done in the second phase because...

    "cannot ATTACH database within transaction"

    and installing the initial schemas outside a transaction is
    horribly slow.
  */
  if( opt->configRepo && *opt->configRepo ){
    bool inTrans2 = false;
    char * inopConfig = fsl__config_inop_rhs(FSL_CONFIGSET_ALL);
    char * inopDb = inopConfig ? fsl__db_setting_inop_rhs() : NULL;
    if(!inopConfig || !inopDb){
      fsl_free(inopConfig);
      rc = FSL_RC_OOM;
      goto end2;
    }
    rc = fsl_db_attach(db, opt->configRepo, "settingSrc");
    if(rc){
      if(FSL_RC_OOM!=rc){
        rc = fsl_cx_err_set(f, rc, "cannot open template repository "
                            "%s: %s", opt->configRepo,
                            rc==db->error.code
                            ? fsl_b_cstr(&db->error.msg)
                            : fsl_rc_cstr(rc));
        if(rc==db->error.code) fsl_error_reset(&db->error);
      }
      fsl_free(inopConfig);
      fsl_free(inopDb);
      goto end2;
    }
    rc = fsl_db_txn_begin(db);
    if(rc){
      fsl_cx_uplift_db_error(f, db);
      goto detach;
    }
    inTrans2 = 1;
    /*
       Copy all settings from the supplied template repository.
    */
    rc = fsl_db_exec(db,
                     "INSERT OR REPLACE INTO {{dbname.repo}}.config"
                     " SELECT name,value,mtime FROM settingSrc.config"
                     "  WHERE (name IN %s OR name IN %s)"
                     "    AND name NOT GLOB 'project-*';",
                     inopConfig, inopDb);
    if(rc) goto detach;
    rc = fsl_db_exec(db,
                     "REPLACE INTO {{dbname.repo}}.reportfmt "
                     "SELECT * FROM settingSrc.reportfmt;");
    if(rc) goto detach;

    /*
       Copy the user permissions, contact information, last modified
       time, and photo for all the "system" users from the supplied
       template repository into the one being setup.  The other
       columns are not copied because they contain security
       information or other data specific to the other repository.
       The list of columns copied by this SQL statement may need to be
       revised in the future.
    */
    rc = fsl_db_exec(db, "UPDATE {{dbname.repo}}.user AS user SET"
      "  cap = (SELECT u2.cap FROM settingSrc.user u2"
      "         WHERE u2.login = user.login),"
      "  info = (SELECT u2.info FROM settingSrc.user u2"
      "          WHERE u2.login = user.login),"
      "  mtime = (SELECT u2.mtime FROM settingSrc.user u2"
      "           WHERE u2.login = user.login),"
      "  photo = (SELECT u2.photo FROM settingSrc.user u2"
      "           WHERE u2.login = user.login)"
      " WHERE user.login IN ('anonymous','nobody','developer','reader');");

    detach:
    if(rc && FSL_RC_OOM!=rc && !f->error.code){
      rc = fsl_cx_err_set(f, rc, "cannot copy settings from template "
                          "repository %s: %s", opt->configRepo,
                          rc==db->error.code
                          ? fsl_b_cstr(&db->error.msg)
                          : fsl_rc_cstr(rc));
      if(rc==db->error.code) fsl_error_reset(&db->error);
    }
    fsl_free(inopConfig);
    fsl_free(inopDb);
    if(inTrans2){
      if(!rc) rc = fsl_db_txn_end(db,0);
      else fsl_db_txn_end(db,1);
    }
    fsl_db_detach(db, "settingSrc");
    if(rc) goto end2;
  }

  if(opt->commitMessage && *opt->commitMessage){
    /* Set up initial commit. */
    fsl_deck d = fsl_deck_empty;
    fsl_cx_err_reset(f);
    fsl_deck_init(f, &d, FSL_SATYPE_CHECKIN);
    rc = fsl_deck_C_set(&d, opt->commitMessage, -1);
    if(!rc) rc = fsl_deck_D_set(&d, fsl_db_julian_now(db));
    if(!rc) rc = fsl__deck_R_set(&d, FSL_MD5_INITIAL_HASH);
    if(!rc && opt->commitMessageMimetype && *opt->commitMessageMimetype){
      rc = fsl_deck_N_set(&d, opt->commitMessageMimetype, -1);
    }
    /* Reminder: setting tags in "wrong" (unsorted) order to
       test/assert that the sorting gets done automatically. */
    if(!rc) rc = fsl_deck_T_add(&d, FSL_TAGTYPE_PROPAGATING, NULL,
                                "sym-trunk", NULL);
    if(!rc) rc = fsl_deck_T_add(&d, FSL_TAGTYPE_PROPAGATING, NULL,
                                "branch", "trunk");
    if(!rc) rc =fsl_deck_U_set(&d, userName);
    if(!rc){
      rc = fsl_deck_save(&d, 0);
    }
    fsl_deck_finalize(&d);
  }

  end2:
  if(f == &F){
    fsl_cx_finalize(f);
    if(rc) fsl_file_unlink(opt->filename);
  }
  return rc;
}

static int fsl_repo_dir_names_rid( fsl_cx * const f, fsl_id_t rid,
                                   fsl_list * const tgt,
                                   bool addSlash){
  fsl_db * dbR = fsl_needs_repo(f);
  fsl_deck D = fsl_deck_empty;
  fsl_deck * d = &D;
  int rc = 0;
  fsl_stmt st = fsl_stmt_empty;
  bool made = false;
  int count = 0;
  fsl_card_F const * fc;
  /*
    This is a poor-man's impl. A more efficient one would calculate
    the directory names without using the database.
  */
  assert(rid>0);
  assert(dbR);
  rc = fsl_deck_load_rid( f, d, rid, FSL_SATYPE_CHECKIN);
  if(rc){
    fsl_deck_clean(d);
    return rc;
  }
  rc = fsl_deck_F_rewind(d);
  fsl_deck_F_each(d, fc, rc){
    assert(fc->name && *fc->name);
    if(!st.stmt){
      rc = fsl_db_exec(dbR, "CREATE TEMP TABLE IF NOT EXISTS "
                       "{{temp.tmp_filelist}}"
                       "(n TEXT UNIQUE ON CONFLICT IGNORE)");
      if(!rc){
        made = true;
        rc = fsl_db_prepare(dbR, &st,
                            "INSERT INTO {{temp.tmp_filelist}}(n) "
                            "VALUES(fsl_dirpart(?,%d))",
                            addSlash ? 1 : 0);
      }
      if(rc) goto end;
      assert(st.stmt);
    }
    rc = fsl_stmt_bind_text(&st, 1, fc->name, -1, 0);
    if(!rc){
      rc = fsl_stmt_step(&st);
      if(FSL_RC_STEP_DONE==rc){
        ++count;
        rc = 0;
      }
    }
    fsl_stmt_reset(&st);
    fc = 0;
  }

  if(!rc && (count>0)){
    fsl_stmt_finalize(&st);
    rc = fsl_db_prepare(dbR, &st,
                        "SELECT n FROM {{temp.tmp_filelist}} WHERE n "
                        "IS NOT NULL ORDER BY n %s",
                        fsl_cx_filename_collation(f));
    while( !rc && (FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&st))) ){
      fsl_size_t nLen = 0;
      char const * name = fsl_stmt_g_text(&st, 0, &nLen);
      rc = 0;
      if(name){
        char * cp;
        assert(nLen);
        cp = fsl_strndup( name, (fsl_int_t)nLen );
        if(!cp){
          rc = FSL_RC_OOM;
          break;
        }
        rc = fsl_list_append(tgt, cp);
        if(rc){
          fsl_free(cp);
          break;
        }
      }
    }
    if(FSL_RC_STEP_DONE==rc) rc = 0;
  }

  end:
  if(rc && !f->error.code && dbR->error.code){
    fsl_cx_uplift_db_error(f, dbR);
  }
  fsl_stmt_finalize(&st);
  fsl_deck_clean(d);
  if(made) fsl__db_temp_drop(dbR, "tmp_filelist");
  return rc;
}

int fsl_repo_dir_names( fsl_cx * const f, fsl_id_t rid, fsl_list * const tgt,
                        bool addSlash ){
  fsl_db * const db = fsl_needs_repo(f);
  if(!db) return FSL_RC_NOT_A_REPO;
  else if(!tgt) return FSL_RC_MISUSE;
  int rc = fsl_cx_txn_begin(f);
  if(rc) return rc;
  if(rid>=0){
    if( 0==rid ){
      /* Dir list for current checkout version */
      fsl__ckout_rid(f, &rid);
      if( !rid ){
        rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                            "The rid argument is 0 (indicating "
                            "the current checkout), but there is "
                            "no opened checkout.");
        goto end;
      }
    }
    assert(rid>0);
    rc = fsl_repo_dir_names_rid(f, rid, tgt, addSlash);
  }else{
    /* Dir list across all versions */
    fsl_stmt s = fsl_stmt_empty;
    rc = fsl_db_prepare(db, &s,
                        "SELECT DISTINCT(fsl_dirpart(name,%d)) dname "
                        "FROM {{dbname.repo}}.filename WHERE dname IS NOT NULL "
                        "ORDER BY dname", addSlash ? 1 : 0);
    if(rc){
      fsl_cx_uplift_db_error(f, db);
      assert(!s.stmt);
      goto end;
    }
    while( !rc && (FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&s)))){
      fsl_size_t len = 0;
      char const * col = fsl_stmt_g_text(&s, 0, &len);
      char * cp = fsl_strndup( col, (fsl_int_t)len );
      if(!cp){
        rc = FSL_RC_OOM;
        break;
      }
      rc = fsl_list_append(tgt, cp);
      if(rc) fsl_free(cp);
    }
    if(FSL_RC_STEP_DONE==rc) rc = 0;
    fsl_stmt_finalize(&s);
  }
end:
  fsl_cx_txn_end_v2(f, false, false)/*we only read*/;
  return rc;
}

/* UNTESTED */
bool fsl_repo_is_readonly(fsl_cx const * f){
  if(!f || !f->dbMain) return false;
  else{
    char const * zRole = fsl__db_schema(f->dbMain, FSL_DBROLE_REPO)
      /* The repo's schema has this name whether it was opened first
         (and renamed from "main") or ATTACHed. */;
    return !!sqlite3_db_readonly(f->dbMain->dbh, zRole);
  }
}

int fsl__repo_record_filename(fsl_cx * const f){
  fsl_db * dbR = fsl_needs_repo(f);
  fsl_db * dbC;
  fsl_db * dbConf = NULL;
  char const * zCDir;
  char const * zName = dbR ? dbR->filename : NULL;
  int rc;
  if(!dbR) return FSL_RC_NOT_A_REPO;
  fsl_b * const full = fsl__cx_scratchpad(f);
  assert(zName);
  assert(f);
  rc = fsl_file_canonical_name(zName, full, 0);
  if(rc){
    fsl_cx_err_set(f, rc, "Error %s canonicalizing filename: %s",
                   fsl_rc_cstr(rc), zName);
    goto end;
  }

  /*
    If global config is open, write the repo db's name to it, unless
    the repository is tables of a host's main db, which are no file to
    find.
  */
  dbConf = fsl_cx_db_config(f);
  if(dbConf && !fsl__db_repo_prefix(f->dbMain)){
    int const dbRole = (f->dbMain==&f->db.gconfig.db)
      ? FSL_DBROLE_MAIN : FSL_DBROLE_CONFIG;
    rc = fsl_db_exec(dbConf,
                     "INSERT OR IGNORE INTO %s.global_config(name,value) "
                     "VALUES('repo:%q',1)",
                     fsl_db_role_name(dbRole),
                     fsl_b_cstr(full));
    if(rc){
      fsl_cx_uplift_db_error(f, dbConf);
      goto end;
    }
  }

  dbC = fsl_cx_db_ckout(f);
  if(dbC && (zCDir=f->db.ckout.dir)){
    /* If we have a checkout, update its repo's list of checkouts... */
    /* Assumption: if we have an opened checkout, dbR is ATTACHed with
       the role REPO. */
    int ro;
    assert(dbR);
    ro = sqlite3_db_readonly(dbR->dbh,
                             fsl__db_schema(dbR, FSL_DBROLE_REPO));
    assert(ro>=0);
    if(!ro){
      fsl_b localRoot = fsl_b_empty;
      rc = fsl_file_canonical_name(zCDir, &localRoot, 1);
      if(rc && FSL_RC_OOM!=rc){
        fsl_cx_err_set(f, rc, "Error %R canonicalizing checkout "
                       "directory name: %s", rc, zCDir);
      }
      if(0==rc){
        if(dbConf){
          /*
            If global config is open, write the checkout db's name to it.
          */
          int const dbRole = (f->dbMain==&f->db.gconfig.db)
            ? FSL_DBROLE_MAIN : FSL_DBROLE_CONFIG;
          rc = fsl_db_exec(dbConf,
                           "REPLACE INTO %s.global_config(name,value) "
                           "VALUES('ckout:%q',1)",
                           fsl_db_role_name(dbRole),
                           fsl_b_cstr(&localRoot));
        }
        if(0==rc){
          /* We know that repo is ATTACHed to ckout here. */
          assert(dbR == dbC);
          rc = fsl_db_exec(dbR,
                           "REPLACE INTO {{dbname.repo}}.config(name, value, mtime) "
                           "VALUES('ckout:%q', 1, fsl_now())",
                           fsl_b_cstr(&localRoot));
        }
      }
      fsl_b_clear(&localRoot);
    }
  }

  end:
  if(rc && !f->error.code){
    if(f->dbMain->error.code) fsl_cx_uplift_db_error(f, f->dbMain);
    else if(dbConf && dbConf->error.code) fsl_cx_uplift_db_error(f, dbConf);
  }
  fsl__cx_scratchpad_yield(f, full);
  return rc;

}

bool fsl_rid_is_a_checkin(fsl_cx * f, fsl_id_t rid){
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  if(!db || (rid<0)) return 0;
  else if(0==rid){
    /* Corner case: empty repo */
    return !fsl_db_exists(db, "SELECT 1 FROM {{dbname.repo}}.blob WHERE rid>0");
  }
  else{
    fsl_db_err_reset(db);
    bool rv = false;
    fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_ridIsCheckin);
    if( q ){
      rv = FSL_RC_STEP_ROW==fsl_stmt_bind_step_v2(q, "R", rid);
      fsl__cx_stmt_yield(f, q);
    }
    if(db->error.code){
      fsl_cx_uplift_db_error(f, db);
    }
    return rv;
  }
}

int fsl_repo_extract( fsl_cx * const f, fsl_repo_extract_opt const * const opt_ ){
  if(!f || !opt_->callback) return FSL_RC_MISUSE;
  else if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  else if(opt_->checkinRid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE, "RID must be positive.");
  }else{
    int rc;
    fsl_deck mf = fsl_deck_empty;
    fsl_b * const content = opt_->extractContent
      ? fsl__cx_content_buffer(f)
      : NULL;
    fsl_id_t fid;
    fsl_repo_extract_state xst = fsl_repo_extract_state_empty;
    fsl_card_F const * fc = NULL;
    fsl_repo_extract_opt const opt = *opt_
      /* Copy in case the caller modifies it via their callback. If we
         find an interesting use for such modification then we can
         remove this copy. */;
    rc = fsl_deck_load_rid(f, &mf, opt.checkinRid, FSL_SATYPE_CHECKIN);
    if(rc) goto end;
    assert(mf.f==f);
    xst.f = f;
    xst.checkinRid = opt.checkinRid;
    xst.callbackState = opt.callbackState;
    xst.content = opt.extractContent ? content : NULL;
    /* Calculate xst.count.fileCount... */
    assert(0==xst.count.fileCount);
    if(mf.B.uuid){/*delta. The only way to count this reliably
                   is to walk though the whole card list. */
      rc = fsl_deck_F_rewind(&mf);
      fsl_deck_F_each(&mf, fc, rc){
        ++xst.count.fileCount;
      }
      if(rc) goto end;
      fc = NULL;
    }else{
      xst.count.fileCount = mf.F.used;
    }
    assert(0==xst.count.fileNumber);
    rc = fsl_deck_F_rewind(&mf);
    fsl_deck_F_each(&mf, fc, rc){
      assert(fc->uuid
             && "We shouldn't get F-card deletions via fsl_deck_F_next()");
      ++xst.count.fileNumber;
      fid = fsl_uuid_to_rid(f, fc->uuid);
      if(fid<0){
        assert(f->error.code);
        rc = f->error.code;
      }else if(!fid){
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "File %s [%s] is not in the repository.",
                            fc->name, fc->uuid);
      }else if(opt.extractContent){
        fsl_b_reuse(content);
        rc = fsl_content_get(f, fid, content);
        //assert(FSL_RC_RANGE!=rc);
      }
      if(!rc){
        /** Call the callback. */
        xst.fCard = fc;
        assert(fid>0);
        xst.content = content;
        xst.fileRid = fid;
        rc = opt.callback( &xst );
        if(FSL_RC_BREAK==rc){
          rc = 0;
          break;
        }
      }
    }/* for-each-F-card loop */
    end:
    if(content) fsl__cx_content_buffer_yield(f);
    fsl_deck_finalize(&mf);
    return rc;
  }
}

int fsl__repo_import_blob( fsl_cx * f, fsl_input_f in, void * inState,
                           fsl_id_t * rid, fsl_uuid_str * uuid ){
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  if(!f || !in) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  else{
    int rc;
    fsl_b buf = fsl_b_empty;
    rc = fsl_b_fill_from(&buf, in, inState);
    if(rc){
      if(FSL_RC_OOM!=rc){
        rc = fsl_cx_err_set(f, rc, "Error %R reading blob content "
                            "from input source.", rc);
      }
    }else{
      fsl_id_t theRid = 0;
      rc = fsl__content_put_ex( f, &buf, NULL, 0, 0, 0, &theRid);
      if(!rc){
        if(rid) *rid = theRid;
        if(uuid){
          *uuid = fsl_rid_to_uuid(f, theRid);
          if(!*uuid) rc = f->error.code ? f->error.code : FSL_RC_OOM;
        }
      }
    }
    fsl_b_clear(&buf);
    return rc;
  }
}

int fsl__repo_import_buffer( fsl_cx * f, fsl_b const * in,
                            fsl_id_t * rid, fsl_uuid_str * uuid ){
  if(!f || !in) return FSL_RC_MISUSE;
  else{
    /* Workaround: input ptr is const and input needs to modify
       (only) the cursor. So we'll cheat rather than require a non-const
       input...
    */
    fsl_b cursorKludge = fsl_b_empty;
    fsl_b_external(&cursorKludge, in->mem, in->used);
    int const rc = fsl__repo_import_blob(f, fsl_input_f_buffer, &cursorKludge,
                                         rid, uuid );
    assert(cursorKludge.mem == in->mem);
    return rc;
  }
}


int fsl_repo_blob_lookup( fsl_cx * const f, fsl_b const * const src,
                          fsl_id_t * const ridOut, fsl_uuid_str * hashOut ){
  int rc;
  fsl_b hash_ = fsl_b_empty;
  fsl_b * hash;
  fsl_id_t rid = 0;
  if(!fsl_cx_db_repo(f)) return FSL_RC_NOT_A_REPO;
  hash = hashOut ? &hash_ : fsl__cx_scratchpad(f);
  /* First check the auxiliary hash to see if there is already an artifact
     that uses the auxiliary hash name */
  rc = fsl_cx_hash_buffer(f, true, src, hash);
  if(FSL_RC_UNSUPPORTED==rc){
    /* The auxiliary hash option is incompatible with our hash policy.
       We'll just try again with the preferred policy. */
    rc = 0;
  }else if(rc){
    goto end;
  }
  rid = hash->used ? fsl_uuid_to_rid(f, fsl_b_cstr(hash)) : 0;
  if( rid < 0 ){
    assert(f->error.code);
    rc = f->error.code;
    goto end;
  }else if( !rid ){
    /* No existing artifact with the auxiliary hash name.  Therefore, use
       the primary hash name. */
    fsl_b_reuse(hash);
    rc = fsl_cx_hash_buffer(f, false, src, hash);
    if(rc) goto end;
    rid = fsl_uuid_to_rid(f, fsl_b_cstr(hash));
    if( !rid ){
      rc = FSL_RC_NOT_FOUND;
    }else if(rid<0){
      rc = f->error.code;
    }
  }
  end:
  if(!rc || rc==FSL_RC_NOT_FOUND){
    if(hashOut){
      assert(hash == &hash_);
      *hashOut = fsl_b_take(hash)/*transfer*/;
    }
  }
  if(!rc && ridOut){
    *ridOut = rid;
  }
  if(hash == &hash_){
    fsl_b_clear(hash);
  }else{
    assert(!hash_.mem);
    fsl__cx_scratchpad_yield(f, hash);
  }
  return rc;
}

int fsl__repo_fingerprint_search( fsl_cx * const f, fsl_id_t rcvid,
                                 char ** zOut ){
  int rc = 0;
  fsl_db * const db = fsl_needs_repo(f);
  if(!db) return FSL_RC_NOT_A_REPO;
  fsl_b * const sql = fsl__cx_scratchpad(f);
  fsl_stmt q = fsl_stmt_empty;
  int version = 1 /* Fingerprint version to check: 0 or 1 */;
  try_again:
  /*
   * We check both v1 and v0 fingerprints, in that order. From Fossil
   * db.c:
   *
   * The original fingerprint algorithm used "quote(mtime)".  But this could
   * give slightly different answers depending on how the floating-point
   * hardware is configured.  For example, it gave different answers on
   * native Linux versus running under valgrind.
   */
  if(0==version){
    fsl_stmt_finalize(&q);
    fsl__db_appendf(db, sql,
                    "SELECT rcvid, quote(uid), quote(mtime), "
                    "quote(nonce), quote(ipaddr) "
                    "FROM {{dbname.repo}}.rcvfrom ");
  }else{
    assert(1==version);
    fsl__db_appendf(db, sql,
                    "SELECT rcvid, quote(uid), datetime(mtime), "
                    "quote(nonce), quote(ipaddr) "
                    "FROM {{dbname.repo}}.rcvfrom ");
  }
  rc = (rcvid>0)
    ? fsl_b_appendf(sql, "WHERE rcvid=%" FSL_ID_T_PFMT, rcvid)
    : fsl_b_append(sql, "ORDER BY rcvid DESC LIMIT 1", -1);
  if(rc) goto end;
  rc = fsl_db_prepare(db, &q, "%b", sql);
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, db, rc);
    goto end;
  }
  rc = fsl_stmt_step(&q);
  switch(rc){
    case FSL_RC_STEP_ROW:{
      fsl_md5_cx hash = fsl_md5_cx_empty;
      fsl_size_t len = 0;
      fsl_id_t const rvid = fsl_stmt_g_id(&q, 0);
      unsigned char digest[16] = {0};
      char hex[FSL_STRLEN_MD5+1] = {0};
      for(int i = 1; i <= 4; ++i){
        char const * z = fsl_stmt_g_text(&q, i, &len);
        fsl_md5_update(&hash, z, len);
      }
      fsl_md5_final(&hash, digest);
      fsl_md5_digest_to_base16(digest, hex);
      *zOut = fsl_mprintf("%" FSL_ID_T_PFMT "/%s", rvid, hex);
      rc = *zOut ? 0 : FSL_RC_OOM;
      break;
    }
    case FSL_RC_STEP_DONE:
      if(1==version){
        version = 0;
        fsl_b_reuse(sql);
        goto try_again;
      }
      rc = FSL_RC_NOT_FOUND;
      break;
    default:
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      break;
  }
  end:
  fsl__cx_scratchpad_yield(f, sql);
  fsl_stmt_finalize(&q);
  return rc;
}

int fsl_repo_manifest_write(fsl_cx * const f,
                            fsl_id_t manifestRid,
                            fsl_b * const pManifest,
                            fsl_b * const pHash,
                            fsl_b * const pTags) {
  fsl_db * const db = fsl_needs_repo(f);
  if(!db) return FSL_RC_NOT_A_REPO;
  if(manifestRid<=0){
    manifestRid = f->db.ckout.rid;
    if(manifestRid<=0){
      return fsl_cx_err_set(f, 0==f->db.ckout.rid
                            ? FSL_RC_RANGE
                            : FSL_RC_NOT_A_CKOUT,
                            "%s(): no checkin version was specified "
                            "and %s.", __func__,
                            0==f->db.ckout.rid
                            ? "checkout has no version"
                            : "no checkout is opened");
    }
  }
  int rc = 0;
  char * str = 0;
  fsl_uuid_str ridHash = 0;
  fsl_b * bHash = 0;
  assert(manifestRid>0);

  if(pManifest){
    fsl_b_reuse(pManifest);
    rc = fsl_content_get(f, manifestRid, pManifest);
    if(rc) goto end;
  }
  if(pHash){
    if(f->db.ckout.rid!=manifestRid){
      bHash = fsl__cx_scratchpad(f);
      rc = fsl_rid_to_uuid2(f, manifestRid, bHash);
      if(rc) goto end;
      ridHash = (char *)bHash->mem;
    }else{
      ridHash = f->db.ckout.uuid;
    }
    assert(ridHash);
    fsl_b_append(pHash, ridHash, -1);
    rc = fsl_b_append(pHash, "\n", 1);
    if(rc) goto end;
  }
  if(pTags){
    fsl_stmt q = fsl_stmt_empty;
    fsl_db * const db = fsl_cx_db_repo(f);
    assert(db && "We can't have a checkout w/o a repo.");
    str = fsl_db_g_text(db, NULL, "SELECT VALUE FROM {{dbname.repo}}.tagxref "
                        "WHERE rid=%" FSL_ID_T_PFMT
                        " AND tagid=%d /*%s()*/",
                        manifestRid, FSL_TAGID_BRANCH, __func__);
    rc = fsl_b_appendf(pTags, "branch %z\n", str);
    str = 0;
    if(rc) goto end;
    rc = fsl_db_prepare(db, &q,
                        "SELECT substr(tagname, 5)"
                        "  FROM {{dbname.repo}}.tagxref AS tagxref, {{dbname.repo}}.tag AS tag"
                        " WHERE tagxref.rid=%" FSL_ID_T_PFMT
                        "   AND tagxref.tagtype>0"
                        "   AND tag.tagid=tagxref.tagid"
                        "   AND tag.tagname GLOB 'sym-*'"
                        " /*%s()*/",
                        manifestRid, __func__);
    if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
    while( 0==rc && fsl__cx_stmt_step_each(f, &q, &rc) ){
      const char *zName = fsl_stmt_g_text(&q, 0, NULL);
      rc = fsl_b_appendf(pTags, "tag %s\n", zName);
    }
    fsl_stmt_finalize(&q);
  }
  end:
  if(bHash) fsl__cx_scratchpad_yield(f, bHash);
  return rc;
}

/**
   Internal state for the rebuild process.
*/
struct FslRebuildState {
  fsl_cx * f;
  fsl_db * db;
  fsl_rebuild_opt const * opt;
  fsl_stmt qSize;
  fsl_stmt qChild;
  fsl_id_bag idsDone;
  fsl_msg_rebuild step;
};
typedef struct FslRebuildState FslRebuildState;
static const FslRebuildState FslRebuildState_empty = {
  .f = NULL, .db = NULL, .opt = NULL,
  .qSize = fsl_stmt_empty_m,
  .qChild = fsl_stmt_empty_m,
  .idsDone = fsl_id_bag_empty_m,
  .step = fsl_msg_rebuild_empty_m
};

static int fsl__rebuild_update_schema(FslRebuildState * const frs){
  int rc = 0;
  char * zBlobSchema = NULL;
  char * const zBlob = fsl_mprintf("%s%s",
                                   fsl__db_repo_prefix(frs->db)
                                   ? fsl__db_repo_prefix(frs->db) : "",
                                   "blob");
  if(!zBlob) return fsl_cx_err_set(frs->f, FSL_RC_OOM, NULL);

  /* Verify that the PLINK table has a new column added by the
  ** 2014-11-28 schema change.  Create it if necessary.  This code
  ** can be removed in the future, once all users have upgraded to the
  ** 2014-11-28 or later schema.
  */
  if(!fsl__db_table_has_column(frs->db, FSL_DBROLE_REPO, "plink", "baseid")){
    rc = fsl_cx_exec(frs->f,
                     "ALTER TABLE {{dbname.repo}}.plink ADD COLUMN baseid");
    if(rc) goto end;

  }

  /* Verify that the MLINK table has the newer columns added by the
  ** 2015-01-24 schema change.  Create them if necessary.  This code
  ** can be removed in the future, once all users have upgraded to the
  ** 2015-01-24 or later schema.
  */
  if( !fsl__db_table_has_column(frs->db, FSL_DBROLE_REPO, "mlink", "isaux") ){
    rc = fsl_cx_exec_multi(frs->f,
      "ALTER TABLE {{dbname.repo}}.mlink ADD COLUMN pmid INTEGER DEFAULT 0;"
      "ALTER TABLE {{dbname.repo}}.mlink ADD COLUMN isaux BOOLEAN DEFAULT 0;"
    );
    if(rc) goto end;
  }

  /* We're going to skip several older (2011) schema updates for the
     time being on the grounds of YAGNI. */

  /**
     Update the repository schema for Fossil version 2.0.  (2017-02-28)
     (1) Change the CHECK constraint on BLOB.UUID so that the length
     is greater than or equal to 40, not exactly equal to 40.
  */
  zBlobSchema =
    fsl_db_g_text(frs->db, NULL, "SELECT sql FROM %!Q.sqlite_schema"
                  " WHERE name=%Q", fsl__db_schema(frs->db, FSL_DBROLE_REPO),
                  zBlob);
  if(!zBlobSchema){
    /* ^^^^ reminder: fossil(1) simply ignores this case, silently
       doing nothing instead. */
    if(frs->db->error.code){
      rc = fsl_cx_uplift_db_error(frs->f, frs->db);
    }else{
      rc = fsl_cx_err_set(frs->f, FSL_RC_DB,
                          "cannot rebuild: no blob table in "
                          "repository %s",
                          fsl_cx_db_file_repo(frs->f, NULL));
    }
    goto end;
  }
  /* Search for:  length(uuid)==40
  **              0123456789 12345   */
  for(int i=10; zBlobSchema[i]; i++){
    if( zBlobSchema[i]=='='
        && fsl_strncmp(&zBlobSchema[i-6],"(uuid)==40",10)==0 ){
      int rc2 = 0, wasDefensive = 0;
      zBlobSchema[i] = '>';
      sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE, -1,
                        &wasDefensive);
      sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE, 0, &rc2);
      rc = fsl_cx_exec_multi(frs->f,
           "PRAGMA writable_schema=ON;"
           "UPDATE %!Q.sqlite_schema SET sql=%Q WHERE name %s %Q;"
           "PRAGMA writable_schema=OFF;",
           fsl__db_schema(frs->db, FSL_DBROLE_REPO), zBlobSchema,
           /* LIKE ignores case, as fossil(1)'s does, but takes '_' in a
              prefix for any character. */
           fsl__db_repo_prefix(frs->db) ? "=" : "LIKE", zBlob
      );
      sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE,
                        wasDefensive, &rc2);
      break;
    }
  }
  if(rc) goto end;
  rc = fsl_cx_exec(frs->f,
    "CREATE VIEW IF NOT EXISTS "
    "  {{dbname.repo}}.artifact(rid,rcvid,size,atype,srcid,hash,content) AS "
    "    SELECT {{bare.repo.blob}}.rid,rcvid,size,1,srcid,uuid,content"
    "      FROM {{bare.repo.blob}} LEFT JOIN {{bare.repo.delta}}"
    " ON ({{bare.repo.blob}}.rid={{bare.repo.delta}}.rid);"
    /* The view's body names no schema: SQLite forbids a view stored in
       one database to name another schema, and it resolves within its
       own database anyway. Its tables are the repository's, prefixed
       like the view itself if the repository is tables of a host's
       main db, and fsl_repo_export() renames both back. */
  );

  end:
  fsl_free(zBlobSchema);
  fsl_free(zBlob);
  return rc;
}

#define INTCHECK frs->f->interrupted ? frs->f->interrupted :
/**
   Inserts rid into frs->idsDone and calls
   frs->f->cxConfig.listener.callback. Returns 0 on success.
*/
static int fsl__rebuild_step_done(FslRebuildState * const frs, fsl_id_t rid){
  assert( !fsl_id_bag_contains(&frs->idsDone, rid) );
  assert( (int)frs->step.artifactType >= (int)FSL_SATYPE_INVALID );
  assert( (int)frs->step.artifactType < (int)FSL_SATYPE_count );
  int rc = fsl_id_bag_insert(&frs->idsDone, rid);
  ++frs->step.stepNumber;
  frs->step.rid = rid;
  if( FSL_SATYPE_INVALID==frs->step.artifactType ){
    frs->step.artifactType = FSL_SATYPE_ANY;
  }
  ++frs->step.metrics.counts[frs->step.artifactType];
  if( frs->step.blobSize<0 ){
    ++frs->step.metrics.phantomCount;
  }else{
    frs->step.metrics.sizes[frs->step.artifactType] += frs->step.blobSize;
  }
  /* TODO (2025-08-09). Need to fix f-rebuild.c at the same time. */
  if( 0==rc && frs->f->cxConfig.listener.callback ){
    rc = fsl_cx_emit(frs->f, FSL_MSG_REBUILD, &frs->step);
  }
  return rc ? rc : (INTCHECK 0);
}

/**
   If rc is not 0, FSL_RC_OOM, or the context's interruption code,
   this prefixes the context's error message with the rid and hash of
   the artifact rid. If no message is set, it sets one from zWhat,
   which describes the failed step, and the name of rc. Returns rc.
*/
static int fsl__rebuild_err(FslRebuildState * const frs, fsl_id_t rid,
                            int rc, char const * zWhat){
  fsl_cx * const f = frs->f;
  if(!rc || FSL_RC_OOM==rc || rc==f->interrupted) return rc;
  char * const zHash =
    fsl_db_g_text(frs->db, NULL, "SELECT uuid FROM {{dbname.repo}}.blob WHERE rid=%"
                  FSL_ID_T_PFMT, rid);
  fsl_b msg = fsl_b_empty;
  bool const hasInner = f->error.code && f->error.msg.used;
  if(hasInner || !zWhat){
    fsl_b_appendf(&msg, "rebuild failed at rid %" FSL_ID_T_PFMT
                  " [%s]: %s", rid, zHash ? zHash : "unknown hash",
                  hasInner ? fsl_b_cstr(&f->error.msg) : fsl_rc_cstr(rc));
  }else{
    fsl_b_appendf(&msg, "rebuild failed at rid %" FSL_ID_T_PFMT
                  " [%s]: %s: %R", rid,
                  zHash ? zHash : "unknown hash", zWhat, rc);
  }
  if(!msg.errCode){
    f->error.code = rc;
    fsl_b_swap(&msg, &f->error.msg);
  }else if(!f->error.code){
    f->error.code = rc;
    fsl_b_reuse(&f->error.msg);
  }
  fsl_b_clear(&msg);
  fsl_free(zHash);
  return rc;
}

/**
   Rebuilds cross-referencing state for the given RID and its content,
   recursively on all of its descendents. The contents of the input
   buffer are taken over by this routine.

   If other artifacts are deltas based off of the given artifact, they
   are processed as well.

   Returns 0 on success.
*/
static int fsl__rebuild_step(FslRebuildState * const frs, fsl_id_t rid,
                             int64_t blobSize, fsl_b * const content){
  fsl_deck deck = fsl_deck_empty;
  fsl_b deckContent = fsl_b_empty;
  fsl_id_bag idsChildren = fsl_id_bag_empty;
  int rc = 0;
  if(rc) goto end;
  assert(rid>0);
  assert( fsl_cx_txn_level(frs->f)>0 );
  if(!frs->qSize.stmt){
    rc = fsl_cx_prepare(frs->f, &frs->qSize,
                        "UPDATE {{dbname.repo}}.blob SET size=?1 WHERE rid=?2/*%s()*/",
                        __func__);
    if(rc) goto end;
  }else{
    fsl_stmt_reset(&frs->qSize);
  }
  while(0==rc && rid>0){
    fsl_id_t const parentRid = rid;
    if( frs->opt->verifyHashes ){
      /* content is rid's full content here, and each artifact's
         content is built exactly once by this walk, so this is the
         cheapest point at which to check every hash. */
      fsl_uuid_str const uuid = fsl_rid_to_uuid(frs->f, rid);
      rc = uuid
        ? fsl__repo_check_hash(frs->f, rid, uuid, content)
        : (frs->f->error.code ? frs->f->error.code : FSL_RC_OOM);
      fsl_free(uuid);
      if(rc){
        rc = fsl__rebuild_err(frs, rid, rc, NULL);
        break;
      }
    }
    //MARKER(("TODO: %s(rid=%d)\n", __func__, (int)rid));
    if(blobSize != (int64_t)content->used){
      /* Fix [blob.size] field if needed. (Why would this ever be
         needed?) Much later: the blob.size gets out of sync with
         expected semantics sometimes, _presumably_ involving syncing
         of deltas, where their size is their deltified size instead
         of their fully-expanded size. It is needed, and fossil(1) has
         this same step. */
      rc = fsl_stmt_bind_step(&frs->qSize, "IR", (int64_t)content->used, rid);
      if(rc){
        rc = fsl__rebuild_err(frs, rid,
               fsl_cx_uplift_db_error2(frs->f, frs->qSize.db, rc),
               "cannot update blob.size");
        break;
      }
      blobSize = (int64_t)content->used;
    }
    /* Find all deltas based off of rid... */
    fsl_stmt * const qDeltaS2R =
      fsl__cx_stmt(frs->f, fsl__cx_stmt_e_deltaS2R);
    if( qDeltaS2R ){
      rc = fsl_stmt_bind_fmt(qDeltaS2R, "R", rid);
      if(rc){
        rc = fsl__rebuild_err(frs, rid,
               fsl_cx_uplift_db_error2(frs->f, qDeltaS2R->db, rc),
               "cannot look up deltas");
        fsl__cx_stmt_yield(frs->f, qDeltaS2R);
        break;
      }
      fsl_id_bag_reuse(&idsChildren);
      while(0==rc && fsl__cx_stmt_step_each(frs->f, qDeltaS2R, &rc)){
        fsl_id_t const cid = fsl_stmt_g_id(qDeltaS2R, 0);
        if(!fsl_id_bag_contains(&frs->idsDone, cid)){
          rc = fsl_id_bag_insert(&idsChildren, cid);
        }
      }
      fsl_stmt_reset(qDeltaS2R);
      fsl__cx_stmt_yield(frs->f, qDeltaS2R);
    }else{
       rc = fsl__rebuild_err(frs, rid, frs->f->error.code,
                             "cannot look up deltas");
    }
    rc = INTCHECK rc;
    if(rc) break;

    fsl_size_t const nChild = fsl_id_bag_count(&idsChildren);
    if(fsl_id_bag_contains(&frs->idsDone, rid)){
      /* Kludge! This check should not be necessary. Testing with the
         libfossil repo, this check is not required on the main x86
         dev machine but is on a Raspberry Pi 4, for reasons
         as-yet-unknown. On the latter, artifact
         1ee529429e2aa6ffbeffb0cf73bb51a34a8547b8 (an opaque file, not
         a fossil artifact) makes it into frs->idsDone
         unexpectedly(?), triggering an assert() in
         fsl__rebuild_step_done().

         2025-08-09: is that still the case?
      */
      goto doChildren;
    }
    if(nChild){
      /* Parsing the deck will mutate the buffer, so we need a copy of
         the input content to apply the next delta to. */
      rc = fsl_b_copy(&deckContent, content);
      if(rc) break;
    }else{
      /* We won't be applying any deltas, so use the deck content the
         user passed in. */
      fsl_b_swap(content, &deckContent);
      fsl_b_clear(content);
    }
    frs->step.blobSize = blobSize;
    /* At this point fossil(1) decides between rebuild and
       deconstruct, performing different work for each. We're skipping
       the deconstruct option for now but may want to add it
       later. See fossil's rebuild.c:rebuild_step(). Note that
       deconstruct is not a capability intended for normal client
       use. It's primarily for testing of fossil itself. */
    fsl_deck_init(frs->f, &deck, FSL_SATYPE_ANY);
    //MARKER(("rid=%d\n", (int)rid));
    rc = INTCHECK fsl_deck_parse2(&deck, &deckContent, rid)
      /* But isn't it okay if rid is not an artifact? */;
    switch(rc){
      case 0:
        frs->step.artifactType = deck.type;
        rc = INTCHECK fsl__deck_crosslink(&deck);
        rc = fsl__rebuild_err(frs, rid, rc, "cannot crosslink");
        break;
      case FSL_RC_OOM:
        break;
      default:
#if 0
        MARKER(("err=%s for rid=%d content=\n%.*s\n", fsl_rc_cstr(rc), (int)rid,
                (int)deckContent.used, (char const *)deckContent.mem));
#endif
        if(frs->f->interrupted) break;
        /* Assume deck is not an artifact (draft-fossil-repo-state-00
           section 4.4). Fall through and continue processing the
           delta children. */
        fsl_cx_err_reset(frs->f);
        rc = 0;
        frs->step.artifactType = FSL_SATYPE_INVALID;
        break;
    }
    fsl_b_clear(&deckContent);
    fsl_deck_finalize(&deck);
    rc = INTCHECK rc;
    if(0==rc && 0==(rc = frs->f->interrupted)){
      rc = fsl__rebuild_step_done( frs, rid );
    }
    if(rc) break;
    /* Process all dependent deltas recursively... */
    doChildren:
    rid = 0;
    fsl_size_t i = 1;
    for(fsl_id_t cid = fsl_id_bag_first(&idsChildren);
         0==rc && cid!=0; cid = fsl_id_bag_next(&idsChildren, cid), ++i){
      int64_t sz;
      if(!frs->qChild.stmt){
        rc = fsl_cx_prepare(frs->f, &frs->qChild,
                            "SELECT content, size "
                            "FROM {{dbname.repo}}.blob WHERE rid=?1/*%s()*/",
                            __func__);
        if(rc) break;
      }else{
        fsl_stmt_reset(&frs->qChild);
      }
      fsl_stmt_bind_id(&frs->qChild, 1, cid);
      if( FSL_RC_STEP_ROW==fsl_stmt_step(&frs->qChild) &&
          (sz = fsl_stmt_g_int64(&frs->qChild, 1))>=0 ){
        fsl_b next = fsl_b_empty;
        fsl_b delta = fsl_b_empty;
        void const * blob = 0;
        fsl_size_t deltaBlobSize = 0;
        rc = INTCHECK fsl_stmt_get_blob(&frs->qChild, 0, &blob, &deltaBlobSize);
        if(rc){
          rc = fsl__rebuild_err(frs, cid,
                 fsl_cx_uplift_db_error2(frs->f, frs->qChild.db, rc),
                 "cannot read delta");
          goto outro;
        }
        fsl_b_external(&delta, blob, (fsl_int_t)deltaBlobSize);
        rc = INTCHECK fsl_b_uncompress(&delta, &delta);
        if(rc){
          rc = fsl__rebuild_err(frs, cid, rc, "cannot uncompress delta");
          goto outro;
        }
        rc = INTCHECK fsl_b_delta_apply(content, &delta, &next);
        fsl_stmt_reset(&frs->qChild);
        fsl_b_clear(&delta);
        if(rc){
          if(FSL_RC_OOM!=rc && rc!=frs->f->interrupted){
            fsl_cx_err_set(frs->f, rc, "cannot apply delta to parent "
                           "rid %" FSL_ID_T_PFMT ": %R", parentRid, rc);
          }
          rc = fsl__rebuild_err(frs, cid, rc, NULL);
          goto outro;
        }
        if(i<nChild){
          rc = INTCHECK fsl__rebuild_step(frs, cid, sz, &next);
          assert(!next.mem);
        }else{
          rid = cid;
          blobSize = sz;
          fsl_b_clear(content);
          *content = next/*transfer ownership*/;
        }
        if(0==rc) continue;
        outro:
        assert(0!=rc);
        fsl_stmt_reset(&frs->qChild);
        fsl_b_clear(&delta);
        fsl_b_clear(&next);
        break;
      }else{
        fsl_stmt_reset(&frs->qChild);
        fsl_b_clear(content);
      }
    }
  }
  end:
  fsl_deck_finalize(&deck);
  fsl_b_clear(content);
  fsl_b_clear(&deckContent);
  fsl_id_bag_clear(&idsChildren);
  return rc ? rc : (INTCHECK 0);
}
#undef INTCHECK
/**
   Check to see if the "sym-trunk" tag exists.  If not, create it and
   attach it to the very first check-in. Returns 0 on success.
*/
static int fsl__rebuild_tag_trunk(FslRebuildState * const frs){
  fsl_id_t const tagid =
    fsl_db_g_id(frs->db, 0,
                "SELECT 1 FROM {{dbname.repo}}.tag WHERE tagname='sym-trunk'");
  if(tagid>0) return 0;
  fsl_id_t const rid =
    fsl_db_g_id(frs->db, 0,
                "SELECT pid FROM {{dbname.repo}}.plink AS x WHERE NOT EXISTS"
                "(SELECT 1 FROM {{dbname.repo}}.plink WHERE cid=x.pid)");
  if(rid==0) return 0;

  /* Add the trunk tag to the root of the whole tree */
  int rc = 0;
  fsl_b * const b = fsl_cx_b_borrow(frs->f);
  rc = b ? fsl_rid_to_uuid2(frs->f, rid, b) : frs->f->error.code;
  switch(rc){
    case FSL_RC_NOT_FOUND:
      fsl_cx_err_reset(frs->f);
      rc = 0/*fossil ignores this case without an error*/;
      break;
    case 0: {
      fsl_deck d = fsl_deck_empty;
      char const * zUuid = fsl_b_cstr(b);
      fsl_deck_init(frs->f, &d, FSL_SATYPE_CONTROL);
      rc = fsl_deck_T_add(&d, FSL_TAGTYPE_PROPAGATING,
                          zUuid, "sym-trunk", NULL);
      if(0==rc) rc = fsl_deck_T_add(&d, FSL_TAGTYPE_PROPAGATING,
                                    zUuid, "branch", "trunk");
      if(0==rc){
        char const * userName = fsl_cx_user_guess(frs->f);
        if(!userName){
          rc = fsl_cx_err_set(frs->f, FSL_RC_NOT_FOUND,
                              "Cannot determine user name for "
                              "control artifact.");
        }else{
          rc = fsl_deck_U_set(&d, userName);
        }
      }
      if(0==rc){
        /* A control artifact requires a D-card; fsl_deck_save() rejects
           the deck without one. fossil(1) builds this same artifact via
           tag_add_artifact(), which always emits a D card. */
        rc = fsl_deck_D_set(&d, fsl_db_julian_now(frs->db));
      }
      if(0==rc){
        rc = fsl_deck_save(&d, fsl_content_is_private(frs->f, rid));
      }
      fsl_deck_finalize(&d);
      break;
    }
    default: break;
  }
  fsl_cx_b_return(frs->f, b);
  return rc;
}

/**
   For fsl_repo_rebuild() of repository tables of a host's main db:
   appends to sql a DROP TABLE IF EXISTS for each table which zSchema
   (fsl_schema_repo2() or fsl_schema_forum()) creates, with f's
   repository table prefix. Returns 0 or FSL_RC_OOM.
*/
static int fsl__rebuild_drop_derived(fsl_cx * const f, char const * zSchema,
                                     fsl_b * const sql){
  static char const zKw[] = "CREATE TABLE {{dbname.repo}}.";
  int rc = 0;
  for( char const * z = strstr(zSchema, zKw); 0==rc && z;
       z = strstr(z, zKw) ){
    fsl_size_t n = 0;
    z += sizeof(zKw) - 1;
    while( '_'==z[n] || fsl_isalnum(z[n]) ) ++n;
    rc = fsl_b_appendf(sql, "DROP TABLE IF EXISTS %!Q.\"%s%.*s\";\n",
                       fsl__db_schema(f->dbMain, FSL_DBROLE_REPO),
                       fsl__db_repo_prefix(f->dbMain), (int)n, z);
  }
  return rc ? fsl_cx_err_set(f, rc, NULL) : 0;
}

static int fsl__rebuild(fsl_cx * const f, fsl_rebuild_opt const * const opt){
  fsl_stmt s = fsl_stmt_empty;
  fsl_stmt q = fsl_stmt_empty;
  fsl_db * const db = fsl_cx_db_repo(f);
  int rc;
  FslRebuildState frs = FslRebuildState_empty;
  fsl_b * const sql = fsl_cx_b_borrow(f);
  if( !sql ) return f->error.code;

  assert(db);
  assert(opt);
  frs.f = frs.step.f = f;
  frs.db = db;
  frs.opt = frs.step.opt = opt;
  rc = fsl__rebuild_update_schema(&frs);
  if(rc) goto end;
  if( !sql->capacity ){
    fsl_b_reserve(sql, 1024 * 4);
  }
  fsl__cx_content_caches_clear(f);

  /* DROP all tables which are not part of our One True Vision of the
     repo db...

     2022-07-31: we might want to stop doing this because: if fossil
     adds new tables, there may be a lag in getting them into
     libfossil and we don't necessarily want to nuke those. OTOH, all
     such tables would be transient/rebuildable state, so if we nuke
     them then a rebuild from fossil(1) would correct it.

     2024-12-06: https://fossil-scm.org/home/info/aeec557e897f
     reimplements this slightly but the full implications of doing it
     that way are not yet clear.

     If the repository is tables of a host's main db, which the host
     may share, only the tables which libfossil's transient schemas
     create are dropped (fsl__rebuild_drop_derived()), so that no
     table of the host's is ever dropped, even one named with the
     repository's prefix.
 */
  if( fsl__db_repo_prefix(f->dbMain) ){
    rc = fsl__rebuild_drop_derived(f, fsl_schema_repo2(), sql);
    if( 0==rc ) rc = fsl__rebuild_drop_derived(f, fsl_schema_forum(), sql);
  }else{
    rc = fsl_cx_prepare(f, &q,
     "SELECT name FROM %!Q.sqlite_schema /*scan*/"
     " WHERE type='table'"
     " AND name NOT IN ('admin_log', 'blob','delta','rcvfrom','user','alias',"
                       "'config','shun','private','reportfmt',"
                       "'concealed','accesslog','modreq',"
                       "'purgeevent','purgeitem','unversioned',"
                      "'ticket','ticketchng',"
                       "'subscriber','pending_alert','chat'"
                      ")"
     " AND name NOT GLOB 'sqlite_*'"
     " AND name NOT GLOB 'fx_*'"
     " AND name NOT GLOB 'ftsidx_*'"
     " AND name NOT GLOB 'chatfts1_*'",
     fsl__db_schema(f->dbMain, FSL_DBROLE_REPO)
    );
    while( fsl__cx_stmt_step_each(f, &q, &rc) ){
      rc = fsl_b_appendf(sql, "DROP TABLE IF EXISTS %!Q.%!Q;\n",
                         fsl__db_schema(f->dbMain, FSL_DBROLE_REPO),
                         fsl_stmt_g_text(&q, 0, NULL));
    }
    rc = fsl_stmt_finalize(&q);
  }
  if(0==rc && fsl_b_size(sql)){
    rc = fsl_cx_exec_multi(f, "%b", sql);
  }
  if(rc) goto end;

  rc = fsl_cx_exec_multi(f, fsl_schema_repo2())
    /* the format string, so that its schema placeholders expand */;
  if(0==rc) rc = fsl__cx_ticket_create_table(f);
  if(0==rc) rc = fsl__shunned_remove(f);
  if(0==rc){
    rc = fsl_cx_exec_multi(f,
      "INSERT INTO {{dbname.repo}}.unclustered"
      " SELECT rid FROM {{dbname.repo}}.blob EXCEPT SELECT rid FROM {{dbname.repo}}.private;"
      "DELETE FROM {{dbname.repo}}.unclustered"
      " WHERE rid IN (SELECT rid FROM {{dbname.repo}}.shun JOIN {{dbname.repo}}.blob USING(uuid));"
      "DELETE FROM {{dbname.repo}}.config WHERE name IN ('remote-code', 'remote-maxid');"
      "UPDATE {{dbname.repo}}.user SET mtime=fsl_now() WHERE mtime IS NULL;"
    );
  }
  if(rc) goto end;

  /* The following should be count(*) instead of max(rid). max(rid) is
  ** an adequate approximation, however, and is much faster for large
  ** repositories. */
  if(1){
    frs.step.artifactCount =
      (fsl_size_t)fsl_db_g_int64(db, 0, "SELECT count(*) FROM {{dbname.repo}}.blob");
  }else{
    frs.step.artifactCount =
      (fsl_size_t)fsl_db_g_id(db, 0, "SELECT max(rid) FROM {{dbname.repo}}.blob");
  }

  //totalSize += incrSize*2;
  rc = fsl_cx_prepare(f, &s,
     "SELECT rid, size FROM {{dbname.repo}}.blob AS blob /*scan*/"
     " WHERE NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.shun WHERE uuid=blob.uuid)"
     "   AND NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.delta WHERE rid=blob.rid)"
     "%s", opt->randomize ? " ORDER BY RANDOM()" : ""
  );
  if(rc) goto end;
  rc = fsl__crosslink_begin(f)
    /* Maintenace reminder: if this call succeeds, BE SURE that
       we do not skip past the fsl__crosslink_end() call via
       (goto end). Doing so would get the transaction stack out
       of sync. */;
  if(rc) goto end /*to skip fsl__crosslink_end() call!*/;
  while( 0==rc ){
    /* Do not fold a failed step into the loop condition: a cursor
    ** aborted by a rollback elsewhere is then indistinguishable from a
    ** normal end-of-scan, and the rebuild reports success having
    ** crosslinked only part of the repository. */
    int const stepRc = fsl_stmt_step(&s);
    if( FSL_RC_STEP_DONE==stepRc ) break;
    else if( FSL_RC_STEP_ROW!=stepRc ){
      rc = fsl_cx_uplift_db_error2(f, s.db, stepRc);
      break;
    }
    fsl_id_t const rid = fsl_stmt_g_id(&s, 0);
    int64_t const size = fsl_stmt_g_int64(&s, 1);
    if( size>=0 ){
      fsl_b content = fsl_b_empty;
      rc = fsl_content_get(f, rid, &content);
      if(0==rc){
        rc = fsl__rebuild_step(&frs, rid, size, &content);
        assert(!content.mem);
      }else{
        rc = fsl__rebuild_err(&frs, rid, rc, "cannot load content");
      }
      fsl_b_clear(&content);
    }
  }
  fsl_stmt_finalize(&s);
  if(rc) goto crosslink_end;
  rc = fsl_cx_prepare(f, &s,
     "SELECT rid, size FROM {{dbname.repo}}.blob AS blob"
     " WHERE NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.shun WHERE uuid=blob.uuid)"
     "%s", opt->randomize ? " ORDER BY RANDOM()" : ""
  );
  while( 0==rc ){
    /* Same reasoning as the first scan loop above. */
    int const stepRc = fsl_stmt_step(&s);
    if( FSL_RC_STEP_DONE==stepRc ) break;
    else if( FSL_RC_STEP_ROW!=stepRc ){
      rc = fsl_cx_uplift_db_error2(f, s.db, stepRc);
      break;
    }
    fsl_id_t const rid = fsl_stmt_g_id(&s, 0);
    int64_t const size = fsl_stmt_g_int64(&s, 1);
    if( size>=0 ){
      if( !fsl_id_bag_contains(&frs.idsDone, rid) ){
        fsl_b content = fsl_b_empty;
        rc = fsl_content_get(f, rid, &content);
        if(0==rc){
          rc = fsl__rebuild_step(&frs, rid, size, &content);
          assert(!content.mem);
        }else{
          rc = fsl__rebuild_err(&frs, rid, rc, "cannot load content");
        }
        /*
          2021-12-17: hmmm... while debugging the problem reported here:

          https://fossil-scm.org/forum/forumpost/f4cc31863179f843

          It was discovered that fossil will simply skip any content
          it cannot read in this step, even if it's skipped over
          because of a broken blob-to-delta mapping (whereas fossil's
          test-integrity command will catch that case). If such a case
          happens to us, fsl_content_get() fails with FSL_RC_PHANTOM.
          That seems to me to be the right thing to do, as such a case
          is indicative of db corruption. However, if we skip over
          these then we cannot rebuild a repo which has such (invalid)
          state.

          Feature or bug?

          For now let's keep it strict and fail if we can't fetch the
          content. We can reevaluate that decision later if needed. We
          can add a fsl_rebuild_opt::ignorePhantomFailure (better name
          pending!) flag which tells us how the user would prefer to
          deal with this.
        */
        fsl_b_clear(&content);
      }
    }else{
      rc = fsl_cx_exec_multi(f, "INSERT OR IGNORE INTO {{dbname.repo}}.phantom "
                             "VALUES(%" FSL_ID_T_PFMT ")", rid);
      if(0==rc){
        frs.step.blobSize = -1;
        frs.step.artifactType = FSL_SATYPE_INVALID;
        rc = fsl__rebuild_step_done(&frs, rid);
      }
    }
  }
  fsl_stmt_finalize(&s);
  crosslink_end:
  rc = fsl__crosslink_end(f, rc);
  if(rc) goto end;
  rc = fsl__rebuild_tag_trunk(&frs);
  if(rc) goto end;
  //if( opt->createClusters ) rc = fsl__create_cluster(f);
  rc = fsl_cx_exec_multi(f,
     "REPLACE INTO {{dbname.repo}}.config(name,value,mtime) VALUES('content-schema',%Q,fsl_now());"
     "REPLACE INTO {{dbname.repo}}.config(name,value,mtime) VALUES('aux-schema',%Q,fsl_now());"
     "REPLACE INTO {{dbname.repo}}.config(name,value,mtime) "
       "VALUES('rebuilt','libfossil %q %q',fsl_now());",
     FSL_CONTENT_SCHEMA, FSL_AUX_SCHEMA,
     fsl_buildinfo(FSL_BUILDINFO_VERSION_HASH),
     fsl_buildinfo(FSL_BUILDINFO_VERSION_TIMESTAMP)
  );
  end:
  fsl_cx_b_return(f, sql);
  fsl_stmt_finalize(&s);
  fsl_stmt_finalize(&frs.qSize);
  fsl_stmt_finalize(&frs.qChild);
  fsl_id_bag_clear(&frs.idsDone);

  if( frs.step.stepNumber ){
    frs.step.errCode = rc;
    if( !rc ) frs.step.stepNumber = 0
                /* else keep the step number for error reporting */;
    int const rc2 = fsl_cx_emit(frs.f, FSL_MSG_REBUILD, &frs.step);
    if( rc2 && !rc ) rc = rc2;
  }
  return rc;
}

int fsl_repo_rebuild(fsl_cx * const f, fsl_rebuild_opt const * opt){
  int rc = 0;
  fsl_db * const db = fsl_needs_repo(f);
  if( !db ) return FSL_RC_NOT_A_REPO;
  if( !opt ) opt = &fsl_rebuild_opt_empty;
#if 0
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if(0==rc){
    rc = fsl__rebuild(f, opt);
    int const rc2 =
      fsl_cx_txn_end_v2(f, !opt->dryRun && 0==rc, false);
    if(0==rc && 0!=rc2) rc = rc2;
  }
#else
  fsl__cx_txn_local(f, rc, !opt->dryRun, {
      rc = fsl__rebuild(f, opt);
    });
#endif
  fsl_cx_interrupt(f, 0, NULL);
  return rc;
}

int fsl_repo_journal_mode_set(fsl_cx * const f, char const * zMode){
  fsl_db * const db = fsl_cx_db_repo(f);
  char * zGot = NULL;
  int rc;
  if( !db ){
    return fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                          "No repository is opened.");
  }
  if( !zMode || (fsl_stricmp(zMode, "wal")
                 && fsl_stricmp(zMode, "delete")
                 && fsl_stricmp(zMode, "truncate")
                 && fsl_stricmp(zMode, "persist")) ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Invalid repository journal mode: %s",
                          zMode ? zMode : "NULL");
  }
  if( fsl__db_repo_prefix(db) ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "The repository is tables of a host's main "
                          "db, whose journal mode is the host's.");
  }
  if( !sqlite3_get_autocommit(db->dbh) ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot change the journal mode inside a "
                          "transaction.");
  }
  rc = fsl_db_get_text(db, &zGot, NULL, "PRAGMA %s.journal_mode=%s",
                       fsl__db_schema(db, FSL_DBROLE_REPO), zMode);
  if( rc || !zGot || fsl_stricmp(zGot, zMode) ){
    rc = fsl_cx_err_set(f, FSL_RC_LOCKED,
                        "Cannot change the repository db's journal "
                        "mode to %s%s%s.", zMode, rc ? ": " : "",
                        rc ? sqlite3_errmsg(db->dbh) : "");
    fsl_db_err_reset(db);
  }
  fsl_free(zGot);
  return rc;
}


/** The schemas fsl_repo_export() and fsl_repo_import() ATTACH: the
    other file, and an empty in-memory db for fsl__repo_copy(). */
#define FSL__REPO_COPY_DB "fsl_copy_db"
#define FSL__REPO_COPY_TMP "fsl_copy_tmp"

int fsl__repo_copy_sql(fsl_b * const b, char const * zSql,
                              char const * zSchema, char const * zName){
  static char const * const azKw[] = {
    "TABLE ", "INDEX ", "VIEW ", "TRIGGER ", NULL
  };
  char const * z = zSql;
  char const * zAt;
  int i;
  if( fsl_strnicmp(z, "CREATE ", 7) ) return FSL_RC_RANGE;
  z += 7;
  if( 0==fsl_strnicmp(z, "UNIQUE ", 7) ) z += 7;
  for( i = 0; azKw[i]
         && fsl_strnicmp(z, azKw[i], (fsl_int_t)fsl_strlen(azKw[i])); ++i ){}
  if( !azKw[i] ) return FSL_RC_RANGE;
  zAt = z += fsl_strlen(azKw[i]);
  if( '"'==*z || '\''==*z || '`'==*z || '['==*z ){
    char const q = '['==*z ? ']' : *z;
    for( ++z; *z; ++z ){
      if( *z==q ){
        if( ']'!=q && q==z[1] ){ ++z; continue; }
        break;
      }
    }
    if( !*z ) return FSL_RC_RANGE;
    ++z;
  }else{
    while( *z && !fsl_isspace(*z) && '('!=*z ) ++z;
  }
  return z==zAt ? FSL_RC_RANGE
    : fsl_b_appendf(b, "%.*s%!Q.%!Q%s", (int)(zAt - zSql), zSql,
                    zSchema, zName, z);
}

/**
   For fsl_repo_export() and fsl_repo_import(), in their transaction
   on f's main db, which has an empty schema FSL__REPO_COPY_TMP
   ATTACHed: copies the tables of schema zSrc whose names start with
   zSrcPre, their rows as stored (artifacts are not re-encoded) and
   their indexes, views and triggers, to schema zDst, with zDstPre in
   place of zSrcPre in each name. Each object is first made in
   FSL__REPO_COPY_TMP, where SQLite's ALTER TABLE RENAME renames its
   tables wherever they are named (REFERENCES clauses, indexes, the
   bodies of views and triggers), so that its SQL is right for zDst.

   Left out are the virtual tables, i.e. the full-text search indexes,
   whose module arguments name tables (e.g. fts5's content=) which a
   rename does not touch, with their shadow tables, and the documents
   of fossil(1)'s search index (ftsdocs, with its indexes, and the view
   ftscontent), so
   that the copy has no search index, rather than one which names
   another's tables or fails: "fossil fts-config index on" makes it
   anew, and fossil(1) makes its chat index as it needs it.
*/
static int fsl__repo_copy(fsl_cx * const f, char const * zSrc,
                          char const * zSrcPre, char const * zDst,
                          char const * zDstPre){
  fsl_db * const db = f->dbMain;
  fsl_b * const sql = fsl__cx_scratchpad(f);
  fsl_stmt q = fsl_stmt_empty;
  int const nSrc = (int)fsl_strlen(zSrcPre);
  int const nDst = (int)fsl_strlen(zDstPre);
  int rc;
  if( fsl_db_g_int32(db, 0, "PRAGMA legacy_alter_table") ){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "Cannot copy a repository's "
                        "tables with PRAGMA legacy_alter_table=ON.");
    goto end;
  }
  /* Each object, under its own name, in FSL__REPO_COPY_TMP... */
  rc = fsl_cx_prepare(f, &q,
    "SELECT name, sql FROM %!Q.sqlite_schema AS s"
    " WHERE name GLOB '%q*' AND name NOT GLOB 'sqlite_*'"
    " AND sql IS NOT NULL AND sql NOT LIKE 'CREATE VIRTUAL %%'"
    " AND substr(name, %d) NOT IN ('ftsdocs','ftscontent')"
    " AND substr(tbl_name, %d) NOT IN ('ftsdocs','ftscontent')"
    " AND NOT EXISTS(SELECT 1 FROM %!Q.sqlite_schema AS v"
    "   WHERE v.name GLOB '%q*' AND v.sql LIKE 'CREATE VIRTUAL %%'"
    "   AND (s.name GLOB v.name||'_*' OR s.tbl_name=v.name"
    "        OR s.tbl_name GLOB v.name||'_*'))"
    " ORDER BY rowid", zSrc, zSrcPre, nSrc + 1, nSrc + 1, zSrc, zSrcPre);
  while( fsl__cx_stmt_step_each(f, &q, &rc) ){
    rc = fsl__repo_copy_sql(sql, fsl_stmt_g_text(&q, 1, NULL),
                            FSL__REPO_COPY_TMP,
                            fsl_stmt_g_text(&q, 0, NULL));
    if( 0==rc ) rc = fsl_b_append(sql, ";\n", 2);
  }
  fsl_stmt_finalize(&q);
  if( 0==rc && sql->used ) rc = fsl_cx_exec_multi(f, "%b", sql);
  /* ... its tables renamed there, wherever they are named... */
  if( 0==rc && fsl_strcmp(zSrcPre, zDstPre) ){
    fsl_b_reuse(sql);
    rc = fsl_cx_prepare(f, &q, "SELECT name, %Q||substr(name, %d)"
                        " FROM %!Q.sqlite_schema WHERE type='table'"
                        " AND name NOT GLOB 'sqlite_*' ORDER BY rowid",
                        zDstPre, nSrc + 1, FSL__REPO_COPY_TMP);
    while( fsl__cx_stmt_step_each(f, &q, &rc) ){
      rc = fsl_b_appendf(sql, "ALTER TABLE %!Q.%!Q RENAME TO %!Q;\n",
                         FSL__REPO_COPY_TMP, fsl_stmt_g_text(&q, 0, NULL),
                         fsl_stmt_g_text(&q, 1, NULL));
    }
    fsl_stmt_finalize(&q);
    if( 0==rc && sql->used ) rc = fsl_cx_exec_multi(f, "%b", sql);
  }
  /* ... and then made in zDst: the tables, filled with the rows, then
     the rest. */
  if( 0==rc ){
    fsl_b_reuse(sql);
    rc = fsl_cx_prepare(f, &q,
      "SELECT type, sql, CASE WHEN type='table' THEN name"
      " ELSE %Q||substr(name, %d) END AS n, %Q||substr(name, %d)"
      " FROM %!Q.sqlite_schema WHERE sql IS NOT NULL"
      " AND name NOT GLOB 'sqlite_*' ORDER BY type<>'table', rowid",
      zDstPre, nSrc + 1, zSrcPre, nDst + 1, FSL__REPO_COPY_TMP);
    while( fsl__cx_stmt_step_each(f, &q, &rc) ){
      char const * const zNew = fsl_stmt_g_text(&q, 2, NULL);
      rc = fsl__repo_copy_sql(sql, fsl_stmt_g_text(&q, 1, NULL), zDst,
                              zNew);
      if( 0==rc ) rc = fsl_b_append(sql, ";\n", 2);
      if( 0==rc && 0==fsl_strcmp("table", fsl_stmt_g_text(&q, 0, NULL)) ){
        rc = fsl_b_appendf(sql, "INSERT INTO %!Q.%!Q SELECT * FROM %!Q.%!Q;\n",
                           zDst, zNew, zSrc, fsl_stmt_g_text(&q, 3, NULL));
      }
    }
    fsl_stmt_finalize(&q);
    if( 0==rc && sql->used ) rc = fsl_cx_exec_multi(f, "%b", sql);
  }
  if( 0==rc
      && fsl_db_exists(db, "SELECT 1 FROM %!Q.sqlite_schema"
                       " WHERE name='sqlite_sequence'", zSrc)
      && fsl_db_exists(db, "SELECT 1 FROM %!Q.sqlite_schema"
                       " WHERE name='sqlite_sequence'", zDst) ){
    /* AUTOINCREMENT counters, which may be ahead of the rows. */
    rc = fsl_cx_exec_multi(f,
      "DELETE FROM %!Q.sqlite_sequence WHERE name IN"
      " (SELECT %Q||substr(name, %d) FROM %!Q.sqlite_sequence"
      "  WHERE name GLOB '%q*');"
      "INSERT INTO %!Q.sqlite_sequence(name, seq)"
      " SELECT %Q||substr(name, %d), seq FROM %!Q.sqlite_sequence"
      " WHERE name GLOB '%q*' AND %Q||substr(name, %d) IN"
      " (SELECT name FROM %!Q.sqlite_schema WHERE type='table');",
      zDst, zDstPre, nSrc + 1, zSrc, zSrcPre,
      zDst, zDstPre, nSrc + 1, zSrc, zSrcPre, zDstPre, nSrc + 1, zDst);
  }
  end:
  if( rc && !f->error.code ) rc = fsl_cx_uplift_db_error2(f, db, rc);
  fsl__cx_scratchpad_yield(f, sql);
  return rc;
}

/**
   Fails with FSL_RC_MISUSE if zFile, an existing file, is a db file of
   f's db connection, e.g. f's repository or checkout db or a host's
   main db, which fsl_repo_export() must not overwrite.
*/
static int fsl__repo_export_target_check(fsl_cx * const f,
                                         char const * zFile){
  fsl_b * const b1 = fsl__cx_scratchpad(f);
  fsl_b * const b2 = fsl__cx_scratchpad(f);
  fsl_stmt q = fsl_stmt_empty;
  int rc = fsl_file_canonical_name(zFile, b1, false);
  if( 0==rc ) rc = fsl__file_realpath(b1);
  if( rc ) rc = fsl_cx_err_set(f, rc, NULL);
  else rc = fsl_cx_prepare(f, &q, "SELECT file FROM pragma_database_list"
                           " WHERE file<>''");
  while( 0==rc && fsl__cx_stmt_step_each(f, &q, &rc) ){
    fsl_b_reuse(b2);
    rc = fsl_b_append(b2, fsl_stmt_g_text(&q, 0, NULL), -1);
    if( 0==rc ) rc = fsl__file_realpath(b2);
    if( rc ) rc = fsl_cx_err_set(f, rc, NULL);
    else if( 0==fsl_cx_filename_cmp(f, fsl_b_cstr(b1), fsl_b_cstr(b2)) ){
      rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "Cannot export to %s, a db "
                          "file of this context's connection.", zFile);
    }
  }
  fsl_stmt_finalize(&q);
  fsl__cx_scratchpad_yield(f, b1);
  fsl__cx_scratchpad_yield(f, b2);
  return rc;
}

int fsl_repo_export(fsl_cx * const f, char const * zFile, bool overwrite){
  static char const * const azSuffix[] = {"", "-journal", "-wal", "-shm",
                                          NULL};
  fsl_db * const db = fsl_needs_repo(f);
  bool created = false, attached = false, attachedTmp = false;
  bool inTxn = false;
  int rc = 0;
  if( !db ) return FSL_RC_NOT_A_REPO;
  else if( !zFile || !*zFile ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE, "No file name to export to.");
  }else if( !sqlite3_get_autocommit(db->dbh) ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE, "Cannot export inside a "
                          "transaction, as SQLite cannot ATTACH there.");
  }
  if( 0==fsl_file_access(zFile, 0) ){
    if( !overwrite ){
      return fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                            "File already exists: %s", zFile);
    }
    rc = fsl__repo_export_target_check(f, zFile);
    for( int i = 0; 0==rc && azSuffix[i]; ++i ){
      /* Along with its journals, which SQLite would otherwise apply
         to the new file. */
      char * const z = fsl_mprintf("%s%s", zFile, azSuffix[i]);
      if( !z ) rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
      else if( 0==fsl_file_access(z, 0) && fsl_file_unlink(z) ){
        rc = fsl_cx_err_set(f, FSL_RC_IO, "Cannot remove %s.", z);
      }
      fsl_free(z);
    }
    if( rc ) return rc;
  }
  {
    FILE * const ff = fsl_fopen(zFile, "w");
    if( !ff ){
      return fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_IO),
                            "Cannot create %s.", zFile);
    }
    fsl_fclose(ff);
    created = true;
  }
  rc = fsl_db_attach(db, zFile, FSL__REPO_COPY_DB);
  attached = 0==rc;
  if( 0==rc ){
    rc = fsl_db_attach(db, ":memory:", FSL__REPO_COPY_TMP);
    attachedTmp = 0==rc;
  }
  if( rc ) rc = fsl_cx_uplift_db_error2(f, db, rc);
  else{
    rc = fsl_cx_txn_begin(f);
    inTxn = 0==rc;
  }
  if( 0==rc ){
    char const * const zPre = fsl__db_repo_prefix(db);
    rc = fsl_cx_exec(f, "PRAGMA %!Q.application_id=252006673",
                     FSL__REPO_COPY_DB);
    if( 0==rc ){
      rc = fsl__repo_copy(f, fsl__db_schema(db, FSL_DBROLE_REPO),
                          zPre ? zPre : "", FSL__REPO_COPY_DB, "");
    }
  }
  if( inTxn ){
    int const rc2 = fsl_cx_txn_end(f, 0!=rc);
    if( 0==rc ) rc = rc2;
  }
  if( attachedTmp ) fsl_db_detach(db, FSL__REPO_COPY_TMP);
  if( attached ){
    int const rc2 = fsl_db_detach(db, FSL__REPO_COPY_DB);
    if( 0==rc && rc2 ) rc = fsl_cx_uplift_db_error2(f, db, rc2);
  }
  if( rc && !f->error.code ) rc = fsl_cx_uplift_db_error2(f, db, rc);
  if( rc && created ) fsl_file_unlink(zFile);
  fsl_db_err_reset(db);
  return rc;
}

int fsl_repo_import(fsl_cx * const f, char const * zFile,
                    char const * zPrefix){
  fsl_db * db;
  bool attached = false, attachedTmp = false, inTxn = false;
  int rc;
  if( !zFile || 0!=fsl_file_access(zFile, 0) ){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Repository db [%s] not found or cannot be read.",
                          zFile ? zFile : "NULL");
  }else if( !f->db.host.dbh ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE, "Importing a repository "
                          "needs a context on a host db handle "
                          "(fsl_cx_host_db()).");
  }else if( !sqlite3_get_autocommit(f->db.host.dbh) ){
    return fsl_cx_err_set(f, FSL_RC_MISUSE, "Cannot import inside a "
                          "transaction, as SQLite cannot ATTACH there.");
  }
  {
    /* What can be checked before closing what f has opened: the
       prefix, and that zFile is a repository. */
    fsl_db h = fsl_db_empty;
    fsl__db_borrow(&h, f->db.host.dbh);
    rc = fsl__cx_repo_prefix_check(f, &h, zPrefix);
    if( 0==rc ) rc = fsl__repo_host_free_check(f, &h, zPrefix);
    if( 0==rc ){
      rc = fsl_db_attach(&h, zFile, FSL__REPO_COPY_DB);
      if( rc ) rc = fsl_cx_uplift_db_error2(f, &h, rc);
      else{
        int32_t const n = fsl_db_g_int32(&h, 0,
          "SELECT count(*) FROM %!Q.sqlite_schema WHERE name COLLATE"
          " nocase IN ('blob','delta','rcvfrom','user','config',"
          "'mlink','plink')", FSL__REPO_COPY_DB);
        fsl_db_detach(&h, FSL__REPO_COPY_DB);
        if( 7!=n ){
          rc = fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                              "Not a valid repository: %s", zFile);
        }
      }
    }
    fsl_db_close(&h)/*does not close the host's handle*/;
    if( rc ) return rc;
  }
  rc = fsl_close_scm_dbs(f);
  if( 0==rc ) rc = fsl__cx_attach_repo_prefixed(f, zPrefix);
  if( rc ) return rc;
  db = f->dbMain;
  if( 0==rc ){
    rc = fsl_db_attach(db, zFile, FSL__REPO_COPY_DB);
    attached = 0==rc;
  }
  if( 0==rc ){
    rc = fsl_db_attach(db, ":memory:", FSL__REPO_COPY_TMP);
    attachedTmp = 0==rc;
  }
  if( 0==rc ){
    rc = fsl_cx_txn_begin(f);
    inTxn = 0==rc;
  }
  if( 0==rc ) rc = fsl__repo_host_claim(f, zPrefix);
  if( 0==rc ) rc = fsl__repo_copy(f, FSL__REPO_COPY_DB, "", "main", zPrefix);
  if( 0==rc && !fsl__repo_looks_valid(f) ){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                        "Not a valid repository: %s", zFile);
  }
  if( inTxn ){
    int const rc2 = fsl_cx_txn_end(f, 0!=rc);
    if( 0==rc ) rc = rc2;
  }
  if( attachedTmp ) fsl_db_detach(db, FSL__REPO_COPY_TMP);
  if( attached ) fsl_db_detach(db, FSL__REPO_COPY_DB);
  if( rc && !f->error.code ) rc = fsl_cx_uplift_db_error2(f, db, rc);
  fsl_db_err_reset(db);
  fsl_close_scm_dbs(f);
  return rc ? rc : fsl_repo_open_host(f, zPrefix);
}
#undef FSL__REPO_COPY_DB
#undef FSL__REPO_COPY_TMP

int fsl_cidiff(fsl_cx * const f, fsl_cidiff_opt const * const opt){
  fsl_deck d1 = fsl_deck_empty;
  fsl_deck d2 = fsl_deck_empty;
  fsl_card_F const * fc1;
  fsl_card_F const * fc2;
  int rc;
  fsl_cidiff_state cst = fsl_cidiff_state_empty;
  if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  rc = fsl_deck_load_rid(f, &d1, opt->v1, FSL_SATYPE_CHECKIN);
  if(rc) goto end;
  rc = fsl_deck_load_rid(f, &d2, opt->v2, FSL_SATYPE_CHECKIN);
  if(rc) goto end;
  rc = fsl_deck_F_rewind(&d1);
  if(0==rc) rc = fsl_deck_F_rewind(&d2);
  if(rc) goto end;
  fsl_deck_F_next(&d1, &fc1);
  fsl_deck_F_next(&d2, &fc2);
  cst.f = f;
  cst.opt = opt;
  cst.d1 = &d1;
  cst.d2 = &d2;
  rc = opt->callback(&cst);
  cst.stepType = FSL_RC_STEP_ROW;
  while(0==rc && (fc1 || fc2)){
    int nameCmp;
    cst.changes = FSL_CIDIFF_NONE;
    if(!fc1) nameCmp = 1;
    else if(!fc2) nameCmp = -1;
    else{
      nameCmp = fsl_strcmp(fc1->name, fc2->name);
      if(fc2->priorName){
        if(0==nameCmp){
          cst.changes |= FSL_CIDIFF_FILE_RENAMED;
        }else if(0==fsl_strcmp(fc1->name, fc2->priorName)){
          /**
             Treat these as being the same file for this purpose.

             We ostensibly know that fc1 was renamed to fc2->name here
             BUT there's a corner case we can't sensibly determine
             here: file A renamed to B and file C renamed to A. If
             both of those F-cards just happen to align at this point
             in this loop, we're mis-informing the user. Reliably
             catching that type of complex situation requires
             significant hoop-jumping, as can be witness in
             fsl_ckout_merge() (which still misses some convoluted
             cases).
          */
          nameCmp = 0;
          cst.changes |= FSL_CIDIFF_FILE_RENAMED;
        }
      }
      if(fc1->perm!=fc2->perm){
        cst.changes |= FSL_CIDIFF_FILE_PERMS;
      }
    }
    if(nameCmp<0){
      nameCmp = -1/*see below*/;
      assert(fc1);
      cst.changes |= FSL_CIDIFF_FILE_REMOVED;
      cst.fc1 = fc1; cst.fc2 = NULL;
    }else if(nameCmp>0){
      nameCmp = 1/*see below*/;
      cst.changes |= FSL_CIDIFF_FILE_ADDED;
      cst.fc1 = NULL; cst.fc2 = fc2;
    }else{
      cst.fc1 = fc1; cst.fc2 = fc2;
    }
    if(fc1 && fc2 && 0!=fsl_strcmp(fc1->uuid, fc2->uuid)){
      cst.changes |= FSL_CIDIFF_FILE_MODIFIED;
    }
    rc = opt->callback(&cst);
    switch(rc ? 2 : nameCmp){
      case  2: break;
      case -1: rc = fsl_deck_F_next(&d1, &fc1); break;
      case  1: rc = fsl_deck_F_next(&d2, &fc2); break;
      case  0:
        rc = fsl_deck_F_next(&d1, &fc1);
        if(0==rc) rc = fsl_deck_F_next(&d2, &fc2);
        break;
      default:
        fsl__fatal(FSL_RC_MISUSE,"Internal API misuse.");
    }
  }/*while(f-cards)*/
  if(0==rc){
    cst.fc1 = cst.fc2 = NULL;
    cst.stepType = FSL_RC_STEP_DONE;
    rc = opt->callback(&cst);
  }
  end:
  fsl_deck_finalize(&d1);
  fsl_deck_finalize(&d2);
  return rc;
}


bool fsl_repo_forbids_delta_manifests(fsl_cx * const f){
  return fsl_config_get_bool(f, FSL_CONFDB_REPO, true,
                             "forbid-delta-manifests");
}

int fsl_tkt_id_to_rids(fsl_cx * const f, char const * tktId,
                       fsl_id_t ** ridList){
  fsl_db * const dbR = fsl_needs_repo(f);
  if(!dbR) return FSL_RC_NOT_A_REPO;
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  fsl_id_t * rids = 0;
  int const isFullId = fsl_is_uuid(tktId);
  unsigned int n = 0;
  if(FSL_STRLEN_SHA1<isFullId){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Ticket ID is not valid. Expecting <=%d bytes of "
                          "lower-case hex values.", FSL_STRLEN_SHA1);
  }
  fsl_db_err_reset(dbR);
  rc = fsl_cx_txn_begin(f);
  if(rc) return rc;
  if(isFullId){
    // Expect an exact match...
    assert(FSL_STRLEN_SHA1==isFullId);
    rc = fsl_cx_prepare(f, &q,
                        "SELECT b.rid, b.uuid FROM {{dbname.repo}}.blob b, {{dbname.repo}}.tagxref x, {{dbname.repo}}.tag t "
                        "WHERE t.tagname = 'tkt-'||%Q "
                        "AND t.tagid=x.tagid AND x.rid=b.rid "
                        "ORDER BY x.mtime, x.rowid",
                        tktId);
  }else{
    /* Check for an ambiguous match of an ID prefix... */
    int32_t const c =
      fsl_db_g_int32(dbR, -1,
                     "SELECT COUNT(distinct tagname) FROM {{dbname.repo}}.tag "
                     "WHERE tagname GLOB 'tkt-%q*'", tktId);
    if( c>1 ){
      rc = fsl_cx_err_set(f, FSL_RC_AMBIGUOUS,
                          "Ticket ID prefix is ambiguous: %s",
                          tktId);
      goto end;
    }else{
      if( c<0 && dbR->error.code ){
        rc = fsl_cx_uplift_db_error(f, dbR);
        goto end;
      }
      if( c<=0 ){
        assert( 0==n );
        goto not_found;
      }
    }
    rc = fsl_cx_prepare(f, &q,
                        "SELECT b.rid, b.uuid FROM {{dbname.repo}}.blob b, {{dbname.repo}}.tagxref x, {{dbname.repo}}.tag t "
                        "WHERE t.tagname GLOB 'tkt-%q*' "
                        "AND t.tagid=x.tagid AND x.rid=b.rid "
                        "ORDER BY x.mtime, x.rowid",
                        tktId);
  }
  if(rc) goto end;
  // Count how many we have to allocate for...
  while(fsl__cx_stmt_step_each(f, &q, &rc)) ++n;
  if(rc) goto end;
  fsl_stmt_reset(&q);
  not_found:
  if(!n){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "No ticket found with ID%s %s.",
                        isFullId ? "" : " prefix",
                        tktId);
    goto end;
  }
  // Populate the result list...
  rids = (fsl_id_t*)fsl_malloc(sizeof(fsl_id_t)*(n+1));
  if(!rids){
    rc = FSL_RC_OOM;
    goto end;
  }
  unsigned i = 0;
  while(fsl__cx_stmt_step_each(f, &q, &rc)){
    assert(i<n);
    rids[i++] = fsl_stmt_g_id(&q, 0);
  }
  if(rc) goto end;
  assert(i==n);
  rids[i] = 0;
  end:
  if(0==rc) *ridList = rids;
  else fsl_free(rids);
  fsl_stmt_finalize(&q);
  fsl_cx_txn_end_v2(f,false,false);
  return rc;
}

int fsl_branch_main(fsl_cx *f, char const **zOut, bool forceReload){
  if( !forceReload && f->db.repo.mainBranch ){
    *zOut = f->db.repo.mainBranch;
    return 0;
  }
  if( !fsl_needs_repo(f) ) return FSL_RC_NOT_A_REPO;
  fsl_b * const b = fsl__cx_scratchpad(f);
  char const * z = 0;
  int rc;
  rc = fsl_config_get_buffer(f, FSL_CONFDB_REPO, "main-branch", b);
  switch( rc ){
    case 0:
      z = fsl_b_cstr(b);
      break;
    case FSL_RC_NOT_FOUND:
      fsl_cx_err_reset(f);
      rc = 0;
      z = "trunk";
      break;
    default:
      break;
  }
  if( 0==rc ){
    char * const zz = fsl_strdup(z);
    if( zz ){
      fsl_free( f->db.repo.mainBranch );
      *zOut = f->db.repo.mainBranch = zz;
    }else{
      fsl_report_oom;
      rc = FSL_RC_OOM;
    }
  }
  fsl__cx_scratchpad_yield(f, b);
  return rc;
}


static int fsl__uperm_add(fsl_cx * f, fsl_uperm * p, char const *zCap,
                          unsigned level, int chFromPerm){
  int rc = 0;
  for( ; 0==rc && *zCap; ++zCap ){
    switch( (int)*zCap ){
      case (int)' ': case (int)'\t': break;
      case 's':   p->setup = 1;
        FSL_SWITCH_FALL_THROUGH /* into Admin */;
      case 'a':   p->admin = p->readTicket = p->writeTicket = p->zip =
                             p->readWiki = p->writeWiki = p->newWiki =
                             p->appendWiki = p->hyperlink = p->clone =
                             p->newTicket = p->password = p->readAddr =
                             p->ticketReport = p->attach = p->appendTicket =
                             p->moderateWiki = p->moderateTicket =
                             p->readForum = p->writeForum = p->moderateForum =
                             p->trustedForum = p->adminForum = p->chat =
                             p->emailAlert = p->announce = p->debug = 1;
        FSL_SWITCH_FALL_THROUGH /* into Read/Write */;
      case 'i':   p->read = p->write = 1;  break;
      case 'o':   p->read = 1;             break;
      case 'z':   p->zip = 1;              break;

      case 'h':   p->hyperlink = 1;        break;
      case 'g':   p->clone = 1;            break;
      case 'p':   p->password = 1;         break;

      case 'j':   p->readWiki = 1;         break;
      case 'k':   p->writeWiki = p->readWiki =
                  p->appendWiki =1;        break;
      case 'm':   p->appendWiki = 1;       break;
      case 'f':   p->newWiki = 1;          break;
      case 'l':   p->moderateWiki = 1;     break;

      case 'e':   p->readAddr = 1;         break;
      case 'r':   p->readTicket = 1;       break;
      case 'n':   p->newTicket = 1;        break;
      case 'w':   p->writeTicket = p->readTicket =
                  p->newTicket = p->appendTicket = 1; break;
      case 'c':   p->appendTicket = 1;     break;
      case 'q':   p->moderateTicket = 1;   break;
      case 't':   p->ticketReport = 1;     break;
      case 'b':   p->attach = 1;           break;
      case 'x':   p->privateContent = 1;   break;
      case 'y':   p->writeUnversioned = 1; break;

      case '6':   p->adminForum = 1;    FSL_SWITCH_FALL_THROUGH;
      case '5':   p->moderateForum = 1; FSL_SWITCH_FALL_THROUGH;
      case '4':   p->trustedForum = 1;  FSL_SWITCH_FALL_THROUGH;
      case '3':   p->writeForum = 1;    FSL_SWITCH_FALL_THROUGH;
      case '2':   p->readForum = 1;        break;

      case '7':   p->emailAlert = 1;       break;
      case 'A':   p->announce = 1;         break;
      case 'C':   p->chat = 1;             break;
      case 'D':   p->debug = 1;            break;

      case (int)'u':
      case (int)'v': {
        if( chFromPerm==(int)*zCap || level>1 ){
          /* Don't recurse. level>1 catches indirect recursion like
             u=>v=>u. */
          break;
        }
        bool * const pB = 'u'==*zCap ? &p->xReader : &p->xDeveloper;
        if( *pB ) break;
        fsl_db * const db = f ? fsl_needs_repo(f) : 0;
        if( !db ){
          rc = f ? FSL_RC_NOT_A_REPO : FSL_RC_MISUSE;
          break;
        }
        char * z = 0;
        rc = fsl_db_get_text(db, &z, NULL,
                             "SELECT cap FROM {{dbname.repo}}.user WHERE login=%Q /*%s()*/",
                             ('u'==*zCap) ? "reader" : "developer",
                             __func__);
        if( rc ){
          rc = fsl_cx_uplift_db_error(f, db);
          assert( !z );
          break;
        }
        if( z ){
          rc = fsl__uperm_add(f, p, z, level+1, (int)*zCap);
          fsl_free(z);
        }
        if( 0==rc ) *pB = true;
        break;
      }
      default:
        rc = f
          ? fsl_cx_err_set(f, FSL_RC_RANGE, "Invalid permissions char '%c' (0x%02x)",
                           *zCap, (unsigned char)*zCap)
          : FSL_RC_RANGE;
        break;
    }
  }
  return rc;
}

int fsl_uperm_add(fsl_cx * f, fsl_uperm * pTgt, char const *zCap){
  return fsl__uperm_add(f, pTgt, zCap, 0, 0);
}

int fsl_repo_project_code( fsl_cx * f, char const **pOut ){
  if(f->cache.projectCode){
    *pOut = f->cache.projectCode;
    return 0;
  }else{
    fsl_b b = fsl_b_empty;
    int rc = fsl_config_get_buffer(f, FSL_CONFDB_REPO,
                                   "project-code", &b);
    if( 0==rc ){
      *pOut = f->cache.projectCode = (char*)b.mem/*transfer ownership*/;
    }else{
      fsl_b_clear(&b);
      if( FSL_RC_NOT_FOUND==rc ){
        rc = fsl_cx_err_set(f, rc, "Repository has no project-code.");
      }
    }
    return rc;
  }
}


#undef MARKER
/* end of file src/repo.c */
/* start of file src/sc.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2025 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2025 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**
  This file contains the fsl_sc impls for the sync transport layer.
  This layer is effectively "client-level", in that fsl_sc is designed
  to be extensible by clients.
*/

#include <stdbool.h>
#include <stdio.h> /* FILE class */
#include <assert.h>
#include <stdlib.h> /* bsearch() */
#include <string.h> /* memcpy() */
#include <errno.h>

#if FSL_PLATFORM_IS_UNIX
#  include <unistd.h>
#  include <fcntl.h>
#  include <sys/stat.h>
#elif FSL_PLATFORM_IS_WINDOWS
#  include <io.h> /* open(), read() */
#  include <fcntl.h>
#  include <sys/stat.h>
#else
#  error "don't know which #include to use for open(2) and read(2)."
#endif

#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

fsl_sc * fsl_sc_self(fsl_sc *ch){
  return ch;
}

void fsl_sc_cleanup(fsl_sc * const ch){
  if(ch){
    if( ch->cleanup ) ch->cleanup(ch);
    fsl_url_cleanup(&ch->url);
    fsl_b_clear(&ch->requestHeaders);
    fsl_b_clear(&ch->scratch);
  }
}

/**
   Returns the most bytes ch reads for one reply

   This is the max response + framing + headers
*/
static fsl_size_t fsl__sc_reply_max(fsl_sc * const ch){
  fsl_size_t const n = fsl_xfer_max_response(ch->xfer);
  return n + n/16 + 64*1024;
}

/**
   Sets ch->xfer's error state for a reply longer than
   fsl__sc_reply_max() and returns FSL_RC_RANGE.
*/
static int fsl__sc_reply_too_long(fsl_sc * const ch){
  return fsl_xfer_errorf(ch->xfer, FSL_RC_RANGE,
                         "Reply is longer than %" FSL_SIZE_T_PFMT
                         " bytes", fsl__sc_reply_max(ch));
}

/**
   State for fsl_input_f_sc_capped().
*/
typedef struct {
  fsl_input_f in;
  void * inState;
  fsl_size_t n;    /* bytes read so far */
  fsl_size_t max;
} fsl__sc_capped;

/**
   A fsl_input_f which reads from state->in, and fails with
   FSL_RC_RANGE once it has read more than state->max bytes in all.
   state is a fsl__sc_capped.
*/
static int fsl_input_f_sc_capped(void * state, void * dest,
                                 fsl_size_t * n){
  fsl__sc_capped * const c = state;
  int const rc = c->in(c->inState, dest, n);
  if( rc ) return rc;
  c->n += *n;
  return c->n>c->max ? FSL_RC_RANGE : 0;
}

#define fsl__sc_popen_decl \
  assert(ch->impl.type == fsl_sc_popen.impl.type); \
  fsl_sc_popen_state * const st = ch->impl.p; \
  assert( st )

static void fsl_sc_popen_unlinkResponseFile(fsl_sc *ch, bool freeIt){
  fsl__sc_popen_decl;
  if( st->response.fp ){
    fsl_fclose(st->response.fp);
    st->response.fp = 0;
    st->response.fd = -1;
  }else if( st->response.fd >= 0 ){
    close( st->response.fd );
    st->response.fd = -1;
  }
  if( st->response.filename ){
    if( ch->flags & FSL_SC_F_LEAVE_TEMP_FILES  ){
      fsl_cx_emit(fsl_xfer_cx(ch->xfer), FSL_MSG_TMPFILE,
                  st->response.filename);
    }else{
      fsl_file_unlink(st->response.filename);
    }
    if( freeIt ){
      fsl_free( st->response.filename );
      st->response.filename = 0;
    }
  }
}

static void fsl_sc_popen_unlinkRequestFile(fsl_sc *ch){
  fsl__sc_popen_decl;
  if( st->request.fp ){
    fsl_fclose( st->request.fp );
    st->request.fp = NULL;
  }
  if( st->request.filename ){
    if( ch->flags & FSL_SC_F_LEAVE_TEMP_FILES ){
      fsl_cx_emit(fsl_xfer_cx(ch->xfer), FSL_MSG_TMPFILE,
                  st->request.filename);
    }else{
      fsl_file_unlink(st->request.filename);
    }
    fsl_free(st->request.filename);
    st->request.filename = 0;
  }
}

/**
   Closes the child process, if any, and returns its exit status as
   documented for fsl__pclose2(), or 0 if no child was open.
*/
static int fsl_sc_popen_pclose(fsl_sc * ch, bool unlinkTmpFiles){
  fsl__sc_popen_decl;
  int status = 0;
  if( unlinkTmpFiles ){
    fsl_sc_popen_unlinkRequestFile(ch);
    fsl_sc_popen_unlinkResponseFile(ch, true);
  }
  if( st->process.fdStdOut>=0 ){
    status = fsl__pclose2( st->process.fdStdOut, st->process.fStdIn,
                           st->process.pid );
    st->process.fdStdOut = -1;
    st->process.fStdIn = NULL;
    st->process.pid = 0;
  }
  return status;
}

#define popenTempFileName(LETTER) \
  fsl_mprintf("%s-%d.%c", st->misc.tmpfilePrefix, (int)st->request.count, LETTER)

static int fsl_sc_popen_initRequestFile(fsl_sc * const ch){
  fsl__sc_popen_decl;
  int rc = 0;

  fsl_sc_popen_unlinkRequestFile(ch);
  ++st->request.count;
  assert( st->misc.tmpfilePrefix );
  st->request.filename = popenTempFileName('q');
  if( st->request.filename ){
    st->request.fp = fsl_fopen(st->request.filename, "w+b");
    if( !st->request.fp ){
      rc = fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                           "%s: error opening temp POST data file "
                           "for writing", ch->name);
    }else{
      fsl__tmpchmod( st->request.filename );
    }
  }else{
    fsl_report_oom;
    rc = FSL_RC_OOM;
  }
  return rc;
}

static int fsl_sc_popen_initResponseFile(fsl_sc * const ch){
  fsl__sc_popen_decl;

  ++st->response.count;
  if( fsl_sc_popen_e_filebuf == st->response.mode
      || fsl_sc_popen_e_fd == st->response.mode ){
    fsl_sc_popen_unlinkResponseFile(ch, false);
    assert( st->misc.tmpfilePrefix );
    st->response.filename = popenTempFileName('a');
    if( !st->response.filename ){
      fsl_report_oom;
      return FSL_RC_OOM;
    }
  }
  return 0;
}

#undef popenTempFileName

static int fsl_sc_popen_xInit(fsl_sc * const ch, enum fsl_sc_init_e mode){
  fsl__sc_popen_decl;
  int rc = 0;

  assert( (FSL_SC_INIT_INITIAL | FSL_SC_INIT_REQUEST) & mode );
  if( !st->bin.location ){
    /* Find the binary, if needed... */
    assert( FSL_SC_INIT_INITIAL & mode );
    char const * zBinName = st->bin.name
      ? st->bin.name
      : ch->name;
    if( !zBinName ){
      rc = fsl_xfer_errorf(ch->xfer, FSL_RC_MISUSE,
                           "fsl_sc::name or fsl_sc_popen_state::bin::name "
                           "must be set before calling %s()",
                           __func__);
    }else{
      rc = fsl__find_bin( NULL, zBinName, &st->bin.location );
      switch( rc ){
        default: break;
        case 0: assert( st->bin.location ); break;
        case FSL_RC_NOT_FOUND:
          rc = fsl_xfer_errorf(ch->xfer, rc,
                               "Cannot find %s binary in $PATH", zBinName);
          break;
      }
    }
    if( 0==rc ){
      fsl_b b = fsl_b_empty;
      rc = fsl__tmpfile(&b, "libfossil-popen");
      if( b.mem ){
        st->misc.tmpfilePrefix = fsl_b_str(&b);
        b = fsl_b_empty;
      }
      if( rc && FSL_RC_OOM!=rc ){
        rc = fsl_xfer_errorf(ch->xfer, rc,
                             "Cannot create a temp file name for "
                             "the %s request and response", zBinName);
      }
    }
    if( 0==rc && st->impl.init ){
      rc = st->impl.init(ch);
    }
    if( 0==rc && 0==fsl_strcmp("file", ch->url.scheme) ){
      fsl_fstat fst = fsl_fstat_empty;
      rc = fsl_stat(ch->url.path, &fst, false);
      if( FSL_RC_NOT_FOUND==rc ){
        rc = fsl_xfer_errorf(ch->xfer, rc, "no such file: \"%s\"",
                             ch->url.path);
      }else if( rc ){
        rc = fsl_xfer_errorf(ch->xfer, rc, "fsl_stat(%s) failed with code %R",
                             ch->url.path, rc);
      }else if( FSL_FSTAT_TYPE_FILE!=fst.type ){
        rc = fsl_xfer_errorf(ch->xfer, FSL_RC_TYPE, "[%s] is not a file",
                             ch->url.path);
      }
    }
    if( rc ) goto end;
  }

  assert( 0==rc );
  assert( st->impl.buildCommandLine );
  if( FSL_SC_INIT_REQUEST & mode ){
    rc = fsl_sc_popen_initRequestFile(ch);
  }

end:
  return rc;
}

static int fsl_sc_popen_xAppend(fsl_sc * const ch, void const * src, fsl_size_t n){
  fsl__sc_popen_decl;
  assert( st->request.fp );
  //fsl_sc_debugf(ch, "append(): %.*s", (int)n, (char const *)src);
  return 1==fwrite(src, n, 1, st->request.fp)
    ? 0
    : fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                     "Error writing to POST data file %s",
                      st->request.filename);
}

/**
   Reports that ch's child process wrote no reply and ended with the
   given non-0 status, as returned by fsl_sc_popen_pclose(). The
   child's own diagnostics, if any, went to stderr.
*/
static int fsl_sc_popen_no_reply(fsl_sc * const ch, int status){
  fsl__sc_popen_decl;
  char const * const zBin = st->bin.name ? st->bin.name : ch->name;
  assert( status );
  if( status<0 ){
    return fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                           "%s was killed by signal %d and sent no reply",
                           zBin, -status);
  }
  if( 127==status /*assume command-not found for fossil*/ ){
    return fsl_xfer_errorf(ch->xfer, FSL_RC_NOT_FOUND,
                           "%s exited with status %d (command not found). "
                           "Try adding ?fossil=/remote/path/to/fossil to the "
                           "sync URL.", zBin, status);
  }else{
    return fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                           "%s exited with status %d%s and sent no reply",
                           zBin, status,
                           127==status ? " (command not found)" : "");
  }
}

static int fsl_sc_popen_xSubmit(fsl_sc * const ch,
                                fsl_b const * bLoginCard){
  fsl__sc_popen_decl;
  int rc;
  if( 0 && st->request.filename ){
    //fsl_system("ls -latd /tmp/stephan/libfo*");
    fsl_fstat fs = fsl_fstat_empty;
    MARKER(("stat(%s)=%s\n", st->request.filename,
            fsl_rc_cstr(fsl_stat(st->request.filename, &fs, false))));
  }

  fsl_sc_popen_unlinkResponseFile(ch, true);
  assert( st->request.filename );
  assert( st->request.fp );
  if( ch->requestHeaders.used ){
    /* We need to prepend the request headers to the request. We use a
       separate temp file for this.  TODO: if st->request.fp is
       relatively small, stream it into ch->requestHeaders then
       replace its contents with that buffer. */
    fsl_b * const b = &ch->requestHeaders;
    //MARKER(("Request headers swap-around!\n"));
    fsl_int_t const nReq = fsl_file_size(st->request.filename);
    if( nReq >= 0 && nReq < (1024 * 512/*arbitrary*/) ){
      /* More memory-hungry, but simpler... */
      rewind( st->request.fp );
      rc = fsl_stream(fsl_input_f_FILE, st->request.fp,
                      fsl_output_f_b, b);
      if( 0==rc ){
        rewind( st->request.fp );
        fsl_b_rewind(b);
        rc = fsl_stream(fsl_input_f_buffer, b, fsl_output_f_FILE, st->request.fp);
        fflush( st->request.fp );
      }
      if( rc && FSL_RC_OOM!=rc ){
        rc = fsl_xfer_errorf(ch->xfer, rc,
                             "Error prepending HTTP headers to "
                             "request file %s", st->request.filename);
      }
      assert( rc || fsl_file_size(st->request.filename)==(fsl_int_t)b->used );
    }else{
      char * zTmpFile = fsl_mprintf("%s.2", st->request.filename);
      if( !zTmpFile ){
        fsl_report_oom;
        rc = FSL_RC_OOM;
      }else{
        FILE * const fNewReq = fsl_fopen(zTmpFile, "w+b");
        if( !fNewReq ){
          rc = fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                               "Error creating request payload temp file %s",
                               zTmpFile);
        }else if( 1==fwrite(b->mem, b->used, 1, fNewReq) ){
          rewind( st->request.fp );
          rc = fsl_stream(fsl_input_f_FILE, st->request.fp,
                          fsl_output_f_FILE, fNewReq);
          if( rc && FSL_RC_OOM!=rc ){
            rc = fsl_xfer_errorf(ch->xfer, rc,
                                 "Error copying request file %s to %s",
                                 st->request.filename, zTmpFile);
          }
        }else{
          rc = fsl_xfer_errorf(ch->xfer, fsl_errno_to_rc(errno, FSL_RC_IO),
                               "Error writing to request payload temp file %s",
                               zTmpFile);
        }
        fsl_fclose(fNewReq);
      }
      if( 0==rc ){
        fsl_b_reuse(b);
        fsl_sc_popen_unlinkRequestFile(ch);
        assert( !st->request.fp );
        st->request.filename = zTmpFile;
      }else{
        fsl_free(zTmpFile);
      }
    }
    if( rc ) goto end;
  }/* ch->requestHeaders */

  fsl_fclose( st->request.fp );
  st->request.fp = 0;
  assert( st->request.filename );

  rc = fsl_sc_popen_initResponseFile(ch);
  if( 0==rc ){
    rc = st->impl.buildCommandLine(ch, fsl_b_reuse( &st->cmd ),
                                   bLoginCard);
  }
  if( rc ) goto end;
  fsl_xfer_debugf(ch->xfer, "Command line: %b", &st->cmd);
  rc = fsl__popen2(fsl_b_cstr(&st->cmd), st->request.filename,
                   &st->process.fdStdOut, &st->process.fStdIn,
                   &st->process.pid);
  if( rc ){
    rc = fsl_xfer_errorf(ch->xfer, rc, "Could not run external command: %b",
                         &st->cmd);
    goto end;
  }
  assert( 0==rc );
  assert( st->process.fdStdOut>0 );

  switch( st->response.mode ){

    case fsl_sc_popen_e_membuf:{
      /* Buffer the response. */
      int status;
      fsl__sc_capped in = {
        fsl_input_f_fd, &st->process.fdStdOut, 0, fsl__sc_reply_max(ch)
      };
      fsl_b_reuse(&st->response.b);
      rc = fsl_b_fill_from(&st->response.b, fsl_input_f_sc_capped, &in);
      if( in.n>in.max ){
        rc = fsl__sc_reply_too_long(ch);
      }else if( rc && FSL_RC_OOM!=rc ){
        rc = fsl_xfer_errorf(ch->xfer, rc, "Error reading the output of %s",
                             st->bin.name ? st->bin.name : ch->name);
      }
      status = fsl_sc_popen_pclose(ch, true);
      if( 0==rc && status && 0==st->response.b.used ){
        rc = fsl_sc_popen_no_reply(ch, status);
      }
      break;
    }

    case fsl_sc_popen_e_filebuf:
      assert( st->response.filename );
      if( st->response.filename ){
        /* Buffer the response via st->response.filename, immediately
           piping all of the binary's stdout to there. We read the
           response from this new handle. See comments in
           case:fsl_sc_popen_e_direct. */
        //MARKER(("Buffering via %s\n", st->response.filename));
        assert( st->response.fd < 0 );
        assert( !st->response.fp );
#if 1
        FILE * fp = fsl_fopen(st->response.filename, "w+b");
        if( !fp ){
          rc = fsl_xfer_errorf(ch->xfer, fsl_errno_to_rc(errno,FSL_RC_IO),
                             "Cannot open file %s", st->response.filename);
          break;
        }
        fsl__tmpchmod( st->request.filename );
        fsl__sc_capped in = {
          fsl_input_f_fd, &st->process.fdStdOut, 0, fsl__sc_reply_max(ch)
        };
        rc = fsl_stream( fsl_input_f_sc_capped, &in,
                         fsl_output_f_FILE, fp );
        int const status = fsl_sc_popen_pclose(ch, false);
        if( in.n>in.max ){
          rc = fsl__sc_reply_too_long(ch);
        }else if( rc && FSL_RC_OOM!=rc ){
          rc = fsl_xfer_errorf(ch->xfer, rc,
                               "Error copying the output of %s to %s",
                               st->bin.name ? st->bin.name : ch->name,
                               st->response.filename);
        }else if( 0==rc && status
                  && fsl_file_size(st->response.filename)<=0 ){
          rc = fsl_sc_popen_no_reply(ch, status);
        }
        if( 0==rc ){
          rewind(fp);
          st->response.fp = fp;
          //st->response.fd = fileno(fp);
        }else{
          fsl_fclose(fp);
        }
#else
        /* Same as above but use an unbuffered file descriptor */
        int fd = open(st->response.filename,
                      O_EXCL | O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
        if( fd<0 ){
          rc = fsl_xfer_errorf(ch->xfer, fsl_errno_to_rc(errno,FSL_RC_IO),
                             "Cannot open file %s", st->response.filename);
          break;
        }
        rc = fsl_stream( fsl_input_f_fd, &st->process.fdStdOut,
                         fsl_output_f_fd, &fd );
        fsl_sc_popen_pclose(st, false);
        if( rc ){
          close(fd);
          rc = fsl_xfer_errorf(ch->xfer, rc, "Error streaming response to %s",
                             st->response.filename);
        }else{
          st->response.fd = fd;
          lseek(fd, 0, SEEK_SET);
        }
        //MARKER(("rc=%d\n", rc));
#endif
      }
      break;

    case fsl_sc_popen_e_fd:
      /*  Buffer the response via st->response.filename so we can
          later stream input from the binary's stdout. This mode does
          not work: it was failing with "file not found" for the
          response file, and the commands no longer write that file
          themselves, so nothing fills it. Use
          fsl_sc_popen_e_filebuf. */
      assert( st->response.filename );
      assert( st->response.fd<0 );
      st->response.fd = open(st->response.filename, O_RDONLY);
      if( st->response.fd<0 ){
        rc = fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                           "Error %R opening response file %s",
                           fsl_errno_to_rc(errno, FSL_RC_IO),
                           st->response.filename);
      }
      break;

    case fsl_sc_popen_e_direct:
      /* For some reason, reading the response directly from the
         binary's stdout st->process.fdStdOut, i.e. in
         fsl_sc_popen_e_direct mode, is misbehaving in a weird way: it
         seems to mostly work and then consumes only part of one
         cfile/file card, leaving the rest of the card for for the
         next read-line op, which then fails to parse the non-card
         input */
    default:
      break;
  }
end:
  return rc;
}

/**
   fsl_sc::read() impl for fsl_sc_popen.
*/
static int fsl_sc_popen_xRead(fsl_sc * const ch, fsl_b * tgt, fsl_int_t howMuch){
  int rc = 0;
  fsl__sc_popen_decl;
  switch( st->response.mode ){

    default:
      fsl__fatal(FSL_RC_MISUSE, "Impossible fsl_sc_popen_e_e value\n");
      break;

    case fsl_sc_popen_e_membuf:
      if( st->response.b.used ){
        fsl_b * const br = &st->response.b;
        fsl_size_t const cu = br->cursor;
        switch( howMuch ){
          case FSL_SC_READ_LINE:
            /* Read one line */
            rc = fsl_b_copy_lines(tgt, br, 1);
            if( !rc && cu==br->cursor ){
              /* End of input */
              rc = FSL_RC_BREAK;
            }
            break;

          case FSL_SC_READ_ALL:
            fsl_b_swap(&st->response.b, tgt);
            break;

          default:
            assert( howMuch > 0 );
            /* Read an absolute amount */
            fsl_b_err_clear(tgt);
            if( howMuch + cu > br->used ){
              rc = fsl_xfer_errorf(ch->xfer, FSL_RC_RANGE,
                                 "Not enough buffer (%u bytes) to serve %u bytes",
                                 (unsigned)(br->used - cu), (unsigned)howMuch);
            }else{
              rc = fsl_b_append(tgt, br->mem+cu, howMuch);
              if( 0==rc ){
                br->cursor += howMuch;
              }
            }
            break;
        }
      }else{
        rc = FSL_RC_BREAK;
      }
      break;

    case fsl_sc_popen_e_direct:
    case fsl_sc_popen_e_filebuf:
    case fsl_sc_popen_e_fd:{
      enum { Sz = 1024 * 2 /* input buffer size */ };
      unsigned char buf[Sz];
      FILE * const fp =
        1 ? st->response.fp : NULL
        /* Reading from st->response.fp is significantly faster than
           unbuffered reading from fileno(st->response.fp). */;
      int const fdIn = fp
        ? -1
        : (fsl_sc_popen_e_fd == st->response.mode
           ? st->response.fd
           : st->process.fdStdOut);
      assert(fsl_sc_popen_e_filebuf == st->response.mode
             || fsl_sc_popen_e_direct == st->response.mode
             || fsl_sc_popen_e_fd == st->response.mode);
      assert( fp ? (fsl_sc_popen_e_filebuf == st->response.mode)
              : (fsl_sc_popen_e_filebuf != st->response.mode) );
      assert( fp ? fdIn<0 : fdIn>0 );

      switch( howMuch ){

        case FSL_SC_READ_LINE:{
          fsl_size_t nLine = 0;
          char * line = 0;
          if( fp ){
            line = fgets((char *)buf, Sz, fp);
            if( !line ){
              rc = feof(fp)
                ? FSL_RC_BREAK
                : fsl_xfer_error(ch->xfer, FSL_RC_IO,
                               "Read from response failed");
            }else{
              /* fsl_strlen() here is a genuine performance hog. One
                 alternative would be to use getline(3) instead of
                 fgets(3), but that requires a malloc()-allocated buffer
                 which it may realloc(). */
              nLine = (fsl_size_t)strlen(line);//fsl_strlen(line)
              /* strlen() is far more performant than either
                 fsl_strlen() or a local loop. */;
            }
          }else{
            rc = fsl__fdgets(fdIn, buf, Sz, &line, &nLine);
            //MARKER(("xread %"FSL_INT_T_PFMT " rc=%d nLine=%u\n", howMuch, rc, (unsigned)nLine));
            if( rc ){
              rc = fsl_xfer_error(ch->xfer, rc,
                                "fgets() of child-process's stdout failed");
            }
          }
          //MARKER(("get-line: [%.*s]\n", (int)nLine, line));
          if( 0==rc ){
            if( !nLine ){
              rc = FSL_RC_BREAK;
            }
#if 0
            /* Leave this to the higher-up xfer APIs? */
            else if( '\n' != line[nLine-1] ){
              rc = fsl_xfer_error(ch->xfer, FSL_RC_SYNTAX,
                                "No newline found in input");
            }
#endif
            else{
              //MARKER(("get-line: [%.*s]\n", (int)nLine, line));
              rc = fsl_b_append(tgt, line, (fsl_int_t)nLine);
            }
          }
          break;
        }

        case FSL_SC_READ_ALL:{
          fsl__sc_capped in = {
            fp ? fsl_input_f_FILE : fsl_input_f_fd,
            fp ? (void *)fp : (void *)&fdIn,
            0, fsl__sc_reply_max(ch)
          };
          rc = fsl_stream(fsl_input_f_sc_capped, &in, fsl_output_f_b, tgt);
          if( in.n>in.max ){
            rc = fsl__sc_reply_too_long(ch);
          }else if( rc && FSL_RC_OOM!=rc ){
            rc = fsl_xfer_error(ch->xfer, rc, "Read from response failed");
          }
          break;
        }

        default:
          /* Read an absolute amount */
          assert( howMuch > 0 );
          fsl_b_err_clear(tgt);
          while( 0==rc && howMuch > 0 ){
            size_t const n = (howMuch>=Sz ? Sz : (size_t)howMuch);
            fsl_int_t const rd = fp
              ? (fsl_int_t)fread(buf, n, 1, fp)
              : (fsl_int_t)read(fdIn, buf, n);
            if( fp && 1!=rd && feof(fp) ){
              rc = fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                                   "unexpected end of response: "
                                   "%" FSL_INT_T_PFMT " bytes still "
                                   "expected", howMuch);
            }else if( fp ? 1!=rd : -1==rd ){
              //MARKER(("errno=%s\n", strerror(errno)));
              rc = fsl_xfer_errorf(ch->xfer,
                                   fsl_errno_to_rc(errno, FSL_RC_IO),
                                   "error reading %u bytes",
                                   (unsigned)n);
            }else if( !fp && n==(fsl_size_t)howMuch && (size_t)rd != n ){
              rc = fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                                   "short read: %u of %u bytes",
                                   (unsigned)rd, (unsigned)n);
            }else{
              assert( (fsl_int_t)n > 0 && "Else overflow");
              assert( (size_t)howMuch >= n );
              howMuch -= n;
              assert( howMuch >= 0 );
              rc = fsl_b_append(tgt, buf, (fsl_int_t)n);
            }
          }
          break;
      }/*switch(howMuch)*/
      break;
    }/*case non-membuf*/
  }/* switch(st->response.mode) */
  return rc;
}

static void fsl_sc_popen_xCleanup(fsl_sc * const ch){
  fsl__sc_popen_decl;
  if(st->impl.cleanup){
    st->impl.cleanup(st);
  }
  fsl_sc_popen_pclose(ch, true);
  assert( st->response.fd < 0 );
  fsl_b_clear(&st->response.b);
  fsl_free(st->bin.location);
  fsl_free(st->misc.tmpfilePrefix);
  fsl_b_clear(&st->cmd);
  if( st->misc.allocStamp ){
    assert( st->misc.allocStamp == st );
    ch->impl = fsl_sc_popen.impl;
    *st = fsl_sc_popen_state_empty;
    fsl_free(st);
  }else{
    *st = fsl_sc_popen_state_empty;
  }
}

const fsl_sc_popen_state fsl_sc_popen_state_empty =
  fsl_sc_popen_state_init("<unnamed>", 0, 0, 0);


#define fsl__sc_popen_init(NAME,STATETYPE,SCFLAGS) { \
  .xfer = NULL, .name = NAME,                        \
  .url = fsl_url_empty_m,                            \
  .flags = SCFLAGS,                                  \
  .impl = {.p = 0, .type = &fsl_sc_popen},           \
  .init = fsl_sc_popen_xInit,                        \
  .append = fsl_sc_popen_xAppend,                    \
  .submit = fsl_sc_popen_xSubmit,                    \
  .read = fsl_sc_popen_xRead,                        \
  .cleanup = fsl_sc_popen_xCleanup,                  \
  .self = fsl_sc_self                                \
}

const fsl_sc fsl_sc_popen =
  fsl__sc_popen_init("popen", fsl_sc_popen_state_empty,0);

/**
   fsl_sc_popen::impl::buildCommandLine() impl for curl.
*/
static int fsl_sc_popen_curl_buildCommandLine(fsl_sc * const ch,
                                              fsl_b * const b,
                                              fsl_b const * bLoginCard){
  int rc = 0;
  fsl_error * const err = fsl_cx_err_e(ch->xfer->f);
  fsl_url const * const url = &ch->url;
  fsl__sc_popen_decl;
  char const * const curlArgs[] = {
    st->bin.location,
    "--silent",
    /*"-XPOST", is implied by --data-binary and curl -v warns about
      this. */
    "--include",
    "--user-agent", "libfossil " FSL_LIBRARY_VERSION,
    "-H", (FSL_SC_F_COMPRESSED & ch->flags)
    ? "Content-Type: application/x-fossil"
    : "Content-Type: application/x-fossil-uncompressed",
    "--data-binary" /* @st->request.filename */
  };
  assert( st->bin.location );
  assert( url->raw );
  assert( st->request.filename );
  assert( !st->request.fp );
  fsl_error_reset(err);
  for( unsigned int i = 0;
       0==rc &&i < sizeof(curlArgs)/sizeof(curlArgs[0]);
       ++i ){
    rc = fsl_b_esc_arg_v2(b, err, curlArgs[i], 0==i);
  }
  if( 0==rc && (ch->flags & FSL_SC_F_TLS_ACCEPT_ANY_CERT) ){
    rc = fsl_b_esc_arg_v2(b, err, "--insecure", false);
  }
  if( rc ) return rc;

  if( !b->errCode ){ /* --data-binary @filename */
    fsl_b * const bName = fsl_b_reuse(&ch->scratch);
    fsl_b_appendch(bName, '@');
    fsl_b_append(bName, st->request.filename, -1);
    fsl_b_esc_arg_v2(b, err, fsl_b_cstr(bName), true);
    if( bName->errCode ) return bName->errCode;
  }

  /* curl writes the response to stdout, which the channel copies to
     the response file: see fsl_sc_popen_xSubmit(). */

  if( !b->errCode && bLoginCard ){
    /* The card holds the user name from the URL, so it is
       URL-encoded, as for the native channel's Cookie header, and
       the argument is escaped for the shell. */
    fsl_b * const bc = fsl_b_reuse(&ch->scratch);
    fsl_b_appendf(bc, "x-f-l-c=%t", fsl_b_cstr(bLoginCard));
    if( bc->errCode ) return bc->errCode;
    fsl_b_esc_arg_v2(b, err, "--cookie", false);
    fsl_b_esc_arg_v2(b, err, fsl_b_cstr(bc), false);
  }

  if( url->username ){
    /* Strip username[:password] from the URL because curl will add a
       HTTP Basic Authentication header for it, which we don't
       want. */
    fsl_b * const bu = fsl_b_reuse(&ch->scratch);
    fsl_url_render(url, bu, FSL_URL_RENDER_NO_USER);
    if( bu->errCode ) b->errCode = bu->errCode;
    else{
      fsl_b_esc_arg_v2(b, err, fsl_b_cstr(bu), false);
    }
  }else{
    fsl_b_esc_arg_v2(b, err, url->raw, false);
  }

#if FSL_PLATFORM_IS_UNIX
  //stderr is useful for dianosing curl invocation errors
  //fsl_b_append(b, " 2>/dev/null", 12);
#endif
  return b->errCode ? b->errCode : err->code;
}

const fsl_sc_popen_state fsl_sc_popen_state_curl =
  fsl_sc_popen_state_init("curl",
                          0,
                          fsl_sc_popen_curl_buildCommandLine, 0);

const fsl_sc fsl_sc_popen_curl =
  fsl__sc_popen_init("popen<curl>", fsl_sc_popen_state_curl,0);

/**
   fsl_sc_popen::impl::buildCommandLine() impl for fossil(1)'s
   test-http command (which is how fossil implements local-file sync
   and SSH sync).
*/
static int fsl_sc_popen_fth_buildCommandLine(fsl_sc * ch,
                                             fsl_b * const b,
                                             fsl_b const * bLoginCard){
  fsl_error * const err = fsl_cx_err_e(fsl_xfer_cx(ch->xfer));
  fsl__sc_popen_decl;
  assert( st->bin.location );
  assert( ch->url.raw );
  assert( st->request.filename );
  assert( !st->request.fp );
  (void)bLoginCard;
  fsl_error_reset(err);
  fsl_b_esc_arg_v2(b, err, st->bin.location, true);
  fsl_b_esc_arg_v2(b, err, "test-http", false);
  fsl_b_esc_arg_v2(b, err, ch->url.path, true);
  /* No redirections: fsl__popen2() gives the command the request
     file as its stdin, and the channel copies its stdout to the
     response file. See fsl_sc_popen_xSubmit(). */
#if FSL_PLATFORM_IS_UNIX
  if( FSL_SC_F_SUPPRESS_STDERR & ch->flags ){
    fsl_b_append(b, " 2>/dev/null", 12);
  }
#endif
  return b->errCode ? b->errCode : err->code;
}

const fsl_sc_popen_state fsl_sc_popen_state_fth =
  fsl_sc_popen_state_init("fossil",
                          0,
                          fsl_sc_popen_fth_buildCommandLine, 0);

const fsl_sc fsl_sc_popen_fth =
  fsl__sc_popen_init("popen<fossil test-http>",
                     fsl_sc_popen_state_fth,
                     FSL_SC_F_REQUEST_HEADERS);


/**
   fsl_sc_popen::impl::buildCommandLine() impl for an ssh-based impl
   which remotely invoke's fossil(1)'s test-http command (which is how
   fossil implements ssh sync).
*/
static int fsl_sc_popen_ssh_buildCommandLine(fsl_sc * ch,
                                             fsl_b * const b,
                                             fsl_b const * bLoginCard){
  fsl_error * const err = fsl_cx_err_e(fsl_xfer_cx(ch->xfer));
  char const *zRemoteFossil = "fossil"
    /* remote fossil binary, overridden via url
       ?fossil=/path/to/fossil */;
  fsl__sc_popen_decl;
  assert( st->bin.location );
  assert( ch->url.raw );
  assert( st->request.filename );
  assert( !st->request.fp );
  (void)bLoginCard;
  fsl_error_reset(err);
  if( !ch->url.path || !*ch->url.path ){
    return fsl_error_set(err, FSL_RC_MISUSE,
                         "ssh:// URL does not specify a path to the repository");
  }
  fsl_b_esc_arg_v2(b, err, st->bin.location, true);
  //if( 0==(FSL_SC_F_COMPRESSED & ch->flags) ){
  //slow...
  //  fsl_b_esc_arg_v2(b, err, "-C", false);
  //}
  if( ch->url.port>0 ){
    /* ssh takes the port as an option, not in host:port colon format. */
    fsl_b_appendf(b, " -p %d", (int)ch->url.port);
  }
  fsl_b_esc_arg_v2(b, err, "-T", false);
  fsl_b_esc_arg_v2(b, err, "--", false);
  if( 0==b->errCode ){
    /* Add user/host... */
    fsl_b * const bScratch = fsl_b_reuse(&ch->scratch);
    assert( !bScratch->errCode );
    if( ch->url.username ){
      fsl_b_appendf(bScratch, "%s@", ch->url.username);
    }
    if( '['==ch->url.host[0] ){
      /* fsl_url_parse() keeps an IP literal's brackets. ssh takes
         [user@]hostname, with an IPv6 address bare. */
      fsl_size_t const n = fsl_strlen(ch->url.host);
      assert( n>2 && ']'==ch->url.host[n-1] );
      fsl_b_append(bScratch, ch->url.host + 1, (fsl_int_t)(n - 2));
    }else{
      fsl_b_append(bScratch, ch->url.host, -1);
    }
    b->errCode = bScratch->errCode;
    fsl_b_esc_arg_v2(b, err, fsl_b_cstr(bScratch), false);
    if( 0==b->errCode ){
      /* Check for fossil=... URL arg... */
      fsl_cx * const f = fsl_xfer_cx(ch->xfer);
      fsl_b * const bKey = fsl_cx_b_borrow(f);
      if( !bKey ) return f->error.code;
      char const *zTail = 0;
      fsl_b_reserve(bKey, 16);
      while( fsl_url_next_query_arg(&ch->url, &zTail, bKey, bScratch) ){
        if( fsl_b_eq(bKey, "fossil", 6) ){
          fsl_b_esc_arg_v2(b, err, fsl_b_cstr(bScratch), true);
          zRemoteFossil = 0;
          break;
        }
      }
      b->errCode = bKey->errCode ? bKey->errCode : bScratch->errCode;
      fsl_cx_b_return(f, bKey);
      fsl_b_reuse(bScratch);
    }
  }
  if( zRemoteFossil ){
    fsl_b_esc_arg_v2(b, err, zRemoteFossil, true);
  }
  fsl_b_esc_arg_v2(b, err, "test-http", false);
  /* The path after the host is relative to the remote user.
     One slash makes is relative to homedir, second slash is absolute.
     So ssh://host/x.fossil means ~/x.fossil, and ssh://host//x.fossil
     means /x.fossil. The username as given to or assumed by ssh as usual. */
  fsl_b_esc_arg_v2(b, err,
                   ('/'==ch->url.path[0] && ch->url.path[1])
                   ? ch->url.path+1 : ch->url.path, true);
  /* No redirections: fsl__popen2() gives the command the request
     file as its stdin, and the channel copies its stdout to the
     response file. See fsl_sc_popen_xSubmit(). */
#if FSL_PLATFORM_IS_UNIX
  if( FSL_SC_F_SUPPRESS_STDERR & ch->flags ){
    fsl_b_append(b, " 2>/dev/null", 12);
  }
#endif
  return b->errCode ? b->errCode : err->code;
}

const fsl_sc_popen_state fsl_sc_popen_state_ssh =
  fsl_sc_popen_state_init("ssh",
                          0,
                          fsl_sc_popen_ssh_buildCommandLine, 0);

const fsl_sc fsl_sc_popen_ssh =
  fsl__sc_popen_init("popen<ssh>",
                     fsl_sc_popen_state_ssh,
                     FSL_SC_F_REQUEST_HEADERS
  );

#undef fsl__sc_popen_decl


struct fsl_sc_tracer_state {
  fsl_sc * ch;
  fsl_outputer * out;
  fsl_flag32_t flags;
};
typedef struct fsl_sc_tracer_state fsl_sc_tracer_state;

#define tracer__decl \
  assert( &fsl_sc_tracer_empty == ch->impl.type ); \
  fsl_sc_tracer_state * const tst = ch->impl.p;    \
  fsl_sc * const orig = tst->ch;                   \
  assert(orig); assert(orig != ch)

#define origDebug(MASK) if( tst->flags & (MASK) )
#define rcOrEmpty rc ? fsl_rc_cstr(rc) : ""

static void tracer__trace(fsl_sc * const ch,
                          fsl_sc * const orig,
                          fsl_sc_tracer_state * const tst,
                          char const * zFmt, ...){
  assert( orig->xfer->config->listener.callback );
  va_list args;
  fsl_b * const b = fsl_b_reuse(&ch->scratch);
  va_start(args,zFmt);
  assert(tst->out);
  fsl_b_appendf(b, "fsl_sc<%s>::", orig->name);
  if( 0==fsl_b_appendfv(b, zFmt, args) ){
    if( b->mem[b->used-1] != '\n' ){
      fsl_b_appendch(b, '\n');
    }
    tst->out->out(tst->out->state, b->mem, b->used);
  }
  va_end(args);
}

static int tracer__init(fsl_sc * const ch, enum fsl_sc_init_e mode){
  tracer__decl;
  int const rc = orig->init(orig, mode);
  origDebug(FSL_SC_TRACER_init) {
    fsl_b_reserve(&ch->scratch, 128);
    tracer__trace(ch, orig, tst, "init(mode=0x%0x) %s",
                  mode, rcOrEmpty);
  }
  return rc;
}

static int tracer__read(fsl_sc * const ch, fsl_b * tgt,
                        fsl_int_t howMuch){
  tracer__decl;
  int const rc = orig->read(orig, tgt, howMuch);
  origDebug(FSL_SC_TRACER_read) {
    tracer__trace(ch, orig, tst, "read(%" FSL_INT_T_PFMT ") %s",
                  howMuch, rcOrEmpty);
  }
  return rc;
}

static int tracer__append(fsl_sc * const ch, void const * src,
                          fsl_size_t n){
  tracer__decl;
  int const rc = orig->append(orig, src, n);
  origDebug(FSL_SC_TRACER_append) {
    tracer__trace(ch, orig, tst, "append(%" FSL_SIZE_T_PFMT ") %s",
                  n, rcOrEmpty);
  }
  return rc;
}

static void tracer__cleanup(fsl_sc * const ch){
  tracer__decl;
  origDebug(FSL_SC_TRACER_cleanup) {
    tracer__trace(ch, orig, tst, "cleanup()");
  }
  fsl_sc_cleanup(orig);
  fsl_free( ch->impl.p );
  *ch = fsl_sc_tracer_empty;
}

static int tracer__submit(fsl_sc * const ch,
                          fsl_b const * bLoginCard){
  tracer__decl;
  int const rc = orig->submit(orig, bLoginCard);
  origDebug(FSL_SC_TRACER_submit) {
    tracer__trace(ch, orig, tst, "submit(%s) %s",
                  bLoginCard
                  ? fsl_b_cstr(bLoginCard)
                  : "",
                  rcOrEmpty);
  }
  return rc;
}

static fsl_sc * tracer__self(fsl_sc *ch){
  tracer__decl;
  fsl_sc * const rv = orig->self(orig);
  origDebug(FSL_SC_TRACER_self) {
    tracer__trace(ch, orig, tst, "self(%s) = %s",
                  ch->name, rv->name);
  }
  return rv;
}

#undef origDebug
#undef rcOrEmpty
#undef tracer__decl

const fsl_sc fsl_sc_tracer_empty = {
  .name = "tracer",
  .xfer = 0,
  .impl = {.p = NULL, .type = NULL},
  .init  = tracer__init,
  .append = tracer__append,
  .submit  = tracer__submit,
  .read = tracer__read,
  .cleanup = tracer__cleanup,
  .self = tracer__self
};

fsl_sc * fsl_sc_tracer_init(fsl_sc *chTrace, fsl_sc *ch,
                            fsl_flag32_t traceFlags,
                            fsl_outputer * out){
  fsl_sc_tracer_state * tst = fsl_malloc(sizeof(*tst));
  if( !tst ) return 0;
  tst->ch = ch;
  tst->flags = traceFlags;
  tst->out = out;
  *chTrace = fsl_sc_tracer_empty;
  chTrace->impl.p = tst;
  chTrace->impl.type = &fsl_sc_tracer_empty;
  chTrace->xfer = ch->xfer;
  assert( tracer__self==chTrace->self );
  fsl_b_reserve(&ch->scratch, 192);
  return chTrace;
}

#if 0
fsl_sc * fsl_sc_for_url( char const * zUrl ){
  fsl_sc * rv = NULL;
  fsl_url u = fsl_url_empty;
  if( 0!=fsl_url_parse(&u, zUrl) ) return NULL;
  else if( 0==fsl_strcmp("http",u.scheme)
      || 0==fsl_strcmp("https",u.scheme) ){
    rv = fsl_malloc(
      sizeof(*rv) + sizeof(fsl_sc_popen_state)
    );
    fsl_sc_popen_state * const st = rv
      ? (fsl_sc_popen_state *)(rv + 1)
      : 0;
    if( !st ) goto end;
    *rv = fsl_sc_popen;
    *st = fsl_sc_popen_state_curl;
    assert( &fsl_sc_popen_state_empty == rv->impl.type );
    rv->impl.p = st;
  }
end:
  fsl_url_cleanup(&u);
  return rv;
}
#endif

#undef MARKER
#undef fsl__sc_popen_init

/* ===================================================================
   Native socket/TLS sync channel: fsl_sc_socket.

   Merged from the standalone src/sc-socket.c. A drop-in peer of
   fsl_sc_popen_curl for http:// and https:// which speaks HTTP over a
   TCP socket directly, removing the external curl dependency. The
   https:// path uses OpenSSL and is compiled in only with
   -DFSL_NATIVE_TLS_OPENSSL (linked with -lssl -lcrypto); without it,
   http:// works and https:// reports a clear error.

   This channel uses the library-generated HTTP request headers
   (FSL_SC_F_REQUEST_HEADERS), as the "fossil test-http" channel does:
   the library writes the full request line, headers, login cookie, and
   the terminating blank line into ch->requestHeaders. submit() emits
   those followed by the request body, and leaves the entire HTTP
   response (status line, headers, body) for the library to parse via
   read().
   =================================================================== */
#if defined(_WIN32)
#  include <winsock2.h>
#  include <ws2tcpip.h>
#  include <limits.h>
#  if defined(_MSC_VER)
#    pragma comment(lib, "ws2_32")
#  endif
   /* <ws2def.h> defines BIGENDIAN, which sha1.c reads as the host
      byte order. Windows is always little-endian. */
#  undef BIGENDIAN
#  undef LITTLEENDIAN
#else
#  include <poll.h>
#  include <arpa/inet.h>
#  include <netdb.h>
#  include <netinet/in.h>
#  include <netinet/tcp.h>
#  include <limits.h>
#  include <pthread.h>
#  include <signal.h>
#  include <sys/socket.h>
#  include <sys/time.h>
#  include <sys/types.h>
#endif
#if defined(FSL_NATIVE_TLS_OPENSSL)
#  include <openssl/ssl.h>
#  include <openssl/err.h>
#  include <openssl/evp.h>
#  include <openssl/x509.h>
#  include <openssl/x509v3.h>
#endif

/*
** The few places where Winsock differs from POSIX sockets. A socket
** is kept in an int: Windows guarantees a SOCKET's value fits in 32
** bits, and OpenSSL's SSL_set_fd() takes an int there too. Winsock
** reports errors through WSAGetLastError() rather than errno, so
** fsl__sock_errno() copies a failed call's error into errno, as the
** nearest errno value, and the code below handles both alike.
*/
#if defined(_WIN32)
#  define fsl__sock_close(S) closesocket((SOCKET)(S))
#  define poll WSAPoll
#  undef gai_strerror
#  define gai_strerror gai_strerrorA
static void fsl__sock_errno(void){
  switch( WSAGetLastError() ){
    case WSAEINTR: errno = EINTR; break;
    case WSAEWOULDBLOCK:
    case WSAETIMEDOUT: errno = EAGAIN; break;
    case WSAECONNREFUSED: errno = ECONNREFUSED; break;
    case WSAECONNRESET: errno = ECONNRESET; break;
    case WSAECONNABORTED: errno = ECONNABORTED; break;
    case WSAENETUNREACH: errno = ENETUNREACH; break;
    case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
    default: errno = EIO; break;
  }
}
/* send() and recv() take an int length on Windows. */
#  define FSL__SOCK_LEN(N) ((int)((N)>INT_MAX ? INT_MAX : (N)))
#else
#  define fsl__sock_close(S) close(S)
#  define fsl__sock_errno() ((void)0)
#  define FSL__SOCK_LEN(N) ((size_t)(N))
#endif

/* Per-channel private state, hung off fsl_sc::impl.p. */
typedef struct fsl_sc_socket_state {
  fsl_sc_stream_ops ops;   /* the I/O: ours, or the caller's */
  bool connected;          /* ops.connect() succeeded, ops.close() not yet */
  fsl_b out;          /* outbound request body, built via append() */
  fsl_b in;           /* inbound response: full HTTP reply */
  fsl_size_t inCursor;     /* read offset into `in` */
  bool responseLoaded;     /* submit() has populated `in` */
  bool eof;                /* the peer ended `in` by closing it cleanly */
  /* The rest is for the sockets and TLS of the callbacks in this
     file, which this channel passes itself to as ops.state. */
  fsl_sc * ch;             /* the channel, for its flags and URL */
  bool native;             /* ops are ours: the URL must be http(s) */
  int fd;                  /* connected socket, or -1 */
  bool tls;                /* https? */
  bool uncleanEof;         /* a TLS read ended with no close_notify */
#if defined(FSL_NATIVE_TLS_OPENSSL)
  SSL_CTX * sslCtx;
  SSL * ssl;
#endif
} fsl_sc_socket_state;

/* impl.type marker for semi-typesafety, per the fsl_sc convention. */
static const int fsl_sc_socket_type_marker = 0;
/* impl.type of a channel from fsl_sc_stream_init(), whose impl.p is the
   caller's fsl_sc_stream_ops until init(INITIAL) allocates the state. Its
   value differs from the socket marker's so that they cannot share an
   address. */
static const int fsl_sc_stream_type_marker = 1;
#define SOCK_STATE(ch) \
  fsl_sc_socket_state * const st = (fsl_sc_socket_state*)(ch)->impl.p; \
  assert((ch)->impl.type == &fsl_sc_socket_type_marker)

/*
** Describes errno value e. The socket's SO_RCVTIMEO and SO_SNDTIMEO
** make a read or write which makes no progress fail with EAGAIN.
*/
static char const * fsl_sc_errno_str(int e){
  return (EAGAIN==e || EWOULDBLOCK==e) ? "timed out" : strerror(e);
}

/*
** True if host holds a byte outside ASCII. The channel does not
** convert an internationalised domain name to its ASCII form (IDNA),
** and neither does fossil(1).
*/
static bool fsl_sc_host_is_non_ascii(char const *host){
  for( ; *host; ++host ){
    if( (unsigned char)*host >= 0x80 ) return true;
  }
  return false;
}

/* ---- TLS layer (OpenSSL), compiled only when requested ---- */
#if defined(FSL_NATIVE_TLS_OPENSSL)
/*
** Writes the lower-case hex SHA-256 of cert to zOut
*/
static void fsl__sc_tls_fingerprint(X509 *cert, char *zOut){
  unsigned char md[EVP_MAX_MD_SIZE];
  unsigned int n = 0, i;
  if( !X509_digest(cert, EVP_sha256(), md, &n) ) n = 0;
  for( i=0; i<n; ++i ){
    zOut[i*2] = "0123456789abcdef"[md[i]>>4];
    zOut[i*2+1] = "0123456789abcdef"[md[i]&0xf];
  }
  zOut[n*2] = 0;
}

/*
** Returns setting zKey from the repository or, failing that, from the
** global config db, as fossil(1)'s db_get() does, or NULL. The global
** config db is opened if needed. A setting which cannot be read is
** treated as unset, so the caller falls back to its default.
*/
static char * fsl__sc_tls_setting(fsl_cx * const f, char const * zKey){
  char * z = fsl_cx_db_repo(f)
    ? fsl_config_get_text(f, FSL_CONFDB_REPO, zKey, NULL) : NULL;
  if( !z ){
    if( fsl_config_open(f, NULL) ) fsl_cx_err_reset(f);
    else z = fsl_config_get_text(f, FSL_CONFDB_GLOBAL, zKey, NULL);
  }
  return z;
}

/*
** Loads the trust store into ctx. When $SSL_CERT_FILE or $SSL_CERT_DIR
** is set, OpenSSL's default paths use it, as fossil(1) gives the
** environment first priority. Otherwise the ssl-ca-location setting
** is used when it refers to an existing file or directory, and
** OpenSSL's defaults when it does not.
*/
static int fsl__sc_tls_trust(fsl_cx * const f, SSL_CTX * ctx){
  char * zCa = NULL;
  int d = 0, ok;
  if( f && !getenv(X509_get_default_cert_file_env())
      && !getenv(X509_get_default_cert_dir_env()) ){
    zCa = fsl__sc_tls_setting(f, "ssl-ca-location");
    if( zCa ) d = fsl_dir_check(zCa);
  }
  if( d>0 ) ok = SSL_CTX_load_verify_locations(ctx, NULL, zCa);
  else if( d<0 ) ok = SSL_CTX_load_verify_locations(ctx, zCa, NULL);
  else ok = SSL_CTX_set_default_verify_paths(ctx);
  fsl_free(zCa);
  return ok;
}

/*
** Returns true if the cert:HOST setting holds zFp, the fingerprint of
** a certificate which failed verification. fossil(1) stores that
** setting when its user accepts such a certificate and asks for the
** exception to be remembered.
*/
static bool fsl__sc_tls_exception(fsl_cx * const f, char const *host,
                                  char const *zFp){
  char * zKey;
  char * zVal = NULL;
  bool rv;
  if( !f || !*zFp ) return false;
  zKey = fsl_mprintf("cert:%s", host);
  if( !zKey ) return false;
  for( char * z = zKey + 5; *z; ++z ){
    if( *z>='A' && *z<='Z' ) *z += 'a' - 'A';
  }
  zVal = fsl__sc_tls_setting(f, zKey);
  rv = zVal && 0==fsl_strcmp(zVal, zFp);
  fsl_free(zVal);
  fsl_free(zKey);
  return rv;
}

/*
** Sets the name the server's certificate must match: an IP address
** is matched against the certificate's IP addresses, any other host
** against its DNS names.
*/
static int fsl__sc_tls_host(SSL *ssl, char const *host){
  if( X509_VERIFY_PARAM_set1_ip_asc(SSL_get0_param(ssl), host) ){
    return 0;
  }
  ERR_clear_error();
#if OPENSSL_VERSION_MAJOR >= 4
  /* OpenSSL 4 deprecates SSL_set1_host() in favour of this. */
  return SSL_set1_dnsname(ssl, host) ? 0 : FSL_RC_IO;
#else
  return SSL_set1_host(ssl, host) ? 0 : FSL_RC_IO;
#endif
}

/*
** True if host is an IP address. RFC 6066 permits only a DNS name in
** the TLS server name indication.
*/
static bool fsl__sc_tls_host_is_ip(char const *host){
  struct in_addr a4;
  struct in6_addr a6;
  return 1==inet_pton(AF_INET, host, &a4)
    || 1==inet_pton(AF_INET6, host, &a6);
}

/*
** Performs the TLS handshake on st->fd and verifies the server's
** certificate chain against the trust store, and its name against
** host. A certificate which fails verification is accepted when
** fossil(1) has a remembered exception for it. f, which may be NULL,
** supplies the settings. If verify is false, as for
** FSL_SC_F_TLS_ACCEPT_ANY_CERT, any certificate is accepted. An IPv6
** address in host has no brackets.
**
** On failure, writes a description of the failure to zErr. A failed
** verification returns FSL_RC_ACCESS and describes OpenSSL's reason
** and the certificate's SHA-256 fingerprint. Any other failure
** returns FSL_RC_IO and takes its description from OpenSSL's error
** queue or from errno.
*/
static int fsl_sc_tls_handshake(fsl_cx * const f, fsl_sc_socket_state *st,
                                char const *host, bool verify,
                                char *zErr, size_t nErr){
  SSL_CTX * ctx;
  SSL * ssl = NULL;
  X509 * cert;
  long vrc;
  int sslRc;
  int rc = FSL_RC_IO;
  char zFp[EVP_MAX_MD_SIZE*2+1];
  char zDotless[256];
  char const * zTlsName = host;  /* host as the TLS layer needs it */
  {
    /* A fully qualified name may end with a dot, as in
       "example.com.". Strip it before being put into TLS server names
       (RFC 6066) or certificate names. */
    fsl_size_t const n = fsl_strlen(host);
    if( n>1 && '.'==host[n-1] && n<sizeof(zDotless) ){
      memcpy(zDotless, host, n-1);
      zDotless[n-1] = 0;
      zTlsName = zDotless;
    }
  }
  SSL_library_init();
  ERR_clear_error();
  zErr[0] = 0;
  ctx = SSL_CTX_new(TLS_client_method());
  if( !ctx ) goto err;
  if( verify && !fsl__sc_tls_trust(f, ctx) ) goto err;
  ssl = SSL_new(ctx);
  if( !ssl ) goto err;
  SSL_set_fd(ssl, st->fd);
#ifdef SSL_set_tlsext_host_name
  /* The server name must be an ASCII DNS name (RFC 6066). */
  if( !fsl__sc_tls_host_is_ip(zTlsName)
      && !fsl_sc_host_is_non_ascii(zTlsName) ){
    SSL_set_tlsext_host_name(ssl, zTlsName);
  }
#endif
  if( verify && fsl__sc_tls_host(ssl, zTlsName) ) goto err;
  errno = 0;
  if( (sslRc = SSL_connect(ssl))!=1 ){
    int const e = SSL_get_error(ssl, sslRc);
    if( SSL_ERROR_SYSCALL==e && !ERR_peek_error() ){
      fsl_snprintf(zErr, (fsl_size_t)nErr, "%s",
                   errno ? fsl_sc_errno_str(errno)
                   : "connection closed by peer");
    }
    goto err;
  }
  rc = FSL_RC_ACCESS;
  cert = SSL_get_peer_certificate(ssl);
  if( !cert ){
    fsl_snprintf(zErr, (fsl_size_t)nErr, "no certificate presented");
    goto err;
  }
  vrc = verify ? SSL_get_verify_result(ssl) : X509_V_OK;
  if( X509_V_OK!=vrc ){
    fsl__sc_tls_fingerprint(cert, zFp);
    if( !fsl__sc_tls_exception(f, host, zFp) ){
      fsl_snprintf(zErr, (fsl_size_t)nErr, "%s (sha256 %s)",
                   X509_verify_cert_error_string(vrc), zFp);
    }
  }
  X509_free(cert);
  if( zErr[0] ) goto err;
  st->sslCtx = ctx; st->ssl = ssl;
  return 0;
err:
  if( !zErr[0] ){
    unsigned long const e = ERR_peek_last_error();
    if( e ) ERR_error_string_n(e, zErr, nErr);
    else fsl_snprintf(zErr, (fsl_size_t)nErr, "no detail from OpenSSL");
  }
  ERR_clear_error();
  if( ssl ) SSL_free(ssl);
  if( ctx ) SSL_CTX_free(ctx);
  return rc;
}
/*
** Interprets rc, the non-positive result of SSL_read() or
** SSL_write(). Returns 0 at the end of the stream, including a peer
** which closes the connection without TLS's close_notify alert, which
** many servers do: the HTTP layer checks the body against its
** Content-Length. Otherwise returns -1, and either leaves errno set
** by the failed system call, or describes OpenSSL's reason in zErr.
** A read or write which timed out leaves errno set to EAGAIN.
*/
static fsl_int_t fsl_sc_tls_result(fsl_sc_socket_state *st, int rc,
                                   char *zErr, size_t nErr){
  int const sysErr = errno;
  int const e = SSL_get_error(st->ssl, rc);
  unsigned long const ee = ERR_peek_error();
  if( SSL_ERROR_ZERO_RETURN==e ) return 0;
  if( SSL_ERROR_WANT_READ==e || SSL_ERROR_WANT_WRITE==e ){
    /* The blocking socket's SO_RCVTIMEO or SO_SNDTIMEO expired. */
    errno = sysErr ? sysErr : EAGAIN;
    return -1;
  }
  if( SSL_ERROR_SYSCALL==e && !ee ){
    errno = sysErr;
    if( !sysErr ) st->uncleanEof = true;
    return sysErr ? -1 : 0;
  }
#ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
  if( SSL_ERROR_SSL==e
      && SSL_R_UNEXPECTED_EOF_WHILE_READING==ERR_GET_REASON(ee) ){
    ERR_clear_error();
    st->uncleanEof = true;
    return 0;
  }
#endif
  if( ee ) ERR_error_string_n(ERR_peek_last_error(), zErr, nErr);
  else fsl_snprintf(zErr, (fsl_size_t)nErr, "SSL error %d", e);
  ERR_clear_error();
  errno = 0;
  return -1;
}
static fsl_int_t fsl_sc_tls_write(fsl_sc_socket_state *st,
                                  void const *p, fsl_size_t n,
                                  char *zErr, size_t nErr){
  int rc;
  zErr[0] = 0;
  ERR_clear_error();
  errno = 0;
  rc = SSL_write(st->ssl, p, n>(fsl_size_t)INT_MAX ? INT_MAX : (int)n);
  return rc>0 ? (fsl_int_t)rc : fsl_sc_tls_result(st, rc, zErr, nErr);
}
static fsl_int_t fsl_sc_tls_read(fsl_sc_socket_state *st,
                                 void *p, fsl_size_t n,
                                 char *zErr, size_t nErr){
  int rc;
  zErr[0] = 0;
  ERR_clear_error();
  errno = 0;
  rc = SSL_read(st->ssl, p, n>(fsl_size_t)INT_MAX ? INT_MAX : (int)n);
  return rc>0 ? (fsl_int_t)rc : fsl_sc_tls_result(st, rc, zErr, nErr);
}
static void fsl_sc_tls_close(fsl_sc_socket_state *st){
  if( st->ssl ){ SSL_shutdown(st->ssl); SSL_free(st->ssl); st->ssl=0; }
  if( st->sslCtx ){ SSL_CTX_free(st->sslCtx); st->sslCtx=0; }
}
#endif /* FSL_NATIVE_TLS_OPENSSL */

#if defined(_WIN32)
/* Windows has no SIGPIPE: a write to a closed socket fails. */
typedef struct { int unused; } fsl_sc_sigpipe_state;
static void fsl_sc_sigpipe_block(fsl_sc_sigpipe_state *s){ (void)s; }
static void fsl_sc_sigpipe_restore(fsl_sc_sigpipe_state const *s){
  (void)s;
}
#else
/*
** Writing to a socket whose peer has closed it raises SIGPIPE, which
** kills the process by default. OpenSSL writes with write(2), so
** MSG_NOSIGNAL cannot help it. The library leaves the process's signal
** dispositions alone: it blocks SIGPIPE in the calling thread while it
** uses the socket, so that a write fails with EPIPE, and on restoring
** the mask discards a SIGPIPE which became pending in the meantime.
*/
typedef struct {
  sigset_t old;     /* signal mask to restore */
  bool wasPending;  /* SIGPIPE was already pending before blocking */
} fsl_sc_sigpipe_state;

static void fsl_sc_sigpipe_block(fsl_sc_sigpipe_state *s){
  sigset_t set, pending;
  sigemptyset(&set);
  sigaddset(&set, SIGPIPE);
  pthread_sigmask(SIG_BLOCK, &set, &s->old);
  sigpending(&pending);
  s->wasPending = 1==sigismember(&pending, SIGPIPE);
}

static void fsl_sc_sigpipe_restore(fsl_sc_sigpipe_state const *s){
  sigset_t pending;
  int const savedErrno = errno;
  sigpending(&pending);
  if( !s->wasPending && 1==sigismember(&pending, SIGPIPE) ){
    sigset_t set;
    int sig = 0;
    sigemptyset(&set);
    sigaddset(&set, SIGPIPE);
    sigwait(&set, &sig);
  }
  pthread_sigmask(SIG_SETMASK, &s->old, NULL);
  errno = savedErrno;
}
#endif /* SIGPIPE handling */

/*
** Open a TCP connection to host:port, set TCP_NODELAY, and (for https)
** perform the TLS handshake.
*/
static int fsl_sc_sock_connect(void * const state, fsl_url const * const url,
                               fsl_xfer * const xf){
  fsl_sc_socket_state * const st = (fsl_sc_socket_state*)state;
  char zPort[16];
  char zHost[64];
  char const * zAddr = url->host;
  struct addrinfo hints, *ai = 0, *p = 0;
  int gai;
  int lastErrno = 0;

  if( st->fd >= 0 ) return 0; /* already connected */
  fsl_snprintf(zPort, sizeof(zPort), "%d",
               (int)(url->port ? url->port : (st->tls ? 443 : 80)));
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;
  if( '['==url->host[0] ){
    /* fsl_url_parse() keeps an IP literal's brackets, which
       getaddrinfo() and the TLS layer do not accept. */
    fsl_size_t const n = fsl_strlen(url->host);
    if( n<3 || n-2>=sizeof(zHost) ){
      return fsl_xfer_errorf(xf, FSL_RC_RANGE,
                             "Invalid IP literal host: %s", url->host);
    }
    memcpy(zHost, url->host+1, n-2);
    zHost[n-2] = 0;
    zAddr = zHost;
  }
  gai = getaddrinfo(zAddr, zPort, &hints, &ai);
  if( gai!=0 ){
    return fsl_xfer_errorf(xf, FSL_RC_IO,
                           "getaddrinfo(%s:%s) failed: %s%s",
                           url->host, zPort, gai_strerror(gai),
                           fsl_sc_host_is_non_ascii(url->host)
                           ? " (give an internationalised domain name"
                             " in its ASCII xn-- form)"
                           : "");
  }
  for( p=ai; p; p=p->ai_next ){
    int fd = (int)socket(p->ai_family, p->ai_socktype, p->ai_protocol);
    if( fd<0 ){ fsl__sock_errno(); lastErrno = errno; continue; }
    if( connect(fd, p->ai_addr, (int)p->ai_addrlen)<0 ){
      fsl__sock_errno();
      lastErrno = errno;
      fsl__sock_close(fd);
      continue;
    }
    { int on = 1; setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
                             (void*)&on, sizeof(on)); }
    {
      /* Bounds every read and write, including the TLS handshake
         and the TLS reads, which do not poll(). */
#if defined(_WIN32)
      DWORD const ms = (DWORD)fsl_xfer_socket_timeout(xf) * 1000;
      setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char const*)&ms, sizeof(ms));
      setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char const*)&ms, sizeof(ms));
#else
      struct timeval tv;
      tv.tv_sec = fsl_xfer_socket_timeout(xf);
      tv.tv_usec = 0;
      setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, sizeof(tv));
      setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (void*)&tv, sizeof(tv));
#endif
    }
    st->fd = fd;
    break;
  }
  freeaddrinfo(ai);
  if( st->fd<0 ){
    return fsl_xfer_errorf(xf, FSL_RC_IO,
                           "Could not connect to %s:%s: %s", url->host,
                           zPort, lastErrno
                           ? strerror(lastErrno) : "no usable address");
  }
  if( st->tls ){
#if defined(FSL_NATIVE_TLS_OPENSSL)
    char zErr[256];
    int const rc = fsl_sc_tls_handshake(
      xf ? fsl_xfer_cx(xf) : NULL, st, zAddr,
      0==(st->ch->flags & FSL_SC_F_TLS_ACCEPT_ANY_CERT),
      zErr, sizeof(zErr));
    if( rc ){
      /* Else a later submit() would find the socket connected and
         write to it with no TLS session. */
      fsl__sock_close(st->fd);
      st->fd = -1;
    }
    if( FSL_RC_ACCESS==rc ){
      return fsl_xfer_errorf(xf, rc,
                             "Unable to verify SSL cert from %s: %s",
                             url->host, zErr);
    }else if( rc ){
      return fsl_xfer_errorf(xf, rc,
                             "TLS handshake with %s:%s failed: %s",
                             url->host, zPort, zErr);
    }
#else
    fsl__sock_close(st->fd);
    st->fd = -1;
    return fsl_xfer_error(xf, FSL_RC_MISUSE,
                          "https requires building with FSL_NATIVE_TLS_OPENSSL.");
#endif
  }
  return 0;
}

/* ops.write() of the sockets: one write, EINTR retried. */
static fsl_int_t fsl_sc_sock_write(void * const state, void const * const p,
                                   fsl_size_t const n, fsl_xfer * const xf){
  fsl_sc_socket_state * const st = (fsl_sc_socket_state*)state;
  char zErr[256];
  fsl_int_t got;
  for(;;){
    zErr[0] = 0;
    if( st->tls ){
#if defined(FSL_NATIVE_TLS_OPENSSL)
      got = fsl_sc_tls_write(st, p, n, zErr, sizeof(zErr));
#else
      got = -1;
      errno = 0;
      fsl_snprintf(zErr, sizeof(zErr), "TLS write failed");
#endif
    }else{
      got = (fsl_int_t)send(st->fd, p, FSL__SOCK_LEN(n), 0);
      if( got<0 ) fsl__sock_errno();
    }
    if( got<0 && errno==EINTR ) continue;
    break;
  }
  if( got<=0 ){
    fsl_xfer_errorf(xf, FSL_RC_IO, "Short write to socket for %s: %s",
                    st->ch->self(st->ch)->url.host,
                    0==got ? "connection closed"
                    : (zErr[0] ? zErr : fsl_sc_errno_str(errno)));
    return -1;
  }
  return got;
}

/*
** ops.read() of the sockets. A bounded poll() keeps a silent peer
** from wedging the sync.
*/
static fsl_int_t fsl_sc_sock_read(void * const state, void * const dest,
                                  fsl_size_t const n, fsl_xfer * const xf){
  fsl_sc_socket_state * const st = (fsl_sc_socket_state*)state;
  char zErr[256];
  fsl_int_t got = -1;
  char const * const zHost = st->ch->self(st->ch)->url.host;
  st->uncleanEof = false;
  for(;;){
    zErr[0] = 0;
    if( st->tls ){
#if defined(FSL_NATIVE_TLS_OPENSSL)
      got = fsl_sc_tls_read(st, dest, n, zErr, sizeof(zErr));
#else
      got = -1;
      errno = 0;
      fsl_snprintf(zErr, sizeof(zErr), "TLS read failed");
#endif
      if( got<0 && errno==EINTR ) continue;
      if( got<0 && (EAGAIN==errno || EWOULDBLOCK==errno) ){
        return FSL_SC_STREAM_TIMEOUT;
      }
    }else{
      struct pollfd pfd;
      int nPoll;
      pfd.fd = st->fd; pfd.events = POLLIN;
      nPoll = poll(&pfd, 1, fsl_xfer_socket_timeout(xf)*1000);
      if( nPoll<0 ) fsl__sock_errno();
      if( nPoll<0 && errno==EINTR ) continue;
      if( nPoll<0 ){
        fsl_xfer_errorf(xf, FSL_RC_IO,
                        "poll() on socket for %s failed: %s",
                        zHost, strerror(errno));
        return -1;
      }
      if( 0==nPoll ) return FSL_SC_STREAM_TIMEOUT;
      got = (fsl_int_t)recv(st->fd, dest, FSL__SOCK_LEN(n), 0);
      if( got<0 ) fsl__sock_errno();
      if( got<0 && errno==EINTR ) continue;
    }
    break;
  }
  if( got<0 ){
    fsl_xfer_errorf(xf, FSL_RC_IO, "Read error from socket for %s: %s",
                    zHost, zErr[0] ? zErr : strerror(errno));
    return -1;
  }
  return 0==got && st->uncleanEof ? FSL_SC_STREAM_UNCLEAN : got;
}

/* ops.close() of the sockets. */
static void fsl_sc_sock_close(void * const state){
  fsl_sc_socket_state * const st = (fsl_sc_socket_state*)state;
#if defined(FSL_NATIVE_TLS_OPENSSL)
  if( st->tls ) fsl_sc_tls_close(st);
#endif
  if( st->fd>=0 ){ fsl__sock_close(st->fd); st->fd = -1; }
}

/*
** The three calls below are the channel's use of its ops. A callback
** which failed has set the error state, or has not, and either way
** the transfer must fail with a message: fsl_sc_stream_failed()
** returns the code of the error in the state and, if there is none,
** sets one which names the callback.
*/
static int fsl_sc_stream_failed(fsl_sc * const ch, char const * zCallback){
  fsl_error const * const err = fsl_cx_err_e(fsl_xfer_cx(ch->xfer));
  if( err->code ) return err->code;
  return fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                         "%s() failed for %s and set no error message",
                         zCallback, ch->self(ch)->url.host);
}

/* Closes the connection if there is one. */
static void fsl_sc_stream_close(fsl_sc_socket_state * const st){
  if( st->connected ){
    st->connected = false;
    if( st->ops.close ) st->ops.close(st->ops.state);
  }
}

/* Writes all n bytes via ops.write(). */
static int fsl_sc_socket_write_all(fsl_sc *ch, void const *p, fsl_size_t n){
  SOCK_STATE(ch);
  char const *z = (char const *)p;
  while( n>0 ){
    fsl_int_t const got = st->ops.write(st->ops.state, z, n, ch->xfer);
    if( got<1 ) return fsl_sc_stream_failed(ch, "write");
    if( (fsl_size_t)got>n ){
      return fsl_xfer_errorf(ch->xfer, FSL_RC_MISUSE,
                             "write() reported %" FSL_SIZE_T_PFMT
                             " bytes written of %" FSL_SIZE_T_PFMT,
                             (fsl_size_t)got, n);
    }
    z += got; n -= (fsl_size_t)got;
  }
  return 0;
}

/*
** Read the whole HTTP response into st->in (cursor at 0), leaving the
** status line, headers, and body intact for the library to parse. A
** bounded poll() keeps a silent peer from wedging the sync. Reads until
** the peer closes the connection (HTTP/1.0 close-delimited).
*/
/*
** If the slurped response declares Transfer-Encoding: chunked, rewrite
** st->in so its body is de-chunked, leaving the status line and headers
** intact for the library's HTTP parser (which reads the body until EOF
** on the uncompressed clone path). A no-op otherwise, so close-delimited
** and Content-Length responses are untouched. HTTP/1.1 servers may send
** chunked even when "Connection: close" was requested, so this must be
** handled for the 1.1 upgrade to be correct.
*/
static int fsl_sc_socket_dechunk_if_needed(fsl_sc *ch){
  SOCK_STATE(ch);
  unsigned char * const m = (unsigned char*)st->in.mem;
  fsl_size_t const n = st->in.used;

  if( !m || n<4 ) return 0;

  fsl_size_t i, hdrEnd = 0, p, hdrStart = 0;
  bool chunked = false;
  bool haveContentLength = false;
  bool haveTransferEncoding = false;
  bool lengthOk = false;     /* each Content-Length parsed, all equal */
  fsl_size_t contentLength = 0;
  /* ch->xfer is NULL for raw/test-tool use of this channel (e.g.
  ** f-sync test-httpmsg before it wires one in) -- see the ch->xfer
  ** guards throughout this function's error paths below, which exist
  ** for exactly that case. Without a live fsl_xfer there is no
  ** fsl_cx to borrow pooled buffers from, so fall back to plain,
  ** unpooled ones instead of asserting this can't happen. */
  fsl_cx * const f = ch->xfer ? fsl_xfer_cx(ch->xfer) : NULL;
  int rc = 0;
  fsl_b outLocal = fsl_b_empty;
  fsl_b bodyLocal = fsl_b_empty;
  fsl_b *out = NULL;
  fsl_b *body = NULL;
  for(;;){
    /* Find the header block of the final reply, skipping empty lines
       and interim (1xx) replies before it, as the HTTP parser in
       xfer.c does. */
    while( hdrStart+1<n && m[hdrStart]=='\r' && m[hdrStart+1]=='\n' ){
      hdrStart += 2;
    }
    hdrEnd = 0;
    for( i=hdrStart; i+3 < n; ++i ){
      if( m[i]=='\r'&&m[i+1]=='\n'&&m[i+2]=='\r'&&m[i+3]=='\n' ){
        hdrEnd = i+4; break;
      }
    }
    if( 0==hdrEnd ) goto end; /* no header terminator; leave as-is */
    if( hdrEnd-hdrStart>9 && 0==memcmp(m+hdrStart, "HTTP/1.", 7)
        && ' '==m[hdrStart+8] && '1'==m[hdrStart+9] ){
      hdrStart = hdrEnd;
      continue;
    }
    break;
  }
  for( i=hdrStart; i < hdrEnd; ){
    fsl_size_t j = i, k;
    while( j<hdrEnd && m[j]!='\n' ) ++j;
    if( j<hdrEnd ) ++j;
    if( 0==fsl_strnicmp((char const*)m+i, "content-length:", 15) ){
      fsl_size_t v = 0;
      bool any = false;
      for( k=i+15; k<j && (m[k]==' ' || m[k]=='\t'); ++k ){}
      for( ; k<j && m[k]>='0' && m[k]<='9'; ++k ){
        unsigned const d = (unsigned)(m[k] - '0');
        if( v > (((fsl_size_t)-1) - d) / 10u ){ any = false; break; }
        v = v*10u + d;
        any = true;
      }
      /* xfer.c accepts a repeated value, and reports a malformed value
         or two different ones. */
      lengthOk = any && (!haveContentLength
                         || (lengthOk && v==contentLength));
      haveContentLength = true;
      contentLength = v;
    }else if( 0==fsl_strnicmp((char const*)m+i, "transfer-encoding:", 18) ){
      bool bOk = false;
      if( haveTransferEncoding ){
        rc = ch->xfer
          ? fsl_xfer_error(ch->xfer, FSL_RC_IO,
                           "Reply has repeated Transfer-Encoding headers.")
          : FSL_RC_IO;
        goto end;
      }
      haveTransferEncoding = true;
      for( k=i+18; k<j && (m[k]==' ' || m[k]=='\t'); ++k ){}
      if( k+7<=j && 0==fsl_strnicmp((char const*)m+k, "chunked", 7) ){
        k += 7;
        while( k<j && (m[k]==' ' || m[k]=='\t' || m[k]=='\r') ) ++k;
        bOk = k==j-1;
      }
      if( !bOk ){
        rc = ch->xfer
          ? fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                            "Unsupported transfer-encoding: %.*s",
                            (int)(j-i), (char const*)m+i)
          : FSL_RC_IO;
        goto end;
      }
      chunked = true;
    }
    i = j;
  }
  if( !chunked ){
    /* The reply ends after Content-Length bytes of body (RFC 9112
       section 6.3). Anything the peer sends after them, such as a
       second reply, is dropped, as fossil(1) drops it. A shorter
       body is left for the HTTP parser to report. */
    if( lengthOk && n-hdrEnd > contentLength ){
      st->in.used = hdrEnd + contentLength;
    }else if( !haveContentLength && st->eof ){
      /* A reply with neither Content-Length nor chunks ends where the
         connection did. Say how long it is, which the HTTP parser
         wants. */
      fsl_b bHead = fsl_b_empty;
      fsl_b_append(&bHead, m, hdrEnd-2);
      fsl_b_appendf(&bHead, "Content-Length: %" FSL_SIZE_T_PFMT "\r\n\r\n",
                    n-hdrEnd);
      rc = fsl_b_append(&bHead, m+hdrEnd, n-hdrEnd);
      if( 0==rc ) fsl_b_swap(&st->in, &bHead);
      fsl_b_clear(&bHead);
    }
    goto end;
  }
  if( haveContentLength ){
    rc = ch->xfer
      ? fsl_xfer_error(ch->xfer, FSL_RC_IO,
                       "Reply has both Content-Length and "
                       "Transfer-Encoding.")
      : FSL_RC_IO;
    goto end;
  }

  out = f ? fsl_cx_b_borrow(f) : &outLocal;
  body = f ? fsl_cx_b_borrow(f) : &bodyLocal;
  if( !out || !body ){
    assert( f );
    rc = f->error.code;
    goto end;
  }

  /* De-chunk the body into a scratch buffer first, since we need its
  ** length before we can write the Content-Length header. */
  p = hdrEnd;
  while( 0==rc ){
    fsl_size_t len = 0;
    bool any = false;
    if( p>=n ){
      if( ch->xfer ){
        rc = fsl_xfer_error(ch->xfer, FSL_RC_IO,
                            "Chunked response ended without terminator.");
      }else{
        rc = FSL_RC_IO;
      }
      break;
    }
    while( p<n && (m[p]==' ' || m[p]=='\t') ) ++p;
    while( p<n && m[p]!='\r' && m[p]!='\n' && m[p]!=';' ){
      int const c = m[p];
      int d;
      if( c>='0'&&c<='9' ) d = c-'0';
      else if( c>='a'&&c<='f' ) d = c-'a'+10;
      else if( c>='A'&&c<='F' ) d = c-'A'+10;
      else break;
      if( len > (((fsl_size_t)-1) - (fsl_size_t)d) / 16u ){
        if( ch->xfer ){
          rc = fsl_xfer_error(ch->xfer, FSL_RC_IO,
                              "Invalid chunked response size.");
        }else{
          rc = FSL_RC_IO;
        }
        break;
      }
      len = len*16u + (fsl_size_t)d; any = true; ++p;
    }
    if( rc ) break;
    if( !any ){
      if( ch->xfer ){
        rc = fsl_xfer_error(ch->xfer, FSL_RC_IO,
                            "Malformed chunked response size.");
      }else{
        rc = FSL_RC_IO;
      }
      break;
    }
    {
      /* After the size comes either the line end or, after optional
         spaces or tabs, ';' and an extension, which is ignored (RFC
         9112 section 7.1.1). Anything else means the size line is
         malformed. */
      fsl_size_t q = p;
      bool bad = false;
      while( q<n && (m[q]==' ' || m[q]=='\t') ) ++q;
      if( q<n && ';'==m[q] ){
        static char const zToken[] = "!#$%&'*+-.^_`|~";
        ++q;
        while( q<n && (m[q]==' ' || m[q]=='\t') ) ++q;
        bad = q>=n
          || !(fsl_isalnum(m[q]) || strchr(zToken, (char)m[q]));
      }else if( q<n && (q>p || (m[q]!='\r' && m[q]!='\n')) ){
        bad = true;
      }
      /* A CR is allowed only before the LF which ends the line (RFC
         9112 section 2.2), and a NUL nowhere in it. */
      for( q=p; !bad && q<n && '\n'!=m[q]; ++q ){
        bad = !m[q] || ('\r'==m[q] && q+1<n && '\n'!=m[q+1]);
      }
      if( bad ){
        if( ch->xfer ){
          rc = fsl_xfer_error(ch->xfer, FSL_RC_IO,
                              "Malformed chunked response size line.");
        }else{
          rc = FSL_RC_IO;
        }
        break;
      }
    }
    while( p<n && m[p]!='\n' ) ++p;  /* skip chunk extensions / CR */
    if( p>=n ){
      if( ch->xfer ){
        rc = fsl_xfer_error(ch->xfer, FSL_RC_IO,
                            "Truncated chunked response body.");
      }else{
        rc = FSL_RC_IO;
      }
      break;
    }
    ++p;                             /* consume the \n */
    if( 0==len ){
      bool trailerDone = false;
      /* Discard trailer headers, if any, but require their final empty
         line (RFC 9112 section 7.1). */
      while( p<n ){
        fsl_size_t const t = p;
        while( p<n && m[p]!='\n' ) ++p;
        if( p>=n ) break;
        ++p;
        if( (p-t)==1 || ((p-t)==2 && m[t]=='\r') ){
          trailerDone = true;
          break;
        }
      }
      if( !trailerDone ){
        rc = ch->xfer
          ? fsl_xfer_error(ch->xfer, FSL_RC_IO,
                           "Truncated chunked response trailer.")
          : FSL_RC_IO;
      }
      break;
    }
    if( len > n-p ){
      if( ch->xfer ){
        rc = fsl_xfer_error(ch->xfer, FSL_RC_IO,
                            "Truncated chunked response body.");
      }else{
        rc = FSL_RC_IO;
      }
      break;
    }
    rc = fsl_b_append(body, m+p, len);
    p += len;
    /* The chunk data ends with CRLF (RFC 9112 section 7.1). Any other
       byte there means the chunk size was wrong. */
    if( p<n && m[p]=='\r' ) ++p;
    if( 0==rc && (p>=n || m[p]!='\n') ){
      if( ch->xfer ){
        rc = fsl_xfer_error(ch->xfer, FSL_RC_IO,
                            "Malformed chunked response: no line end "
                            "after chunk data.");
      }else{
        rc = FSL_RC_IO;
      }
      break;
    }
    ++p;
  }
  if( rc ) goto end;

  /* Rebuild the header block: copy any interim replies before it as
  ** they are, then every header line except the transfer-encoding
  ** one, then add a Content-Length the parser wants. */
  if( hdrStart ) rc = fsl_b_append(out, m, hdrStart);
  i = hdrStart;
  while( 0==rc && i < hdrEnd ){
    fsl_size_t j = i;
    while( j<hdrEnd && m[j]!='\n' ) ++j;
    if( j<hdrEnd ) ++j;             /* include the \n */
    if( j-i==2 && m[i]=='\r' ) break; /* blank line ends the headers */
    if( 0!=fsl_strnicmp((char const*)m+i, "transfer-encoding:", 18) ){
      rc = fsl_b_append(out, m+i, j-i);
    }
    i = j;
  }
  if( 0==rc ){
    fsl_b_appendf(out, "Content-Length: %" FSL_SIZE_T_PFMT "\r\n\r\n",
                       body->used);
    rc = fsl_b_append(out, body->mem, body->used);
    if( 0==rc ){
      fsl_b_swap(&st->in, out);
    }
  }
end:
  if( f ){
    fsl_cx_b_return(f, body);
    fsl_cx_b_return(f, out);
  }else{
    fsl_b_clear(&bodyLocal);
    fsl_b_clear(&outLocal);
  }
  return rc;
}

static int fsl_sc_socket_slurp_response(fsl_sc *ch){
  SOCK_STATE(ch);
  char buf[16384];
  fsl_size_t const maxReply = fsl__sc_reply_max(ch);
  int rc = 0;
  st->eof = false;
  for(;;){
    fsl_int_t const got = st->ops.read(st->ops.state, buf,
                                       (fsl_size_t)sizeof(buf), ch->xfer);
    if( FSL_SC_STREAM_TIMEOUT==got ){
      if( st->in.used ){
        /* A peer which keeps the connection open after its reply. The
           HTTP parser checks the reply against its Content-Length. */
        break;
      }
      rc = fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                           "No response from %s within %d seconds",
                           ch->self(ch)->url.host,
                           fsl_xfer_socket_timeout(ch->xfer));
      break;
    }
    if( got<0 && FSL_SC_STREAM_UNCLEAN!=got ){
      rc = fsl_sc_stream_failed(ch, "read");
      break;
    }
    if( got==0 || FSL_SC_STREAM_UNCLEAN==got ){
      st->eof = 0==got; /* peer closed: end of response */
      break;
    }
    if( (fsl_size_t)got>sizeof(buf) ){
      rc = fsl_xfer_errorf(ch->xfer, FSL_RC_MISUSE,
                           "read() reported %" FSL_SIZE_T_PFMT
                           " bytes read of %" FSL_SIZE_T_PFMT,
                           (fsl_size_t)got, (fsl_size_t)sizeof(buf));
      break;
    }
    rc = fsl_b_append(&st->in, buf, (fsl_size_t)got);
    if( rc ) break;
    if( st->in.used>maxReply ){
      rc = fsl__sc_reply_too_long(ch);
      break;
    }
  }
  /* The response was read close-delimited (HTTP/1.0): the peer has
     closed its side. Tear our side down too, so that the next request
     (e.g. the next clone round-trip) opens a fresh connection instead
     of writing to a dead socket. The full response is already
     buffered in st->in, which read() serves from memory, so closing
     the connection here is safe. */
  fsl_sc_stream_close(st);
  if( 0==rc ) rc = fsl_sc_socket_dechunk_if_needed(ch);
  st->inCursor = 0;
  st->responseLoaded = true;
  return rc;
}

/* ---- fsl_sc vtable ---- */

static int fsl_sc_socket_xInit(fsl_sc *ch, enum fsl_sc_init_e mode){
  fsl_sc * const self = ch->self(ch);
  fsl_sc_socket_state * st;
  if( FSL_SC_INIT_INITIAL==mode
      && ch->impl.type==&fsl_sc_stream_type_marker ){
    /* A caller's stream: ch->impl.p is its ops. Our state, which this
       copy of the channel owns, takes their place. */
    st = (fsl_sc_socket_state*)fsl_malloc(sizeof(fsl_sc_socket_state));
    if( !st ) return FSL_RC_OOM;
    memset(st, 0, sizeof(*st));
    st->ops = *(fsl_sc_stream_ops const *)ch->impl.p;
    st->fd = -1;
    ch->impl.p = st;
    ch->impl.type = &fsl_sc_socket_type_marker;
  }
  st = (fsl_sc_socket_state*)ch->impl.p;
  assert( ch->impl.type == &fsl_sc_socket_type_marker );
  if( FSL_SC_INIT_INITIAL==mode ){
    char const * const scheme = self->url.scheme;
    st->ch = self;
    if( st->native ){
      if( !scheme
          || (0!=fsl_strcmp(scheme,"http") && 0!=fsl_strcmp(scheme,"https")) ){
        return fsl_xfer_errorf(ch->xfer, FSL_RC_MISUSE,
                               "Native channel requires http/https URL, "
                               "not %s.", scheme ? scheme : "(no scheme)");
      }
      st->tls = (0==fsl_strcmp(scheme,"https"));
    }
    st->fd = -1;
  }
  if( FSL_SC_INIT_REQUEST==mode ){
    fsl_b_reuse(&st->out);
  }
  return 0;
}

static int fsl_sc_socket_xAppend(fsl_sc *ch, void const *pIn, fsl_size_t n){
  SOCK_STATE(ch);
  return fsl_b_append(&st->out, pIn, n);
}

/*
** Emit the library-generated request headers (which already include
** the request line, the login Cookie when authenticating, and the
** terminating blank line) followed by the request body, then read the
** entire response. loginCard is unused here: the library funnels the
** cookie into requestHeaders when FSL_SC_F_REQUEST_HEADERS is set,
** which this channel always sets. If a caller supplies headers that
** are not already blank-line-terminated (e.g. a hand-built request),
** the terminator is added so the request remains well-formed.
*/
static int fsl_sc_socket_submit(fsl_sc *ch, fsl_b const *loginCard){
  SOCK_STATE(ch);
  fsl_sc * const self = ch->self(ch);
  int rc;
  fsl_b_reuse(&st->in);
  st->inCursor = 0;
  st->responseLoaded = false;
  (void)loginCard;
  fsl_sc_stream_close(st) /* a connection left by a failed round */;
  rc = st->ops.connect(st->ops.state, &self->url, ch->xfer);
  if( rc ) return fsl_sc_stream_failed(ch, "connect");
  st->connected = true;

  if( self->requestHeaders.used ){
    fsl_b const * const h = &self->requestHeaders;
    /* Upgrade the library-generated "...HTTP/1.0\r\n" request line to
    ** HTTP/1.1, adding "Connection: close" so the peer still closes the
    ** connection after the response (preserving our close-delimited read
    ** model and avoiding keep-alive). Servers/proxies that reject HTTP/1.0
    ** then accept us. The rewrite is done on a local copy, so the
    ** library's buffer and the other channels are untouched. If the caller
    ** already supplied an HTTP/1.1 request line (e.g. the standalone
    ** channel test), no substitution occurs. */
    static char const v10[] = "HTTP/1.0\r\n";
    static char const v11[] = "HTTP/1.1\r\nConnection: close\r\n";
    char const * const z = (char const*)h->mem;
    fsl_size_t i, hit = (fsl_size_t)-1;
    for( i=0; i+10 <= h->used; ++i ){
      if( 0==memcmp(z+i, v10, 10) ){ hit = i; break; }
    }
    if( (fsl_size_t)-1 != hit ){
      /* ch->xfer is NULL for raw/test-tool use of this channel (e.g.
      ** the standalone channel test), same as in
      ** fsl_sc_socket_dechunk_if_needed() -- fall back to a plain,
      ** unpooled buffer rather than crash when there is no fsl_cx to
      ** borrow one from. This buffer is acquired lazily, only when a
      ** rewrite is actually needed, so the common already-1.1 case
      ** never touches it at all. */
      fsl_cx * const f = ch->xfer ? fsl_xfer_cx(ch->xfer) : NULL;
      fsl_b hbLocal = fsl_b_empty;
      fsl_b * const hb = f ? fsl_cx_b_borrow(f) : &hbLocal;
      if( !hb ){
        assert( f );
        return fsl_xfer_error(ch->xfer, f->error.code, 0);
      }
      fsl_b_append(hb, z, hit);
      fsl_b_append(hb, v11, (fsl_size_t)(sizeof(v11)-1));
      fsl_b_append(hb, z+hit+10, h->used-hit-10);
      rc = hb->errCode
        ? hb->errCode
        : fsl_sc_socket_write_all(ch, hb->mem, hb->used);
      if( f ){
        assert( hb != &hbLocal );
        fsl_cx_b_return(f, hb);
      }else{
        assert( hb == &hbLocal );
        fsl_b_clear(hb);
      }
    }else{
      rc = fsl_sc_socket_write_all(ch, h->mem, h->used);
    }
    if( rc ) return rc;
    /* Add a header terminator only if the caller did not already
    ** provide one (the library path always does). */
    if( h->used<4
        || 0!=memcmp((char const*)h->mem + h->used - 4, "\r\n\r\n", 4) ){
      rc = fsl_sc_socket_write_all(ch, "\r\n", 2);
      if( rc ) return rc;
    }
  }else{
    rc = fsl_sc_socket_write_all(ch, "\r\n", 2);
    if( rc ) return rc;
  }
  if( st->out.used ){
    rc = fsl_sc_socket_write_all(ch, st->out.mem, st->out.used);
    if( rc ) return rc;
  }
  return fsl_sc_socket_slurp_response(ch);
}

static int fsl_sc_socket_xSubmit(fsl_sc *ch, fsl_b const *loginCard){
  fsl_sc_sigpipe_state sp;
  int rc;
  fsl_sc_sigpipe_block(&sp);
  rc = fsl_sc_socket_submit(ch, loginCard);
  fsl_sc_sigpipe_restore(&sp);
  return rc;
}

static int fsl_sc_socket_xRead(fsl_sc *ch, fsl_b *tgt, fsl_int_t howMuch){
  SOCK_STATE(ch);
  fsl_size_t avail;
  unsigned char const * base;
  if( !st->responseLoaded ){
    return fsl_xfer_error(ch->xfer, FSL_RC_MISUSE,
                          "read() called before submit() loaded a response.");
  }
  avail = st->in.used - st->inCursor;
  base = (unsigned char const *)st->in.mem + st->inCursor;

  if( FSL_SC_READ_ALL==howMuch ){
    int rc = fsl_b_append(tgt, base, avail);
    st->inCursor = st->in.used;
    return rc;
  }
  if( FSL_SC_READ_LINE==howMuch ){
    fsl_size_t i = 0, take;
    int rc;
    if( 0==avail ) return FSL_RC_BREAK; /* clean EOF */
    while( i<avail && base[i]!='\n' ) ++i;
    take = (i<avail) ? (i+1) : avail; /* include newline if present */
    rc = fsl_b_append(tgt, base, take);
    if( rc ) return rc;
    st->inCursor += take;
    return 0;
  }
  /* howMuch > 0: deliver exactly that many bytes. */
  if( (fsl_size_t)howMuch > avail ){
    return fsl_xfer_errorf(ch->xfer, FSL_RC_IO,
                           "Short read: wanted %d, have %u.",
                           (int)howMuch, (unsigned)avail);
  }
  {
    int rc = fsl_b_append(tgt, base, (fsl_size_t)howMuch);
    if( rc ) return rc;
    st->inCursor += (fsl_size_t)howMuch;
    return 0;
  }
}

static void fsl_sc_socket_xCleanup(fsl_sc *ch){
  fsl_sc_socket_state * const st = ch->impl.type==&fsl_sc_socket_type_marker
    ? (fsl_sc_socket_state*)ch->impl.p : NULL;
  if( st ){
    if( st->connected ){
      /* A TLS close writes the close_notify alert. */
      fsl_sc_sigpipe_state sp;
      fsl_sc_sigpipe_block(&sp);
      fsl_sc_stream_close(st);
      fsl_sc_sigpipe_restore(&sp);
    }
    fsl_b_clear(&st->out);
    fsl_b_clear(&st->in);
    if( st->native ){
#if defined(_WIN32)
      WSACleanup() /* pairs with fsl_sc_socket_state_init() */;
#endif
    }
    fsl_free(st);
    ch->impl.p = 0;
  }
}

const fsl_sc fsl_sc_socket = {
  .xfer = 0,
  .name = "http-socket",
  .url = fsl_url_empty_m,
  .flags = FSL_SC_F_REQUEST_HEADERS,
  .impl = { .p = 0, .type = &fsl_sc_socket_type_marker },
  .init = fsl_sc_socket_xInit,
  .append = fsl_sc_socket_xAppend,
  .submit = fsl_sc_socket_xSubmit,
  .read = fsl_sc_socket_xRead,
  .cleanup = fsl_sc_socket_xCleanup,
  .self = fsl_sc_self,
  .requestHeaders = fsl_b_empty_m,
  .scratch = fsl_b_empty_m
};

int fsl_sc_socket_state_init(fsl_sc *ch){
  fsl_sc_socket_state * st;
  assert( ch->impl.type == &fsl_sc_socket_type_marker );
  st = (fsl_sc_socket_state*)fsl_malloc(sizeof(fsl_sc_socket_state));
  if( !st ) return FSL_RC_OOM;
#if defined(_WIN32)
  {
    /* Winsock counts WSAStartup() calls; xCleanup() makes the
       matching WSACleanup(). */
    WSADATA wsa;
    if( WSAStartup(MAKEWORD(2,2), &wsa) ){
      fsl_free(st);
      return FSL_RC_IO;
    }
  }
#endif
  memset(st, 0, sizeof(*st));
  st->fd = -1;
  st->out = fsl_b_empty;
  st->in = fsl_b_empty;
  st->native = true;
  st->ops.connect = fsl_sc_sock_connect;
  st->ops.read = fsl_sc_sock_read;
  st->ops.write = fsl_sc_sock_write;
  st->ops.close = fsl_sc_sock_close;
  st->ops.state = st;
  ch->impl.p = st;
  return 0;
}

/* The channel of fsl_sc_stream_init(). Its flags and methods are those
   of the sockets: only its ops and its name differ. */
static const fsl_sc fsl_sc_stream_proto = {
  .xfer = 0,
  .name = "stream",
  .url = fsl_url_empty_m,
  .flags = FSL_SC_F_REQUEST_HEADERS,
  .impl = { .p = 0, .type = &fsl_sc_stream_type_marker },
  .init = fsl_sc_socket_xInit,
  .append = fsl_sc_socket_xAppend,
  .submit = fsl_sc_socket_xSubmit,
  .read = fsl_sc_socket_xRead,
  .cleanup = fsl_sc_socket_xCleanup,
  .self = fsl_sc_self,
  .requestHeaders = fsl_b_empty_m,
  .scratch = fsl_b_empty_m
};

int fsl_sc_stream_init(fsl_sc * const ch, fsl_sc_stream_ops const * const ops){
  if( !ch || !ops || !ops->connect || !ops->read || !ops->write ){
    return FSL_RC_MISUSE;
  }
  *ch = fsl_sc_stream_proto;
  ch->impl.p = (void *)ops;
  return 0;
}

#undef SOCK_STATE
/* end of file src/sc.c */
/* start of file src/schema.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 Stephan Beal (https://wanderinghorse.net).


  This program is free software; you can redistribute it and/or
  modify it under the terms of the Simplified BSD License (also
  known as the "2-Clause License" or "FreeBSD License".)

  This program is distributed in the hope that it will be useful,
  but without any warranty; without even the implied warranty of
  merchantability or fitness for a particular purpose.

  *****************************************************************************
  This file implements schema-related parts of the library.
*/
#include <assert.h>


char const * fsl_schema_ckout(void){
  extern char const * fsl_schema_ckout_cstr;
  return fsl_schema_ckout_cstr;
}

char const * fsl_schema_repo2(void){
  extern char const * fsl_schema_repo2_cstr;
  return fsl_schema_repo2_cstr;
}

char const * fsl_schema_repo1(void){
  extern char const * fsl_schema_repo1_cstr;
  return fsl_schema_repo1_cstr;
}

char const * fsl_schema_config(void){
  extern char const * fsl_schema_config_cstr;
  return fsl_schema_config_cstr;
}

char const * fsl_schema_ticket_reports(void){
  extern char const * fsl_schema_ticket_reports_cstr;
  return fsl_schema_ticket_reports_cstr;
}

char const * fsl_schema_ticket(void){
  extern char const * fsl_schema_ticket_cstr;
  return fsl_schema_ticket_cstr;
}

char const * fsl_schema_forum(void){
  extern char const * fsl_schema_forum_cstr;
  return fsl_schema_forum_cstr;
}
/* end of file src/schema.c */
/* start of file src/search.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/*
  This file houses some FTS-search-related functionality.

  libfossil does not aim to reproduce all search functionality
  provided by fossil. Initially, at least, the only planned feature
  parity is that of updating the search index as content is
  added/updated.
*/
#include <assert.h>
#include <memory.h> /* memcmp() */

/* Only for debugging */
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

/**
   Returns 0 if f has no search index or a repo is not opened, else 4
   for an FTS4 index and 5 for an FTS5. If forceRecheck is false then
   a cached values is returned after the first call. If forceRecheck
   is true, the cached value is updated.
 */
static int fsl__search_ndx_exists(fsl_cx * const f, bool forceRecheck){
  fsl_db * const db = fsl_cx_db_repo(f);
  if(db && (f->cache.searchIndexExists<0 || forceRecheck) ){
    const bool b = fsl_db_table_exists(db, FSL_DBROLE_REPO, "ftsdocs");
    if(b){
      f->cache.searchIndexExists =
        fsl__db_table_has_column(db, FSL_DBROLE_REPO, "ftsdocs", "rowid")
        ? 5 // FTS5 (fossil as of 2023-01-24)
        : (fsl__db_table_has_column(db, FSL_DBROLE_REPO, "ftsdocs", "docid")
           ? 4 : 0);
      assert(f->cache.searchIndexExists==4 || f->cache.searchIndexExists==5);
    }else{
      f->cache.searchIndexExists = 0;
    }
  }
  return f->cache.searchIndexExists;
}

static char fsl_satype_letter(fsl_satype_e t){
  switch(t){
    case FSL_SATYPE_CHECKIN: return 'c';
    case FSL_SATYPE_WIKI: return 'w';
    case FSL_SATYPE_TICKET: return 't';
    case FSL_SATYPE_FORUMPOST: return 'f';
    case FSL_SATYPE_TECHNOTE: return 'e';
    default:
      assert(!"Internal misuse of fsl_satype_letter()");
      return 0;
  }
}

int fsl__search_doc_touch(fsl_cx * const f, fsl_satype_e saType,
                         fsl_id_t rid, const char * docName){
  const int ftsVers = fsl__search_ndx_exists(f, false);
  if(!ftsVers || fsl_content_is_private(f, rid)) return 0;
  assert(ftsVers==4 || ftsVers==5 || !"If this fails then our search-index-exists check is wrong.");
  char zType[2] = {0,0};
  zType[0] = fsl_satype_letter(saType);
#if 0
  /* See MARKER() call in the #else block */
  assert(*zType);
  return *zType ? 0 : FSL_RC_MISUSE;
#else
  /* Reminder: fossil(1) does some once-per-connection init here which
     installs UDFs used by the search process. Those will be significant
     for us if we add the search features to the library. */
  assert(zType[0] && "Misuse of fsl__search_doc_touch()'s 2nd parameter.");
  fsl_db * const db = fsl_cx_db_repo(f);
  int rc = 0;
  char const * zDocId = 4==ftsVers ? "docid" : "rowid";
  rc = fsl_db_exec(db,
       "DELETE FROM {{dbname.repo}}.ftsidx WHERE %s IN"
       "    (SELECT rowid FROM {{dbname.repo}}.ftsdocs WHERE type=%Q AND rid=%"FSL_ID_T_PFMT" AND idxed)",
       zDocId, zType, rid );
  if(rc){
    // For reasons i don't understand, this query fails with "SQL logic error"
    // when run from here, but succeeds fine in fossil and fossil's SQL shell.
    MARKER(("type=%s rid=%"FSL_ID_T_PFMT" rc=%s\n",
            zType, rid, fsl_rc_cstr(rc)));
    goto end;
  }
  rc = fsl_db_exec(db,
       "REPLACE INTO {{dbname.repo}}.ftsdocs(type,rid,name,idxed)"
       " VALUES(%Q,%"FSL_ID_T_PFMT",%Q,0)",
       zType, rid, docName );
  if(rc) goto end;
  if( FSL_SATYPE_WIKI==saType || FSL_SATYPE_TECHNOTE==saType ){
    rc = fsl_db_exec(db,
        "DELETE FROM {{dbname.repo}}.ftsidx WHERE %s IN"
        "    (SELECT rowid FROM {{dbname.repo}}.ftsdocs WHERE type=%Q AND name=%Q AND idxed)",
        zDocId, zType, docName );
    if(!rc) rc = fsl_db_exec(db,
        "DELETE FROM {{dbname.repo}}.ftsdocs WHERE type=%Q AND name=%Q AND rid!=%"FSL_ID_T_PFMT,
        zType, docName, rid );
  }
  /* All forum posts are always indexed */
  end:
  return rc ? fsl_cx_uplift_db_error2(f, db, rc) : 0;
#endif
}

#undef MARKER
/* end of file src/search.c */
/* start of file src/sha1.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
#include <assert.h>
#include <string.h> /* strlen() */
#include <stddef.h> /* NULL on linux */
#include <errno.h>

#include <sys/types.h>

/*************** File:  lib/sha1.c ****************/
/*
** Code obtained from GitHub
**
**     https://github.com/cr-marcstevens/sha1collisiondetection
**
** at commit   a06f1adbe5522f3c939cd6a3f13d5ec7f4c1a988   (2025-10-25).
**
** Downloaded on 2026-10-16.
*/
/***
* Copyright 2017 Marc Stevens <[email protected]>, Dan Shumow ([email protected])
* Distributed under the MIT Software License.
* See accompanying file LICENSE.txt or copy at
* https://opensource.org/licenses/MIT
***/
/*************** File:  LICENSE.txt ***************/
/*
** MIT License
**
** Copyright (c) 2017:
**     Marc Stevens
**     Cryptology Group
**     Centrum Wiskunde & Informatica
**     P.O. Box 94079, 1090 GB Amsterdam, Netherlands
**     [email protected]
**
**     Dan Shumow
**     Microsoft Research
**     [email protected]
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
*/

#include <string.h>
#include <memory.h>


#define DVMASKSIZE 1
typedef struct { int dvType; int dvK; int dvB; int testt; int maski; int maskb; uint32_t dm[80]; } dv_info_t;
#define DOSTORESTATE58
#define DOSTORESTATE65
typedef void(*sha1_recompression_type)(uint32_t*, uint32_t*, const uint32_t*, const uint32_t*);
typedef fsl_sha1_cx SHA1_CTX;

/******************** File: lib/ubc_check.[ch] **************************/
/***
* Copyright 2017 Marc Stevens <[email protected]>, Dan Shumow <[email protected]>
* Distributed under the MIT Software License.
* See accompanying file LICENSE.txt or copy at
* https://opensource.org/licenses/MIT
***/

// this file was generated by the 'parse_bitrel' program in the tools section
// using the data files from directory 'tools/data/3565'
//
// sha1_dvs contains a list of SHA-1 Disturbance Vectors (DV) to check
// dvType, dvK and dvB define the DV: I(K,B) or II(K,B) (see the paper)
// dm[80] is the expanded message block XOR-difference defined by the DV
// testt is the step to do the recompression from for collision detection
// maski and maskb define the bit to check for each DV in the dvmask returned by ubc_check
//
// ubc_check takes as input an expanded message block and verifies the unavoidable bitconditions for all listed DVs
// it returns a dvmask where each bit belonging to a DV is set if all unavoidable bitconditions for that DV have been met
// thus one needs to do the recompression check for each DV that has its bit set
//
// ubc_check is programmatically generated and the unavoidable bitconditions have been hardcoded
// a directly verifiable version named ubc_check_verify can be found in ubc_check_verify.c
// ubc_check has been verified against ubc_check_verify using the 'ubc_check_test' program in the tools section

#include <stdint.h>

static const uint32_t DV_I_43_0_bit 	= (uint32_t)(1) << 0;
static const uint32_t DV_I_44_0_bit 	= (uint32_t)(1) << 1;
static const uint32_t DV_I_45_0_bit 	= (uint32_t)(1) << 2;
static const uint32_t DV_I_46_0_bit 	= (uint32_t)(1) << 3;
static const uint32_t DV_I_46_2_bit 	= (uint32_t)(1) << 4;
static const uint32_t DV_I_47_0_bit 	= (uint32_t)(1) << 5;
static const uint32_t DV_I_47_2_bit 	= (uint32_t)(1) << 6;
static const uint32_t DV_I_48_0_bit 	= (uint32_t)(1) << 7;
static const uint32_t DV_I_48_2_bit 	= (uint32_t)(1) << 8;
static const uint32_t DV_I_49_0_bit 	= (uint32_t)(1) << 9;
static const uint32_t DV_I_49_2_bit 	= (uint32_t)(1) << 10;
static const uint32_t DV_I_50_0_bit 	= (uint32_t)(1) << 11;
static const uint32_t DV_I_50_2_bit 	= (uint32_t)(1) << 12;
static const uint32_t DV_I_51_0_bit 	= (uint32_t)(1) << 13;
static const uint32_t DV_I_51_2_bit 	= (uint32_t)(1) << 14;
static const uint32_t DV_I_52_0_bit 	= (uint32_t)(1) << 15;
static const uint32_t DV_II_45_0_bit 	= (uint32_t)(1) << 16;
static const uint32_t DV_II_46_0_bit 	= (uint32_t)(1) << 17;
static const uint32_t DV_II_46_2_bit 	= (uint32_t)(1) << 18;
static const uint32_t DV_II_47_0_bit 	= (uint32_t)(1) << 19;
static const uint32_t DV_II_48_0_bit 	= (uint32_t)(1) << 20;
static const uint32_t DV_II_49_0_bit 	= (uint32_t)(1) << 21;
static const uint32_t DV_II_49_2_bit 	= (uint32_t)(1) << 22;
static const uint32_t DV_II_50_0_bit 	= (uint32_t)(1) << 23;
static const uint32_t DV_II_50_2_bit 	= (uint32_t)(1) << 24;
static const uint32_t DV_II_51_0_bit 	= (uint32_t)(1) << 25;
static const uint32_t DV_II_51_2_bit 	= (uint32_t)(1) << 26;
static const uint32_t DV_II_52_0_bit 	= (uint32_t)(1) << 27;
static const uint32_t DV_II_53_0_bit 	= (uint32_t)(1) << 28;
static const uint32_t DV_II_54_0_bit 	= (uint32_t)(1) << 29;
static const uint32_t DV_II_55_0_bit 	= (uint32_t)(1) << 30;
static const uint32_t DV_II_56_0_bit 	= (uint32_t)(1) << 31;

static const dv_info_t sha1_dvs[] =
{
  {1,43,0,58,0,0, { 0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803,0x80000161,0x80000599 } }
, {1,44,0,58,0,1, { 0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803,0x80000161 } }
, {1,45,0,58,0,2, { 0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803 } }
, {1,46,0,58,0,3, { 0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c } }
, {1,46,2,58,0,4, { 0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020,0x0000039a,0x00000132 } }
, {1,47,0,58,0,5, { 0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6 } }
, {1,47,2,58,0,6, { 0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020,0x0000039a } }
, {1,48,0,58,0,7, { 0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408 } }
, {1,48,2,58,0,8, { 0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020 } }
, {1,49,0,58,0,9, { 0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164 } }
, {1,49,2,58,0,10, { 0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590 } }
, {1,50,0,65,0,11, { 0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018 } }
, {1,50,2,65,0,12, { 0x20000030,0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060 } }
, {1,51,0,65,0,13, { 0xe8000000,0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202 } }
, {1,51,2,65,0,14, { 0xa0000003,0x20000030,0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a } }
, {1,52,0,65,0,15, { 0x04000010,0xe8000000,0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012 } }
, {2,45,0,58,0,16, { 0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4,0x80000054,0x00000967 } }
, {2,46,0,58,0,17, { 0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4,0x80000054 } }
, {2,46,2,58,0,18, { 0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c,0x000005b6,0x0000106a,0x00000b90,0x00000152 } }
, {2,47,0,58,0,19, { 0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4 } }
, {2,48,0,58,0,20, { 0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a } }
, {2,49,0,58,0,21, { 0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d } }
, {2,49,2,58,0,22, { 0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c,0x000005b6 } }
, {2,50,0,65,0,23, { 0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b } }
, {2,50,2,65,0,24, { 0xd0000072,0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c } }
, {2,51,0,65,0,25, { 0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b } }
, {2,51,2,65,0,26, { 0x00000043,0xd0000072,0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e } }
, {2,52,0,65,0,27, { 0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014 } }
, {2,53,0,65,0,28, { 0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089 } }
, {2,54,0,65,0,29, { 0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107 } }
, {2,55,0,65,0,30, { 0x00000010,0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b } }
, {2,56,0,65,0,31, { 0x2600001a,0x00000010,0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046 } }
, {0,0,0,0,0,0, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}
};

static void ubc_check(const uint32_t W[80], uint32_t dvmask[1])
{
  uint32_t mask = ~((uint32_t)(0));
  mask &= (((((W[44]^W[45])>>29)&1)-1) | ~(DV_I_48_0_bit|DV_I_51_0_bit|DV_I_52_0_bit|DV_II_45_0_bit|DV_II_46_0_bit|DV_II_50_0_bit|DV_II_51_0_bit));
  mask &= (((((W[49]^W[50])>>29)&1)-1) | ~(DV_I_46_0_bit|DV_II_45_0_bit|DV_II_50_0_bit|DV_II_51_0_bit|DV_II_55_0_bit|DV_II_56_0_bit));
  mask &= (((((W[48]^W[49])>>29)&1)-1) | ~(DV_I_45_0_bit|DV_I_52_0_bit|DV_II_49_0_bit|DV_II_50_0_bit|DV_II_54_0_bit|DV_II_55_0_bit));
  mask &= ((((W[47]^(W[50]>>25))&(1<<4))-(1<<4)) | ~(DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_51_0_bit|DV_II_56_0_bit));
  mask &= (((((W[47]^W[48])>>29)&1)-1) | ~(DV_I_44_0_bit|DV_I_51_0_bit|DV_II_48_0_bit|DV_II_49_0_bit|DV_II_53_0_bit|DV_II_54_0_bit));
  mask &= (((((W[46]>>4)^(W[49]>>29))&1)-1) | ~(DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit|DV_II_50_0_bit|DV_II_55_0_bit));
  mask &= (((((W[46]^W[47])>>29)&1)-1) | ~(DV_I_43_0_bit|DV_I_50_0_bit|DV_II_47_0_bit|DV_II_48_0_bit|DV_II_52_0_bit|DV_II_53_0_bit));
  mask &= (((((W[45]>>4)^(W[48]>>29))&1)-1) | ~(DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit|DV_II_49_0_bit|DV_II_54_0_bit));
  mask &= (((((W[45]^W[46])>>29)&1)-1) | ~(DV_I_49_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_47_0_bit|DV_II_51_0_bit|DV_II_52_0_bit));
  mask &= (((((W[44]>>4)^(W[47]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit|DV_II_48_0_bit|DV_II_53_0_bit));
  mask &= (((((W[43]>>4)^(W[46]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit|DV_II_47_0_bit|DV_II_52_0_bit));
  mask &= (((((W[43]^W[44])>>29)&1)-1) | ~(DV_I_47_0_bit|DV_I_50_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_49_0_bit|DV_II_50_0_bit));
  mask &= (((((W[42]>>4)^(W[45]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_51_0_bit));
  mask &= (((((W[41]>>4)^(W[44]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_50_0_bit));
  mask &= (((((W[40]^W[41])>>29)&1)-1) | ~(DV_I_44_0_bit|DV_I_47_0_bit|DV_I_48_0_bit|DV_II_46_0_bit|DV_II_47_0_bit|DV_II_56_0_bit));
  mask &= (((((W[54]^W[55])>>29)&1)-1) | ~(DV_I_51_0_bit|DV_II_47_0_bit|DV_II_50_0_bit|DV_II_55_0_bit|DV_II_56_0_bit));
  mask &= (((((W[53]^W[54])>>29)&1)-1) | ~(DV_I_50_0_bit|DV_II_46_0_bit|DV_II_49_0_bit|DV_II_54_0_bit|DV_II_55_0_bit));
  mask &= (((((W[52]^W[53])>>29)&1)-1) | ~(DV_I_49_0_bit|DV_II_45_0_bit|DV_II_48_0_bit|DV_II_53_0_bit|DV_II_54_0_bit));
  mask &= ((((W[50]^(W[53]>>25))&(1<<4))-(1<<4)) | ~(DV_I_50_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_48_0_bit|DV_II_54_0_bit));
  mask &= (((((W[50]^W[51])>>29)&1)-1) | ~(DV_I_47_0_bit|DV_II_46_0_bit|DV_II_51_0_bit|DV_II_52_0_bit|DV_II_56_0_bit));
  mask &= ((((W[49]^(W[52]>>25))&(1<<4))-(1<<4)) | ~(DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_47_0_bit|DV_II_53_0_bit));
  mask &= ((((W[48]^(W[51]>>25))&(1<<4))-(1<<4)) | ~(DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_52_0_bit));
  mask &= (((((W[42]^W[43])>>29)&1)-1) | ~(DV_I_46_0_bit|DV_I_49_0_bit|DV_I_50_0_bit|DV_II_48_0_bit|DV_II_49_0_bit));
  mask &= (((((W[41]^W[42])>>29)&1)-1) | ~(DV_I_45_0_bit|DV_I_48_0_bit|DV_I_49_0_bit|DV_II_47_0_bit|DV_II_48_0_bit));
  mask &= (((((W[40]>>4)^(W[43]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_50_0_bit|DV_II_49_0_bit|DV_II_56_0_bit));
  mask &= (((((W[39]>>4)^(W[42]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_49_0_bit|DV_II_48_0_bit|DV_II_55_0_bit));
  if (mask & (DV_I_44_0_bit|DV_I_48_0_bit|DV_II_47_0_bit|DV_II_54_0_bit|DV_II_56_0_bit))
    mask &= (((((W[38]>>4)^(W[41]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_48_0_bit|DV_II_47_0_bit|DV_II_54_0_bit|DV_II_56_0_bit));
  mask &= (((((W[37]>>4)^(W[40]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_47_0_bit|DV_II_46_0_bit|DV_II_53_0_bit|DV_II_55_0_bit));
  if (mask & (DV_I_52_0_bit|DV_II_48_0_bit|DV_II_51_0_bit|DV_II_56_0_bit))
    mask &= (((((W[55]^W[56])>>29)&1)-1) | ~(DV_I_52_0_bit|DV_II_48_0_bit|DV_II_51_0_bit|DV_II_56_0_bit));
  if (mask & (DV_I_52_0_bit|DV_II_48_0_bit|DV_II_50_0_bit|DV_II_56_0_bit))
    mask &= ((((W[52]^(W[55]>>25))&(1<<4))-(1<<4)) | ~(DV_I_52_0_bit|DV_II_48_0_bit|DV_II_50_0_bit|DV_II_56_0_bit));
  if (mask & (DV_I_51_0_bit|DV_II_47_0_bit|DV_II_49_0_bit|DV_II_55_0_bit))
    mask &= ((((W[51]^(W[54]>>25))&(1<<4))-(1<<4)) | ~(DV_I_51_0_bit|DV_II_47_0_bit|DV_II_49_0_bit|DV_II_55_0_bit));
  if (mask & (DV_I_48_0_bit|DV_II_47_0_bit|DV_II_52_0_bit|DV_II_53_0_bit))
    mask &= (((((W[51]^W[52])>>29)&1)-1) | ~(DV_I_48_0_bit|DV_II_47_0_bit|DV_II_52_0_bit|DV_II_53_0_bit));
  if (mask & (DV_I_46_0_bit|DV_I_49_0_bit|DV_II_45_0_bit|DV_II_48_0_bit))
    mask &= (((((W[36]>>4)^(W[40]>>29))&1)-1) | ~(DV_I_46_0_bit|DV_I_49_0_bit|DV_II_45_0_bit|DV_II_48_0_bit));
  if (mask & (DV_I_52_0_bit|DV_II_48_0_bit|DV_II_49_0_bit))
    mask &= ((0-(((W[53]^W[56])>>29)&1)) | ~(DV_I_52_0_bit|DV_II_48_0_bit|DV_II_49_0_bit));
  if (mask & (DV_I_50_0_bit|DV_II_46_0_bit|DV_II_47_0_bit))
    mask &= ((0-(((W[51]^W[54])>>29)&1)) | ~(DV_I_50_0_bit|DV_II_46_0_bit|DV_II_47_0_bit));
  if (mask & (DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit))
    mask &= ((0-(((W[50]^W[52])>>29)&1)) | ~(DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit));
  if (mask & (DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit))
    mask &= ((0-(((W[49]^W[51])>>29)&1)) | ~(DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit));
  if (mask & (DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit))
    mask &= ((0-(((W[48]^W[50])>>29)&1)) | ~(DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit));
  if (mask & (DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit))
    mask &= ((0-(((W[47]^W[49])>>29)&1)) | ~(DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit));
  if (mask & (DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit))
    mask &= ((0-(((W[46]^W[48])>>29)&1)) | ~(DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit));
  mask &= ((((W[45]^W[47])&(1<<6))-(1<<6)) | ~(DV_I_47_2_bit|DV_I_49_2_bit|DV_I_51_2_bit));
  if (mask & (DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit))
    mask &= ((0-(((W[45]^W[47])>>29)&1)) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit));
  mask &= (((((W[44]^W[46])>>6)&1)-1) | ~(DV_I_46_2_bit|DV_I_48_2_bit|DV_I_50_2_bit));
  if (mask & (DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit))
    mask &= ((0-(((W[44]^W[46])>>29)&1)) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit));
  mask &= ((0-((W[41]^(W[42]>>5))&(1<<1))) | ~(DV_I_48_2_bit|DV_II_46_2_bit|DV_II_51_2_bit));
  mask &= ((0-((W[40]^(W[41]>>5))&(1<<1))) | ~(DV_I_47_2_bit|DV_I_51_2_bit|DV_II_50_2_bit));
  if (mask & (DV_I_44_0_bit|DV_I_46_0_bit|DV_II_56_0_bit))
    mask &= ((0-(((W[40]^W[42])>>4)&1)) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_II_56_0_bit));
  mask &= ((0-((W[39]^(W[40]>>5))&(1<<1))) | ~(DV_I_46_2_bit|DV_I_50_2_bit|DV_II_49_2_bit));
  if (mask & (DV_I_43_0_bit|DV_I_45_0_bit|DV_II_55_0_bit))
    mask &= ((0-(((W[39]^W[41])>>4)&1)) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_II_55_0_bit));
  if (mask & (DV_I_44_0_bit|DV_II_54_0_bit|DV_II_56_0_bit))
    mask &= ((0-(((W[38]^W[40])>>4)&1)) | ~(DV_I_44_0_bit|DV_II_54_0_bit|DV_II_56_0_bit));
  if (mask & (DV_I_43_0_bit|DV_II_53_0_bit|DV_II_55_0_bit))
    mask &= ((0-(((W[37]^W[39])>>4)&1)) | ~(DV_I_43_0_bit|DV_II_53_0_bit|DV_II_55_0_bit));
  mask &= ((0-((W[36]^(W[37]>>5))&(1<<1))) | ~(DV_I_47_2_bit|DV_I_50_2_bit|DV_II_46_2_bit));
  if (mask & (DV_I_45_0_bit|DV_I_48_0_bit|DV_II_47_0_bit))
    mask &= (((((W[35]>>4)^(W[39]>>29))&1)-1) | ~(DV_I_45_0_bit|DV_I_48_0_bit|DV_II_47_0_bit));
  if (mask & (DV_I_48_0_bit|DV_II_48_0_bit))
    mask &= ((0-((W[63]^(W[64]>>5))&(1<<0))) | ~(DV_I_48_0_bit|DV_II_48_0_bit));
  if (mask & (DV_I_45_0_bit|DV_II_45_0_bit))
    mask &= ((0-((W[63]^(W[64]>>5))&(1<<1))) | ~(DV_I_45_0_bit|DV_II_45_0_bit));
  if (mask & (DV_I_47_0_bit|DV_II_47_0_bit))
    mask &= ((0-((W[62]^(W[63]>>5))&(1<<0))) | ~(DV_I_47_0_bit|DV_II_47_0_bit));
  if (mask & (DV_I_46_0_bit|DV_II_46_0_bit))
    mask &= ((0-((W[61]^(W[62]>>5))&(1<<0))) | ~(DV_I_46_0_bit|DV_II_46_0_bit));
  mask &= ((0-((W[61]^(W[62]>>5))&(1<<2))) | ~(DV_I_46_2_bit|DV_II_46_2_bit));
  if (mask & (DV_I_45_0_bit|DV_II_45_0_bit))
    mask &= ((0-((W[60]^(W[61]>>5))&(1<<0))) | ~(DV_I_45_0_bit|DV_II_45_0_bit));
  if (mask & (DV_II_51_0_bit|DV_II_54_0_bit))
    mask &= (((((W[58]^W[59])>>29)&1)-1) | ~(DV_II_51_0_bit|DV_II_54_0_bit));
  if (mask & (DV_II_50_0_bit|DV_II_53_0_bit))
    mask &= (((((W[57]^W[58])>>29)&1)-1) | ~(DV_II_50_0_bit|DV_II_53_0_bit));
  if (mask & (DV_II_52_0_bit|DV_II_54_0_bit))
    mask &= ((((W[56]^(W[59]>>25))&(1<<4))-(1<<4)) | ~(DV_II_52_0_bit|DV_II_54_0_bit));
  if (mask & (DV_II_51_0_bit|DV_II_52_0_bit))
    mask &= ((0-(((W[56]^W[59])>>29)&1)) | ~(DV_II_51_0_bit|DV_II_52_0_bit));
  if (mask & (DV_II_49_0_bit|DV_II_52_0_bit))
    mask &= (((((W[56]^W[57])>>29)&1)-1) | ~(DV_II_49_0_bit|DV_II_52_0_bit));
  if (mask & (DV_II_51_0_bit|DV_II_53_0_bit))
    mask &= ((((W[55]^(W[58]>>25))&(1<<4))-(1<<4)) | ~(DV_II_51_0_bit|DV_II_53_0_bit));
  if (mask & (DV_II_50_0_bit|DV_II_52_0_bit))
    mask &= ((((W[54]^(W[57]>>25))&(1<<4))-(1<<4)) | ~(DV_II_50_0_bit|DV_II_52_0_bit));
  if (mask & (DV_II_49_0_bit|DV_II_51_0_bit))
    mask &= ((((W[53]^(W[56]>>25))&(1<<4))-(1<<4)) | ~(DV_II_49_0_bit|DV_II_51_0_bit));
  mask &= ((((W[51]^(W[50]>>5))&(1<<1))-(1<<1)) | ~(DV_I_50_2_bit|DV_II_46_2_bit));
  mask &= ((((W[48]^W[50])&(1<<6))-(1<<6)) | ~(DV_I_50_2_bit|DV_II_46_2_bit));
  if (mask & (DV_I_51_0_bit|DV_I_52_0_bit))
    mask &= ((0-(((W[48]^W[55])>>29)&1)) | ~(DV_I_51_0_bit|DV_I_52_0_bit));
  mask &= ((((W[47]^W[49])&(1<<6))-(1<<6)) | ~(DV_I_49_2_bit|DV_I_51_2_bit));
  mask &= ((((W[48]^(W[47]>>5))&(1<<1))-(1<<1)) | ~(DV_I_47_2_bit|DV_II_51_2_bit));
  mask &= ((((W[46]^W[48])&(1<<6))-(1<<6)) | ~(DV_I_48_2_bit|DV_I_50_2_bit));
  mask &= ((((W[47]^(W[46]>>5))&(1<<1))-(1<<1)) | ~(DV_I_46_2_bit|DV_II_50_2_bit));
  mask &= ((0-((W[44]^(W[45]>>5))&(1<<1))) | ~(DV_I_51_2_bit|DV_II_49_2_bit));
  mask &= ((((W[43]^W[45])&(1<<6))-(1<<6)) | ~(DV_I_47_2_bit|DV_I_49_2_bit));
  mask &= (((((W[42]^W[44])>>6)&1)-1) | ~(DV_I_46_2_bit|DV_I_48_2_bit));
  mask &= ((((W[43]^(W[42]>>5))&(1<<1))-(1<<1)) | ~(DV_II_46_2_bit|DV_II_51_2_bit));
  mask &= ((((W[42]^(W[41]>>5))&(1<<1))-(1<<1)) | ~(DV_I_51_2_bit|DV_II_50_2_bit));
  mask &= ((((W[41]^(W[40]>>5))&(1<<1))-(1<<1)) | ~(DV_I_50_2_bit|DV_II_49_2_bit));
  if (mask & (DV_I_52_0_bit|DV_II_51_0_bit))
    mask &= ((((W[39]^(W[43]>>25))&(1<<4))-(1<<4)) | ~(DV_I_52_0_bit|DV_II_51_0_bit));
  if (mask & (DV_I_51_0_bit|DV_II_50_0_bit))
    mask &= ((((W[38]^(W[42]>>25))&(1<<4))-(1<<4)) | ~(DV_I_51_0_bit|DV_II_50_0_bit));
  if (mask & (DV_I_48_2_bit|DV_I_51_2_bit))
    mask &= ((0-((W[37]^(W[38]>>5))&(1<<1))) | ~(DV_I_48_2_bit|DV_I_51_2_bit));
  if (mask & (DV_I_50_0_bit|DV_II_49_0_bit))
    mask &= ((((W[37]^(W[41]>>25))&(1<<4))-(1<<4)) | ~(DV_I_50_0_bit|DV_II_49_0_bit));
  if (mask & (DV_II_52_0_bit|DV_II_54_0_bit))
    mask &= ((0-((W[36]^W[38])&(1<<4))) | ~(DV_II_52_0_bit|DV_II_54_0_bit));
  mask &= ((0-((W[35]^(W[36]>>5))&(1<<1))) | ~(DV_I_46_2_bit|DV_I_49_2_bit));
  if (mask & (DV_I_51_0_bit|DV_II_47_0_bit))
    mask &= ((((W[35]^(W[39]>>25))&(1<<3))-(1<<3)) | ~(DV_I_51_0_bit|DV_II_47_0_bit));
  if (mask) {

    if (mask & DV_I_43_0_bit)
      if (
        !((W[61]^(W[62]>>5)) & (1<<1))
        || !(!((W[59]^(W[63]>>25)) & (1<<5)))
        || !((W[58]^(W[63]>>30)) & (1<<0))
      )  mask &= ~DV_I_43_0_bit;
    if (mask & DV_I_44_0_bit)
      if (
        !((W[62]^(W[63]>>5)) & (1<<1))
        || !(!((W[60]^(W[64]>>25)) & (1<<5)))
        || !((W[59]^(W[64]>>30)) & (1<<0))
      )  mask &= ~DV_I_44_0_bit;
    if (mask & DV_I_46_2_bit)
      mask &= ((~((W[40]^W[42])>>2)) | ~DV_I_46_2_bit);
    if (mask & DV_I_47_2_bit)
      if (
        !((W[62]^(W[63]>>5)) & (1<<2))
        || !(!((W[41]^W[43]) & (1<<6)))
      )  mask &= ~DV_I_47_2_bit;
    if (mask & DV_I_48_2_bit)
      if (
        !((W[63]^(W[64]>>5)) & (1<<2))
        || !(!((W[48]^(W[49]<<5)) & (1<<6)))
      )  mask &= ~DV_I_48_2_bit;
    if (mask & DV_I_49_2_bit)
      if (
        !(!((W[49]^(W[50]<<5)) & (1<<6)))
        || !((W[42]^W[50]) & (1<<1))
        || !(!((W[39]^(W[40]<<5)) & (1<<6)))
        || !((W[38]^W[40]) & (1<<1))
      )  mask &= ~DV_I_49_2_bit;
    if (mask & DV_I_50_0_bit)
      mask &= ((((W[36]^W[37])<<7)) | ~DV_I_50_0_bit);
    if (mask & DV_I_50_2_bit)
      mask &= ((((W[43]^W[51])<<11)) | ~DV_I_50_2_bit);
    if (mask & DV_I_51_0_bit)
      mask &= ((((W[37]^W[38])<<9)) | ~DV_I_51_0_bit);
    if (mask & DV_I_51_2_bit)
      if (
        !(!((W[51]^(W[52]<<5)) & (1<<6)))
        || !(!((W[49]^W[51]) & (1<<6)))
        || !(!((W[37]^(W[37]>>5)) & (1<<1)))
        || !(!((W[35]^(W[39]>>25)) & (1<<5)))
      )  mask &= ~DV_I_51_2_bit;
    if (mask & DV_I_52_0_bit)
      mask &= ((((W[38]^W[39])<<11)) | ~DV_I_52_0_bit);
    if (mask & DV_II_46_2_bit)
      mask &= ((((W[47]^W[51])<<17)) | ~DV_II_46_2_bit);
    if (mask & DV_II_48_0_bit)
      if (
        !(!((W[36]^(W[40]>>25)) & (1<<3)))
        || !((W[35]^(W[40]<<2)) & (1<<30))
      )  mask &= ~DV_II_48_0_bit;
    if (mask & DV_II_49_0_bit)
      if (
        !(!((W[37]^(W[41]>>25)) & (1<<3)))
        || !((W[36]^(W[41]<<2)) & (1<<30))
      )  mask &= ~DV_II_49_0_bit;
    if (mask & DV_II_49_2_bit)
      if (
        !(!((W[53]^(W[54]<<5)) & (1<<6)))
        || !(!((W[51]^W[53]) & (1<<6)))
        || !((W[50]^W[54]) & (1<<1))
        || !(!((W[45]^(W[46]<<5)) & (1<<6)))
        || !(!((W[37]^(W[41]>>25)) & (1<<5)))
        || !((W[36]^(W[41]>>30)) & (1<<0))
      )  mask &= ~DV_II_49_2_bit;
    if (mask & DV_II_50_0_bit)
      if (
        !((W[55]^W[58]) & (1<<29))
        || !(!((W[38]^(W[42]>>25)) & (1<<3)))
        || !((W[37]^(W[42]<<2)) & (1<<30))
      )  mask &= ~DV_II_50_0_bit;
    if (mask & DV_II_50_2_bit)
      if (
        !(!((W[54]^(W[55]<<5)) & (1<<6)))
        || !(!((W[52]^W[54]) & (1<<6)))
        || !((W[51]^W[55]) & (1<<1))
        || !((W[45]^W[47]) & (1<<1))
        || !(!((W[38]^(W[42]>>25)) & (1<<5)))
        || !((W[37]^(W[42]>>30)) & (1<<0))
      )  mask &= ~DV_II_50_2_bit;
    if (mask & DV_II_51_0_bit)
      if (
        !(!((W[39]^(W[43]>>25)) & (1<<3)))
        || !((W[38]^(W[43]<<2)) & (1<<30))
      )  mask &= ~DV_II_51_0_bit;
    if (mask & DV_II_51_2_bit)
      if (
        !(!((W[55]^(W[56]<<5)) & (1<<6)))
        || !(!((W[53]^W[55]) & (1<<6)))
        || !((W[52]^W[56]) & (1<<1))
        || !((W[46]^W[48]) & (1<<1))
        || !(!((W[39]^(W[43]>>25)) & (1<<5)))
        || !((W[38]^(W[43]>>30)) & (1<<0))
      )  mask &= ~DV_II_51_2_bit;
    if (mask & DV_II_52_0_bit)
      if (
        !(!((W[59]^W[60]) & (1<<29)))
        || !(!((W[40]^(W[44]>>25)) & (1<<3)))
        || !(!((W[40]^(W[44]>>25)) & (1<<4)))
        || !((W[39]^(W[44]<<2)) & (1<<30))
      )  mask &= ~DV_II_52_0_bit;
    if (mask & DV_II_53_0_bit)
      if (
        !((W[58]^W[61]) & (1<<29))
        || !(!((W[57]^(W[61]>>25)) & (1<<4)))
        || !(!((W[41]^(W[45]>>25)) & (1<<3)))
        || !(!((W[41]^(W[45]>>25)) & (1<<4)))
      )  mask &= ~DV_II_53_0_bit;
    if (mask & DV_II_54_0_bit)
      if (
        !(!((W[58]^(W[62]>>25)) & (1<<4)))
        || !(!((W[42]^(W[46]>>25)) & (1<<3)))
        || !(!((W[42]^(W[46]>>25)) & (1<<4)))
      )  mask &= ~DV_II_54_0_bit;
    if (mask & DV_II_55_0_bit)
      if (
        !(!((W[59]^(W[63]>>25)) & (1<<4)))
        || !(!((W[57]^(W[59]>>25)) & (1<<4)))
        || !(!((W[43]^(W[47]>>25)) & (1<<3)))
        || !(!((W[43]^(W[47]>>25)) & (1<<4)))
      )  mask &= ~DV_II_55_0_bit;
    if (mask & DV_II_56_0_bit)
      if (
        !(!((W[60]^(W[64]>>25)) & (1<<4)))
        || !(!((W[44]^(W[48]>>25)) & (1<<3)))
        || !(!((W[44]^(W[48]>>25)) & (1<<4)))
      )  mask &= ~DV_II_56_0_bit;
  }

  dvmask[0]=mask;
}

/******************** End Of File: lib/ubc_check.c *******************/
/******************** Continue with: lib/sha1.c **********************/
/***
* Copyright 2017 Marc Stevens <[email protected]>, Dan Shumow ([email protected])
* Distributed under the MIT Software License.
* See accompanying file LICENSE.txt or copy at
* https://opensource.org/licenses/MIT
***/

#define rotate_right(x,n) (((x)>>(n))|((x)<<(32-(n))))
#define rotate_left(x,n)  (((x)<<(n))|((x)>>(32-(n))))

#define sha1_bswap32(x) \
  {x = ((x << 8) & 0xFF00FF00) | ((x >> 8) & 0xFF00FF); x = (x << 16) | (x >> 16);}

#define sha1_mix(W, t)  (rotate_left(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1))

#if defined(BIGENDIAN)
  #define sha1_load(m, t) (m[t])
#else
  #define sha1_load(m, t, temp)  { temp = m[t]; sha1_bswap32(temp); }
#endif /*define(BIGENDIAN)*/

#define sha1_store(W, t, x)  *(volatile uint32_t *)&W[t] = x

#define sha1_f1(b,c,d) ((d)^((b)&((c)^(d))))
#define sha1_f2(b,c,d) ((b)^(c)^(d))
#define sha1_f3(b,c,d) (((b)&(c))+((d)&((b)^(c))))
#define sha1_f4(b,c,d) ((b)^(c)^(d))

#define HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, m, t) \
  { e += rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999 + m[t]; b = rotate_left(b, 30); }
#define HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, m, t) \
  { e += rotate_left(a, 5) + sha1_f2(b,c,d) + 0x6ED9EBA1 + m[t]; b = rotate_left(b, 30); }
#define HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, m, t) \
  { e += rotate_left(a, 5) + sha1_f3(b,c,d) + 0x8F1BBCDC + m[t]; b = rotate_left(b, 30); }
#define HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, m, t) \
  { e += rotate_left(a, 5) + sha1_f4(b,c,d) + 0xCA62C1D6 + m[t]; b = rotate_left(b, 30); }

#define HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, m, t) \
  { b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999 + m[t]; }
#define HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, m, t) \
  { b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f2(b,c,d) + 0x6ED9EBA1 + m[t]; }
#define HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, m, t) \
  { b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f3(b,c,d) + 0x8F1BBCDC + m[t]; }
#define HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, m, t) \
  { b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f4(b,c,d) + 0xCA62C1D6 + m[t]; }

#define SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, t, temp) \
  {sha1_load(m, t, temp); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999; b = rotate_right(b, 2);}

#define SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(a, b, c, d, e, W, t, temp) \
  {temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999; b = rotate_right(b, 2); }

#define SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, t, temp) \
  {temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f2(b,c,d) + 0x6ED9EBA1; b = rotate_right(b, 2); }

#define SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, t, temp) \
  {temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f3(b,c,d) + 0x8F1BBCDC; b = rotate_right(b, 2); }

#define SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, t, temp) \
  {temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f4(b,c,d) + 0xCA62C1D6; b = rotate_right(b, 2); }


#define SHA1_STORE_STATE(i) states[i][0] = a; states[i][1] = b; states[i][2] = c; states[i][3] = d; states[i][4] = e;

static void sha1_compression_W(uint32_t ihv[5], const uint32_t W[80])
{
  uint32_t a = ihv[0], b = ihv[1], c = ihv[2], d = ihv[3], e = ihv[4];

  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 0);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 1);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 2);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 3);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 4);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 5);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 6);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 7);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 8);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 9);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 10);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 11);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 12);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 13);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 14);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 15);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 16);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 17);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 18);
  HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 19);

  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 20);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 21);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 22);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 23);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 24);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 25);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 26);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 27);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 28);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 29);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 30);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 31);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 32);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 33);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 34);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 35);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 36);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 37);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 38);
  HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 39);

  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 40);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 41);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 42);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 43);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 44);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 45);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 46);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 47);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 48);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 49);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 50);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 51);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 52);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 53);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 54);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 55);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 56);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 57);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 58);
  HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 59);

  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 60);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 61);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 62);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 63);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 64);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 65);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 66);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 67);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 68);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 69);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 70);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 71);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 72);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 73);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 74);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 75);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 76);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 77);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 78);
  HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 79);

  ihv[0] += a; ihv[1] += b; ihv[2] += c; ihv[3] += d; ihv[4] += e;
}


static void sha1_compression_states(uint32_t ihv[5], const uint32_t m[16], uint32_t W[80], uint32_t states[80][5])
{
  uint32_t a = ihv[0], b = ihv[1], c = ihv[2], d = ihv[3], e = ihv[4];
  uint32_t temp;

#ifdef DOSTORESTATE00
  SHA1_STORE_STATE(0)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 0, temp);

#ifdef DOSTORESTATE01
  SHA1_STORE_STATE(1)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(e, a, b, c, d, m, W, 1, temp);

#ifdef DOSTORESTATE02
  SHA1_STORE_STATE(2)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(d, e, a, b, c, m, W, 2, temp);

#ifdef DOSTORESTATE03
  SHA1_STORE_STATE(3)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(c, d, e, a, b, m, W, 3, temp);

#ifdef DOSTORESTATE04
  SHA1_STORE_STATE(4)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(b, c, d, e, a, m, W, 4, temp);

#ifdef DOSTORESTATE05
  SHA1_STORE_STATE(5)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 5, temp);

#ifdef DOSTORESTATE06
  SHA1_STORE_STATE(6)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(e, a, b, c, d, m, W, 6, temp);

#ifdef DOSTORESTATE07
  SHA1_STORE_STATE(7)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(d, e, a, b, c, m, W, 7, temp);

#ifdef DOSTORESTATE08
  SHA1_STORE_STATE(8)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(c, d, e, a, b, m, W, 8, temp);

#ifdef DOSTORESTATE09
  SHA1_STORE_STATE(9)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(b, c, d, e, a, m, W, 9, temp);

#ifdef DOSTORESTATE10
  SHA1_STORE_STATE(10)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 10, temp);

#ifdef DOSTORESTATE11
  SHA1_STORE_STATE(11)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(e, a, b, c, d, m, W, 11, temp);

#ifdef DOSTORESTATE12
  SHA1_STORE_STATE(12)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(d, e, a, b, c, m, W, 12, temp);

#ifdef DOSTORESTATE13
  SHA1_STORE_STATE(13)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(c, d, e, a, b, m, W, 13, temp);

#ifdef DOSTORESTATE14
  SHA1_STORE_STATE(14)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(b, c, d, e, a, m, W, 14, temp);

#ifdef DOSTORESTATE15
  SHA1_STORE_STATE(15)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 15, temp);

#ifdef DOSTORESTATE16
  SHA1_STORE_STATE(16)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(e, a, b, c, d, W, 16, temp);

#ifdef DOSTORESTATE17
  SHA1_STORE_STATE(17)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(d, e, a, b, c, W, 17, temp);

#ifdef DOSTORESTATE18
  SHA1_STORE_STATE(18)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(c, d, e, a, b, W, 18, temp);

#ifdef DOSTORESTATE19
  SHA1_STORE_STATE(19)
#endif
  SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(b, c, d, e, a, W, 19, temp);



#ifdef DOSTORESTATE20
  SHA1_STORE_STATE(20)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 20, temp);

#ifdef DOSTORESTATE21
  SHA1_STORE_STATE(21)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 21, temp);

#ifdef DOSTORESTATE22
  SHA1_STORE_STATE(22)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 22, temp);

#ifdef DOSTORESTATE23
  SHA1_STORE_STATE(23)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 23, temp);

#ifdef DOSTORESTATE24
  SHA1_STORE_STATE(24)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 24, temp);

#ifdef DOSTORESTATE25
  SHA1_STORE_STATE(25)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 25, temp);

#ifdef DOSTORESTATE26
  SHA1_STORE_STATE(26)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 26, temp);

#ifdef DOSTORESTATE27
  SHA1_STORE_STATE(27)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 27, temp);

#ifdef DOSTORESTATE28
  SHA1_STORE_STATE(28)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 28, temp);

#ifdef DOSTORESTATE29
  SHA1_STORE_STATE(29)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 29, temp);

#ifdef DOSTORESTATE30
  SHA1_STORE_STATE(30)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 30, temp);

#ifdef DOSTORESTATE31
  SHA1_STORE_STATE(31)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 31, temp);

#ifdef DOSTORESTATE32
  SHA1_STORE_STATE(32)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 32, temp);

#ifdef DOSTORESTATE33
  SHA1_STORE_STATE(33)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 33, temp);

#ifdef DOSTORESTATE34
  SHA1_STORE_STATE(34)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 34, temp);

#ifdef DOSTORESTATE35
  SHA1_STORE_STATE(35)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 35, temp);

#ifdef DOSTORESTATE36
  SHA1_STORE_STATE(36)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 36, temp);

#ifdef DOSTORESTATE37
  SHA1_STORE_STATE(37)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 37, temp);

#ifdef DOSTORESTATE38
  SHA1_STORE_STATE(38)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 38, temp);

#ifdef DOSTORESTATE39
  SHA1_STORE_STATE(39)
#endif
  SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 39, temp);



#ifdef DOSTORESTATE40
  SHA1_STORE_STATE(40)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 40, temp);

#ifdef DOSTORESTATE41
  SHA1_STORE_STATE(41)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 41, temp);

#ifdef DOSTORESTATE42
  SHA1_STORE_STATE(42)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 42, temp);

#ifdef DOSTORESTATE43
  SHA1_STORE_STATE(43)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 43, temp);

#ifdef DOSTORESTATE44
  SHA1_STORE_STATE(44)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 44, temp);

#ifdef DOSTORESTATE45
  SHA1_STORE_STATE(45)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 45, temp);

#ifdef DOSTORESTATE46
  SHA1_STORE_STATE(46)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 46, temp);

#ifdef DOSTORESTATE47
  SHA1_STORE_STATE(47)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 47, temp);

#ifdef DOSTORESTATE48
  SHA1_STORE_STATE(48)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 48, temp);

#ifdef DOSTORESTATE49
  SHA1_STORE_STATE(49)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 49, temp);

#ifdef DOSTORESTATE50
  SHA1_STORE_STATE(50)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 50, temp);

#ifdef DOSTORESTATE51
  SHA1_STORE_STATE(51)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 51, temp);

#ifdef DOSTORESTATE52
  SHA1_STORE_STATE(52)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 52, temp);

#ifdef DOSTORESTATE53
  SHA1_STORE_STATE(53)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 53, temp);

#ifdef DOSTORESTATE54
  SHA1_STORE_STATE(54)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 54, temp);

#ifdef DOSTORESTATE55
  SHA1_STORE_STATE(55)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 55, temp);

#ifdef DOSTORESTATE56
  SHA1_STORE_STATE(56)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 56, temp);

#ifdef DOSTORESTATE57
  SHA1_STORE_STATE(57)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 57, temp);

#ifdef DOSTORESTATE58
  SHA1_STORE_STATE(58)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 58, temp);

#ifdef DOSTORESTATE59
  SHA1_STORE_STATE(59)
#endif
  SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 59, temp);




#ifdef DOSTORESTATE60
  SHA1_STORE_STATE(60)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 60, temp);

#ifdef DOSTORESTATE61
  SHA1_STORE_STATE(61)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 61, temp);

#ifdef DOSTORESTATE62
  SHA1_STORE_STATE(62)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 62, temp);

#ifdef DOSTORESTATE63
  SHA1_STORE_STATE(63)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 63, temp);

#ifdef DOSTORESTATE64
  SHA1_STORE_STATE(64)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 64, temp);

#ifdef DOSTORESTATE65
  SHA1_STORE_STATE(65)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 65, temp);

#ifdef DOSTORESTATE66
  SHA1_STORE_STATE(66)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 66, temp);

#ifdef DOSTORESTATE67
  SHA1_STORE_STATE(67)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 67, temp);

#ifdef DOSTORESTATE68
  SHA1_STORE_STATE(68)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 68, temp);

#ifdef DOSTORESTATE69
  SHA1_STORE_STATE(69)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 69, temp);

#ifdef DOSTORESTATE70
  SHA1_STORE_STATE(70)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 70, temp);

#ifdef DOSTORESTATE71
  SHA1_STORE_STATE(71)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 71, temp);

#ifdef DOSTORESTATE72
  SHA1_STORE_STATE(72)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 72, temp);

#ifdef DOSTORESTATE73
  SHA1_STORE_STATE(73)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 73, temp);

#ifdef DOSTORESTATE74
  SHA1_STORE_STATE(74)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 74, temp);

#ifdef DOSTORESTATE75
  SHA1_STORE_STATE(75)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 75, temp);

#ifdef DOSTORESTATE76
  SHA1_STORE_STATE(76)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 76, temp);

#ifdef DOSTORESTATE77
  SHA1_STORE_STATE(77)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 77, temp);

#ifdef DOSTORESTATE78
  SHA1_STORE_STATE(78)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 78, temp);

#ifdef DOSTORESTATE79
  SHA1_STORE_STATE(79)
#endif
  SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 79, temp);



  ihv[0] += a; ihv[1] += b; ihv[2] += c; ihv[3] += d; ihv[4] += e;
}




#define SHA1_RECOMPRESS(t) \
void sha1recompress_fast_ ## t (uint32_t ihvin[5], uint32_t ihvout[5], const uint32_t me2[80], const uint32_t state[5]) \
{ \
  uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; \
  if (t > 79) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 79); \
  if (t > 78) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 78); \
  if (t > 77) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 77); \
  if (t > 76) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 76); \
  if (t > 75) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 75); \
  if (t > 74) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 74); \
  if (t > 73) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 73); \
  if (t > 72) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 72); \
  if (t > 71) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 71); \
  if (t > 70) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 70); \
  if (t > 69) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 69); \
  if (t > 68) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 68); \
  if (t > 67) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 67); \
  if (t > 66) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 66); \
  if (t > 65) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 65); \
  if (t > 64) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 64); \
  if (t > 63) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 63); \
  if (t > 62) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 62); \
  if (t > 61) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 61); \
  if (t > 60) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 60); \
  if (t > 59) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 59); \
  if (t > 58) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 58); \
  if (t > 57) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 57); \
  if (t > 56) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 56); \
  if (t > 55) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 55); \
  if (t > 54) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 54); \
  if (t > 53) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 53); \
  if (t > 52) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 52); \
  if (t > 51) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 51); \
  if (t > 50) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 50); \
  if (t > 49) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 49); \
  if (t > 48) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 48); \
  if (t > 47) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 47); \
  if (t > 46) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 46); \
  if (t > 45) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 45); \
  if (t > 44) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 44); \
  if (t > 43) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 43); \
  if (t > 42) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 42); \
  if (t > 41) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 41); \
  if (t > 40) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 40); \
  if (t > 39) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 39); \
  if (t > 38) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 38); \
  if (t > 37) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 37); \
  if (t > 36) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 36); \
  if (t > 35) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 35); \
  if (t > 34) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 34); \
  if (t > 33) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 33); \
  if (t > 32) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 32); \
  if (t > 31) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 31); \
  if (t > 30) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 30); \
  if (t > 29) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 29); \
  if (t > 28) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 28); \
  if (t > 27) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 27); \
  if (t > 26) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 26); \
  if (t > 25) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 25); \
  if (t > 24) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 24); \
  if (t > 23) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 23); \
  if (t > 22) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 22); \
  if (t > 21) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 21); \
  if (t > 20) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 20); \
  if (t > 19) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 19); \
  if (t > 18) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 18); \
  if (t > 17) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 17); \
  if (t > 16) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 16); \
  if (t > 15) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 15); \
  if (t > 14) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 14); \
  if (t > 13) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 13); \
  if (t > 12) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 12); \
  if (t > 11) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 11); \
  if (t > 10) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 10); \
  if (t > 9) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 9); \
  if (t > 8) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 8); \
  if (t > 7) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 7); \
  if (t > 6) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 6); \
  if (t > 5) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 5); \
  if (t > 4) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 4); \
  if (t > 3) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 3); \
  if (t > 2) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 2); \
  if (t > 1) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 1); \
  if (t > 0) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 0); \
  ihvin[0] = a; ihvin[1] = b; ihvin[2] = c; ihvin[3] = d; ihvin[4] = e; \
  a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; \
  if (t <= 0) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 0); \
  if (t <= 1) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 1); \
  if (t <= 2) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 2); \
  if (t <= 3) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 3); \
  if (t <= 4) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 4); \
  if (t <= 5) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 5); \
  if (t <= 6) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 6); \
  if (t <= 7) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 7); \
  if (t <= 8) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 8); \
  if (t <= 9) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 9); \
  if (t <= 10) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 10); \
  if (t <= 11) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 11); \
  if (t <= 12) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 12); \
  if (t <= 13) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 13); \
  if (t <= 14) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 14); \
  if (t <= 15) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 15); \
  if (t <= 16) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 16); \
  if (t <= 17) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 17); \
  if (t <= 18) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 18); \
  if (t <= 19) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 19); \
  if (t <= 20) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 20); \
  if (t <= 21) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 21); \
  if (t <= 22) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 22); \
  if (t <= 23) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 23); \
  if (t <= 24) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 24); \
  if (t <= 25) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 25); \
  if (t <= 26) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 26); \
  if (t <= 27) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 27); \
  if (t <= 28) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 28); \
  if (t <= 29) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 29); \
  if (t <= 30) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 30); \
  if (t <= 31) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 31); \
  if (t <= 32) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 32); \
  if (t <= 33) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 33); \
  if (t <= 34) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 34); \
  if (t <= 35) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 35); \
  if (t <= 36) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 36); \
  if (t <= 37) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 37); \
  if (t <= 38) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 38); \
  if (t <= 39) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 39); \
  if (t <= 40) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 40); \
  if (t <= 41) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 41); \
  if (t <= 42) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 42); \
  if (t <= 43) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 43); \
  if (t <= 44) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 44); \
  if (t <= 45) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 45); \
  if (t <= 46) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 46); \
  if (t <= 47) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 47); \
  if (t <= 48) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 48); \
  if (t <= 49) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 49); \
  if (t <= 50) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 50); \
  if (t <= 51) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 51); \
  if (t <= 52) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 52); \
  if (t <= 53) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 53); \
  if (t <= 54) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 54); \
  if (t <= 55) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 55); \
  if (t <= 56) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 56); \
  if (t <= 57) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 57); \
  if (t <= 58) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 58); \
  if (t <= 59) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 59); \
  if (t <= 60) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 60); \
  if (t <= 61) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 61); \
  if (t <= 62) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 62); \
  if (t <= 63) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 63); \
  if (t <= 64) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 64); \
  if (t <= 65) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 65); \
  if (t <= 66) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 66); \
  if (t <= 67) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 67); \
  if (t <= 68) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 68); \
  if (t <= 69) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 69); \
  if (t <= 70) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 70); \
  if (t <= 71) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 71); \
  if (t <= 72) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 72); \
  if (t <= 73) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 73); \
  if (t <= 74) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 74); \
  if (t <= 75) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 75); \
  if (t <= 76) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 76); \
  if (t <= 77) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 77); \
  if (t <= 78) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 78); \
  if (t <= 79) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 79); \
  ihvout[0] = ihvin[0] + a; ihvout[1] = ihvin[1] + b; ihvout[2] = ihvin[2] + c; ihvout[3] = ihvin[3] + d; ihvout[4] = ihvin[4] + e; \
}

SHA1_RECOMPRESS(0)
SHA1_RECOMPRESS(1)
SHA1_RECOMPRESS(2)
SHA1_RECOMPRESS(3)
SHA1_RECOMPRESS(4)
SHA1_RECOMPRESS(5)
SHA1_RECOMPRESS(6)
SHA1_RECOMPRESS(7)
SHA1_RECOMPRESS(8)
SHA1_RECOMPRESS(9)

SHA1_RECOMPRESS(10)
SHA1_RECOMPRESS(11)
SHA1_RECOMPRESS(12)
SHA1_RECOMPRESS(13)
SHA1_RECOMPRESS(14)
SHA1_RECOMPRESS(15)
SHA1_RECOMPRESS(16)
SHA1_RECOMPRESS(17)
SHA1_RECOMPRESS(18)
SHA1_RECOMPRESS(19)

SHA1_RECOMPRESS(20)
SHA1_RECOMPRESS(21)
SHA1_RECOMPRESS(22)
SHA1_RECOMPRESS(23)
SHA1_RECOMPRESS(24)
SHA1_RECOMPRESS(25)
SHA1_RECOMPRESS(26)
SHA1_RECOMPRESS(27)
SHA1_RECOMPRESS(28)
SHA1_RECOMPRESS(29)

SHA1_RECOMPRESS(30)
SHA1_RECOMPRESS(31)
SHA1_RECOMPRESS(32)
SHA1_RECOMPRESS(33)
SHA1_RECOMPRESS(34)
SHA1_RECOMPRESS(35)
SHA1_RECOMPRESS(36)
SHA1_RECOMPRESS(37)
SHA1_RECOMPRESS(38)
SHA1_RECOMPRESS(39)

SHA1_RECOMPRESS(40)
SHA1_RECOMPRESS(41)
SHA1_RECOMPRESS(42)
SHA1_RECOMPRESS(43)
SHA1_RECOMPRESS(44)
SHA1_RECOMPRESS(45)
SHA1_RECOMPRESS(46)
SHA1_RECOMPRESS(47)
SHA1_RECOMPRESS(48)
SHA1_RECOMPRESS(49)

SHA1_RECOMPRESS(50)
SHA1_RECOMPRESS(51)
SHA1_RECOMPRESS(52)
SHA1_RECOMPRESS(53)
SHA1_RECOMPRESS(54)
SHA1_RECOMPRESS(55)
SHA1_RECOMPRESS(56)
SHA1_RECOMPRESS(57)
SHA1_RECOMPRESS(58)
SHA1_RECOMPRESS(59)

SHA1_RECOMPRESS(60)
SHA1_RECOMPRESS(61)
SHA1_RECOMPRESS(62)
SHA1_RECOMPRESS(63)
SHA1_RECOMPRESS(64)
SHA1_RECOMPRESS(65)
SHA1_RECOMPRESS(66)
SHA1_RECOMPRESS(67)
SHA1_RECOMPRESS(68)
SHA1_RECOMPRESS(69)

SHA1_RECOMPRESS(70)
SHA1_RECOMPRESS(71)
SHA1_RECOMPRESS(72)
SHA1_RECOMPRESS(73)
SHA1_RECOMPRESS(74)
SHA1_RECOMPRESS(75)
SHA1_RECOMPRESS(76)
SHA1_RECOMPRESS(77)
SHA1_RECOMPRESS(78)
SHA1_RECOMPRESS(79)

static const sha1_recompression_type sha1_recompression_step[80] =
{
  sha1recompress_fast_0, sha1recompress_fast_1, sha1recompress_fast_2, sha1recompress_fast_3, sha1recompress_fast_4, sha1recompress_fast_5, sha1recompress_fast_6, sha1recompress_fast_7, sha1recompress_fast_8, sha1recompress_fast_9,
  sha1recompress_fast_10, sha1recompress_fast_11, sha1recompress_fast_12, sha1recompress_fast_13, sha1recompress_fast_14, sha1recompress_fast_15, sha1recompress_fast_16, sha1recompress_fast_17, sha1recompress_fast_18, sha1recompress_fast_19,
  sha1recompress_fast_20, sha1recompress_fast_21, sha1recompress_fast_22, sha1recompress_fast_23, sha1recompress_fast_24, sha1recompress_fast_25, sha1recompress_fast_26, sha1recompress_fast_27, sha1recompress_fast_28, sha1recompress_fast_29,
  sha1recompress_fast_30, sha1recompress_fast_31, sha1recompress_fast_32, sha1recompress_fast_33, sha1recompress_fast_34, sha1recompress_fast_35, sha1recompress_fast_36, sha1recompress_fast_37, sha1recompress_fast_38, sha1recompress_fast_39,
  sha1recompress_fast_40, sha1recompress_fast_41, sha1recompress_fast_42, sha1recompress_fast_43, sha1recompress_fast_44, sha1recompress_fast_45, sha1recompress_fast_46, sha1recompress_fast_47, sha1recompress_fast_48, sha1recompress_fast_49,
  sha1recompress_fast_50, sha1recompress_fast_51, sha1recompress_fast_52, sha1recompress_fast_53, sha1recompress_fast_54, sha1recompress_fast_55, sha1recompress_fast_56, sha1recompress_fast_57, sha1recompress_fast_58, sha1recompress_fast_59,
  sha1recompress_fast_60, sha1recompress_fast_61, sha1recompress_fast_62, sha1recompress_fast_63, sha1recompress_fast_64, sha1recompress_fast_65, sha1recompress_fast_66, sha1recompress_fast_67, sha1recompress_fast_68, sha1recompress_fast_69,
  sha1recompress_fast_70, sha1recompress_fast_71, sha1recompress_fast_72, sha1recompress_fast_73, sha1recompress_fast_74, sha1recompress_fast_75, sha1recompress_fast_76, sha1recompress_fast_77, sha1recompress_fast_78, sha1recompress_fast_79,
};

static void sha1_process(SHA1_CTX* ctx, const uint32_t block[16])
{
  unsigned i, j;
  uint32_t ubc_dv_mask[DVMASKSIZE];
  uint32_t ihvtmp[5];
  for (i=0; i < DVMASKSIZE; ++i)
    ubc_dv_mask[i]=0;
  ctx->ihv1[0] = ctx->ihv[0];
  ctx->ihv1[1] = ctx->ihv[1];
  ctx->ihv1[2] = ctx->ihv[2];
  ctx->ihv1[3] = ctx->ihv[3];
  ctx->ihv1[4] = ctx->ihv[4];

  sha1_compression_states(ctx->ihv, block, ctx->m1, ctx->states);

  if (ctx->detect_coll)
  {
    if (ctx->ubc_check)
    {
      ubc_check(ctx->m1, ubc_dv_mask);
    }

    for (i = 0; sha1_dvs[i].dvType != 0; ++i)
    {
      if ((0 == ctx->ubc_check) || (((uint32_t)(1) << sha1_dvs[i].maskb) & ubc_dv_mask[sha1_dvs[i].maski]))
      {
        for (j = 0; j < 80; ++j)
          ctx->m2[j] = ctx->m1[j] ^ sha1_dvs[i].dm[j];
        (sha1_recompression_step[sha1_dvs[i].testt])(ctx->ihv2, ihvtmp, ctx->m2, ctx->states[sha1_dvs[i].testt]);
        // to verify SHA-1 collision detection code with collisions for reduced-step SHA-1
        if ((ihvtmp[0] == ctx->ihv[0] && ihvtmp[1] == ctx->ihv[1] && ihvtmp[2] == ctx->ihv[2] && ihvtmp[3] == ctx->ihv[3] && ihvtmp[4] == ctx->ihv[4])
          || (ctx->reduced_round_coll && ctx->ihv1[0] == ctx->ihv2[0] && ctx->ihv1[1] == ctx->ihv2[1] && ctx->ihv1[2] == ctx->ihv2[2] && ctx->ihv1[3] == ctx->ihv2[3] && ctx->ihv1[4] == ctx->ihv2[4]))
        {
          ctx->found_collision = 1;

          if (ctx->callback != NULL)
            ctx->callback(ctx->total - 64, ctx->ihv1, ctx->ihv2, ctx->m1, ctx->m2);

          if (ctx->safe_hash)
          {
            sha1_compression_W(ctx->ihv, ctx->m1);
            sha1_compression_W(ctx->ihv, ctx->m1);
          }

          break;
        }
      }
    }
  }
}

static const unsigned char sha1_padding[64] =
{
  0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

#undef DVMASKSIZE
#undef DOSTORESTATE58
#undef DOSTORESTATE65
#undef rotate_right
#undef rotate_left
#undef sha1_bswap32
#undef sha1_mix
#undef sha1_load
#undef sha1_store
#undef sha1_f1
#undef sha1_f2
#undef sha1_f3
#undef sha1_f4
#undef HASHCLASH_SHA1COMPRESS_ROUND1_STEP
#undef HASHCLASH_SHA1COMPRESS_ROUND2_STEP
#undef HASHCLASH_SHA1COMPRESS_ROUND3_STEP
#undef HASHCLASH_SHA1COMPRESS_ROUND4_STEP
#undef HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW
#undef HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW
#undef HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW
#undef HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW
#undef SHA1COMPRESS_FULL_ROUND1_STEP_LOAD
#undef SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND
#undef SHA1COMPRESS_FULL_ROUND2_STEP
#undef SHA1COMPRESS_FULL_ROUND3_STEP
#undef SHA1COMPRESS_FULL_ROUND4_STEP
#undef SHA1_STORE_STATE
#undef SHA1_RECOMPRESS

void fsl_sha1_init(fsl_sha1_cx *ctx){
  /* SHA1 initialization constants */
  memset(ctx, 0, sizeof(*ctx));
  ctx->total = 0;
  ctx->ihv[0] = 0x67452301;
  ctx->ihv[1] = 0xEFCDAB89;
  ctx->ihv[2] = 0x98BADCFE;
  ctx->ihv[3] = 0x10325476;
  ctx->ihv[4] = 0xC3D2E1F0;
  ctx->found_collision = 0;
  ctx->safe_hash = 1;
  ctx->ubc_check = 1;
  ctx->detect_coll = 1;
  ctx->reduced_round_coll = 0;
  ctx->callback = NULL;
}


/*
 * Run your data through this.
 */
void fsl_sha1_update( fsl_sha1_cx *ctx, void const * data_,
                      fsl_size_t len ){
  const unsigned char *buf = data_;
  unsigned left, fill;
  if (len == 0)
    return;

  left = ctx->total & 63;
  fill = 64 - left;

  if (left && len >= fill)
  {
    ctx->total += fill;
    memcpy(ctx->buffer + left, buf, fill);
    sha1_process(ctx, (uint32_t*)(ctx->buffer));
    buf += fill;
    len -= fill;
    left = 0;
  }
  while (len >= 64)
  {
    ctx->total += 64;
    if( (uintptr_t)buf & 3 ){
      /* A uint32_t load from a misaligned buf is undefined behaviour,
         as upstream sha1dc's SHA1DC_ALLOW_UNALIGNED_ACCESS notes. */
      memcpy(ctx->buffer, buf, 64);
      sha1_process(ctx, (uint32_t*)(ctx->buffer));
    }else{
      sha1_process(ctx, (uint32_t*)(buf));
    }
    buf += 64;
    len -= 64;
  }
  if (len > 0)
  {
    ctx->total += len;
    memcpy(ctx->buffer + left, buf, len);
  }
}

/*
   Convert a digest into base-16.  digest should be declared as
   "unsigned char digest[20]" in the calling function.  The SHA1
   digest is stored in the first 20 bytes.  zBuf should
   be "char zBuf[41]".
*/
void fsl_sha1_digest_to_base16(unsigned char const *digest, char *zBuf){
  static char const zEncode[] = "0123456789abcdef";
  int ix;

  for(ix=0; ix<FSL_STRLEN_SHA1/2; ix++){
    *zBuf++ = zEncode[(*digest>>4)&0xf];
    *zBuf++ = zEncode[*digest++ & 0xf];
  }
  *zBuf = '\0';
}

int fsl_sha1_final(fsl_sha1_cx *ctx, unsigned char * digest){
  uint32_t last = ctx->total & 63;
  uint32_t padn = (last < 56) ? (56 - last) : (120 - last);
  uint64_t total;
  fsl_sha1_update(ctx, sha1_padding, padn);

  total = ctx->total - padn;
  total <<= 3;
  ctx->buffer[56] = (unsigned char)(total >> 56);
  ctx->buffer[57] = (unsigned char)(total >> 48);
  ctx->buffer[58] = (unsigned char)(total >> 40);
  ctx->buffer[59] = (unsigned char)(total >> 32);
  ctx->buffer[60] = (unsigned char)(total >> 24);
  ctx->buffer[61] = (unsigned char)(total >> 16);
  ctx->buffer[62] = (unsigned char)(total >> 8);
  ctx->buffer[63] = (unsigned char)(total);
  sha1_process(ctx, (uint32_t*)(ctx->buffer));
  if( !digest ) return ctx->found_collision;
  digest[0] = (unsigned char)(ctx->ihv[0] >> 24);
  digest[1] = (unsigned char)(ctx->ihv[0] >> 16);
  digest[2] = (unsigned char)(ctx->ihv[0] >> 8);
  digest[3] = (unsigned char)(ctx->ihv[0]);
  digest[4] = (unsigned char)(ctx->ihv[1] >> 24);
  digest[5] = (unsigned char)(ctx->ihv[1] >> 16);
  digest[6] = (unsigned char)(ctx->ihv[1] >> 8);
  digest[7] = (unsigned char)(ctx->ihv[1]);
  digest[8] = (unsigned char)(ctx->ihv[2] >> 24);
  digest[9] = (unsigned char)(ctx->ihv[2] >> 16);
  digest[10] = (unsigned char)(ctx->ihv[2] >> 8);
  digest[11] = (unsigned char)(ctx->ihv[2]);
  digest[12] = (unsigned char)(ctx->ihv[3] >> 24);
  digest[13] = (unsigned char)(ctx->ihv[3] >> 16);
  digest[14] = (unsigned char)(ctx->ihv[3] >> 8);
  digest[15] = (unsigned char)(ctx->ihv[3]);
  digest[16] = (unsigned char)(ctx->ihv[4] >> 24);
  digest[17] = (unsigned char)(ctx->ihv[4] >> 16);
  digest[18] = (unsigned char)(ctx->ihv[4] >> 8);
  digest[19] = (unsigned char)(ctx->ihv[4]);
  return ctx->found_collision;
}

char const * fsl_sha1_final_hex(fsl_sha1_cx *context, char * zHex){
  unsigned char zResult[FSL_STRLEN_SHA1/2];
  fsl_sha1_final(context, zResult);
  fsl_sha1_digest_to_base16(zResult, zHex);
  return (char const *)zHex;
}

int fsl_sha1sum_stream(fsl_input_f src, void * srcState, fsl_b *pCksum){
  enum { BufSize = 1024 * 4 };
  fsl_sha1_cx ctx;
  int rc;
  unsigned char zBuf[BufSize];
  if(!src || !pCksum) return FSL_RC_MISUSE;
  fsl_sha1_init(&ctx);
  for(;;){
    fsl_size_t read = (fsl_size_t)BufSize;
    rc = src(srcState, zBuf, &read);
    if(rc) return rc;
    else if(read) fsl_sha1_update(&ctx, (unsigned char*)zBuf, read);
    if(read < (fsl_size_t)BufSize) break;
  }
  fsl_b_reuse(pCksum);
  rc = fsl_b_reserve(pCksum, FSL_STRLEN_SHA1+1/*NUL*/);
  /*^^^^ DO NOT fsl_b_resize(), as pCksum is, more often than not,
    a cached reused buffer. */
  if(!rc){
    fsl_sha1_final_hex(&ctx, fsl_b_str(pCksum));
    pCksum->used = (fsl_size_t)FSL_STRLEN_SHA1;
    pCksum->mem[pCksum->used] = 0;
  }
  return rc;
}

int fsl_sha1sum_update_stream(fsl_sha1_cx *ctx, fsl_input_f src,
                              void * srcState){
  int rc;
  enum { BufSize = 1024 * 4 };
  unsigned char zBuf[BufSize];
  if(!ctx || !src) return FSL_RC_MISUSE;
  for(;;){
    fsl_size_t read = (fsl_size_t)BufSize;
    rc = src(srcState, zBuf, &read);
    if(rc) return rc;
    else if(read) fsl_sha1_update(ctx, (unsigned char*)zBuf, read);
    if(read < (fsl_size_t)BufSize) break;
  }
  return 0;
}

int fsl_sha1sum_filename(const char *zFilename, fsl_b *pCksum){
  if(!zFilename || !pCksum) return FSL_RC_MISUSE;
  else{
#if 1
    int rc;
    FILE *in = fsl_fopen(zFilename, "rb");
    if(!in) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
    else{
      rc = fsl_sha1sum_stream(fsl_input_f_FILE, in, pCksum);
      fsl_fclose(in);
    }
    return rc;
#else
    /* Requires v1 code which has not yet been ported in. */
    FILE *in;
    fsl_sha1_cx ctx;
    unsigned char zResult[FSL_STRLEN_SHA1/2];
    char zBuf[10240];

    if( fsl_wd_islink(zFilename) ){
      /* Instead of file content, return sha1 of link destination path */
      Blob destinationPath;
      int rc;

      blob_read_link(&destinationPath, zFilename);
      rc = sha1sum_blob(&destinationPath, pCksum);
      blob_reset(&destinationPath);
      return rc;
    }

    in = fossil_fopen(zFilename,"rb");
    if( in==0 ){
      return 1;
    }
    fsl_sha1_init(&ctx);
    for(;;){
      int n;
      n = fread(zBuf, 1, sizeof(zBuf), in);
      if( n<=0 ) break;
      fsl_sha1_update(&ctx, (unsigned char*)zBuf, (unsigned)n);
    }
    fclose_fclose(in);
    blob_zero(pCksum);
    blob_resize(pCksum, FSL_STRLEN_SHA1);
    fsl_sha1_final(&ctx, zResult);
    fsl_sha1_digest_to_base16(zResult, blob_buffer(pCksum));
    return 0;
#endif
  }
}

int fsl_sha1sum_buffer(fsl_b const *pIn, fsl_b *pCksum){
  int const rc = fsl_b_reserve(pCksum,
                                    FSL_STRLEN_SHA1+1/*NUL*/);
  if( 0==rc ){
    fsl_sha1_cx ctx;
    fsl_sha1_init(&ctx);
    fsl_sha1_update(&ctx, pIn->mem, pIn->used);
    fsl_b_reuse(pCksum);
    fsl_sha1_final_hex(&ctx, fsl_b_str(pCksum));
    pCksum->used = (fsl_size_t)FSL_STRLEN_SHA1;
    pCksum->mem[pCksum->used] = 0;
  }
  return rc;
}

int fsl_sha1sum_buffer2(fsl_b const *pIn, fsl_b *pCksum){
  int const rc = fsl_b_reserve(pCksum, pCksum->used
                                    + FSL_STRLEN_SHA1+1/*NUL*/);
  if(!rc){
    fsl_sha1_cx ctx;
    fsl_sha1_init(&ctx);
    fsl_sha1_update(&ctx, pIn->mem, pIn->used);
    fsl_sha1_final_hex(&ctx, (char*)pCksum->mem + pCksum->used);
    pCksum->used += FSL_STRLEN_SHA1;
    assert( 0==pCksum->mem[pCksum->used-1] );
    pCksum->mem[pCksum->used] = 0;
  }
  return rc;
}

char *fsl_sha1sum_cstr(const char *zIn, fsl_int_t len){
  if(!zIn || !len) return NULL;
  else{
    fsl_sha1_cx ctx;
    char * zHex = (char *)fsl_malloc(FSL_STRLEN_SHA1+1);
    if(!zHex) return NULL;
    fsl_sha1_init(&ctx);
    fsl_sha1_update(&ctx, zIn,
                    (len<0) ? fsl_strlen(zIn) : (fsl_size_t)len);
    fsl_sha1_final_hex(&ctx, zHex);
    return zHex;
  }
}
/* end of file src/sha1.c */
/* start of file src/sha3.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
** Copyright (c) 2017 D. Richard Hipp
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
** known as the "2-Clause License" or "FreeBSD License".)
**
** This program is distributed in the hope that it will be useful,
** but without any warranty; without even the implied warranty of
** merchantability or fitness for a particular purpose.
**
** Author contact information:
**   [email protected]
**   http://www.hwaci.com/drh/
**
*******************************************************************************
**
** This file contains an implementation of SHA3 (Keccak) hashing.
*/
/**
   This copy was modified slightly for use with the libfossil API.
*/
#include <assert.h>
#include <string.h> /* strlen() */
#include <stddef.h> /* NULL on linux */
#include <errno.h>
#include <sys/types.h>
#include <assert.h>

#if 0
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)
#endif

/*
** Macros to determine whether the machine is big or little endian,
** and whether or not that determination is run-time or compile-time.
**
** For best performance, an attempt is made to guess at the byte-order
** using C-preprocessor macros.  If that is unsuccessful, or if
** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
** at run-time.
*/
#ifndef SHA3_BYTEORDER
# if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
     defined(__arm__)
#   define SHA3_BYTEORDER    1234
# elif defined(sparc)    || defined(__ppc__)
#   define SHA3_BYTEORDER    4321
# else
#   define SHA3_BYTEORDER 0
# endif
#endif

/*
** A single step of the Keccak mixing function for a 1600-bit state
*/
static void KeccakF1600Step(fsl_sha3_cx *p){
  int i;
  uint64_t B0, B1, B2, B3, B4;
  uint64_t C0, C1, C2, C3, C4;
  uint64_t D0, D1, D2, D3, D4;
  static const uint64_t RC[] = {
    0x0000000000000001ULL,  0x0000000000008082ULL,
    0x800000000000808aULL,  0x8000000080008000ULL,
    0x000000000000808bULL,  0x0000000080000001ULL,
    0x8000000080008081ULL,  0x8000000000008009ULL,
    0x000000000000008aULL,  0x0000000000000088ULL,
    0x0000000080008009ULL,  0x000000008000000aULL,
    0x000000008000808bULL,  0x800000000000008bULL,
    0x8000000000008089ULL,  0x8000000000008003ULL,
    0x8000000000008002ULL,  0x8000000000000080ULL,
    0x000000000000800aULL,  0x800000008000000aULL,
    0x8000000080008081ULL,  0x8000000000008080ULL,
    0x0000000080000001ULL,  0x8000000080008008ULL
  };
# define A00 (p->u.s[0])
# define A01 (p->u.s[1])
# define A02 (p->u.s[2])
# define A03 (p->u.s[3])
# define A04 (p->u.s[4])
# define A10 (p->u.s[5])
# define A11 (p->u.s[6])
# define A12 (p->u.s[7])
# define A13 (p->u.s[8])
# define A14 (p->u.s[9])
# define A20 (p->u.s[10])
# define A21 (p->u.s[11])
# define A22 (p->u.s[12])
# define A23 (p->u.s[13])
# define A24 (p->u.s[14])
# define A30 (p->u.s[15])
# define A31 (p->u.s[16])
# define A32 (p->u.s[17])
# define A33 (p->u.s[18])
# define A34 (p->u.s[19])
# define A40 (p->u.s[20])
# define A41 (p->u.s[21])
# define A42 (p->u.s[22])
# define A43 (p->u.s[23])
# define A44 (p->u.s[24])
# define ROL64(a,x) ((a<<x)|(a>>(64-x)))

  for(i=0; i<24; i+=4){
    C0 = A00^A10^A20^A30^A40;
    C1 = A01^A11^A21^A31^A41;
    C2 = A02^A12^A22^A32^A42;
    C3 = A03^A13^A23^A33^A43;
    C4 = A04^A14^A24^A34^A44;
    D0 = C4^ROL64(C1, 1);
    D1 = C0^ROL64(C2, 1);
    D2 = C1^ROL64(C3, 1);
    D3 = C2^ROL64(C4, 1);
    D4 = C3^ROL64(C0, 1);

    B0 = (A00^D0);
    B1 = ROL64((A11^D1), 44);
    B2 = ROL64((A22^D2), 43);
    B3 = ROL64((A33^D3), 21);
    B4 = ROL64((A44^D4), 14);
    A00 =   B0 ^((~B1)&  B2 );
    A00 ^= RC[i];
    A11 =   B1 ^((~B2)&  B3 );
    A22 =   B2 ^((~B3)&  B4 );
    A33 =   B3 ^((~B4)&  B0 );
    A44 =   B4 ^((~B0)&  B1 );

    B2 = ROL64((A20^D0), 3);
    B3 = ROL64((A31^D1), 45);
    B4 = ROL64((A42^D2), 61);
    B0 = ROL64((A03^D3), 28);
    B1 = ROL64((A14^D4), 20);
    A20 =   B0 ^((~B1)&  B2 );
    A31 =   B1 ^((~B2)&  B3 );
    A42 =   B2 ^((~B3)&  B4 );
    A03 =   B3 ^((~B4)&  B0 );
    A14 =   B4 ^((~B0)&  B1 );

    B4 = ROL64((A40^D0), 18);
    B0 = ROL64((A01^D1), 1);
    B1 = ROL64((A12^D2), 6);
    B2 = ROL64((A23^D3), 25);
    B3 = ROL64((A34^D4), 8);
    A40 =   B0 ^((~B1)&  B2 );
    A01 =   B1 ^((~B2)&  B3 );
    A12 =   B2 ^((~B3)&  B4 );
    A23 =   B3 ^((~B4)&  B0 );
    A34 =   B4 ^((~B0)&  B1 );

    B1 = ROL64((A10^D0), 36);
    B2 = ROL64((A21^D1), 10);
    B3 = ROL64((A32^D2), 15);
    B4 = ROL64((A43^D3), 56);
    B0 = ROL64((A04^D4), 27);
    A10 =   B0 ^((~B1)&  B2 );
    A21 =   B1 ^((~B2)&  B3 );
    A32 =   B2 ^((~B3)&  B4 );
    A43 =   B3 ^((~B4)&  B0 );
    A04 =   B4 ^((~B0)&  B1 );

    B3 = ROL64((A30^D0), 41);
    B4 = ROL64((A41^D1), 2);
    B0 = ROL64((A02^D2), 62);
    B1 = ROL64((A13^D3), 55);
    B2 = ROL64((A24^D4), 39);
    A30 =   B0 ^((~B1)&  B2 );
    A41 =   B1 ^((~B2)&  B3 );
    A02 =   B2 ^((~B3)&  B4 );
    A13 =   B3 ^((~B4)&  B0 );
    A24 =   B4 ^((~B0)&  B1 );

    C0 = A00^A20^A40^A10^A30;
    C1 = A11^A31^A01^A21^A41;
    C2 = A22^A42^A12^A32^A02;
    C3 = A33^A03^A23^A43^A13;
    C4 = A44^A14^A34^A04^A24;
    D0 = C4^ROL64(C1, 1);
    D1 = C0^ROL64(C2, 1);
    D2 = C1^ROL64(C3, 1);
    D3 = C2^ROL64(C4, 1);
    D4 = C3^ROL64(C0, 1);

    B0 = (A00^D0);
    B1 = ROL64((A31^D1), 44);
    B2 = ROL64((A12^D2), 43);
    B3 = ROL64((A43^D3), 21);
    B4 = ROL64((A24^D4), 14);
    A00 =   B0 ^((~B1)&  B2 );
    A00 ^= RC[i+1];
    A31 =   B1 ^((~B2)&  B3 );
    A12 =   B2 ^((~B3)&  B4 );
    A43 =   B3 ^((~B4)&  B0 );
    A24 =   B4 ^((~B0)&  B1 );

    B2 = ROL64((A40^D0), 3);
    B3 = ROL64((A21^D1), 45);
    B4 = ROL64((A02^D2), 61);
    B0 = ROL64((A33^D3), 28);
    B1 = ROL64((A14^D4), 20);
    A40 =   B0 ^((~B1)&  B2 );
    A21 =   B1 ^((~B2)&  B3 );
    A02 =   B2 ^((~B3)&  B4 );
    A33 =   B3 ^((~B4)&  B0 );
    A14 =   B4 ^((~B0)&  B1 );

    B4 = ROL64((A30^D0), 18);
    B0 = ROL64((A11^D1), 1);
    B1 = ROL64((A42^D2), 6);
    B2 = ROL64((A23^D3), 25);
    B3 = ROL64((A04^D4), 8);
    A30 =   B0 ^((~B1)&  B2 );
    A11 =   B1 ^((~B2)&  B3 );
    A42 =   B2 ^((~B3)&  B4 );
    A23 =   B3 ^((~B4)&  B0 );
    A04 =   B4 ^((~B0)&  B1 );

    B1 = ROL64((A20^D0), 36);
    B2 = ROL64((A01^D1), 10);
    B3 = ROL64((A32^D2), 15);
    B4 = ROL64((A13^D3), 56);
    B0 = ROL64((A44^D4), 27);
    A20 =   B0 ^((~B1)&  B2 );
    A01 =   B1 ^((~B2)&  B3 );
    A32 =   B2 ^((~B3)&  B4 );
    A13 =   B3 ^((~B4)&  B0 );
    A44 =   B4 ^((~B0)&  B1 );

    B3 = ROL64((A10^D0), 41);
    B4 = ROL64((A41^D1), 2);
    B0 = ROL64((A22^D2), 62);
    B1 = ROL64((A03^D3), 55);
    B2 = ROL64((A34^D4), 39);
    A10 =   B0 ^((~B1)&  B2 );
    A41 =   B1 ^((~B2)&  B3 );
    A22 =   B2 ^((~B3)&  B4 );
    A03 =   B3 ^((~B4)&  B0 );
    A34 =   B4 ^((~B0)&  B1 );

    C0 = A00^A40^A30^A20^A10;
    C1 = A31^A21^A11^A01^A41;
    C2 = A12^A02^A42^A32^A22;
    C3 = A43^A33^A23^A13^A03;
    C4 = A24^A14^A04^A44^A34;
    D0 = C4^ROL64(C1, 1);
    D1 = C0^ROL64(C2, 1);
    D2 = C1^ROL64(C3, 1);
    D3 = C2^ROL64(C4, 1);
    D4 = C3^ROL64(C0, 1);

    B0 = (A00^D0);
    B1 = ROL64((A21^D1), 44);
    B2 = ROL64((A42^D2), 43);
    B3 = ROL64((A13^D3), 21);
    B4 = ROL64((A34^D4), 14);
    A00 =   B0 ^((~B1)&  B2 );
    A00 ^= RC[i+2];
    A21 =   B1 ^((~B2)&  B3 );
    A42 =   B2 ^((~B3)&  B4 );
    A13 =   B3 ^((~B4)&  B0 );
    A34 =   B4 ^((~B0)&  B1 );

    B2 = ROL64((A30^D0), 3);
    B3 = ROL64((A01^D1), 45);
    B4 = ROL64((A22^D2), 61);
    B0 = ROL64((A43^D3), 28);
    B1 = ROL64((A14^D4), 20);
    A30 =   B0 ^((~B1)&  B2 );
    A01 =   B1 ^((~B2)&  B3 );
    A22 =   B2 ^((~B3)&  B4 );
    A43 =   B3 ^((~B4)&  B0 );
    A14 =   B4 ^((~B0)&  B1 );

    B4 = ROL64((A10^D0), 18);
    B0 = ROL64((A31^D1), 1);
    B1 = ROL64((A02^D2), 6);
    B2 = ROL64((A23^D3), 25);
    B3 = ROL64((A44^D4), 8);
    A10 =   B0 ^((~B1)&  B2 );
    A31 =   B1 ^((~B2)&  B3 );
    A02 =   B2 ^((~B3)&  B4 );
    A23 =   B3 ^((~B4)&  B0 );
    A44 =   B4 ^((~B0)&  B1 );

    B1 = ROL64((A40^D0), 36);
    B2 = ROL64((A11^D1), 10);
    B3 = ROL64((A32^D2), 15);
    B4 = ROL64((A03^D3), 56);
    B0 = ROL64((A24^D4), 27);
    A40 =   B0 ^((~B1)&  B2 );
    A11 =   B1 ^((~B2)&  B3 );
    A32 =   B2 ^((~B3)&  B4 );
    A03 =   B3 ^((~B4)&  B0 );
    A24 =   B4 ^((~B0)&  B1 );

    B3 = ROL64((A20^D0), 41);
    B4 = ROL64((A41^D1), 2);
    B0 = ROL64((A12^D2), 62);
    B1 = ROL64((A33^D3), 55);
    B2 = ROL64((A04^D4), 39);
    A20 =   B0 ^((~B1)&  B2 );
    A41 =   B1 ^((~B2)&  B3 );
    A12 =   B2 ^((~B3)&  B4 );
    A33 =   B3 ^((~B4)&  B0 );
    A04 =   B4 ^((~B0)&  B1 );

    C0 = A00^A30^A10^A40^A20;
    C1 = A21^A01^A31^A11^A41;
    C2 = A42^A22^A02^A32^A12;
    C3 = A13^A43^A23^A03^A33;
    C4 = A34^A14^A44^A24^A04;
    D0 = C4^ROL64(C1, 1);
    D1 = C0^ROL64(C2, 1);
    D2 = C1^ROL64(C3, 1);
    D3 = C2^ROL64(C4, 1);
    D4 = C3^ROL64(C0, 1);

    B0 = (A00^D0);
    B1 = ROL64((A01^D1), 44);
    B2 = ROL64((A02^D2), 43);
    B3 = ROL64((A03^D3), 21);
    B4 = ROL64((A04^D4), 14);
    A00 =   B0 ^((~B1)&  B2 );
    A00 ^= RC[i+3];
    A01 =   B1 ^((~B2)&  B3 );
    A02 =   B2 ^((~B3)&  B4 );
    A03 =   B3 ^((~B4)&  B0 );
    A04 =   B4 ^((~B0)&  B1 );

    B2 = ROL64((A10^D0), 3);
    B3 = ROL64((A11^D1), 45);
    B4 = ROL64((A12^D2), 61);
    B0 = ROL64((A13^D3), 28);
    B1 = ROL64((A14^D4), 20);
    A10 =   B0 ^((~B1)&  B2 );
    A11 =   B1 ^((~B2)&  B3 );
    A12 =   B2 ^((~B3)&  B4 );
    A13 =   B3 ^((~B4)&  B0 );
    A14 =   B4 ^((~B0)&  B1 );

    B4 = ROL64((A20^D0), 18);
    B0 = ROL64((A21^D1), 1);
    B1 = ROL64((A22^D2), 6);
    B2 = ROL64((A23^D3), 25);
    B3 = ROL64((A24^D4), 8);
    A20 =   B0 ^((~B1)&  B2 );
    A21 =   B1 ^((~B2)&  B3 );
    A22 =   B2 ^((~B3)&  B4 );
    A23 =   B3 ^((~B4)&  B0 );
    A24 =   B4 ^((~B0)&  B1 );

    B1 = ROL64((A30^D0), 36);
    B2 = ROL64((A31^D1), 10);
    B3 = ROL64((A32^D2), 15);
    B4 = ROL64((A33^D3), 56);
    B0 = ROL64((A34^D4), 27);
    A30 =   B0 ^((~B1)&  B2 );
    A31 =   B1 ^((~B2)&  B3 );
    A32 =   B2 ^((~B3)&  B4 );
    A33 =   B3 ^((~B4)&  B0 );
    A34 =   B4 ^((~B0)&  B1 );

    B3 = ROL64((A40^D0), 41);
    B4 = ROL64((A41^D1), 2);
    B0 = ROL64((A42^D2), 62);
    B1 = ROL64((A43^D3), 55);
    B2 = ROL64((A44^D4), 39);
    A40 =   B0 ^((~B1)&  B2 );
    A41 =   B1 ^((~B2)&  B3 );
    A42 =   B2 ^((~B3)&  B4 );
    A43 =   B3 ^((~B4)&  B0 );
    A44 =   B4 ^((~B0)&  B1 );
  }
# undef A00
# undef A01
# undef A02
# undef A03
# undef A04
# undef A10
# undef A11
# undef A12
# undef A13
# undef A14
# undef A20
# undef A21
# undef A22
# undef A23
# undef A24
# undef A30
# undef A31
# undef A32
# undef A33
# undef A34
# undef A40
# undef A41
# undef A42
# undef A43
# undef A44
# undef ROL64
}

enum fsl_sha3_hash_size fsl_sha3_hash_size_for_int(int n){
    switch(n){
      case 128: return FSL_SHA3_128; case 160: return FSL_SHA3_160;
      case 192: return FSL_SHA3_192; case 224: return FSL_SHA3_224;
      case 256: return FSL_SHA3_256; case 288: return FSL_SHA3_288;
      case 320: return FSL_SHA3_320; case 352: return FSL_SHA3_352;
      case 384: return FSL_SHA3_384; case 416: return FSL_SHA3_416;
      case 448: return FSL_SHA3_448; case 480: return FSL_SHA3_480;
      case 512: return FSL_SHA3_512;
      default: return FSL_SHA3_INVALID;
    }
}

void fsl_sha3_init(fsl_sha3_cx *cx){
  fsl_sha3_init2(cx, FSL_SHA3_DEFAULT);
}
void fsl_sha3_init2(fsl_sha3_cx *p, enum fsl_sha3_hash_size iSize){
  assert(iSize>0);
  memset(p, 0, sizeof(*p));
  p->size = iSize;
  if( iSize>=128 && iSize<=512 ){
    p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
  }else{
    p->nRate = (1600 - 2*256)/8;
  }
#if SHA3_BYTEORDER==1234
  /* Known to be little-endian at compile-time. No-op */
#elif SHA3_BYTEORDER==4321
  p->ixMask = 7;  /* Big-endian */
#else
  {
    static const unsigned int one = 1;
    if( 1==*(unsigned const char*)&one ){
      /* Little endian.  No byte swapping. */
      p->ixMask = 0;
    }else{
      /* Big endian.  Byte swap. */
      p->ixMask = 7;
    }
  }
#endif
}

void fsl_sha3_update( fsl_sha3_cx *p, void const *aData_, unsigned int nData ){
  unsigned char const * aData = (unsigned char const *)aData_;
  unsigned int i = 0;
#if SHA3_BYTEORDER==1234
  if( (p->nLoaded % 8)==0 && ((intptr_t)aData & 7)==0 ){
  //if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
  // ^^^ original impl, but -pedantic -Wextra warns about UB use of
  // NULL as an operand to the minus op.
    for(; i+7<nData; i+=8){
      uint64_t w;
      memcpy(&w, &aData[i], 8);
      p->u.s[p->nLoaded/8] ^= w;
      p->nLoaded += 8;
      if( p->nLoaded>=p->nRate ){
        KeccakF1600Step(p);
        p->nLoaded = 0;
      }
    }
  }
#endif
  for(; i<nData; i++){
#if SHA3_BYTEORDER==1234
    p->u.x[p->nLoaded] ^= aData[i];
#elif SHA3_BYTEORDER==4321
    p->u.x[p->nLoaded^0x07] ^= aData[i];
#else
    p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
#endif
    p->nLoaded++;
    if( p->nLoaded==p->nRate ){
      KeccakF1600Step(p);
      p->nLoaded = 0;
    }
  }
}

/**
   Works like fsl_sha3_update() but accepts a length of any size,
   passing the data on in pieces which fit that function's unsigned
   int length parameter.
*/
static void fsl__sha3_update_n(fsl_sha3_cx * const cx, void const * data,
                               fsl_size_t n){
  unsigned char const * z = (unsigned char const *)data;
  enum { Chunk = 1<<30 };
  while( n > Chunk ){
    fsl_sha3_update(cx, z, Chunk);
    z += Chunk;
    n -= Chunk;
  }
  fsl_sha3_update(cx, z, (unsigned int)n);
}

/*
** Convert a digest into base-16. must be at least nBytes long
** and zBuf must be at least nBytes*2 bytes long. This routine
** writes nBytes*2 hex-encoded bytes to zBuf, but does not write
** a terminating NUL byte.
*/
static void DigestToBase16(unsigned char *digest, unsigned char *zBuf, unsigned int nByte){
  static const unsigned char zEncode[] = "0123456789abcdef";
  unsigned int ix;
  for(ix=0; ix<nByte; ++ix){
    *zBuf++ = zEncode[(*digest>>4)&0xf];
    *zBuf++ = zEncode[*digest++ & 0xf];
  }
  /* *zBuf = '\0'; */
}

unsigned char const *fsl_sha3_end(fsl_sha3_cx *p){
  unsigned int i;
  if( p->nLoaded==p->nRate-1 ){
    const unsigned char c1 = 0x86;
    fsl_sha3_update(p, &c1, 1);
  }else{
    const unsigned char c2 = 0x06;
    const unsigned char c3 = 0x80;
    fsl_sha3_update(p, &c2, 1);
    p->nLoaded = p->nRate - 1;
    fsl_sha3_update(p, &c3, 1);
  }
  for(i=0; i<p->nRate; i++){
    p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
  }
  DigestToBase16( &p->u.x[p->nRate], p->hex, (int)p->size/8 );
  assert(0 == p->hex[(int)p->size/4+1]);
  return &p->u.x[p->nRate];
}

void fsl_sha3_digest_to_base16(unsigned char const *digest, char *zBuf){
  static char const zEncode[] = "0123456789abcdef";
  int ix;
  for(ix=0; ix<FSL_STRLEN_K256/2; ix++){
    *zBuf++ = zEncode[(*digest>>4)&0xf];
    *zBuf++ = zEncode[*digest++ & 0xf];
  }
  *zBuf = '\0';
}


int fsl_sha3sum_stream(fsl_input_f src, void * srcState, fsl_b *pCksum){
  fsl_sha3_cx ctx;
  int rc;
  enum { BufSize = 1024 * 4 };
  unsigned char zBuf[BufSize];
  if(!src || !pCksum) return FSL_RC_MISUSE;
  fsl_sha3_init(&ctx);
  for(;;){
    fsl_size_t read = (fsl_size_t)BufSize;
    rc = src(srcState, zBuf, &read);
    if(rc) return rc;
    else if(read) fsl_sha3_update(&ctx, (unsigned char*)zBuf, read);
    if(read < (fsl_size_t)BufSize) break;
  }
  fsl_sha3_end(&ctx);
  fsl_b_reuse(pCksum);
  return fsl_b_append(pCksum, ctx.hex, fsl_strlen((const char *)ctx.hex));
}

int fsl_sha3sum_buffer(fsl_b const *pIn, fsl_b *pCksum){
  if(!pIn || !pCksum) return FSL_RC_MISUSE;
  else{
    fsl_sha3_cx ctx;
    int rc;
    fsl_sha3_init(&ctx);
    fsl__sha3_update_n(&ctx, pIn->mem, pIn->used);
    rc = fsl_b_reserve(pCksum, FSL_STRLEN_K256+1/*NUL*/);
    /*^^^^ DO NOT fsl_b_resize(), as pCksum is, more often than not,
      a cached reused buffer. */
    if(!rc){
      fsl_b_reuse(pCksum);
      fsl_sha3_end(&ctx);
      assert(fsl_strlen((char const*)ctx.hex)==FSL_STRLEN_K256);
      rc = fsl_b_append(pCksum, ctx.hex, fsl_strlen((char const*)ctx.hex));
      assert(!rc && "Cannot fail - pre-allocated");
      if(!rc){
        assert(FSL_STRLEN_K256==pCksum->used);
        assert(0==pCksum->mem[FSL_STRLEN_K256]);
      }
    }
    return rc;
  }
}

char *fsl_sha3sum_cstr(const char *zIn, fsl_int_t len){
  if(!zIn || !len) return NULL;
  else{
    fsl_sha3_cx ctx;
    fsl_sha3_init(&ctx);
    fsl__sha3_update_n(&ctx, zIn,
                       (len<0) ? fsl_strlen(zIn) : (fsl_size_t)len);
    fsl_sha3_end(&ctx);
    return fsl_strdup((char const *)ctx.hex);
  }
}

int fsl_sha3sum_filename(const char *zFilename, fsl_b *pCksum){
  if(!zFilename || !pCksum) return FSL_RC_MISUSE;
  else{
#if 1
    int rc;
    FILE *in = fsl_fopen(zFilename, "rb");
    if(!in) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
    else{
      rc = fsl_sha3sum_stream(fsl_input_f_FILE, in, pCksum);
      fsl_fclose(in);
    }
    return rc;
#else
    /* Requires v1 code which has not yet been ported in. */
    FILE *in;
    fsl_sha1_cx ctx;
    char zBuf[10240];
    int rc;

    if( fsl_wd_islink(zFilename) ){
      /* Instead of file content, return sha3 of link destination path */
      Blob destinationPath;
      blob_read_link(&destinationPath, zFilename);
      rc = fsl_sha3sum_buffer(&destinationPath, pCksum);
      fsl_b_clear(&destinationPath);
      return rc;
    }

    in = fossil_fopen(zFilename,"rb");
    if( in==0 ){
      return 1;
    }
    fsl_sha3_init(&ctx);
    for(;;){
      int n;
      n = fread(zBuf, 1, sizeof(zBuf), in);
      if( n<=0 ) break;
      fsl_sha3_update(&ctx, (unsigned char*)zBuf, (unsigned)n);
    }
    fclose_fclose(in);
    blob_zero(pCksum);
    blob_resize(pCksum, FSL_STRLEN_SHA3);
    fsl_sha3_end(&ctx);
    rc = fsl_b_append(pCksum, ctx.hex, fsl_strlen(ctx.hex));
    return rc;
#endif
  }
}

#undef A00
#undef A01
#undef A02
#undef A03
#undef A04
#undef A10
#undef A11
#undef A12
#undef A13
#undef A14
#undef A20
#undef A21
#undef A22
#undef A23
#undef A24
#undef A30
#undef A31
#undef A32
#undef A33
#undef A34
#undef A40
#undef A41
#undef A42
#undef A43
#undef A44
#undef ROL64

#undef SHA3_BYTEORDER
#undef MARKER
/* end of file src/sha3.c */
/* start of file src/strftime.c */
/*******************************************************************************
 *  The Elm Mail System  -  $Revision: 1.3 $   $State: Exp $
 *
 * Public-domain relatively quick-and-dirty implemenation of
 * ANSI library routine for System V Unix systems.
 *
 * Arnold Robbins
 *
 *****************************************************************************
 * Bug reports, patches, comments, suggestions should be sent to:
 * (Note: this routine is provided as is, without support for those sites that
 *    do not have strftime in their library)
 *
 *    Syd Weinstein, Elm Coordinator
 *    [email protected]            dsinc!elm
 *
 *****************************************************************************
 * $Log: strftime.c,v $
 * Revision 1.3  1993/10/09  19:38:51  smace
 * Update to elm 2.4 pl23 release version
 *
 * Revision 5.8  1993/08/23  02:46:51  syd
 * Test ANSI_C, not __STDC__ (which is not set on e.g. AIX).
 * From: decwrl!uunet.UU.NET!fin!chip (Chip Salzenberg)
 *
 * Revision 5.7  1993/08/03  19:28:39  syd
 * Elm tries to replace the system toupper() and tolower() on current
 * BSD systems, which is unnecessary.  Even worse, the replacements
 * collide during linking with routines in isctype.o.  This patch adds
 * a Configure test to determine whether replacements are really needed
 * (BROKE_CTYPE definition).  The <ctype.h> header file is now included
 * globally through hdrs/defs.h and the BROKE_CTYPE patchup is handled
 * there.  Inclusion of <ctype.h> was removed from *all* the individual
 * files, and the toupper() and tolower() routines in lib/opt_utils.c
 * were dropped.
 * From: [email protected] (Chip Rosenthal)
 *
 * Revision 5.6  1993/08/03  19:20:31  syd
 * Implement new timezone handling.  New file lib/get_tz.c with new timezone
 * routines.  Added new TZMINS_USE_xxxxxx and TZNAME_USE_xxxxxx configuration
 * definitions.  Obsoleted TZNAME, ALTCHECK, and TZ_MINUTESWEST configuration
 * definitions.  Updated Configure.  Modified lib/getarpdate.c and
 * lib/strftime.c to use new timezone routines.
 * From: [email protected] (Chip Rosenthal)
 *
 * Revision 5.5  1993/06/10  03:17:45  syd
 * Change from TZNAME_MISSING to TZNAME
 * From: Syd via request from Dan Blanchard
 *
 * Revision 5.4  1993/05/08  19:56:45  syd
 * update to newer version
 * From: Syd
 *
 * Revision 5.3  1993/04/21  01:42:23  syd
 * avoid name conflicts on min and max
 *
 * Revision 5.2  1993/04/16  04:29:34  syd
 * attempt to bsdize a bit strftime
 * From: many via syd
 *
 * Revision 5.1  1993/01/27  18:52:15  syd
 * Initial checkin of contributed public domain routine.
 * This routine is provided as is and not covered by Elm Copyright.
 ****************************************************************************/

/*
 * strftime.c
 *
 * Public-domain relatively quick-and-dirty implementation of
 * ANSI library routine for System V Unix systems.
 *
 * It's written in old-style C for maximal portability.
 * However, since I'm used to prototypes, I've included them too.
 *
 * If you want stuff in the System V ascftime routine, add the SYSV_EXT define.
 * For extensions from SunOS, add SUNOS_EXT.
 * For stuff needed to implement the P1003.2 date command, add POSIX2_DATE.
 * For complete POSIX semantics, add POSIX_SEMANTICS.
 *
 * The code for %c, %x, and %X is my best guess as to what's "appropriate".
 * This version ignores LOCALE information.
 * It also doesn't worry about multi-byte characters.
 * So there.
 *
 * This file is also shipped with GAWK (GNU Awk), gawk specific bits of
 * code are included if GAWK is defined.
 *
 * Arnold Robbins
 * January, February, March, 1991
 * Updated March, April 1992
 * Updated May, 1993
 *
 * Fixes from [email protected]
 * February 1991, May 1992
 * Fixes from Tor Lillqvist [email protected]
 * May, 1993
 *
 * Fast-forward to July 2013...
 *
 * [email protected] copied these sources from:
 *
 * ftp://ftp-archive.freebsd.org/pub/FreeBSD-Archive/old-releases/i386/1.0-RELEASE/ports/elm/lib/strftime.c
 *
 * And made the following changes:
 *
 * Removed ancient non-ANSI decls. Added some headers to get it to
 * compile for me. Renamed functions to fit into my project. Replaced
 * hard tabs with 4 spaces. Added #undefs for all file-private #defines
 * to safe-ify inclusion from/with other files.
 *
 */

#include <time.h>
#include <string.h> /* strchr() and friends */
#include <stdio.h> /* snprintf() */
#include <ctype.h> /* toupper(), islower() */


#define HAVE_GET_TZ_NAME 0
#if HAVE_GET_TZ_NAME
extern char *get_tz_name();
#endif

#if !defined(BSD) && !defined(_MSC_VER)
extern void tzset (void);
#endif
static int weeknumber (const struct tm *timeptr, int firstweekday);

/* defaults: season to taste */
#define SYSV_EXT    1    /* stuff in System V ascftime routine */
#define SUNOS_EXT    1    /* stuff in SunOS strftime routine */
#define POSIX2_DATE    1    /* stuff in Posix 1003.2 date command */
#define VMS_EXT        1    /* include %v for VMS date format */

#if 0
#define POSIX_SEMANTICS    1    /* call tzset() if TZ changes */
#endif

#ifdef POSIX_SEMANTICS
#include <stdlib.h> /* malloc() and friends */
#endif

#if defined(POSIX2_DATE)
#if ! defined(SYSV_EXT)
#define SYSV_EXT    1
#endif
#if ! defined(SUNOS_EXT)
#define SUNOS_EXT    1
#endif
#endif

#if defined(POSIX2_DATE)
static int iso8601wknum(const struct tm *timeptr);
#endif

#undef strchr    /* avoid AIX weirdness */

#if 0
#ifdef __GNUC__
#define inline    __inline__
#else
#define inline    /**/
#endif
#endif

#define range(low, item, hi)    maximum(low, minimum(item, hi))

/* minimum --- return minimum of two numbers */

static inline int
minimum(int a, int b)
{
  return (a < b ? a : b);
}

/* maximum --- return maximum of two numbers */

static inline int
maximum(int a, int b)
{
  return (a > b ? a : b);
}

/* strftime --- produce formatted time */

fsl_size_t
fsl_strftime(char *s, fsl_size_t maxsize, const char *format, const struct tm *timeptr)
{
  enum {TBufLen = 100U};
  char *endp = s + maxsize;
  char *start = s;
  char tbuf[TBufLen];
  int i;
  static short first = 1;
#ifdef POSIX_SEMANTICS
  enum {TZBufLen = 200U};
  static char savetz[TZBufLen] = {0};
  char *tz;
#endif /* POSIX_SEMANTICS */

  /* various tables, useful in North America */
  static char *days_a[] = {
  "Sun", "Mon", "Tue", "Wed",
  "Thu", "Fri", "Sat"
  };
  static char *days_l[] = {
  "Sunday", "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday"
  };
  static char *months_a[] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  };
  static char *months_l[] = {
  "January", "February", "March", "April",
  "May", "June", "July", "August", "September",
  "October", "November", "December"
  };
  static char *ampm[] = { "AM", "PM" };

  if (s == NULL || format == NULL || timeptr == NULL || maxsize == 0)
    return 0;

  if (strchr(format, '%') == NULL && strlen(format) + 1 >= maxsize)
    return 0;

#ifndef POSIX_SEMANTICS
  if (first) {
    tzset();
    first = 0;
  }
#else    /* POSIX_SEMANTICS */
  tz = getenv("TZ");
  if (first) {
    if (tz != NULL) {
      fsl_strlcpy(savetz, tz, TZBufLen);
    }
    tzset();
    first = 0;
  }
  /* if we have a saved TZ, and it is different, recapture and reset */
  if(tz && (tz[0] != savetz[0] || strcmp(tz, savetz) != 0)) {
    i = strlen(tz) + 1;
    if (i < TZBufLen) {
      fsl_strlcpy(savetz, tz, TZBufLen);
    }
    tzset();
  }
#endif    /* POSIX_SEMANTICS */

  for (; *format && s < endp - 1; format++) {
    tbuf[0] = '\0';
    if (*format != '%') {
      *s++ = *format;
      continue;
    }
    again:
    switch (*++format) {
      case '\0':
        *s++ = '%';
        goto out;

      case '%':
        *s++ = '%';
        continue;

      case 'a':    /* abbreviated weekday name */
        if (timeptr->tm_wday < 0 || timeptr->tm_wday > 6)
          fsl_strlcpy(tbuf, "?", TBufLen);
        else
          fsl_strlcpy(tbuf, days_a[timeptr->tm_wday], TBufLen);
        break;

      case 'A':    /* full weekday name */
        if (timeptr->tm_wday < 0 || timeptr->tm_wday > 6)
          fsl_strlcpy(tbuf, "?", TBufLen);
        else
          fsl_strlcpy(tbuf, days_l[timeptr->tm_wday], TBufLen);
        break;

#ifdef SYSV_EXT
      case 'h':    /* abbreviated month name */
#endif
      case 'b':    /* abbreviated month name */
        if (timeptr->tm_mon < 0 || timeptr->tm_mon > 11)
          fsl_strlcpy(tbuf, "?", TBufLen);
        else
          fsl_strlcpy(tbuf, months_a[timeptr->tm_mon], TBufLen);
        break;

      case 'B':    /* full month name */
        if (timeptr->tm_mon < 0 || timeptr->tm_mon > 11)
          fsl_strlcpy(tbuf, "?", TBufLen);
        else
          fsl_strlcpy(tbuf, months_l[timeptr->tm_mon], TBufLen);
        break;

      case 'c':    /* appropriate date and time representation */
        snprintf(tbuf, TBufLen, "%s %s %2d %02d:%02d:%02d %d",
                 days_a[range(0, timeptr->tm_wday, 6)],
                 months_a[range(0, timeptr->tm_mon, 11)],
                 range(1, timeptr->tm_mday, 31),
                 range(0, timeptr->tm_hour, 23),
                 range(0, timeptr->tm_min, 59),
                 range(0, timeptr->tm_sec, 61),
                 timeptr->tm_year + 1900);
        break;

      case 'd':    /* day of the month, 01 - 31 */
        i = range(1, timeptr->tm_mday, 31);
        snprintf(tbuf, TBufLen, "%02d", i);
        break;

      case 'H':    /* hour, 24-hour clock, 00 - 23 */
        i = range(0, timeptr->tm_hour, 23);
        snprintf(tbuf, TBufLen, "%02d", i);
        break;

      case 'I':    /* hour, 12-hour clock, 01 - 12 */
        i = range(0, timeptr->tm_hour, 23);
        if (i == 0)
          i = 12;
        else if (i > 12)
          i -= 12;
        snprintf(tbuf, TBufLen, "%02d", i);
        break;

      case 'j':    /* day of the year, 001 - 366 */
        snprintf(tbuf, TBufLen, "%03d", timeptr->tm_yday + 1);
        break;

      case 'm':    /* month, 01 - 12 */
        i = range(0, timeptr->tm_mon, 11);
        snprintf(tbuf, TBufLen, "%02d", i + 1);
        break;

      case 'M':    /* minute, 00 - 59 */
        i = range(0, timeptr->tm_min, 59);
        snprintf(tbuf, TBufLen, "%02d", i);
        break;

      case 'p':    /* am or pm based on 12-hour clock */
        i = range(0, timeptr->tm_hour, 23);
        if (i < 12)
          fsl_strlcpy(tbuf, ampm[0], TBufLen);
        else
          fsl_strlcpy(tbuf, ampm[1], TBufLen);
        break;

      case 'S':    /* second, 00 - 61 */
        i = range(0, timeptr->tm_sec, 61);
        snprintf(tbuf, TBufLen, "%02d", i);
        break;

      case 'U':    /* week of year, Sunday is first day of week */
        snprintf(tbuf, TBufLen, "%d", weeknumber(timeptr, 0));
        break;

      case 'w':    /* weekday, Sunday == 0, 0 - 6 */
        i = range(0, timeptr->tm_wday, 6);
        snprintf(tbuf, TBufLen, "%d", i);
        break;

      case 'W':    /* week of year, Monday is first day of week */
        snprintf(tbuf, TBufLen, "%d", weeknumber(timeptr, 1));
        break;

      case 'x':    /* appropriate date representation */
        snprintf(tbuf, TBufLen, "%s %s %2d %d",
                 days_a[range(0, timeptr->tm_wday, 6)],
                 months_a[range(0, timeptr->tm_mon, 11)],
                 range(1, timeptr->tm_mday, 31),
                 timeptr->tm_year + 1900);
        break;

      case 'X':    /* appropriate time representation */
        snprintf(tbuf, TBufLen, "%02d:%02d:%02d",
                 range(0, timeptr->tm_hour, 23),
                 range(0, timeptr->tm_min, 59),
                 range(0, timeptr->tm_sec, 61));
        break;

      case 'y':    /* year without a century, 00 - 99 */
        i = timeptr->tm_year % 100;
        snprintf(tbuf, TBufLen, "%d", i);
        break;

      case 'Y':    /* year with century */
        snprintf(tbuf, TBufLen, "%d", 1900 + timeptr->tm_year);
        break;

#if HAVE_GET_TZ_NAME
      case 'Z':    /* time zone name or abbrevation */
        fsl_strlcpy(tbuf, get_tz_name(timeptr), TBufLen);
        break;
#endif

#ifdef SYSV_EXT
      case 'n':    /* same as \n */
        tbuf[0] = '\n';
        tbuf[1] = '\0';
        break;

      case 't':    /* same as \t */
        tbuf[0] = '\t';
        tbuf[1] = '\0';
        break;

      case 'D':    /* date as %m/%d/%y */
        fsl_strftime(tbuf, sizeof tbuf, "%m/%d/%y", timeptr);
        break;

      case 'e':    /* day of month, blank padded */
        snprintf(tbuf, TBufLen, "%2d", range(1, timeptr->tm_mday, 31));
        break;

      case 'r':    /* time as %I:%M:%S %p */
        fsl_strftime(tbuf, sizeof tbuf, "%I:%M:%S %p", timeptr);
        break;

      case 'R':    /* time as %H:%M */
        fsl_strftime(tbuf, sizeof tbuf, "%H:%M", timeptr);
        break;

      case 'T':    /* time as %H:%M:%S */
        fsl_strftime(tbuf, sizeof tbuf, "%H:%M:%S", timeptr);
        break;
#endif

#ifdef SUNOS_EXT
      case 'k':    /* hour, 24-hour clock, blank pad */
        snprintf(tbuf, TBufLen, "%2d", range(0, timeptr->tm_hour, 23));
        break;

      case 'l':    /* hour, 12-hour clock, 1 - 12, blank pad */
        i = range(0, timeptr->tm_hour, 23);
        if (i == 0)
          i = 12;
        else if (i > 12)
          i -= 12;
        snprintf(tbuf, TBufLen, "%2d", i);
        break;
#endif


#ifdef VMS_EXT
      case 'v':    /* date as dd-bbb-YYYY */
        snprintf(tbuf, TBufLen, "%2d-%3.3s-%4d",
                 range(1, timeptr->tm_mday, 31),
                 months_a[range(0, timeptr->tm_mon, 11)],
                 timeptr->tm_year + 1900);
        for (i = 3; i < 6; i++)
          if (islower((int)tbuf[i]))
            tbuf[i] = toupper((int)tbuf[i]);
        break;
#endif


#ifdef POSIX2_DATE
      case 'C':
        snprintf(tbuf, TBufLen, "%02d", (timeptr->tm_year + 1900) / 100);
        break;


      case 'E':
      case 'O':
        /* POSIX locale extensions, ignored for now */
        goto again;

      case 'V':    /* week of year according ISO 8601 */
#if defined(GAWK) && defined(VMS_EXT)
        {
          extern int do_lint;
          extern void warning();
          static int warned = 0;

          if (! warned && do_lint) {
            warned = 1;
            warning(
                    "conversion %%V added in P1003.2/11.3; for VMS style date, use %%v");
          }
        }
#endif
        snprintf(tbuf, TBufLen, "%d", iso8601wknum(timeptr));
        break;

      case 'u':
        /* ISO 8601: Weekday as a decimal number [1 (Monday) - 7] */
        snprintf(tbuf, TBufLen, "%d", timeptr->tm_wday == 0 ? 7 :
                 timeptr->tm_wday);
        break;
#endif    /* POSIX2_DATE */
      default:
        tbuf[0] = '%';
        tbuf[1] = *format;
        tbuf[2] = '\0';
        break;
    }
    i = strlen(tbuf);
    if (i){
      if (s + i < endp - 1) {
        fsl_strlcpy(s, tbuf, TBufLen);
        s += i;
      } else return 0;
      /* reminder: above IF originally had ambiguous else
         placement (no braces).  This placement _appears_ to be
         correct.*/
    }
  }
  out:
  if (s < endp && *format == '\0') {
    *s = '\0';
    return (s - start);
  } else
    return 0;
}

#ifdef POSIX2_DATE
/* iso8601wknum --- compute week number according to ISO 8601 */

static int
iso8601wknum(const struct tm *timeptr)
{
  /*
   * From 1003.2 D11.3:
   *    If the week (Monday to Sunday) containing January 1
   *    has four or more days in the new year, then it is week 1;
   *    otherwise it is week 53 of the previous year, and the
   *    next week is week 1.
   *
   * ADR: This means if Jan 1 was Monday through Thursday,
   *    it was week 1, otherwise week 53.
   */

  int simple_wknum, jan1day, diff, ret;

  /* get week number, Monday as first day of the week */
  simple_wknum = weeknumber(timeptr, 1) + 1;

  /*
   * With thanks and tip of the hatlo to [email protected]
   *
   * What day of the week does January 1 fall on?
   * We know that
   *    (timeptr->tm_yday - jan1.tm_yday) MOD 7 ==
   *        (timeptr->tm_wday - jan1.tm_wday) MOD 7
   * and that
   *     jan1.tm_yday == 0
   * and that
   *     timeptr->tm_wday MOD 7 == timeptr->tm_wday
   * from which it follows that. . .
   */
  jan1day = timeptr->tm_wday - (timeptr->tm_yday % 7);
  if (jan1day < 0)
    jan1day += 7;

  /*
   * If Jan 1 was a Monday through Thursday, it was in
   * week 1.  Otherwise it was last year's week 53, which is
   * this year's week 0.
   */
  if (jan1day >= 1 && jan1day <= 4)
    diff = 0;
  else
    diff = 1;
  ret = simple_wknum - diff;
  if (ret == 0)    /* we're in the first week of the year */
    ret = 53;
  return ret;
}
#endif

/* weeknumber --- figure how many weeks into the year */

/* With thanks and tip of the hatlo to [email protected] */

static int
weeknumber(const struct tm *timeptr, int firstweekday)
{
  if (firstweekday == 0)
    return (timeptr->tm_yday + 7 - timeptr->tm_wday) / 7;
  else
    return (timeptr->tm_yday + 7 -
            (timeptr->tm_wday ? (timeptr->tm_wday - 1) : 6)) / 7;
}

#undef SYSV_EXT
#undef SUNOS_EXT
#undef POSIX2_DATE
#undef VMS_EXT
#undef POSIX_SEMANTICS
#undef adddecl
#undef inline
#undef range
#undef maximum
#undef minimum
#undef HAVE_GET_TZ_NAME
#undef GAWK


/**
   A convenience form of fsl_strftime() which takes its timestamp in
   the form of a Unix Epoc time.
*/
fsl_size_t fsl_strftime_unix(char * dest, fsl_size_t destLen, char const * format,
                             fsl_time_t epochTime, bool convertToLocal){
  time_t orig = (time_t)epochTime;
  struct tm * tim = convertToLocal ? localtime(&orig) : gmtime(&orig);
  return fsl_strftime( dest, destLen, format, tim );
}
/* end of file src/strftime.c */
/* start of file src/tag.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  *****************************************************************************
  This file implements tag-related parts of the library.
*/
#include <assert.h>

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


void fsl_card_T_clean(fsl_card_T *t){
  if(t){
    fsl_free(t->uuid);
    t->uuid = NULL;
    fsl_free(t->name);
    t->name = NULL;
    fsl_free(t->value);
    t->value = NULL;
    *t = fsl_card_T_empty;
  }
}

void fsl_card_T_free(fsl_card_T *t){
  if(t){
    fsl_card_T_clean(t);
    fsl_free(t);
  }
}

fsl_card_T * fsl_card_T_malloc(fsl_tagtype_e tagType,
                               char const * uuid,
                               char const * name,
                               char const * value){
  fsl_card_T * t;
  int const uuidLen = uuid ? fsl_is_uuid(uuid) : 0;
  if(uuid && !uuidLen) return NULL;
  t = (fsl_card_T *)fsl_malloc(sizeof(fsl_card_T));
  if(t){
    int rc = 0;
    *t = fsl_card_T_empty;
    t->type = tagType;
    if(uuid && *uuid){
      t->uuid = fsl_strndup(uuid, uuidLen);
      if(!t->uuid) rc = FSL_RC_OOM;
    }
    if(!rc && name && *name){
      t->name = fsl_strdup(name);
      if(!t->name){
        rc = FSL_RC_OOM;
      }
    }
    if(!rc && value && *value){
      t->value = fsl_strdup(value);
      if(!t->value){
        rc = FSL_RC_OOM;
      }
    }
    if(rc){
      fsl_card_T_free(t);
      t = NULL;
    }
  }
  return t;
}

fsl_id_t fsl_tag_id( fsl_cx * const f, char const * tag, bool create ){
  fsl_db * const db = fsl_needs_repo(f);
  fsl_id_t id = 0;
  int rc;
  if(!db) return -1;
  else if(!tag || !*tag){
    fsl_cx_err_set(f, tag ? FSL_RC_RANGE : FSL_RC_MISUSE,
                   "Invalid tag name.");
    return -1;
  }
  rc = fsl_db_get_id( db, &id,
                         "SELECT tagid FROM {{dbname.repo}}.tag WHERE tagname=%Q",
                         tag);
  if(!rc && (0==id) && create){
    /* Not found - create one. */
    rc = fsl_db_exec(db, "INSERT INTO {{dbname.repo}}.tag(tagname) VALUES(%Q)",
                     tag);
    if(!rc) id = fsl_db_last_insert_id(db);
  }

  if(rc){
    assert(0==id);
    fsl_cx_uplift_db_error( f, db );
    id = -1;
  }
  return id;
}

int fsl__tag_propagate(fsl_cx * const f, fsl_tagtype_e tagType,
                      fsl_id_t pid, fsl_id_t tagid,
                      fsl_id_t origId, const char *zValue,
                      double mtime){
  int rc;
  fsl__pq queue = fsl__pq_empty     /* Queue of artifacts to be tagged */;
  fsl_stmt s = fsl_stmt_empty     /* Query the children of :pid to which to propagate */;
  fsl_stmt ins = fsl_stmt_empty   /* INSERT INTO tagxref */;
  fsl_stmt eventupdate = fsl_stmt_empty  /* UPDATE event */;
  fsl_db * const db = fsl_needs_repo(f);

  assert(FSL_TAGTYPE_CANCEL==tagType || FSL_TAGTYPE_PROPAGATING==tagType);
  assert(f);
  assert(db);
  assert(pid>0);
  assert(tagid>0);

  if((pid<=0 || tagid<=0)
     ||(FSL_TAGTYPE_PROPAGATING!=tagType && FSL_TAGTYPE_CANCEL!=tagType)
     || (FSL_TAGTYPE_PROPAGATING==tagType && origId<=0)){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid tag propagation request: "
                          "tagType=%d pid=%" FSL_ID_T_PFMT
                          " tagid=%" FSL_ID_T_PFMT
                          " origId=%" FSL_ID_T_PFMT ".",
                          (int)tagType, pid, tagid, origId);
  }
  else if(!db) return FSL_RC_NOT_A_REPO;

  rc = fsl__pq_insert(&queue, pid, 0.0, NULL);
  if(rc) return rc;

  rc = fsl_db_prepare(db, &s,
                      "SELECT cid, plink.mtime,"
                      "       coalesce(srcid=0 AND "
                      "       tagxref.mtime<:mtime, %d) AS doit"
                      "  FROM {{dbname.repo}}.plink AS plink LEFT JOIN {{dbname.repo}}.tagxref AS tagxref "
                      "       ON cid=rid AND tagid=%"FSL_ID_T_PFMT
                      " WHERE pid=:pid AND isprim",
                      tagType==FSL_TAGTYPE_PROPAGATING,
                      (fsl_id_t)tagid);
  if(rc) goto end;
  rc = fsl_stmt_bind_double_name(&s, ":mtime", mtime);
  if(rc) goto end;

  if(FSL_TAGTYPE_PROPAGATING==tagType){
    /* Set the propagated tag marker on artifact :rid */
    assert(origId>0);
    rc = fsl_db_prepare(db, &ins,
                        "REPLACE INTO {{dbname.repo}}.tagxref("
                        "  tagid, tagtype, srcid, "
                        "  origid, value, mtime, rid"
                        ") VALUES("
                        "%"FSL_ID_T_PFMT"," /* tagid */
                        "%d,"  /*tagtype*/
                        "0," /*srcid*/
                        "%"FSL_ID_T_PFMT"," /*origId */
                        "%Q," /* zValue */
                        ":mtime,"
                        ":rid"
                        ")",
                        (fsl_id_t)tagid,
                        (int)FSL_TAGTYPE_PROPAGATING,
                        (fsl_id_t)origId, zValue);
    if(!rc) rc = fsl_stmt_bind_double_name(&ins, ":mtime", mtime);
  }else{
    /* Remove all references to the tag from checkin :rid */
    zValue = NULL;
    rc = fsl_db_prepare(db, &ins,
                        "DELETE FROM {{dbname.repo}}.tagxref WHERE "
                        "tagid=%"FSL_ID_T_PFMT
                        " AND rid=:rid", (fsl_id_t)tagid);
  }
  if(rc) goto end;
  if( tagid==FSL_TAGID_BGCOLOR ){
    rc = fsl_db_prepare(db, &eventupdate,
                        "UPDATE {{dbname.repo}}.event SET bgcolor=%Q "
                        "WHERE objid=:rid", zValue);
    if(rc) goto end;
  }

  while( 0 != (pid = fsl__pq_extract(&queue,NULL))){
    fsl_stmt_bind_id_name(&s, ":pid", pid);
#if 0
    MARKER(("Walking over pid %"FSL_ID_T_PFMT
            ", queue.used=%"FSL_SIZE_T_PFMT"\n", pid, queue.used));
#endif
    while( !rc && (fsl__cx_stmt_step_each(f, &s, &rc)) ){
      int32_t const doit = fsl_stmt_g_int32(&s, 2);
      if(doit){
        fsl_id_t cid = fsl_stmt_g_id(&s, 0);
        double mtime = fsl_stmt_g_double(&s,1);
        assert(cid>0);
        assert(mtime>0.0);
        rc = fsl__pq_insert(&queue, cid, mtime, NULL);
        if(!rc) rc = fsl_stmt_bind_id_name(&ins, ":rid", cid);
        if(rc) goto end;
        else {
          rc = fsl_stmt_step(&ins);
          if(FSL_RC_STEP_DONE != rc) goto end;
          rc = 0;
        }
        fsl_stmt_reset(&ins);
        if( FSL_TAGID_BGCOLOR == tagid ){
          rc = fsl_stmt_bind_id_name(&eventupdate, ":rid", cid);
          if(!rc){
            rc = fsl_stmt_step(&eventupdate);
            if(FSL_RC_STEP_DONE != rc) goto end;
            rc = 0;
          }
          fsl_stmt_reset(&eventupdate);
        }else if( FSL_TAGID_BRANCH == tagid ){
          rc = fsl__leaf_eventually_check(f, cid);
        }
      }
    }
    fsl_stmt_reset(&s);
  }
  end:
  fsl_stmt_finalize(&s);
  fsl_stmt_finalize(&ins);
  fsl_stmt_finalize(&eventupdate);
  fsl__pq_clear(&queue);
  if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  return rc;
}

int fsl__tag_propagate_all(fsl_cx * const f, fsl_id_t pid){
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  fsl_db * const db = fsl_cx_db_repo(f);
  if(!f) return FSL_RC_MISUSE;
  else if(pid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE, "Cannot propagate tags "
                          "from invalid rid %" FSL_ID_T_PFMT ".", pid);
  }
  assert(db);
  rc = fsl_db_prepare(db, &q,
                      "SELECT tagid, tagtype, mtime, "
                      "value, origid FROM {{dbname.repo}}.tagxref"
                      " WHERE rid=%"FSL_ID_T_PFMT,
                      pid);
  while( !rc && (fsl__cx_stmt_step_each(f, &q, &rc)) ){
    fsl_id_t const tagid = fsl_stmt_g_id(&q, 0);
    int32_t tagtype = fsl_stmt_g_int32(&q, 1);
    double const mtime = fsl_stmt_g_double(&q, 2);
    const char *zValue = fsl_stmt_g_text(&q, 3, NULL);
    fsl_id_t const origid = fsl_stmt_g_id(&q, 4);
    if( FSL_TAGTYPE_ADD==tagtype ) tagtype = FSL_TAGTYPE_CANCEL
      /* For propagating purposes */;
    rc = fsl__tag_propagate(f, tagtype, pid, tagid,
                           origid, zValue, mtime);
  }
  fsl_stmt_finalize(&q);
  if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  return rc;
}


int fsl__tag_insert( fsl_cx * const f, fsl_tagtype_e tagtype,
                    char const * zTag, char const * zValue,
                    fsl_id_t srcId, double mtime,
                    fsl_id_t rid, fsl_id_t *outRid ){
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  fsl_stmt q = fsl_stmt_empty;
  fsl_id_t tagid;
  int rc = 0;
  char const * zCol;
  if(!f || !zTag) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  tagid = fsl_tag_id(f, zTag, true);
  if(tagid<0){
    assert(f->error.code);
    return f->error.code;
  }
  if( mtime<=0.0 ){
    mtime = fsl_db_julian_now(db);
    if(mtime<0){
      rc = fsl_cx_uplift_db_error2(f, db, FSL_RC_DB);
      return f->error.code ? rc
        : fsl_cx_err_set(f, rc, "Could not get the current time "
                         "for tag %s on rid %" FSL_ID_T_PFMT ".",
                         zTag, rid);
    }
  }

  rc = fsl_db_prepare(db, &q, /* TODO: cached query */
                      "SELECT 1 FROM {{dbname.repo}}.tagxref"
                      " WHERE tagid=%"FSL_ID_T_PFMT
                      "   AND rid=%"FSL_ID_T_PFMT
                      "   AND mtime>=?",
                      (fsl_id_t)tagid, (fsl_id_t)rid);
  if(!rc) rc = fsl_stmt_bind_double(&q, 1, mtime);
  if(!rc) rc = fsl_stmt_step(&q);
  if( FSL_RC_STEP_ROW == rc ){
    /*
      Another entry that is more recent already exists. Do nothing.

      Reminder: the above policy is from the original implementation.
      We might(?) want to return FSL_RC_ACCESS or
      FSL_RC_ALREADY_EXISTS here. The current behaviour seems harmless
      enough, though.

      2026-09: after having had to deal with similar cases in
      fossil(1) since the above comments were written, the do-nothing
      policy most definitely seems like the right thing.
    */
    if(outRid) *outRid = tagid;
    fsl_stmt_finalize(&q);
    return 0;
  }else if(FSL_RC_STEP_DONE != rc){
    goto end;
  }
  fsl_stmt_finalize(&q);
  rc = fsl_db_prepare(db, &q,
                      "REPLACE INTO {{dbname.repo}}.tagxref"
                      "(tagid,tagtype,srcId,origid,value,mtime,rid) "
                      "VALUES("
                      "%"FSL_ID_T_PFMT"," /* tagid */
                      "%d," /* tagtype */
                      "%"FSL_ID_T_PFMT"," /* srcid */
                      "%"FSL_ID_T_PFMT"," /* rid */
                      "%Q," /* zValue */
                      "?," /* mtime */
                      "%"FSL_ID_T_PFMT")" /* rid again */,
                      (fsl_id_t)tagid, (int)tagtype,
                      (fsl_id_t)srcId,
                      (fsl_id_t)rid, zValue, (fsl_id_t)rid
                      );
  if(!rc) fsl_stmt_bind_double(&q, 1, mtime);
  if(!rc) rc = fsl_stmt_step(&q);
  if(FSL_RC_STEP_DONE != rc) goto end;
  rc = 0;
  fsl_stmt_finalize(&q);

  if(FSL_TAGID_BRANCH == tagid ){
    rc = fsl__leaf_eventually_check(f, rid);
    if(rc) goto end;
  }
#if 0
  /* Historical: we have valid use cases for the
     value here.
  */
  else if(FSL_TAGTYPE_CANCEL==tagtype){
    zValue = NULL;
  }
#endif

  zCol = NULL;
  switch(tagid){
    case FSL_TAGID_BGCOLOR:
      zCol = "bgcolor";
      break;
    case FSL_TAGID_COMMENT:
      zCol = "ecomment";
      break;
    case FSL_TAGID_USER: {
      zCol = "euser";
      break;
    }
    case FSL_TAGID_PRIVATE:
      rc = fsl_db_exec(db,
                       "INSERT OR IGNORE INTO "
                       "{{dbname.repo}}.private(rid) VALUES"
                       "(%"FSL_ID_T_PFMT");",
                       (fsl_id_t)rid );
      if(rc) goto end;
      else break;
  }
  if( zCol ){
    rc = fsl_db_exec(db, "UPDATE {{dbname.repo}}.event SET %s=%Q "
                     "WHERE objid=%"FSL_ID_T_PFMT,
                     zCol, zValue, (fsl_id_t)rid);
    if(rc) goto end;
    if( tagid==FSL_TAGID_COMMENT && zValue ){
      rc = fsl__backlink_extract(f, zValue, FSL_BKLNK_MT_NONE, rid,
                                 FSL_BKLNK_COMMENT, mtime, true);
      if(rc) goto end;
    }
  }

  if( FSL_TAGID_DATE == tagid ){
    rc = fsl_db_exec(db, "UPDATE {{dbname.repo}}.event "
                     "SET mtime=julianday(%Q),"
                     "    omtime=coalesce(omtime,mtime)"
                     "WHERE objid=%"FSL_ID_T_PFMT,
                     zValue, (fsl_id_t)rid);
    if(rc) goto end;
  }
  if( FSL_TAGTYPE_ADD == tagtype ) tagtype = FSL_TAGTYPE_CANCEL
    /* For propagation purposes */;
  rc = fsl__tag_propagate(f, tagtype, rid, tagid,
                         rid, zValue, mtime);
  end:
  fsl_stmt_finalize(&q);
  if(0==rc && outRid) *outRid = tagid;
  else if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  return rc;
}

int fsl_tag_sym( fsl_cx * f,
                 fsl_tagtype_e tagType,
                 char const * symToTag,
                 char const * tagName,
                 char const * tagValue,
                 char const * userName,
                 double mtime,
                 fsl_id_t * outId ){
  if(!tagName || !symToTag || !userName) return FSL_RC_MISUSE;
  else if(!*tagName || !*userName || !*symToTag){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Cannot tag: the %s may not be empty.",
                          !*tagName ? "tag name"
                          : (!*userName ? "user name"
                             : "artifact name"));
  }
  else{
    fsl_id_t resolvedRid = 0;
    int rc;
    rc = fsl_sym_to_rid( f, symToTag, FSL_SATYPE_ANY, &resolvedRid );
    if(!rc){
      assert(resolvedRid>0);
      rc = fsl_tag_an_rid(f, tagType, resolvedRid,
                          tagName, tagValue, userName,
                          mtime, outId);
    }
    return rc;
  }
}

int fsl_tag_an_rid( fsl_cx * const f,
                    fsl_tagtype_e tagType,
                    fsl_id_t idToTag,
                    char const * tagName,
                    char const * tagValue,
                    char const * userName,
                    double mtime,
                    fsl_id_t * outId ){
  fsl_db * const dbR = fsl_cx_db_repo(f);
  fsl_deck c = fsl_deck_empty;
  char * resolvedUuid = NULL;

  int rc;
  if(!f || !tagName || !userName) return FSL_RC_MISUSE;
  else if(idToTag<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE, "Cannot tag invalid rid %"
                          FSL_ID_T_PFMT ".", idToTag);
  }
  else if(!*tagName || !*userName){
    return fsl_cx_err_set(f, FSL_RC_RANGE, "Cannot tag rid %"
                          FSL_ID_T_PFMT ": the tag name and user name "
                          "may not be empty.", idToTag);
  }
  else if(!dbR){
    fsl_needs_repo(f) /* sets f's error state */;
    return FSL_RC_NOT_A_REPO;
  }

  if(mtime<=0) mtime = fsl_db_julian_now(dbR);

  resolvedUuid = fsl_rid_to_uuid(f, idToTag);
  if(!resolvedUuid){
    return f->error.code
      ? f->error.code
      : fsl_cx_err_set(f, FSL_RC_RANGE,
                       "Could not resolve UUID for "
                       "rid %"FSL_ID_T_PFMT".",
                       (fsl_id_t)idToTag);
  }
  assert(fsl_is_uuid(resolvedUuid));

#if 0
  tagRid = fsl_tag_id(f, tagName, 1);
  if(tagRid<=0){
    rc = f->error.rc
      ? f->error.rc
      : fsl_cx_err_set(f, FSL_RC_ERROR,
                       "Unknown error while fetching "
                       "ID for tag [%s].",
                       tagName);
    goto end;
  }
#endif

  fsl_deck_init(f, &c, FSL_SATYPE_CONTROL);
  rc = fsl_deck_T_add( &c, tagType, resolvedUuid,
                       tagName, tagValue );
  if(rc) goto end;

  rc = fsl_deck_D_set( &c, mtime );
  if(rc) goto end;

  rc = fsl_deck_U_set( &c, userName );
  if(rc) goto end;

  rc = fsl_deck_save( &c, fsl_content_is_private(f, idToTag) );
  end:
  fsl_free(resolvedUuid);
  if(!rc && outId){
    assert(c.rid>0);
    *outId = c.rid;
  }
  fsl_deck_clean(&c);
  return rc;
}

bool fsl_rid_has_tag_id(fsl_cx * f, fsl_id_t rid, fsl_id_t tagId){
  fsl_stmt * const q = fsl__cx_stmt(f, fsl__cx_stmt_e_ridHasTagId);
  if( !q ) return false;
  bool rv = false;
  int const rc = fsl_stmt_bind_step_v2(q, "RR", rid, tagId);
  if( FSL_RC_STEP_ROW==rc ){
    rv = true;
  }else if( FSL_RC_STEP_DONE!=rc ){
    fsl_cx_uplift_db_error2(f, q->db, rc);
  }
  fsl__cx_stmt_yield(f, q);
  return rv;
}

bool fsl_rid_has_tag(fsl_cx * f, fsl_id_t rid, char const *zTag){
  fsl_id_t tid = fsl_tag_id(f, zTag, false);
  if( tid<=0 ) return false;
  return fsl_rid_has_tag_id(f, rid, tid);
}

int fsl_branch_create(fsl_cx * f, fsl_branch_opt const * opt, fsl_id_t * newRid ){
  int rc;
  fsl_deck parent = fsl_deck_empty;
  fsl_deck deck = fsl_deck_empty;
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  char const * user;
  char const * mainBranch = NULL;
  char isPrivate;
  if(!f || !opt) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  else if(!opt->name || !*opt->name){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Branch name cannot be empty.");
  }
  else if(opt->basisRid<=0){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Invalid basis rid %" FSL_ID_T_PFMT
                          " for new branch [%s].",
                          opt->basisRid, opt->name);
  }
  else if(! (user = opt->user ? opt->user : f->db.repo.user)){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Could not determine fossil user name "
                          "for new branch [%s].", opt->name);
  }
  rc = fsl_branch_main(f, &mainBranch, false);
  if(rc) return rc;
  if( fsl_db_exists(db,
                    "SELECT 1 FROM {{dbname.repo}}.leaf AS l"
                    " WHERE coalesce((SELECT value FROM {{dbname.repo}}.tagxref"
                    "   WHERE rid=l.rid AND tagid=%d AND tagtype>0),%Q)=%Q"
                    " AND NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.tagxref"
                    "   WHERE rid=l.rid AND tagid=%d AND tagtype>0)",
                    FSL_TAGID_BRANCH, mainBranch, opt->name,
                    FSL_TAGID_CLOSED) ){
    return fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                          "Branch [%s] already exists.", opt->name);
  }


  rc = fsl_deck_load_rid(f, &parent, opt->basisRid, FSL_SATYPE_CHECKIN);
  if(rc) goto end;

  assert(parent.rid==opt->basisRid);

  fsl_deck_init(f, &deck, FSL_SATYPE_CHECKIN);

  rc = fsl_deck_D_set(&deck, opt->mtime>0 ? opt->mtime : fsl_db_julian_now(db));
  if(rc) goto end;

  /*
    We cannot simply transfer the list of F-cards from parent to deck
    because their content pointers (when the deck is parsed using
    fsl_deck_parse2()) points to memory in parent.content.

    Prior names are not copied: a branch renames nothing, and the
    parent's prior names belong to the check-in which did the
    renaming. fossil's "branch new" leaves them out too.
  */
  if(parent.B.uuid && fsl_repo_forbids_delta_manifests(f)){
    /* Write a full manifest, as check-ins do: fsl_deck_F_next()
       merges in the parent's baseline and skips deleted files. */
    fsl_card_F const * fc = NULL;
    rc = fsl_deck_F_rewind(&parent);
    fsl_deck_F_each(&parent, fc, rc){
      rc = fsl__deck_F_add2(&deck, fc->name, fc->uuid, fc->perm, NULL,
                            false);
    }
    if(rc) goto end;
  }else{
    if(parent.B.uuid){
      rc = fsl_deck_B_set(&deck, parent.B.uuid);
      if(rc) goto end;
    }
    for( fsl_size_t i = 0; i < parent.F.used; ++i){
      fsl_card_F const * fc = &parent.F.list[i];
      rc = fsl__deck_F_add2(&deck, fc->name, fc->uuid, fc->perm, NULL,
                            false);
      if(rc) goto end;
    }
  }

  rc = fsl_deck_U_set(&deck, user);
  if(rc) goto end;

  rc = fsl_deck_P_add_rid(&deck, parent.rid);
  if(rc) goto end;

  if(opt->comment && *opt->comment){
    rc = fsl_deck_C_set(&deck, opt->comment, -1);
  }else{
    fsl_b * const c = fsl_cx_b_borrow(f);
    rc = c
      ? fsl_b_appendf(c, "Created branch [%s].", opt->name)
      : f->error.code;
    if(!rc){
      rc = fsl_deck_C_set(&deck, (char const *)c->mem, (fsl_int_t)c->used);
    }
    fsl_cx_b_return(f, c);
  }
  if(rc) goto end;


#if 0
  /* This adds almost 18MB of allocations to my small test code! */
  if(deck.F.list.used){
    rc = fsl_deck_R_calc(&deck);
    if(rc) goto end;
  }
#else
  rc = fsl__deck_R_set(&deck, parent.R);
  if(rc) goto end;
#endif

  isPrivate = fsl_content_is_private(f, parent.rid) ? 1 : opt->isPrivate;
#if 0
  /* At one point in history private artifacts were tagged as
     such. That is no longer the case. */
  if(isPrivate){
    rc = fsl_deck_T_add(&deck, FSL_TAGTYPE_ADD,
                        NULL, "private", NULL);
    if(rc) goto end;
  }
#endif

  if(opt->bgColor && ('#'==*opt->bgColor)){
    rc = fsl_deck_T_add(&deck, FSL_TAGTYPE_ADD, NULL, "bgcolor",
                        opt->bgColor);
    if(rc) goto end;
  }

  rc = fsl_deck_T_add(&deck, FSL_TAGTYPE_PROPAGATING,
                      NULL, "branch", opt->name);
  if(!rc){
    /* Add tag named sym-BRANCHNAME... */
    fsl_b * const buf = fsl_cx_b_borrow(f);
    rc = buf ? fsl_b_appendf(buf, "sym-%s", opt->name) : f->error.code;
    if(!rc){
      rc = fsl_deck_T_add(&deck, FSL_TAGTYPE_PROPAGATING,
                          NULL, fsl_b_cstr(buf), NULL);
    }
    fsl_cx_b_return(f, buf);
  }
  if(rc) goto end;

#if 1
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if(rc) goto end;
  else{
    /* cancel all other symbolic tags (branch tags) */
    fsl_stmt q = fsl_stmt_empty;
    rc = fsl_db_prepare(db, &q,
                        "SELECT tagname FROM {{dbname.repo}}.tagxref AS tagxref, {{dbname.repo}}.tag AS tag"
                        " WHERE tagxref.rid=%"FSL_ID_T_PFMT
                        " AND tagxref.tagid=tag.tagid"
                        "   AND tagtype>0 AND tagname GLOB 'sym-*'"
                        " ORDER BY tagname",
                        (fsl_id_t)parent.rid);
    /* On error, fall through to end the transaction. */
    while( !rc && fsl__cx_stmt_step_each(f, &q, &rc) ){
      const char *zTag = fsl_stmt_g_text(&q, 0, NULL);
      rc = fsl_deck_T_add(&deck, FSL_TAGTYPE_CANCEL,
                          NULL, zTag, "cancelled by branch.");
      if(rc) break;
    }
    fsl_stmt_finalize(&q);
    if(!rc){
      rc = fsl_deck_save(&deck, isPrivate);
      if(!rc){
        assert(deck.rid>0);
        rc = fsl_db_exec(db, "INSERT OR IGNORE INTO "
                         "{{dbname.repo}}.unsent VALUES(%"FSL_ID_T_PFMT")",
                         (fsl_id_t)deck.rid);
        if(!rc){
          /* Make the parent a delta of this one. */
          rc = fsl__content_deltify(f, parent.rid, deck.rid, 0);
        }
      }
    }
    if(rc) fsl_cx_txn_end_v2(f, false, false);
    else rc = fsl_cx_txn_end_v2(f, true, false);
    if(rc) goto end;
  }
#else
  /* Only for testing */
  MARKER(("Generating (not saving) branch artifact:\n"));
  rc = fsl_deck_unshuffle(&deck, 0);
  if(rc) goto end;
  rc = fsl_deck_output(&deck, fsl_output_f_FILE, stdout, &f->error);
  if(rc) goto end;
#endif

  end:
  if(!rc && newRid) *newRid = deck.rid;
  else if(rc && !f->error.code){
    if(db->error.code) fsl_cx_uplift_db_error(f,db);
  }
  fsl_deck_finalize(&parent);
  fsl_deck_finalize(&deck);
  return rc;
}

#undef MARKER
/* end of file src/tag.c */
/* start of file src/ticket.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*************************************************************************
  This file implements ticket-related parts of the library.
*/
#include <assert.h>
#include <stdlib.h> /* bsearch() */
#include <string.h> /* memcmp() */

/* Length of the run of whitespace and SQL comments at z. */
static fsl_size_t fsl__tkt_sql_skip(char const * z){
  char const * const z0 = z;
  for(;;){
    if( fsl_isspace(*z) ) ++z;
    else if( '-'==z[0] && '-'==z[1] ){
      while( *z && '\n'!=*z ) ++z;
    }else if( '/'==z[0] && '*'==z[1] ){
      z += 2;
      while( *z && !('*'==z[0] && '/'==z[1]) ) ++z;
      if( *z ) z += 2;
    }else break;
  }
  return (fsl_size_t)(z - z0);
}

/* If z starts with keyword zKw (case-insensitive, then a non-word
   character), returns its length, else 0. */
static fsl_size_t fsl__tkt_sql_kw(char const * z, char const * zKw){
  fsl_size_t const n = fsl_strlen(zKw);
  return (0==fsl_strnicmp(z, zKw, n) && !fsl_isalnum(z[n]) && '_'!=z[n])
    ? n : 0;
}

/* Length of the (possibly quoted) identifier at z, or 0. */
static fsl_size_t fsl__tkt_sql_ident(char const * z){
  char const * const z0 = z;
  if( '"'==*z || '`'==*z || '['==*z ){
    char const q = ('['==*z) ? ']' : *z;
    for( ++z; *z && *z!=q; ++z ){}
    return *z ? (fsl_size_t)(z + 1 - z0) : 0;
  }
  while( fsl_isalnum(*z) || '_'==*z ) ++z;
  return (fsl_size_t)(z - z0);
}

int fsl__ticket_schema_qualify(fsl_db * const db, char const * zIn,
                               fsl_b * const out){
  char const * const zSchema = fsl__db_schema(db, FSL_DBROLE_REPO);
  char const * z = zIn;
  char const * zCopied = zIn;
  int rc = 0;
  while( 0==rc && *z ){
    char const c = *z;
    if( '\''==c || '"'==c || '`'==c || '['==c ){
      /* A string or quoted identifier: copy it as is. */
      char const q = ('['==c) ? ']' : c;
      for( ++z; *z; ++z ){
        if( *z==q ){
          if( '\''==q && '\''==z[1] ){ ++z; continue; }
          ++z;
          break;
        }
      }
      continue;
    }else if( ('-'==c && '-'==z[1]) || ('/'==c && '*'==z[1]) ){
      z += fsl__tkt_sql_skip(z);
      continue;
    }else if( (z==zIn || !(fsl_isalnum(z[-1]) || '_'==z[-1]))
              && fsl__tkt_sql_kw(z, "CREATE") ){
      /* CREATE [UNIQUE] TABLE|INDEX|VIEW|TRIGGER [IF NOT EXISTS]
         [schema.]name. A rebuild drops the ticket tables, and their
         indexes and triggers with them, but not a view, so one made
         without IF NOT EXISTS is dropped here first. */
      char const * p = z + 6;
      fsl_size_t n;
      bool isView = false;
      bool ifNotExists = false;
      p += fsl__tkt_sql_skip(p);
      if( (n = fsl__tkt_sql_kw(p, "UNIQUE")) ) p += n + fsl__tkt_sql_skip(p + n);
      if( (n = fsl__tkt_sql_kw(p, "TABLE")) || (n = fsl__tkt_sql_kw(p, "INDEX"))
          || (n = fsl__tkt_sql_kw(p, "TRIGGER"))
          || ((n = fsl__tkt_sql_kw(p, "VIEW")) && (isView = true)) ){
        p += n;
        p += fsl__tkt_sql_skip(p);
        if( (n = fsl__tkt_sql_kw(p, "IF")) ){
          char const * p2 = p + n;
          p2 += fsl__tkt_sql_skip(p2);
          if( (n = fsl__tkt_sql_kw(p2, "NOT")) ){
            p2 += n + fsl__tkt_sql_skip(p2 + n);
            if( (n = fsl__tkt_sql_kw(p2, "EXISTS")) ){
              p = p2 + n;
              p += fsl__tkt_sql_skip(p);
              ifNotExists = true;
            }
          }
        }
        n = fsl__tkt_sql_ident(p);
        if( n ){
          char const * zName = p;
          fsl_size_t nName = n;
          if( '.'==p[n] ){
            /* A schema name: replaced by db's. */
            fsl_size_t const n2 = fsl__tkt_sql_ident(p + n + 1);
            if( n2 ){
              zName = p + n + 1;
              nName = n2;
            }
          }
          if( isView && !ifNotExists ){
            rc = fsl_b_append(out, zCopied, (fsl_int_t)(z - zCopied));
            if( 0==rc ) rc = fsl_b_appendf(out, "DROP VIEW IF EXISTS %s.%.*s;\n",
                                           zSchema, (int)nName, zName);
            zCopied = z;
          }
          if( 0==rc ) rc = fsl_b_append(out, zCopied, (fsl_int_t)(p - zCopied));
          if( 0==rc ) rc = fsl_b_appendf(out, "%s.%.*s", zSchema,
                                         (int)nName, zName);
          z = zCopied = zName + nName;
          continue;
        }
      }
      z += 6;
      continue;
    }
    ++z;
  }
  if( 0==rc ) rc = fsl_b_append(out, zCopied, (fsl_int_t)(z - zCopied));
  return rc;
}

/**
   The SQL functions which the scratch connection of
   fsl__ticket_schema_install_prefixed() may run: SQLite's own core,
   aggregate, window, date and time, JSON and math functions, sorted
   for bsearch(). Every other function is denied, since a connection
   gets those of every sqlite3_auto_extension() of the process, e.g.
   fsl_sqlext_init()'s fsl_open() or fsl_sync(), or an app's file
   functions, which a ticket schema (repository data, which config sync
   can bring in) must not reach. The sqlite_drop_column() and
   sqlite_rename_*() ones are SQLite's internal ones behind ALTER
   TABLE, which SQL cannot call. Not here: the full-text search
   functions, as virtual tables are refused anyway, and sqlite_log().
   A function of the process's own which takes one of these names
   (e.g. by an auto-extension) passes, as it would in file mode.
*/
static char const * const fsl__tkt_scratch_funcs[] = {
  "->", "->>", "abs", "acos", "acosh", "asin", "asinh", "atan", "atan2",
  "atanh", "avg", "ceil", "ceiling", "changes", "char", "coalesce",
  "concat", "concat_ws", "cos", "cosh", "count", "cume_dist",
  "current_date", "current_time", "current_timestamp", "date",
  "datetime", "degrees", "dense_rank", "exp", "first_value", "floor",
  "format", "glob", "group_concat", "hex", "if", "ifnull", "iif",
  "instr", "json", "json_array", "json_array_insert",
  "json_array_length", "json_error_position", "json_extract",
  "json_group_array", "json_group_object", "json_insert",
  "json_object", "json_patch", "json_pretty", "json_quote",
  "json_remove", "json_replace", "json_set", "json_type", "json_valid",
  "jsonb", "jsonb_array", "jsonb_array_insert", "jsonb_extract",
  "jsonb_group_array", "jsonb_group_object", "jsonb_insert",
  "jsonb_object", "jsonb_patch", "jsonb_remove", "jsonb_replace",
  "jsonb_set", "julianday", "lag", "last_insert_rowid", "last_value",
  "lead", "length", "like", "likelihood", "likely", "ln", "log",
  "log10", "log2", "lower", "ltrim", "max", "min", "mod", "nth_value",
  "ntile", "nullif", "octet_length", "percent_rank", "pi", "pow",
  "power", "printf", "quote", "radians", "random", "randomblob",
  "rank", "replace", "round", "row_number", "rtrim", "sign", "sin",
  "sinh", "sqlite_compileoption_get", "sqlite_compileoption_used",
  "sqlite_drop_column", "sqlite_rename_column", "sqlite_rename_quotefix",
  "sqlite_rename_table", "sqlite_rename_test",
  "sqlite_source_id", "sqlite_version", "sqrt", "strftime",
  "string_agg", "substr", "substring", "subtype", "sum", "tan", "tanh",
  "time", "timediff", "total", "total_changes", "trim", "trunc",
  "typeof", "unhex", "unicode", "unistr", "unistr_quote", "unixepoch",
  "unlikely", "upper", "zeroblob"
};

/** bsearch() comparison for fsl__tkt_scratch_funcs. */
static int fsl__tkt_scratch_func_cmp(void const * pKey, void const * pElem){
  return fsl_stricmp((char const *)pKey, *(char const * const *)pElem);
}

/** State of fsl__tkt_scratch_auth(): what it denied, if anything. */
typedef struct {
  bool denied;
  char zWhat[64];
} fsl__tkt_scratch_state;

/**
   sqlite3_set_authorizer() callback for the scratch connection of
   fsl__ticket_schema_install_prefixed(), which allows only what makes
   and fills tables, indexes, views and triggers of its own in-memory
   db (and what libfossil then does there: ALTER TABLE RENAME, DROP
   TABLE), and of SQL functions only SQLite's own
   (fsl__tkt_scratch_funcs). So it denies ATTACH and DETACH (also
   stopped by SQLITE_LIMIT_ATTACHED=0, as is VACUUM INTO, which
   ATTACHes), PRAGMA, TEMP objects and virtual tables. The in-tree
   SQLite has no load_extension() (SQLITE_OMIT_LOAD_EXTENSION). It
   records what it denied in pState, a fsl__tkt_scratch_state.
*/
static int fsl__tkt_scratch_auth(void * pState, int op, char const * z1,
                                 char const * z2, char const * z3,
                                 char const * z4){
  fsl__tkt_scratch_state * const st = pState;
  (void)z1; (void)z3; (void)z4;
  switch(op){
    case SQLITE_CREATE_INDEX: case SQLITE_CREATE_TABLE:
    case SQLITE_CREATE_TRIGGER: case SQLITE_CREATE_VIEW:
    case SQLITE_DROP_INDEX: case SQLITE_DROP_TABLE:
    case SQLITE_DROP_TRIGGER: case SQLITE_DROP_VIEW:
    case SQLITE_INSERT: case SQLITE_UPDATE: case SQLITE_DELETE:
    case SQLITE_READ: case SQLITE_SELECT: case SQLITE_RECURSIVE:
    case SQLITE_ALTER_TABLE: case SQLITE_TRANSACTION: case SQLITE_SAVEPOINT:
    case SQLITE_REINDEX /* which CREATE INDEX asks for */:
      return SQLITE_OK;
    case SQLITE_FUNCTION:
      if(z2 && bsearch(z2, fsl__tkt_scratch_funcs,
                       sizeof(fsl__tkt_scratch_funcs)
                       / sizeof(fsl__tkt_scratch_funcs[0]),
                       sizeof(fsl__tkt_scratch_funcs[0]),
                       fsl__tkt_scratch_func_cmp)){
        return SQLITE_OK;
      }
      break;
    default:
      break;
  }
  if(!st->denied){
    st->denied = true;
    fsl_snprintf(st->zWhat, sizeof(st->zWhat), "%s",
                 SQLITE_FUNCTION==op && z2 ? z2
                 : SQLITE_PRAGMA==op ? "PRAGMA"
                 : SQLITE_ATTACH==op ? "ATTACH"
                 : SQLITE_DETACH==op ? "DETACH" : "that statement");
  }
  return SQLITE_DENY;
}

/**
   fsl__ticket_schema_install() for repository tables of a host's main
   db with prefix zPre: zSql runs, as data, in a scratch in-memory
   connection of its own, where it can touch nothing else, beside empty
   stand-ins for the repository's other tables. Each object it makes is
   then made in f's repository, renamed, tables first. SQLite's ALTER
   TABLE RENAME renames the tables wherever they are named: renaming
   the stand-ins gives REFERENCES clauses the prefix, and renaming
   zSql's tables once the stand-ins are dropped fails if a trigger or
   view names a table which zSql did not make, which in f's db would be
   a table of the repository's or the host's. No rename follows the
   name of a view, so a view or trigger which names one of zSql's
   views, which in f's db would bind to whatever the host has by that
   name, fails that way too: the views already have their final names
   by then. A schema which makes anything else (a TEMP object, a
   virtual table, whose module arguments name tables which no rename
   follows, a trigger on a table it did not make or on a view), or
   fails there, e.g. as it tries to reach beyond that connection
   (fsl__tkt_scratch_auth()), is refused too, with FSL_RC_CONSISTENCY.
*/
static int fsl__ticket_schema_install_prefixed(fsl_cx * const f,
                                               char const * zPre,
                                               char const * zSql){
  fsl_db * const db = fsl_cx_db_repo(f);
  fsl_db s = fsl_db_empty;
  sqlite3 * dbh = NULL;
  fsl__tkt_scratch_state auth = {false, {0}};
  char * zDenied = NULL;
  fsl_b * const sql = fsl__cx_scratchpad(f);
  fsl_b * const ren = fsl__cx_scratchpad(f);
  fsl_b * const drop = fsl__cx_scratchpad(f);
  fsl_stmt q = fsl_stmt_empty;
  char const * zWhy = NULL;
  int rc = fsl_cx_prepare(f, &q, "SELECT substr(name, %d) FROM"
                          " main.sqlite_schema WHERE type='table'"
                          " AND name GLOB '%q*'",
                          (int)fsl_strlen(zPre) + 1, zPre);
  while( fsl__cx_stmt_step_each(f, &q, &rc) ){
    char const * const z = fsl_stmt_g_text(&q, 0, NULL);
    rc = fsl_b_appendf(sql, "CREATE TABLE main.%!Q(x);\n", z);
    if(!rc) rc = fsl_b_appendf(ren, "ALTER TABLE main.%!Q RENAME TO"
                               " \"%s%s\";\n", z, zPre, z);
    if(!rc) rc = fsl_b_appendf(drop, "DROP TABLE main.\"%s%s\";\n",
                               zPre, z);
  }
  fsl_stmt_finalize(&q);
  if(!rc){
    /* An in-memory db which can reach nothing else, before any of zSql
       runs: SQLite does not allow ATTACH in a transaction, but this
       connection is in autocommit mode. */
    rc = sqlite3_open_v2(":memory:", &dbh, SQLITE_OPEN_READWRITE
                         | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY, NULL);
    if(rc){
      rc = fsl_cx_err_set(f, FSL_RC_DB, "Cannot open a scratch db: %s",
                          dbh ? sqlite3_errmsg(dbh) : "out of memory");
    }else{
      sqlite3_limit(dbh, SQLITE_LIMIT_ATTACHED, 0);
      sqlite3_set_authorizer(dbh, fsl__tkt_scratch_auth, &auth);
      fsl__db_borrow(&s, dbh);
    }
  }
  if(!rc && sql->used) rc = fsl_db_exec_multi(&s, "%b", sql);
  if(!rc){
    /* Its CREATE names, whatever their schema, go to s's main db. */
    fsl_b_reuse(sql);
    s.impl.share.zRepo = fsl_strdup("main");
    rc = s.impl.share.zRepo
      ? fsl__ticket_schema_qualify(&s, zSql, sql) : FSL_RC_OOM;
  }
  if(!rc && fsl_db_exec_multi(&s, "%b", sql)){
    if(auth.denied){
      zWhy = zDenied = fsl_mprintf("it reaches beyond a db of its own, "
                                   "which SQLite's authorizer denied: %s "
                                   "(only SQLite's own functions, and no "
                                   "ATTACH, DETACH, PRAGMA, TEMP object "
                                   "or virtual table)", auth.zWhat);
      if(!zDenied) rc = FSL_RC_OOM;
    }else{
      zWhy = fsl_b_cstr(&s.error.msg);
    }
  }
  if(!rc && !zWhy){
    if(fsl_db_exists(&s, "SELECT 1 FROM temp.sqlite_schema")
       || fsl_db_exists(&s, "SELECT 1 FROM main.sqlite_schema"
                        " WHERE sql LIKE 'CREATE VIRTUAL %%'")){
      zWhy = "it makes a TEMP object or a virtual table";
    }
  }
  if(!rc && !zWhy){
    /* CREATE TRIGGER resolves no functions, and the renames compile
       the triggers without the authorizer, so compile them here, by
       preparing (not running) each statement which fires them, so
       that an unknown function, or one not of fsl__tkt_scratch_funcs,
       is refused. On a view, which only INSTEAD OF triggers make
       writable, those it has none for cannot be prepared, which is
       fine. */
    fsl_stmt t = fsl_stmt_empty;
    fsl_b * const set = fsl__cx_scratchpad(f);
    rc = fsl_db_prepare(&s, &q, "SELECT DISTINCT t.tbl_name, o.type"
                        " FROM main.sqlite_schema t JOIN main.sqlite_schema o"
                        " ON o.name=t.tbl_name WHERE t.type='trigger'");
    while(!rc && !zWhy && FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
      char const * const zTab = fsl_stmt_g_text(&q, 0, NULL);
      bool const isView = 'v'==*fsl_stmt_g_text(&q, 1, NULL);
      fsl_b_reuse(set);
      rc = fsl_db_prepare(&s, &t, "SELECT * FROM main.%!Q", zTab);
      for(int i = 0; !rc && i < fsl_stmt_col_count(&t); ++i){
        rc = fsl_b_appendf(set, "%s%!Q=%!Q", i ? "," : "",
                           fsl_stmt_col_name(&t, i),
                           fsl_stmt_col_name(&t, i));
      }
      fsl_stmt_finalize(&t);
      for(int i = 0; !rc && !zWhy && i < 3; ++i){
        int const prc = 0==i
          ? fsl_db_prepare(&s, &t, "INSERT INTO main.%!Q DEFAULT VALUES",
                           zTab)
          : (1==i ? fsl_db_prepare(&s, &t, "UPDATE main.%!Q SET %b",
                                   zTab, set)
             : fsl_db_prepare(&s, &t, "DELETE FROM main.%!Q", zTab));
        fsl_stmt_finalize(&t);
        if(prc && !(isView && !auth.denied
                    && strstr(fsl_b_cstr(&s.error.msg),
                              "because it is a view"))){
          zWhy = fsl_b_cstr(&s.error.msg);
        }
        if(!zWhy) fsl_db_err_reset(&s);
      }
    }
    fsl_stmt_finalize(&q);
    fsl__cx_scratchpad_yield(f, set);
    if(!rc && auth.denied){
      zWhy = zDenied = fsl_mprintf("its trigger reaches beyond a db of "
                                   "its own, which SQLite's authorizer "
                                   "denied: %s (only SQLite's own "
                                   "functions)", auth.zWhat);
      if(!zDenied) rc = FSL_RC_OOM;
    }
  }
  if(!rc && !zWhy && ren->used && fsl_db_exec_multi(&s, "%b", ren)){
    zWhy = fsl_b_cstr(&s.error.msg);
  }
  if(!rc && !zWhy && fsl_db_exists(&s, "SELECT 1 FROM main.sqlite_schema"
                                   " WHERE type='trigger'"
                                   " AND tbl_name GLOB '%q*'", zPre)){
    zWhy = "it makes a trigger on a table which it does not make";
  }
  if(!rc && !zWhy && drop->used) rc = fsl_db_exec_multi(&s, "%b", drop);
  if(!rc && !zWhy && fsl_db_exists(&s, "SELECT 1 FROM main.sqlite_schema t,"
                                   " main.sqlite_schema v WHERE"
                                   " t.type='trigger' AND v.type='view'"
                                   " AND v.name=t.tbl_name")){
    zWhy = "it makes a trigger on a view";
  }
  if(!rc && !zWhy){
    /* The views take their final names now, so that the renames below
       fail if anything still names one of them. */
    fsl_b_reuse(sql);
    rc = fsl_db_prepare(&s, &q, "SELECT sql, name FROM main.sqlite_schema"
                        " WHERE type='view'");
    while(!rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
      char const * const z = fsl_stmt_g_text(&q, 1, NULL);
      char * const zNew = fsl_mprintf("%s%s", zPre, z);
      rc = zNew ? fsl__repo_copy_sql(sql, fsl_stmt_g_text(&q, 0, NULL),
                                     "main", zNew)
        : FSL_RC_OOM;
      fsl_free(zNew);
      if(!rc) rc = fsl_b_appendf(sql, ";\nDROP VIEW main.%!Q;\n", z);
    }
    fsl_stmt_finalize(&q);
    if(!rc && sql->used && fsl_db_exec_multi(&s, "%b", sql)){
      zWhy = fsl_b_cstr(&s.error.msg);
    }
  }
  if(!rc && !zWhy){
    fsl_b_reuse(ren);
    rc = fsl_db_prepare(&s, &q, "SELECT name FROM main.sqlite_schema"
                        " WHERE type='table' AND name NOT GLOB 'sqlite_*'");
    while(!rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
      char const * const z = fsl_stmt_g_text(&q, 0, NULL);
      rc = fsl_b_appendf(ren, "ALTER TABLE main.%!Q RENAME TO \"%s%s\";\n",
                         z, zPre, z);
    }
    fsl_stmt_finalize(&q);
    if(!rc && ren->used && fsl_db_exec_multi(&s, "%b", ren)){
      zWhy = fsl_b_cstr(&s.error.msg);
    }
  }
  if(!rc && !zWhy){
    /* A view whose tables zSql did not make: the renames check views
       only if there was a table to rename. */
    rc = fsl_db_prepare(&s, &q, "SELECT name FROM main.sqlite_schema"
                        " WHERE type='view'");
    while(!rc && !zWhy && FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
      fsl_stmt v = fsl_stmt_empty;
      if(fsl_db_prepare(&s, &v, "SELECT 1 FROM main.%!Q",
                        fsl_stmt_g_text(&q, 0, NULL))){
        zWhy = fsl_b_cstr(&s.error.msg);
      }
      fsl_stmt_finalize(&v);
    }
    fsl_stmt_finalize(&q);
  }
  if(!rc && !zWhy){
    fsl_b_reuse(sql);
    rc = fsl_db_prepare(&s, &q,
      "SELECT sql, CASE WHEN type IN ('table','view') THEN name"
      " ELSE %Q||name END, type='view'"
      " FROM main.sqlite_schema WHERE sql IS NOT NULL"
      " AND name NOT GLOB 'sqlite_*' ORDER BY type<>'table', rowid", zPre);
    while(!rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
      if(fsl_stmt_g_int32(&q, 2)){
        /* A rebuild leaves the views, which the prefix keeps to this
           repository, so there is nothing of the host's to drop. */
        rc = fsl_b_appendf(sql, "DROP VIEW IF EXISTS %!Q.\"%s\";\n",
                           fsl__db_schema(db, FSL_DBROLE_REPO),
                           fsl_stmt_g_text(&q, 1, NULL));
        if(rc) break;
      }
      rc = fsl__repo_copy_sql(sql, fsl_stmt_g_text(&q, 0, NULL),
                              fsl__db_schema(db, FSL_DBROLE_REPO),
                              fsl_stmt_g_text(&q, 1, NULL));
      if(!rc) rc = fsl_b_append(sql, ";\n", 2);
    }
    fsl_stmt_finalize(&q);
    if(!rc) rc = fsl_cx_exec_multi(f, "%b", sql);
  }
  if(zWhy){
    rc = fsl_cx_err_set(f, FSL_RC_CONSISTENCY, "Refusing the ticket "
                        "schema for the repository tables prefixed %s: "
                        "%s.", zPre, zWhy);
  }else if(rc && !f->error.code){
    rc = s.error.code
      ? fsl_cx_err_set(f, rc, "Ticket schema error: %b", &s.error.msg)
      : fsl_cx_err_set(f, rc, NULL);
  }
  fsl_free(zDenied);
  fsl_db_close(&s)/*does not close the borrowed dbh*/;
  sqlite3_close(dbh);
  fsl__cx_scratchpad_yield(f, sql);
  fsl__cx_scratchpad_yield(f, ren);
  fsl__cx_scratchpad_yield(f, drop);
  return rc;
}

int fsl__ticket_schema_install(fsl_cx * const f, char const * zSql){
  fsl_db * const db = fsl_cx_db_repo(f);
  char const * const zPre = fsl__db_repo_prefix(db);
  int rc;
  if(zPre) return fsl__ticket_schema_install_prefixed(f, zPre, zSql);
  else{
    fsl_b * const q = fsl__cx_scratchpad(f);
    rc = fsl__ticket_schema_qualify(db, zSql, q);
    if(!rc) rc = fsl_cx_exec_multi(f, "%b", q);
    fsl__cx_scratchpad_yield(f, q);
  }
  return rc;
}

int fsl__cx_ticket_create_table(fsl_cx * const f){
  fsl_db * const db = fsl_needs_repo(f);
  int rc;
  if(!db) return FSL_RC_NOT_A_REPO;
  rc = fsl_cx_exec_multi(f,
                         "DROP TABLE IF EXISTS {{dbname.repo}}.ticket;"
                         "DROP TABLE IF EXISTS {{dbname.repo}}.ticketchng;"
                         );
  if(!rc){
    /* The schema is data (possibly a repository's own, in fossil(1)'s
       form), so its placeholders are not expanded: its object names
       are given db's repository schema instead. */
    fsl_b * const buf = fsl__cx_content_buffer(f);
    rc = fsl_cx_schema_ticket(f, buf);
    if(!rc) rc = fsl__ticket_schema_install(f, fsl_b_cstr(buf));
    fsl__cx_content_buffer_yield(f);
  }
  return rc;
}

static int fsl__tkt_field_id(fsl_list const * jli, const char *zFieldName){
  int i;
  fsl_card_J const * jc;
  for(i=0; i<(int)jli->used; ++i){
    jc = (fsl_card_J const *)jli->list[i];
    if( !fsl_strcmp(zFieldName, jc->field) ) return i;
  }
  return -1;
}

/*
  The values of a ticket's fields which are not in the ticketchng
  table and so, unlike those which are, are only linked from in their
  most recent state. fossil(1) calls these "cards". The ones to
  extract the backlinks of, once all of a ticket's artifacts are
  applied, are those of an assignment and the appends after it.
*/
typedef struct {
  char * zValue;
  int mimetype;
  fsl_id_t rid;
  double mtime;
} fsl__tkt_card;

typedef struct {
  fsl__tkt_card * a;
  fsl_size_t n;
  fsl_size_t nAlloc;
} fsl__tkt_cards;

static void fsl__tkt_cards_clear(fsl__tkt_cards * const c){
  for(fsl_size_t i = 0; i < c->n; ++i) fsl_free(c->a[i].zValue);
  c->n = 0;
}

static void fsl__tkt_cards_free(fsl__tkt_cards * const c, fsl_size_t n){
  for(fsl_size_t i = 0; i < n; ++i){
    fsl__tkt_cards_clear(c+i);
    fsl_free(c[i].a);
  }
  fsl_free(c);
}

/*
  Records a value of a field, replacing the earlier ones unless it is
  appended to them.
*/
static int fsl__tkt_cards_add(fsl__tkt_cards * const c, bool append,
                              char const * zValue, int mimetype,
                              fsl_id_t rid, double mtime){
  if( !append ) fsl__tkt_cards_clear(c);
  if( c->n>=c->nAlloc ){
    fsl_size_t const nAlloc = c->nAlloc ? c->nAlloc * 2 : 4;
    fsl__tkt_card * const a =
      (fsl__tkt_card*)fsl_realloc(c->a, nAlloc * sizeof(fsl__tkt_card));
    if( !a ) return FSL_RC_OOM;
    c->a = a;
    c->nAlloc = nAlloc;
  }
  c->a[c->n].zValue = fsl_strdup(zValue ? zValue : "");
  if( !c->a[c->n].zValue ) return FSL_RC_OOM;
  c->a[c->n].mimetype = mimetype;
  c->a[c->n].rid = rid;
  c->a[c->n].mtime = mtime;
  ++c->n;
  return 0;
}

int fsl__cx_ticket_load_fields(fsl_cx * const f, bool forceReload){
  fsl_list * const li = &f->ticket.customFields;
  if(li->used){
    if(!forceReload) return 0;
    fsl__card_J_list_free(li, false);
    /* Fall through and reload ... */
  }else if( !fsl_needs_repo(f) ){
    return FSL_RC_NOT_A_REPO;
  }
  fsl_card_J * jc;
  fsl_stmt q = fsl_stmt_empty;
  int i;
  fsl_b * const tbl = fsl__cx_scratchpad(f);
  /* PRAGMA's table name is a value: a prefixed table's name is bare. */
  int rc = fsl__db_table_name(fsl_cx_db_repo(f), FSL_DBROLE_REPO, "ticket",
                              false, tbl);
  if(!rc) rc = fsl_cx_prepare(f, &q, "PRAGMA %s.table_info(%b)",
                              fsl__db_schema(f->dbMain, FSL_DBROLE_REPO),
                              tbl);
  if(!rc) while( fsl__cx_stmt_step_each(f, &q, &rc) ){
    char const * zFieldName = fsl_stmt_g_text(&q, 1, NULL);
    if(!zFieldName){
      rc = FSL_RC_OOM;
      break;
    }
    f->ticket.hasTicket = 1;
    if( 0==memcmp(zFieldName,"tkt_", 4)){
      if( 0==fsl_strcmp(zFieldName,"tkt_ctime")) f->ticket.hasCTime = 1;
      /* These are core field names, part of every fossil ticket
         table. */
      continue;
    }
    jc = fsl_card_J_malloc(0, zFieldName, NULL);
    if(!jc){
      rc = FSL_RC_OOM;
      break;
    }
    jc->flags = FSL_CARD_J_TICKET;
    rc = fsl_list_append(li, jc);
    if(rc){
      fsl_card_J_free(jc);
      break;
    }
  }
  fsl_stmt_finalize(&q);
  if(rc) goto end;

  fsl_b_reuse(tbl);
  rc = fsl__db_table_name(fsl_cx_db_repo(f), FSL_DBROLE_REPO, "ticketchng",
                          false, tbl);
  if(!rc) rc = fsl_cx_prepare(f, &q, "PRAGMA %s.table_info(%b)",
                              fsl__db_schema(f->dbMain, FSL_DBROLE_REPO),
                              tbl);
  if(!rc) while( fsl__cx_stmt_step_each(f, &q, &rc) ){
    char const * zFieldName = fsl_stmt_g_text(&q, 1, NULL);
    if(!zFieldName){
      rc = FSL_RC_OOM;
      break;
    }
    f->ticket.hasChng = 1;
    if( 0==memcmp(zFieldName,"tkt_", 4)){
      if( 0==fsl_strcmp(zFieldName,"tkt_rid")) f->ticket.hasChngRid = 1;
      /* These are core field names, part of every fossil ticketchng
         table. */
      continue;
    }
    if( (i=fsl__tkt_field_id(li, zFieldName)) >= 0){
      jc = (fsl_card_J*)li->list[i];
      jc->flags |= FSL_CARD_J_CHNG;
      continue;
    }
    jc = fsl_card_J_malloc(0, zFieldName, NULL);
    if(!jc){
      rc = FSL_RC_OOM;
      break;
    }
    jc->flags = FSL_CARD_J_CHNG;
    rc = fsl_list_append(li, jc);
    if(rc){
      fsl_card_J_free(jc);
      break;
    }
  }
  fsl_stmt_finalize(&q);
  end:
  fsl__cx_scratchpad_yield(f, tbl);
  if(!rc){
    fsl_list_sort(li, fsl__qsort_cmp_J_cards);
  }
  return rc;
}

/*
  Extracts the backlinks of the fields of ticket artifact d, for which
  the mimetype of its fields is mimetype. Those of fields which are in
  the ticketchng table are recorded now. The others are added to
  cards, which has an entry for each of the custom fields, for the
  caller to record once it has seen all of the ticket's artifacts.

  Derived from the end of fossil(1) tkt.c:ticket_insert().
*/
static int fsl__ticket_backlinks(fsl_deck * const d, int const mimetype,
                                 fsl__tkt_cards * const cards){
  fsl_cx * const f = d->f;
  fsl_list const * const cf = &f->ticket.customFields;
  int rc = 0;
  for(fsl_size_t i = 0; 0==rc && i < d->J.used; ++i){
    fsl_card_J const * const dJC = (fsl_card_J*)d->J.list[i];
    int const j = fsl__tkt_field_id(cf, dJC->field);
    if(j<0) continue;
    if( ((fsl_card_J const *)cf->list[j])->flags & FSL_CARD_J_CHNG ){
      /* Any old backlinks have been deleted by fsl__ticket_rebuild(). */
      rc = fsl__backlink_extract(f, dJC->value, mimetype, d->rid,
                                 FSL_BKLNK_TICKET, d->D, false);
    }else{
      rc = fsl__tkt_cards_add(cards + j, dJC->append, dJC->value,
                              mimetype, d->rid, d->D);
    }
  }
  return rc;
}

static int fsl__ticket_insert(fsl_deck * const d, fsl_id_t tktId,
                              fsl_id_t * const tgtId,
                              fsl__tkt_cards * const cards){
  /* Derived from fossil(1) tkt.c:ticket_insert() */;
  fsl_cx * const f = d->f;
  fsl_id_t const rid = d->rid;
  int rc = 0;
  fsl_b * const sql1 = fsl__cx_scratchpad(f);
  fsl_b * const sql2 = fsl__cx_scratchpad(f);
  fsl_b * const sql3 = fsl__cx_scratchpad(f);
  fsl_db * const db = fsl_cx_db_repo(f);
  fsl_list const * const cf = &f->ticket.customFields;
  fsl_size_t i;
  int mimetype = FSL_BKLNK_MT_NONE;
  fsl_stmt q = fsl_stmt_empty;
  char * aUsed = 0;
  assert(rid>0 && f!=NULL && db);
  if(0==tktId){
    rc = fsl_cx_exec_multi(f, "INSERT INTO {{dbname.repo}}.ticket(tkt_uuid, tkt_mtime) "
                           "VALUES(%Q, 0)", d->K);
    if(rc) goto end;
    tktId = fsl_db_last_insert_id(db);
  }
  rc = fsl__db_appendf(db, sql1,
                       "UPDATE OR REPLACE {{dbname.repo}}.ticket"
                       " SET tkt_mtime=?1");
  if(0==rc && f->ticket.hasCTime){
    rc = fsl_b_append(sql1, ", tkt_ctime=coalesce(tkt_ctime,?1)", -1);
  }
  if(rc) goto end;
  /* Not a VLA: MSVC does not have them. */
  aUsed = fsl_malloc(cf->used ? cf->used : 1);
  if(!aUsed){
    rc = FSL_RC_OOM;
    goto end;
  }
  memset(aUsed, 0, cf->used);
  for(i = 0; 0==rc && i < d->J.used; ++i){
    fsl_card_J const * const dJC = (fsl_card_J*)d->J.list[i];
    int const j = fsl__tkt_field_id(cf, dJC->field);
    if(j<0){
      /* Ticket has a field which this repo does not have. Skip it. */
      continue;
    }
    aUsed[j] = FSL_CARD_J_TICKET;
    fsl_card_J const * const rJC = (fsl_card_J*)cf->list[j];
    if(rJC->flags & FSL_CARD_J_TICKET){
      if(dJC->append){
        rc = fsl_b_appendf(sql1, ", %!Q=coalesce(%!Q,'') || %Q",
                                dJC->field, dJC->field, dJC->value);
      }else{
        rc = fsl_b_appendf(sql1, ", %!Q=%Q",
                                dJC->field, dJC->value);
      }
      if(rc) break;
    }
    if(rJC->flags & FSL_CARD_J_CHNG){
      rc = fsl_b_appendf(sql2, ",%!Q", dJC->field);
      if(0==rc) rc = fsl_b_appendf(sql3, ",%Q", dJC->value);
      if(rc) break;
    }
    if(0==fsl_strcmp(dJC->field, "mimetype")){
      mimetype = fsl__backlink_mimetype(dJC->value);
    }
  }
  if(rc) goto end;
  rc = fsl_b_appendf(sql1, " WHERE tkt_id=%" FSL_ID_T_PFMT, tktId);
  if(rc) goto end;
  rc = fsl_cx_prepare(f, &q, "%b", sql1);
  if(rc) goto end;
  rc = fsl_stmt_bind_step(&q, "f", d->D);
  fsl_stmt_finalize(&q);
  if(rc) goto end;
  fsl_b_reuse(sql1);
  if(f->ticket.hasChngRid || sql2->used){
    bool fromTkt = false;
    if(f->ticket.hasChngRid){
      rc = fsl_b_append(sql2, ",tkt_rid", -1);
      if(0==rc) rc = fsl_b_appendf(sql3, ",%" FSL_ID_T_PFMT, d->rid);
      if(rc) goto end;
    }
    for(i = 0; 0==rc &&  i < cf->used; ++i){
      fsl_card_J const * const rJC = (fsl_card_J*)cf->list[i];
      if(0==aUsed[i] && (rJC->flags & FSL_CARD_J_BOTH)==FSL_CARD_J_BOTH){
        fromTkt = true;
        rc = fsl_b_appendf(sql2, ",%!Q", rJC->field);
        if(0==rc) rc = fsl_b_appendf(sql3, ",%!Q", rJC->field);
      }
    }
    if(rc) goto end;
    if(fromTkt){
      rc = fsl_cx_prepare(f, &q, "INSERT INTO {{dbname.repo}}.ticketchng(tkt_id,tkt_mtime%b)"
                          "SELECT %"FSL_ID_T_PFMT",?1%b "
                          "FROM {{dbname.repo}}.ticket WHERE tkt_id=%"FSL_ID_T_PFMT,
                          sql2, tktId, sql3, tktId);
    }else{
      rc = fsl_cx_prepare(f, &q, "INSERT INTO {{dbname.repo}}.ticketchng(tkt_id,tkt_mtime%b)"
                          "VALUES(%"FSL_ID_T_PFMT",?1%b)",
                          sql2, tktId, sql3);
    }
    if(0==rc) rc = fsl_stmt_bind_step(&q, "f", d->D);
  }
  if(0==rc){
    fsl_stmt_finalize(&q);
    rc = fsl__ticket_backlinks(d, mimetype, cards);
  }
  end:
  fsl_stmt_finalize(&q);
  fsl_free(aUsed);
  fsl__cx_scratchpad_yield(f, sql1);
  fsl__cx_scratchpad_yield(f, sql2);
  fsl__cx_scratchpad_yield(f, sql3);
  *tgtId = tktId;
  if(rc){
    /* fsl_stmt_bind_step() leaves its error in db's error state. */
    rc = fsl_cx_uplift_db_error2(f, db, rc);
  }
  return rc;
}

static int fsl__ticket_timeline_entry(fsl_deck * const d, bool isNew, fsl_id_t tagId){
  /* Derived from fossil(1) manifest.c:mainfest_ticket_event() */;
  int rc;
  fsl_b * const comment = fsl__cx_scratchpad(d->f);
  fsl_b * const brief = fsl__cx_scratchpad(d->f);
  char * zTitle = 0;
  char * zNewStatus = 0;
  fsl_db * const db = fsl_cx_db_repo(d->f);
  fsl_cx * const f = d->f;
  if(!f->ticket.titleColumn){
    assert(!f->ticket.statusColumn);
    rc = fsl_db_get_text(db, &f->ticket.titleColumn, NULL,
             "SELECT coalesce("
             "(SELECT value FROM {{dbname.repo}}.config WHERE name='ticket-title-expr'),"
             "'title')");
    if(0==rc){
      rc = fsl_db_get_text(db, &f->ticket.statusColumn, NULL,
               "SELECT coalesce("
               "(SELECT value FROM {{dbname.repo}}.config WHERE name='ticket-status-column'),"
               "'status')");
    }
    if(rc){
      rc = fsl_cx_uplift_db_error( f, db );
      goto end;
    }
  }
  rc = fsl_db_get_text(db, &zTitle, NULL,
                       "SELECT coalesce(%!Q,'unknown') "
                       "FROM {{dbname.repo}}.ticket WHERE tkt_uuid=%Q",
                       f->ticket.titleColumn, d->K);
  if(rc){
    fsl_cx_uplift_db_error(d->f, db);
    goto end;
  }
  if(isNew){
    rc = fsl_b_appendf(comment, "New ticket [%!S|%S] <i>%h</i>.",
                            d->K, d->K, zTitle);
    if(0==rc){
      rc = fsl_b_appendf(brief, "New ticket [%!S|%S].",
                              d->K, d->K);
    }
    if(rc) goto end;
  }else{
    // Update an existing ticket...
    char * zNewStatus = 0;
    for(fsl_size_t i = 0; i < d->J.used; ++i){
      fsl_card_J const * const jc = (fsl_card_J*)d->J.list[i];
      if(0==fsl_strcmp(jc->field, f->ticket.statusColumn)){
        zNewStatus = jc->value;
        break;
      }
    }
    if(zNewStatus){
      rc = fsl_b_appendf(comment, "%h ticket [%!S|%S]: <i>%h</i>",
                              zNewStatus, d->K, d->K, zTitle);
      if(!rc && d->J.used>1){
        rc = fsl_b_appendf(comment, " plus %d other change%s",
                                (int)d->J.used-1, d->J.used==2 ? "" : "s");
      }
      if(0==rc) rc = fsl_b_appendf(brief, "%h ticket [%!S|%S].",
                                        zNewStatus, d->K, d->K);
      if(rc) goto end;
    }else{
      rc = fsl_db_get_text(db, &zNewStatus, NULL,
                           "SELECT coalesce(%!Q,'unknown') "
                           "FROM {{dbname.repo}}.ticket WHERE tkt_uuid=%Q",
                           f->ticket.statusColumn, d->K);
      if(rc){
        rc = fsl_cx_uplift_db_error2(f, db, rc);
        goto end;
      }
      rc = fsl_b_appendf(comment, "Ticket [%!S|%S] <i>%h</i> "
                              "status still %h with %d other change%s",
                              d->K, d->K, zTitle, zNewStatus, (int)d->J.used,
                              1==d->J.used ? "" : "s");
      fsl_free(zNewStatus);
      if(rc) goto end;
      rc = fsl_b_appendf(brief, "Ticket [%!S|%S]: %d change%s",
                              d->K, d->K, (int)d->J.used,
                              1==d->J.used ? "" : "s");
      if(rc) goto end;
    }
  }
  assert(0==rc);
  // MISSING: manifest_create_event_triggers()
  rc = fsl_cx_exec(d->f,
                   "REPLACE INTO {{dbname.repo}}.event"
                   "(type, tagid, mtime, objid, user, comment, brief) "
                   "VALUES('t', %"FSL_ID_T_PFMT", %"FSL_JULIAN_T_PFMT", "
                   "%"FSL_ID_T_PFMT",%Q,%B,%B)",
                   tagId, d->D, d->rid, d->U, comment, brief);
  end:
  fsl_free(zTitle);
  fsl_free(zNewStatus);
  fsl__cx_scratchpad_yield(d->f, comment);
  fsl__cx_scratchpad_yield(d->f, brief);
  return rc;
}

int fsl__ticket_rebuild(fsl_cx * const f, char const * zTktKCard){
  int rc;
  fsl_id_t tktId;
  fsl_id_t tagId;
  fsl_db * const db = fsl_needs_repo(f);
  fsl_stmt q = fsl_stmt_empty;
  fsl__tkt_cards * cards = NULL;
  if(!db) return FSL_RC_NOT_A_REPO;
  assert(!f->cache.isCrosslinking);
  rc = fsl__cx_ticket_load_fields(f, false);
  fsl_size_t const nCards = f->ticket.customFields.used;
  if(rc) goto end;
  else if(!f->ticket.hasTicket) return 0;
  char * const zTag = fsl_mprintf("tkt-%s", zTktKCard);
  if(!zTag){
    rc = FSL_RC_OOM;
    goto end;
  }
  tagId = fsl_tag_id(f, zTag, true);
  fsl_free(zTag);
  if(tagId<0){
    rc = f->error.code;
    assert(0!=rc);
    goto end;
  }
  tktId = fsl_db_g_id(db, 0, "SELECT tkt_id FROM {{dbname.repo}}.ticket "
                      "WHERE tkt_uuid=%Q", zTktKCard);
  if(tktId>0){
    if(f->ticket.hasChng){
      rc = fsl_cx_exec(f, "DELETE FROM {{dbname.repo}}.ticketchng "
                       "WHERE tkt_id=%" FSL_ID_T_PFMT,
                       tktId);
    }
    if(!rc) rc = fsl_cx_exec(f, "DELETE FROM {{dbname.repo}}.ticket "
                             "WHERE tkt_id=%" FSL_ID_T_PFMT,
                             tktId);
    if(rc) goto end;
  }
  tktId = 0;
  rc = fsl__backlink_ticket_reset(f, tagId);
  if(rc) goto end;
  cards = (fsl__tkt_cards*)fsl_malloc((nCards ? nCards : 1)
                                      * sizeof(fsl__tkt_cards));
  if(!cards){
    rc = FSL_RC_OOM;
    goto end;
  }
  memset(cards, 0, (nCards ? nCards : 1) * sizeof(fsl__tkt_cards));
  rc = fsl_cx_prepare(f, &q, "SELECT rid FROM {{dbname.repo}}.tagxref "
                      "WHERE tagid=%" FSL_ID_T_PFMT
                      " ORDER BY mtime", tagId);
  int counter = 0;
  /* Potential TODO (fossil does not do this):
     DELETE FROM EVENT WHERE tagid=${tagId} */
  while(0==rc && fsl__cx_stmt_step_each(f, &q, &rc)){
    fsl_deck deck = fsl_deck_empty;
    fsl_id_t const rid = fsl_stmt_g_id(&q, 0);
    rc = fsl_deck_load_rid(f, &deck, rid, FSL_SATYPE_TICKET);
    if(rc) goto outro;
    assert(deck.rid==rid);
    rc = fsl__ticket_insert(&deck, tktId, &tktId, cards);
    if(0==rc){
      rc = fsl__ticket_timeline_entry(&deck, 0==counter++, tagId);
      if(0==rc) rc = fsl__call_xlink_listeners(&deck);
    }
    outro:
    fsl_deck_finalize(&deck);
  }
  /* Now that the latest values of the fields which are not in the
     ticketchng table are known, link from those. */
  for(fsl_size_t i = 0; 0==rc && cards && i < nCards; ++i){
    for(fsl_size_t k = 0; 0==rc && k < cards[i].n; ++k){
      fsl__tkt_card const * const c = &cards[i].a[k];
      rc = fsl__backlink_extract(f, c->zValue, c->mimetype, c->rid,
                                 FSL_BKLNK_TICKET, c->mtime, false);
    }
  }
  end:
  if(cards) fsl__tkt_cards_free(cards, nCards);
  fsl_stmt_finalize(&q);
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, db, rc);
    if(FSL_RC_OOM!=rc && f->error.msg.used){
      /* Say which ticket failed. */
      fsl_b b = fsl_b_empty;
      if(0==fsl_b_appendf(&b, "Rebuilding ticket %s: %b",
                          zTktKCard, &f->error.msg)){
        fsl_b_swap(&b, &f->error.msg);
      }
      fsl_b_clear(&b);
    }
  }
  return rc;
}
/* end of file src/ticket.c */
/* start of file src/udf.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*************************************************************************
  This file houses fsl_cx-related sqlite3 User Defined Functions (UDFs).
*/
#if !defined(FSL_ENABLE_SQLITE_REGEXP)
#  define FSL_ENABLE_SQLITE_REGEXP 0
#endif
#if FSL_ENABLE_SQLITE_REGEXP
#endif
#include <assert.h>

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


/**
   Declares f as the fsl_cx for the calling SQL function, or makes it
   fail if the connection has none. libfossil finds it through the
   connection's context registry (fsl__cx_for_dbh()), not the
   function's user data, because one connection can carry several
   contexts (fsl_cx_host_db()), and because there a function can
   outlive its context: SQLite will not remove a function while a
   statement runs, as when fsl_close() is called from SQL.
*/
#define FSL__UDF_CX(f)                                              \
  fsl_cx * const f = fsl__cx_for_dbh(                               \
    sqlite3_context_db_handle(context));                            \
  if( !f ){                                                         \
    sqlite3_result_error(context, "No libfossil context is bound "  \
                         "to this db connection.", -1);             \
    return;                                                         \
  } (void)0

/**
   SQL function for debugging.

   The print() function writes its arguments to fsl_output()
   if the bound fsl_cx->cxConfig.sqlPrint flag is true.
*/
static void fsl__udf_print(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  FSL__UDF_CX(f);
  assert(f);
  if( f->cxConfig.sqlPrint ){
    int i;
    for(i=0; i<argc; i++){
      char c = i==argc-1 ? '\n' : ' ';
      fsl_outputf(f, "%s%c", sqlite3_value_text(argv[i]), c);
    }
  }
}

/**
   SQL function to return the number of seconds since 1970.  This is
   the same as strftime('%s','now') but is more compact.
*/
static void fsl__udf_now(
  sqlite3_context *context,
  int argc fsl__unused,
  sqlite3_value **argv fsl__unused
){
  (void)argc;
  (void)argv;
  sqlite3_result_int64(context, (sqlite3_int64)time(0));
}

/**
   SQL function to convert a Julian Day to a Unix timestamp.
*/
static void fsl__udf_j2u(
  sqlite3_context *context,
  int argc fsl__unused,
  sqlite3_value **argv fsl__unused
){
  double const jd = (double)sqlite3_value_double(argv[0]);
  (void)argc;
  (void)argv;
  sqlite3_result_int64(context, (sqlite3_int64)fsl_julian_to_unix(jd));
}

/**
   SQL function FSL_CKOUT_DIR([bool includeTrailingSlash=1]) returns
   the top-level checkout directory, optionally (by default) with a
   trailing slash. Returns NULL if the calling context (FSL__UDF_CX)
   has no checkout.
*/
static void fsl__udf_chkout_dir(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  FSL__UDF_CX(f);
  int const includeSlash = argc
    ? sqlite3_value_int(argv[0])
    : 1;
  if(f && f->db.ckout.dir && f->db.ckout.dirLen){
    sqlite3_result_text(context, f->db.ckout.dir,
                        (int)f->db.ckout.dirLen
                        - (includeSlash ? 0 : 1),
                        SQLITE_TRANSIENT);
  }else{
    sqlite3_result_null(context);
  }
}


/**
    SQL Function to return the check-in time for a file.
    Requires (vid,fid) RID arguments, as described for
    fsl_mtime_of_manifest_file().
 */
static void fsl__udf_checkin_mtime(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  FSL__UDF_CX(f);
  fsl_time_t mtime = 0;
  int rc;
  fsl_id_t vid, fid;
  assert(f);
  assert(2<=argc);
  vid = (fsl_id_t)sqlite3_value_int64(argv[0]);
  fid = (fsl_id_t)sqlite3_value_int64(argv[1]);
  rc = fsl_mtime_of_manifest_file(f, vid, fid, &mtime);
  if( rc==0 ){
    sqlite3_result_int64(context, mtime);
  }else if( FSL_RC_OOM==rc ){
    sqlite3_result_error_nomem(context);
  }else if( f->error.msg.used ){
    sqlite3_result_error(context, (char const *)f->error.msg.mem,
                         (int)f->error.msg.used);
  }else{
    char * const z = fsl_mprintf("fsl_mtime_of_manifest_file() failed "
                                 "for vid %" FSL_ID_T_PFMT
                                 ", fid %" FSL_ID_T_PFMT ": %R",
                                 vid, fid, rc);
    sqlite3_result_error(context, z ? z : fsl_rc_cstr(rc), -1);
    fsl_free(z);
  }
}


/**
   SQL UDF binding for fsl_content_get().

   FSL_CONTENT(RID INTEGER | SYMBOLIC_NAME) returns the
   undeltified/uncompressed content of the [blob] record identified by
   the given RID or symbolic name.
*/
static void fsl__udf_blob_content(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  FSL__UDF_CX(f);
  fsl_id_t rid = 0;
  char const * arg;
  int rc;
  fsl_b b = fsl_b_empty;
  assert(f);
  fsl__cx_host_rollback_check(f);
  if(1 != argc){
    sqlite3_result_error(context, "Expecting one argument", -1);
    return;
  }
  if(SQLITE_INTEGER==sqlite3_value_type(argv[0])){
    rid = (fsl_id_t)sqlite3_value_int64(argv[0]);
    arg = NULL;
  }else{
    arg = (const char*)sqlite3_value_text(argv[0]);
    if(!arg){
      sqlite3_result_error(context, "Invalid argument", -1);
      return;
    }
    rc = fsl_sym_to_rid(f, arg, FSL_SATYPE_ANY, &rid);
    if(rc) goto cx_err;
    else if(!rid){
      sqlite3_result_error(context, "No blob found", -1);
      return;
    }
  }
  rc = fsl_content_get(f, rid, &b);
  if( 0==rc ){
    /* Curiously, i'm seeing no difference in allocation counts here whether
       we copy the blob here or pass off ownership... */
    sqlite3_result_blob(context, b.mem, (int)b.used, fsl_free
                        /* transfer b.mem ownership  ^^^^^^^^ */);
    return;
  }
  cx_err:
  fsl_b_clear(&b);
  if(FSL_RC_OOM==rc){
    sqlite3_result_error_nomem(context);
  }else if( f->error.msg.used ){
    assert(f->error.msg.used);
    sqlite3_result_error(context, (char const *)f->error.msg.mem,
                         (int)f->error.msg.used);
  }else{
    sqlite3_result_error(context, fsl_rc_cstr(rc), -1);
  }
}



/**
   Impl for SQL UDF binding for fsl_uncompress(X) and fsl_compress(X)

   If its argument appears to be fossil-(un)compressed, it is
   (un)compressed and that value is returned, else the argument is
   returned as-is.
*/
static void fsl__udf_press(
  bool isCompress,
  sqlite3_context *cx, int argc, sqlite3_value **argv
){
  sqlite3_value * const arg = argc ? argv[0] : NULL;
  void const * const mem = arg ? sqlite3_value_blob(arg) : NULL;
  int const nMem = mem ? sqlite3_value_bytes(arg) : 0;
  if( !mem || !nMem ){
    sqlite3_result_value(cx, arg);
    return;
  }
  if( isCompress==fsl_data_is_compressed(mem, (fsl_size_t)nMem) ){
    sqlite3_result_value(cx, arg);
    return;
  }

  fsl_b b = fsl_b_empty;
  fsl_b_external(&b, mem, (fsl_int_t)nMem);
  int const rc = isCompress
    ? fsl_b_compress(&b, &b)
    : fsl_b_uncompress(&b, &b);
  switch( rc ){
    case 0:
      sqlite3_result_blob(cx, b.mem, (int)b.used, SQLITE_TRANSIENT);
      break;
    case FSL_RC_OOM:
      sqlite3_result_error_nomem(cx);
      break;
    default:{
      char * const z = fsl_mprintf("%s() failed: %R",
                                   isCompress
                                   ? "fsl_compress" : "fsl_uncompress",
                                   rc);
      sqlite3_result_error(cx, z ? z : fsl_rc_cstr(rc), -1);
      fsl_free(z);
      break;
    }
  }
  fsl_b_clear(&b);
}

static void fsl__udf_uncompress(
  sqlite3_context *cx, int argc, sqlite3_value **argv
){
  fsl__udf_press(false, cx, argc, argv);
}
static void fsl__udf_compress(
  sqlite3_context *cx, int argc, sqlite3_value **argv
){
  fsl__udf_press(true, cx, argc, argv);
}

/**
   SQL UDF FSL_SYM2RID(SYMBOLIC_NAME) resolves the name to a [blob].[rid]
   value or triggers an error if it cannot be resolved.

   Maintenance note: fossil(1) has since expanded this UDF to take 2
   args: (name [, type='ci']). where "type" is the conventional
   short-hand form of the artifact type (ci, t, etc.). libfossil,
   otoh, has always accepted only 1 argument and assumed "*" for the
   artifact type. It also supports a "+" suff
*/
static void fsl__udf_sym2rid(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  FSL__UDF_CX(f);
  char const * arg;
  assert(f);
  if(1 != argc){
    sqlite3_result_error(context, "Expecting one argument", -1);
    return;
  }
  arg = (const char*)sqlite3_value_text(argv[0]);
  if(!arg){
    sqlite3_result_error(context, "Expecting a STRING argument", -1);
  }else{
    fsl_id_t rid = 0;
    int const rc = fsl_sym_to_rid(f, arg, FSL_SATYPE_ANY, &rid);
    if(rc){
      if(FSL_RC_OOM==rc){
        sqlite3_result_error_nomem(context);
      }else{
        assert(f->error.msg.used);
        sqlite3_result_error(context, (char const *)f->error.msg.mem,
                             (int)f->error.msg.used);
      }
      fsl_cx_err_reset(f)
        /* This is arguable but keeps this error from poluting
           down-stream code (seen it happen in unit tests).  The irony
           is, it's very possible/likely that the error will propagate
           back up into f->error at some point.
        */;
    }else{
      /* fossil(1) translates rid==0 to NULL here. */
      assert(rid>0);
      sqlite3_result_int64(context, rid);
    }
  }
}

static void fsl__udf_dirpart(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  char const * arg;
  int rc;
  fsl_b b = fsl_b_empty;
  int fSlash = 0;
  if(argc<1 || argc>2){
    sqlite3_result_error(context,
                         "Expecting (string) or (string,bool) arguments",
                         -1);
    return;
  }
  arg = (const char*)sqlite3_value_text(argv[0]);
  if(!arg){
    sqlite3_result_error(context, "Invalid argument", -1);
    return;
  }
  if(argc>1){
    fSlash = sqlite3_value_int(argv[1]);
  }
  rc = fsl_file_dirpart(arg, -1, &b, fSlash ? 1 : 0);
  if(!rc){
    if(b.used && *b.mem){
#if 0
      sqlite3_result_text(context, (char const *)b.mem,
                          (int)b.used, SQLITE_TRANSIENT);
#else
      sqlite3_result_text(context, (char const *)b.mem,
                          (int)b.used, fsl_free);
      b = fsl_b_empty /* we passed ^^^^^ on ownership of b.mem */;
#endif
    }else{
      sqlite3_result_null(context);
    }
  }else{
    if(FSL_RC_OOM==rc){
      sqlite3_result_error_nomem(context);
    }else{
      char * const z = fsl_mprintf("fsl_dirpart(%Q) failed: %R",
                                   arg, rc);
      sqlite3_result_error(context, z ? z : fsl_rc_cstr(rc), -1);
      fsl_free(z);
    }
  }
  fsl_b_clear(&b);
}


/*
   Implement the user() SQL function.  user() takes no arguments and
   returns the user ID of the current user.
*/
static void fsl__udf_user(
  sqlite3_context *context,
  int argc fsl__unused,
  sqlite3_value **argv fsl__unused
){
  FSL__UDF_CX(f);
  assert(f);
  (void)argc;
  (void)argv;
  if(f->db.repo.user){
    sqlite3_result_text(context, f->db.repo.user, -1, SQLITE_STATIC);
  }else{
    sqlite3_result_null(context);
  }
}

/**
   SQL function:

   fsl_is_enqueued(vfile.id)
   fsl_if_enqueued(vfile.id, X, Y)

   On the commit command, when filenames are specified (in order to do
   a partial commit) the vfile.id values for the named files are
   loaded into the fsl_cx state.  This function looks at that state to
   see if a file is named in that list.

   In the first form (1 argument) return TRUE if either no files are
   named (meaning that all changes are to be committed) or if id is
   found in the list.

   In the second form (3 arguments) return argument X if true and Y if
   false unless Y is NULL, in which case always return X.
*/
static void fsl__udf_selected_for_checkin(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int rc = 0;
  FSL__UDF_CX(f);
  fsl_id_bag * const bag = &f->ckin.selectedIds;
  assert(f);
  assert(argc==1 || argc==3);
  if( bag->entryCount ){
    fsl_id_t const iId = (fsl_id_t)sqlite3_value_int64(argv[0]);
    rc = iId ? (fsl_id_bag_contains(bag, iId) ? 1 : 0) : 0;
  }else{
    rc = 1;
  }
  if(1==argc){
    sqlite3_result_int(context, rc);
  }else{
    assert(3 == argc);
    assert( rc==0 || rc==1 );
    if( sqlite3_value_type(argv[2-rc])==SQLITE_NULL ) rc = 1-rc;
    sqlite3_result_value(context, argv[2-rc]);
  }
}

/**
   fsl_match_vfile_or_dir(p1,p2)

   A helper for resolving expressions like:

   WHERE pathname='X' C OR
      (pathname>'X/' C AND pathname<'X0' C)

   i.e. is 'X' a match for the LHS or is it a directory prefix of
   LHS?

   C = empty or COLLATE NOCASE, depending on the case-sensitivity
   setting of the calling context (FSL__UDF_CX). p1 is typically
   vfile.pathname or vfile.origname, and p2 is the string being
   compared against that.

   Resolves to NULL if either argument is NULL, 0 if the comparison
   shown above is false, 1 if the comparison is an exact match, or 2
   if p2 is a directory prefix part of p1.
*/
static void fsl__udf_match_vfile_or_dir(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  FSL__UDF_CX(f);
  char const * p1;
  char const * p2;
  fsl_b * b = 0;
  int rc = 0;
  assert(f);
  if(2 != argc){
    sqlite3_result_error(context, "Expecting two arguments", -1);
    return;
  }
  p1 = (const char*)sqlite3_value_text(argv[0]);
  p2 = (const char*)sqlite3_value_text(argv[1]);
  if(!p1 || !p2){
    sqlite3_result_null(context);
    return;
  }
  int (*cmp)(char const *, char const *) =
    fsl_cx_is_case_sensitive(f, false) ? fsl_strcmp : fsl_stricmp;
  if(0==cmp(p1, p2)){
    sqlite3_result_int(context, 1);
    return;
  }
  b = fsl__cx_scratchpad(f);
  rc = fsl_b_appendf(b, "%s/", p2);
  if(rc) goto oom;
  else if(cmp(p1, fsl_b_cstr(b))>0){
    b->mem[b->used-1] = '0';
    if(cmp(p1, fsl_b_cstr(b))<0)
    rc = 2;
  }
  assert(0==rc || 2==rc);
  sqlite3_result_int(context, rc);
  end:
  fsl__cx_scratchpad_yield(f, b);
  return;
  oom:
  sqlite3_result_error_nomem(context);
  goto end;
}

/**
   F(glob-list-name, filename)

   Returns 1 if the 2nd argument matches any glob in the fossil glob
   list named by the first argument. The first argument must be a name
   resolvable via fsl_glob_name_to_category() or an error is
   triggered. The second value is intended to be a string, but NULL is
   accepted (but never matches anything).

   If no match is found, 0 is returned. An empty glob list never matches
   anything.
*/
static void fsl__udf_cx_glob(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  FSL__UDF_CX(f);
  fsl_list * li = NULL;
  fsl_glob_category_e globType;
  char const * p1;
  char const * p2;
  assert( f );
  assert(2<=argc);
  p2 = (const char*)sqlite3_value_text(argv[1])/*value to check*/;
  if(NULL==p2 || 0==p2[0]){
    sqlite3_result_int(context, 0);
    return;
  }
  p1 = (const char*)sqlite3_value_text(argv[0])/*glob set name*/;
  globType  = fsl_glob_name_to_category(p1);
  if(FSL_GLOBS_INVALID==globType){
    char buf[100] = {0};
    buf[sizeof(buf)-1] = 0;
    fsl_snprintf(buf, (fsl_size_t)sizeof(buf)-1,
                 "Unknown glob pattern name: %#.*s",
                 50, p1 ? p1 : "NULL");
    sqlite3_result_error(context, buf, -1);
    return;
  }
  fsl_cx_glob_list(f, globType, &li, false);
  assert(li);
  sqlite3_result_int(context, fsl_glob_list_matches(li, p2) ? 1 : 0);
}

/* artifact-to-json(RID|ARTIFACT_NAME) */
static void fsl__udf_cx_a2j(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  FSL__UDF_CX(f);
  fsl_b * b = NULL;
  int rc;
  fsl_deck d = fsl_deck_empty;
  assert( f );
  fsl__cx_host_rollback_check(f);
  if(1 != argc){
  error_usage:
    sqlite3_result_error(context, "Expecting one argument: blob.rid "
                         "or artifact symbolic name", -1);
    return;
  }
  switch( sqlite3_value_type(argv[0]) ){
    case SQLITE_INTEGER:
      rc = fsl_deck_load_rid(f, &d, (fsl_id_t)sqlite3_value_int64(argv[0]),
                             FSL_SATYPE_ANY);
      break;
    case SQLITE_TEXT:
      rc = fsl_deck_load_sym(f, &d,
                             (const char *)sqlite3_value_text(argv[0]),
                             FSL_SATYPE_ANY);
      break;
    default:
      goto error_usage;
  }
  switch(rc){
    case 0: break;
    case FSL_RC_OOM:
      sqlite3_result_error_nomem(context);
      goto cleanup;
    default:
      sqlite3_result_null(context);
      // ^^^ for compat with fossil(1)
      /*sqlite3_result_error(context, (char const *)f->error.msg.mem,
        (int)f->error.msg.used);*/
      fsl_cx_err_reset(f)
        /* The NULL result reports the failure, so don't leave it in
           f's error state for unrelated downstream code to find. */;
      goto cleanup;
  }
  b = fsl__cx_content_buffer(f);
  rc = fsl_deck_to_json(&d, fsl_output_f_b, b);
  if( rc ){
    if( FSL_RC_OOM==rc ){
      sqlite3_result_error_nomem(context);
    }else{
      sqlite3_result_null(context);
    }
  }else{
    fsl_size_t n = 0;
    const char * z = fsl_b_cstr2(b, &n);
    sqlite3_result_text(context, z, (int)n, SQLITE_TRANSIENT);
  }
cleanup:
  if(b) fsl__cx_content_buffer_yield(f);
  fsl_deck_finalize(&d);
  return;
}

/**
   Plug in fsl_cx-specific db functionality into the given db handle
   and sets it as f->dbMain. This must only be passed the MAIN db
   handle for the context.
*/
int fsl__cx_init_db(fsl_cx * const f, fsl_db * const db){
  int rc = 0;
  assert(!f->dbMain);
  f->dbMain = db;
  db->role = FSL_DBROLE_MAIN;
  /* This all comes from db.c:db_open()... */
  /* FIXME: check result codes here. */
  sqlite3 * const dbh = db->dbh;
  bool first = false;
  /* The connection's "fsl_cxreg" client data lists the contexts using
     it (see fsl__cxreg). Db routines which do not have their context
     bound as their state reach it via sqlite3_context_db_handle()
     and fsl__cx_for_dbh(). */
  if( fsl__cxreg_join(f, db, &first) ){
    return fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  }
  if( !first ){
    /* Another context on this (host's) connection has already added
       the SQL functions, which find their context per call. */
    return 0;
  }
  bool const borrowed = fsl__db_is_borrowed(db);
  if( !borrowed ){
    /* A host's connection keeps the host's settings. Its
       foreign_keys setting is checked by fsl__cx_attach_host(). */
    sqlite3_busy_timeout(dbh, 5000 /* historical value */);
    sqlite3_wal_autocheckpoint(dbh, 1);  /* Set to checkpoint frequently */
    rc = fsl_cx_exec_multi(f,
                           "PRAGMA foreign_keys=OFF;"
                           // ^^^ vmerge table relies on this for its magical
                           // vmerge.id values.
                           //"PRAGMA main.temp_store=FILE;"
                           //"PRAGMA main.journal_mode=TRUNCATE;"
                           // ^^^ note that WAL is not possible on a TEMP db
                           // and OFF leads to undefined behaviour if
                           // ROLLBACK is used!
                           );
    if(rc) goto end;
  }
#define FLAGS_D SQLITE_UTF8 | SQLITE_DETERMINISTIC
#define FLAGS_I SQLITE_UTF8 | SQLITE_INNOCUOUS
#define FLAGS_DI FLAGS_D | SQLITE_INNOCUOUS
  if( !borrowed ){
    /* Kept for client SQL. The library uses fsl_now(), which cannot
       replace a host's own now(). */
    sqlite3_create_function(dbh, "now", 0, SQLITE_UTF8, 0,
                            fsl__udf_now, 0, 0);
  }
  sqlite3_create_function(dbh, "fsl_now", 0, SQLITE_UTF8, 0,
                          fsl__udf_now, 0, 0);
  /* The functions find their context per call (FSL__UDF_CX), as
     several may share the connection, so they get no user data. */
  sqlite3_create_function(dbh, "fsl_ci_mtime", 2,
                          FLAGS_D, NULL,
                          fsl__udf_checkin_mtime, 0, 0);
  sqlite3_create_function(dbh, "fsl_user", 0,
                          FLAGS_DI, NULL,
                          fsl__udf_user, 0, 0);
  sqlite3_create_function(dbh, "fsl_print", -1,
                          SQLITE_UTF8
                          /* not strictly SQLITE_DETERMINISTIC
                             because it produces arbitrary output */,
                          NULL, fsl__udf_print,0,0);
  sqlite3_create_function(dbh, "fsl_content", 1,
                          FLAGS_D, NULL,
                          fsl__udf_blob_content, 0, 0);
  sqlite3_create_function(dbh, "fsl_sym2rid", 1,
                          FLAGS_I,
                          NULL,
                          fsl__udf_sym2rid, 0, 0);
  sqlite3_create_function(dbh, "fsl_dirpart", 1,
                          FLAGS_D, NULL,
                          fsl__udf_dirpart, 0, 0);
  sqlite3_create_function(dbh, "fsl_dirpart", 2,
                          FLAGS_D, NULL,
                          fsl__udf_dirpart, 0, 0);
  sqlite3_create_function(dbh, "fsl_j2u", 1,
                          FLAGS_DI, NULL,
                          fsl__udf_j2u, 0, 0);
  sqlite3_create_function(dbh, "fsl_artifact_to_json", 1,
                          SQLITE_UTF8, NULL, fsl__udf_cx_a2j, 0, 0 );

  sqlite3_create_function(dbh, "fsl_uncompress", 1,
                          FLAGS_D, NULL,
                          fsl__udf_uncompress, 0, 0);
  sqlite3_create_function(dbh, "fsl_compress", 1,
                          FLAGS_D, NULL,
                          fsl__udf_compress, 0, 0);

  /*
    fsl_i[sf]_selected() both require access to the f's list of
    files being considered for commit.
  */
  sqlite3_create_function(dbh, "fsl_is_enqueued", 1, SQLITE_UTF8, NULL,
                          fsl__udf_selected_for_checkin,0,0 );
  sqlite3_create_function(dbh, "fsl_if_enqueued", 3, SQLITE_UTF8, NULL,
                          fsl__udf_selected_for_checkin,0,0 );

  sqlite3_create_function(dbh, "fsl_ckout_dir", -1,
                          FLAGS_D,
                          NULL, fsl__udf_chkout_dir,0,0 );
  sqlite3_create_function(dbh, "fsl_match_vfile_or_dir", 2,
                          FLAGS_D,
                          NULL, fsl__udf_match_vfile_or_dir,0,0 );
  sqlite3_create_function(dbh, "fsl_glob", 2,
                          FLAGS_D,
                          /* noting that ^^^^^ it's only deterministic
                             for a given statement execution IF no SQL
                             triggers an effect which forces the globs to
                             reload. That "shouldn't ever happen." */
                          NULL, fsl__udf_cx_glob, 0, 0 );

#if FSL_ENABLE_SQLITE_REGEXP
  if( !borrowed ) rc = fsl__regexp_init(dbh, NULL, NULL);
  if( rc ){
    rc = fsl_cx_err_set(f, FSL_RC_ERROR, "Registering the REGEXP SQL "
                        "function failed with sqlite code #%d.", rc);
    goto end;
  }
#endif

  rc = fsl__foci_register(f, db);
  if( rc ) rc = fsl_cx_uplift_db_error2(f, db, rc);
  end:
#undef FLAGS_D
#undef FLAGS_I
#undef FLAGS_DI
  return rc;
}


/**
   Removes f from a borrowed db handle's context registry and, if f was
   the last context using it, the SQL functions and modules
   fsl__cx_init_db() added to it, since the handle outlives f. Keep
   this list in sync with fsl__cx_init_db().
*/
void fsl__cx_uninit_db(fsl_cx * const f, fsl_db * const db){
  static const struct { char const *zName; int nArg; } aFunc[] = {
    {"fsl_now", 0}, {"fsl_ci_mtime", 2}, {"fsl_user", 0},
    {"fsl_print", -1}, {"fsl_content", 1}, {"fsl_sym2rid", 1},
    {"fsl_dirpart", 1}, {"fsl_dirpart", 2}, {"fsl_j2u", 1},
    {"fsl_artifact_to_json", 1}, {"fsl_uncompress", 1},
    {"fsl_compress", 1}, {"fsl_is_enqueued", 1}, {"fsl_if_enqueued", 3},
    {"fsl_ckout_dir", -1}, {"fsl_match_vfile_or_dir", 2},
    {"fsl_glob", 2}
  };
  sqlite3 * const dbh = db->dbh;
  assert( fsl__db_is_borrowed(db) );
  (void)f;
  if( fsl__cxreg_leave(db) ) return /* others still use them */;
  for( unsigned i = 0; i < sizeof(aFunc)/sizeof(aFunc[0]); ++i ){
    sqlite3_create_function(dbh, aFunc[i].zName, aFunc[i].nArg,
                            SQLITE_UTF8, 0, 0, 0, 0);
  }
  sqlite3_create_module(dbh, "fsl_foci", NULL, NULL);
}

#undef MARKER
/* end of file src/udf.c */
/* start of file src/url.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2025 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2025 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*
  This file houses the fsl_url APIs.
*/

#include <assert.h>
#include <stdlib.h> /* strtoul() */
#include <string.h> /* strcspn() */

#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

const fsl_url fsl_url_empty = fsl_url_empty_m;

static inline bool fsl__is_scheme_ch(int i){
  return fsl_isalpha(i);
  //&& i!=(int)'-' && i!=(int)'+' && i!=(int)'.';
}

static int fsl__url_hexval(int c){
  if( c>='0' && c<='9' ) return c-'0';
  if( c>='a' && c<='f' ) return c-'a'+10;
  if( c>='A' && c<='F' ) return c-'A'+10;
  return -1;
}

/*
** Decodes the %XX escapes in z in place, as fossil(1) does for the
** user name and password of a URL. A '%' not followed by two hex
** digits is kept as it is. Returns false if an escape decodes to NUL,
** which cannot be represented in these C strings.
*/
static bool fsl__url_pct_decode(char *z){
  char *zOut = z;
  for( ; *z; ++z ){
    int const hi = '%'==z[0] ? fsl__url_hexval(z[1]) : -1;
    int const lo = hi>=0 ? fsl__url_hexval(z[2]) : -1;
    if( lo>=0 ){
      char const c = (char)(hi*16 + lo);
      if( !c ) return false;
      *zOut++ = c;
      z += 2;
    }else{
      *zOut++ = *z;
    }
  }
  *zOut = 0;
  return true;
}

/*
** Appends z to b, percent-encoding each ASCII character which would
** end or corrupt a URL's user name, password or host name. Bytes of
** non-ASCII UTF-8 are kept, as fossil(1) keeps them, so that a
** rendered URL, and the saved-password key made from it, stays the
** same for a name written in UTF-8.
*/
static void fsl__url_userinfo_append(fsl_b * const b, char const *z){
  for( ; *z; ++z ){
    unsigned char const c = (unsigned char)*z;
    if( c<=0x20 || 0x7f==c || strchr("%:@/?#[]", c) ){
      fsl_b_appendf(b, "%%%02X", (unsigned)c);
    }else{
      fsl_b_appendch(b, (char)c);
    }
  }
}

#ifndef NDEBUG
static void fsl__url_dump(fsl_url const * u){
#define out(M,FMT) MARKER(("u->%-10s = " FMT "\n", #M, u->M))
#define outS(M) if( u->M ) { out(M,"%s"); } (void)0
#define outI(M) if( u->M > 0 ) {out(M,"%d"); } (void)0
  MARKER(("URL: %s\n", u->raw));
  outS(scheme);
  outS(username);
  outS(password);
  outS(host);
  outI(port);
  outS(path);
  outS(query);
  outS(fragment);
#undef out
}
#endif

void fsl_url_cleanup2(fsl_url * const u, bool clearBuffer){
  if( clearBuffer ){
    fsl_b_clear(&u->impl.b);
    *u = fsl_url_empty;
  }else{
    fsl_b const x = u->impl.b;
    *u = fsl_url_empty;
    u->impl.b = x;
    fsl_b_reuse(&u->impl.b);
  }
}

void fsl_url_cleanup(fsl_url * const u){
  fsl_url_cleanup2(u, true);
}

int fsl_url_parse(fsl_url * const u, char const * z){
  int rc = 0;
  enum ParseState {
    e_Start, e_Slashes, e_UserOrHost, e_Host, e_Port,
    e_Path, e_Query, e_Fragment, e_Done,
    e_Err
  };
  fsl_b * const b = &u->impl.b;
  char const *zLeft = z;
  fsl_size_t const nZ = fsl_strlen(z);
  char const * const zEnd = z + nZ;
  enum ParseState state = e_Start;
  bool isFile = false;

  fsl_url_cleanup2(u, false);
  if( !z || !*z ) return FSL_RC_MISUSE;
  fsl_b_reserve(b,
                     nZ * 2
                     + (9 /*NUL bytes*/)
                     + (('.'==*z || '/'==*z)
                        ? 5 /*synthetic "file\0" scheme*/
                        : 0))
    /* Large enough to avoid another allocation. */;
  fsl_b_append( b, z, (fsl_int_t)nZ );
  fsl_b_appendch(b, 0);
  if( b->errCode ) goto oom;
  u->raw = (char const *)b->mem;

#define bstr ((char const *)b->mem + b->used)
#define checkOom(P) if(!(P)) goto oom
#define setstr(MEMBER)                                 \
  assert( z>=zLeft );                                  \
  assert( b->capacity > (b->used + (z - zLeft)) && "Else buffer is too small" ); \
  u->MEMBER = bstr;                                    \
  fsl_b_append(b, zLeft, (fsl_int_t)(z - zLeft)); \
  fsl_b_appendch(b, 0);                           \
  if( b->errCode ) goto end

#define checkEnd(nEXTRA) if( (z + nEXTRA)>=zEnd ) goto syntax_err

start:
  assert( e_Done!=state );
  switch( (rc=b->errCode) ? e_Err : state ){
    case e_Err: break;

    case e_Start:
      if( '/' == *z || '.' == *z
#if defined(_WIN32)
          /* A drive-letter path, e.g. C:/x or C:\x, is a file, not a
             URL with a one-letter scheme. */
          || (z+2<zEnd && fsl_isalpha(z[0]) && ':'==z[1]
              && ('/'==z[2] || '\\'==z[2]))
#endif
          ){
        u->scheme = bstr;
        fsl_b_append(b, "file\0", 5);
        state = e_Slashes;
        isFile = true;
        break;
      }
      for( zLeft = z; z<zEnd && *z; ++z ){
        if( ':'==*z ){
          setstr(scheme);
          /* Schemes are case-insensitive (RFC 3986 section 3.1).
             Keep the lower-case form, which callers compare with. */
          for( char * zs = (char *)u->scheme; *zs; ++zs ){
            if( *zs>='A' && *zs<='Z' ) *zs += 'a' - 'A';
          }
          isFile = 0==fsl_strcmp(u->scheme, "file");
          ++z;
          state = e_Slashes;
          break;
        }else if( !fsl__is_scheme_ch(*z) ){
          goto syntax_err;
        }
      }
      checkEnd(0);
      break;

    case e_Slashes: {
      int nSlash = 0;
      checkEnd(0);
      for( zLeft = z; z+nSlash<zEnd && '/'==z[nSlash]; ++nSlash ){}
      checkEnd(nSlash);
      switch( nSlash ) {
        case 0:
        case 1:
          if( isFile ){
            z = zEnd;
            setstr(path);
            state = e_Done;
            break;
          }
          goto syntax_err;
        case 2:
          zLeft += nSlash;
          if( isFile ){
            z = zEnd;
            setstr(path);
            state = e_Done;
          }else{
            state = e_UserOrHost;
            z = zLeft;
          }
          break;
        default:
          if( 3==nSlash && isFile ){
            zLeft += 2;
            z = zEnd;
            setstr(path);
            state = e_Done;
            break;
          }
          goto syntax_err;
      }
      break;
    }

    case e_UserOrHost:{
      /* Only an '@' before the path, query, or fragment ends a user
         name. */
      char const * zAt = memchr(z, '@', strcspn(z, "/?#"));
      //MARKER(("state=%d zAt=%s\n",state, zAt));
      if( zAt ){
        if( zAt==z ) goto syntax_err;
        size_t const nColon = strcspn(z, ":");
        if( nColon && (z+nColon < zAt) ){ /* X:Y@Z */
          zLeft = z;
          z = z + nColon;
          setstr(username);
          zLeft = ++z;
          z = zAt;
          setstr(password);
          if( !fsl__url_pct_decode((char *)u->password) ) goto syntax_err;
          zLeft = ++z;
        }else{ /* X@Y */
          z = zAt;
          setstr(username);
          zLeft = ++z;
        }
        if( !fsl__url_pct_decode((char *)u->username) ) goto syntax_err;
      }
      state = e_Host;
      break;
    }

    case e_Host:{
      size_t n;
      if( '['==*z ){
        /* IP literal, for example "[::1]", kept with its brackets. It
           must be closed before the path, query, or fragment. */
        n = 1 + strcspn(z + 1, "]/?#");
        if( ']'!=z[n] || n<2 ) goto syntax_err;
        ++n;
        if( z[n] && !strchr("/:?#", z[n]) ) goto syntax_err;
      }else{
        n = strcspn(z, "/:?#");
      }
      if( n ){
        for( size_t i = 0; i < n; ++i ){
          /* RFC 3986 allows no whitespace or control characters in a
             host, and brackets only around an IP literal. */
          unsigned char const c = (unsigned char)z[i];
          if( c<=0x20 || 0x7f==c
              || ('['==c && i) || (']'==c && i!=n-1)
              || (']'==c && '['!=*z) ){
            goto syntax_err;
          }
        }
        zLeft = z;
        z += n;
        setstr(host);
        if( '['!=*u->host ){
          /* A host name may be percent-encoded (RFC 3986 section
             3.2.2), and fossil(1) decodes it. The decoded name may
             not contain whitespace or control characters either. */
          if( !fsl__url_pct_decode((char *)u->host) ) goto syntax_err;
          for( char const * zh = u->host; *zh; ++zh ){
            unsigned char const c = (unsigned char)*zh;
            if( c<=0x20 || 0x7f==c ) goto syntax_err;
          }
        }
        state = (':'==*z)
          ? e_Port
          : (('?'==*z) ? e_Query : e_Path);
      }else{
        /* Empty host, for example "http://user@:80/path". */
        goto syntax_err;
      }
      //MARKER(("state=%d z=%s\n",state, z));
      break;
    }

    case e_Port:{
      if( ':'==*z ){
        char * zTail = 0;
        unsigned long const port = strtoul(z + 1, &zTail, 10);
        zLeft = ++z;
        assert( 0==u->port );
        if( zTail==z
            && (z==zEnd || '/'==*z || '?'==*z || '#'==*z) ){
          /* An empty port, for example "ssh://host:/path". */
          state = (z==zEnd) ? e_Done : e_Path;
        }else if( zTail>z
            && port>0
            && port<=65535
            && (zTail==zEnd || '/'==*zTail
                || '?'==*zTail || '#'==*zTail) ){
          u->port = (uint16_t)port;
          z = zTail;
          state = (z==zEnd) ? e_Done : e_Path;
        }else{
          goto syntax_err;
        }
      }else{
        state = e_Path;
      }
      break;
    }

    case e_Path: {
      if( z>=zEnd ){
        assert( zLeft<=z );
        state = e_Done;
      }else{
        size_t const n = strcspn(z, "?#");
        if( n ){
          zLeft = z;
          z += n;
          setstr(path);
        }
        state = (z<zEnd) ? e_Query : e_Done;
      }
      break;
    }

    case e_Query:{
      assert( z<zEnd );
      assert( '?'==*z || '#'==*z );
      if( '#'==*z ){
        state = e_Fragment;
      }else{
        size_t const n = strcspn(z, "#");
        if( n ){
          zLeft = z;
          z += n;
          setstr(query);
          state = (z < zEnd) ? e_Fragment : e_Done;
        }else{
          /* z points to '?', so strcspn(z, "#") must be non-zero. */
          goto syntax_err;
        }
      }
      break;
    }

    case e_Fragment:{
      assert(z<zEnd && '#'==*z);
      zLeft = z;
      z = zEnd;
      setstr(fragment);
      state = e_Done;
      break;
    }

    case e_Done:
      fsl__fatal(FSL_RC_CANNOT_HAPPEN, "This is impossible");
  }
#undef setstr
#undef checkEnd
#undef checkOom
#undef bstr

  if( e_Start==state ) goto syntax_err;
  if( 0==rc && e_Done!=state ){
    goto start;
  }

end:

  if( 0==rc ){
#ifndef NDEBUG
    if(0) fsl__url_dump(u);
#endif
    if( !u->scheme || !*u->scheme ) goto syntax_err;
    if( isFile ){
      assert( !u->host );
      if( !u->path || !*u->path ) goto syntax_err;
      if( '/'!=*u->raw && '.'!=*u->raw ){
        /* The path of a file: URL may be percent-encoded (RFC 8089),
           and fossil(1) decodes it. A plain path given in place of a
           URL is used as written. */
        if( !fsl__url_pct_decode((char *)u->path) ) goto syntax_err;
      }
    }else{
      if( !u->host || !*u->host ) goto syntax_err;
    }
    assert( u->port >= 0 && u->port<=65535 );
    // TODO: Validate scheme, username, password, host, path, query,
    // and fragment characters against RFC 3986.
  }

  if( rc ){
    fsl_url_cleanup2(u, true);
  }
  return rc;

oom:
  rc = FSL_RC_OOM;
  goto end;

syntax_err:
  rc = FSL_RC_SYNTAX;
  goto end;
}

int fsl_url_render(fsl_url const * const u, fsl_b * const b,
                   fsl_flag32_t flags){
  int rc = b->errCode;
  if( rc ) return rc;

#define ba(piece,N) if(piece) fsl_b_append( b, piece, N )
#define bac(CH) fsl_b_appendch( b, CH )
#define baf fsl_b_appendf
  if( 0==(flags & FSL_URL_RENDER_NO_SCHEME) ){
    ba(u->scheme, -1);
    ba("://", 3);
  }
  if( 0==(flags & FSL_URL_RENDER_NO_USER)
      && u->username ){
    fsl__url_userinfo_append(b, u->username);
    if( u->password && 0==(FSL_URL_RENDER_NO_PASSWORD & flags) ){
      if( FSL_URL_RENDER_MASK_PASSWORD & flags ){
        ba(":****",5);
      }else{
        bac(':');
        fsl__url_userinfo_append(b, u->password);
      }
    }
    bac('@');
  }
  if( u->host && '['!=*u->host ){
    fsl__url_userinfo_append(b, u->host);
  }else{
    ba(u->host, -1);
  }
  if( u->port>0 ){
    /* TODO: elide default ports for http(s) and ssh. */
    baf(b, ":%d", u->port);
  }
  ba(u->path,-1);
  if( 0==(flags & FSL_URL_RENDER_NO_QUERY) ){
    ba(u->query,-1);
    if( 0==(flags & FSL_URL_RENDER_NO_FRAGMENT) ){
      ba(u->fragment,-1);
    }
  }
#undef ba
#undef bac
#undef baf
  return b->errCode;
}

void fsl_url_swap(fsl_url * lhs, fsl_url *rhs){
  if( lhs!=rhs ){
    fsl_url const tmp = *lhs;
    *lhs = *rhs;
    *rhs = tmp;
  }
}

bool fsl_url_next_query_arg(fsl_url const * u, char const **zCursor,
                            fsl_b * bKey, fsl_b * bVal){
  char const * zBegin = *zCursor ? *zCursor : u->query;
  char const * const zEnd = u->fragment
    ? u->fragment : (char const *)(u->impl.b.mem + u->impl.b.used);
  fsl_b_reuse(bKey);
  fsl_b_reuse(bVal);
  if( !zBegin || zBegin>=zEnd ) return false;
  if( !*zCursor && '?'==*zBegin ) ++zBegin;
  char const * z = zBegin;
  for( ; z<zEnd && *z && *z=='&'; ++z ){/*Leading & from prev run*/}
  zBegin = z;
  for( ; z<zEnd && *z && *z!='&' && *z!='='; ++z ){/* next '=' or '&' */}
  if( z==zBegin ) return false;
  if( 0!=fsl_b_appendf(bKey, "%.*T", (int)(z-zBegin), zBegin) ){
    return false;
  }
  if( '='==*z ){
    char const * x = ++z;
    for( ; z<zEnd && *z && *z!='&'; ++z ){}
    if( z>x ){
      if( 0!=fsl_b_appendf(bVal, "%.*T", (int)(z - x), x) ){
        return false;
      }
    }
  }
  *zCursor = z;
  return true;
}

#undef MARKER
/* end of file src/url.c */
/* start of file src/utf8.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
** Copyright (c) 2017 D. Richard Hipp
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
** known as the "2-Clause License" or "FreeBSD License".)
**
** This program is distributed in the hope that it will be useful,
** but without any warranty; without even the implied warranty of
** merchantability or fitness for a particular purpose.
**
** Author contact information:
**   [email protected]
**   http://www.hwaci.com/drh/
**
*******************************************************************************
**
** This file contains an implementation of SHA3 (Keccak) hashing.
*/
/**
   This copy has been modified slightly for use with the libfossil
   API.
*/

#include <assert.h>
#include <stddef.h> /* NULL on linux */
#include <ctype.h>

#ifdef _WIN32
# include <windows.h>
#else
#ifdef __CYGWIN__
# include <sys/cygwin.h>
# define CP_UTF8 65001
  __declspec(dllimport) extern __stdcall int WideCharToMultiByte(int, int,
      const char *, int, const char *, int, const char *, const char *);
  __declspec(dllimport) extern __stdcall int MultiByteToWideChar(int, int,
      const char *, int, wchar_t*, int);
#endif
/* /Cygwin */
/* Assume Unix */
#include <stdlib.h> /* getenv() */
#endif


#if defined(__APPLE__) && !defined(WITHOUT_ICONV)
# include <iconv.h>
#endif

#ifdef _WIN32
/* Converts from the ANSI code page to UTF-8 with the Win32 API rather
   than sqlite3_win32_mbcs_to_utf8(), which is not in the API table a
   loadable SQLite extension sees. */
char *fsl_mbcs_to_utf8(const char *zMbcs){
  int const nWide = MultiByteToWideChar(CP_ACP, 0, zMbcs, -1, 0, 0);
  wchar_t *zWide;
  char *zUtf = 0;
  if( nWide<=0 ) return 0;
  zWide = (wchar_t *)fsl_malloc( nWide * sizeof(wchar_t) );
  if( !zWide ) return 0;
  if( MultiByteToWideChar(CP_ACP, 0, zMbcs, -1, zWide, nWide)>0 ){
    zUtf = fsl_unicode_to_utf8(zWide);
  }
  fsl_free(zWide);
  return zUtf;
}

void fsl_mbcs_free(char *zOld){
  fsl_free(zOld);
}
#endif /* _WIN32 */

void fsl_unicode_free(void *p){
  if(p) fsl_free(p);
}

char *fsl_unicode_to_utf8(const void *zUnicode){
#if defined(_WIN32) || defined(__CYGWIN__)
  int nByte = WideCharToMultiByte(CP_UTF8, 0, zUnicode, -1, 0, 0, 0, 0);
  char *zUtf = (char *)fsl_malloc( nByte );
  if( zUtf ){
    WideCharToMultiByte(CP_UTF8, 0, zUnicode, -1, zUtf, nByte, 0, 0);
  }
  return zUtf;
#else
  return fsl_strdup((char const *)zUnicode);  /* TODO: implement for unix */
#endif
}

void *fsl_utf8_to_unicode(const char *zUtf8){
#if defined(_WIN32) || defined(__CYGWIN__)
  int nByte = MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, 0, 0);
  wchar_t *zUnicode = (wchar_t *)fsl_malloc( nByte * 2 );
  if( zUnicode ){
    MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, zUnicode, nByte);
  }
  return zUnicode;
#else
  return fsl_strdup(zUtf8);  /* TODO: implement for unix */
#endif
}

/*
   We find that the built-in isspace() function does not work for
   some international character sets.  So here is a substitute.
*/
bool fsl_isspace(int c){
  switch(c){
    case 9: case 10: case 11:
    case 12: case 13: case 32: return true;
  }
  return false;
}

/*
   Other replacements for ctype.h functions.
*/
bool fsl_islower(int c){ return c>='a' && c<='z'; }
bool fsl_isupper(int c){ return c>='A' && c<='Z'; }
bool fsl_isdigit(int c){ return c>='0' && c<='9'; }
int fsl_tolower(int c){
  return fsl_isupper(c) ? c - 'A' + 'a' : c;
}
int fsl_toupper(int c){
  return fsl_islower(c) ? c - 'a' + 'A' : c;
}
bool fsl_isalpha(int c){
  return (c>='a' && c<='z') || (c>='A' && c<='Z');
}
bool fsl_isalnum(int c){
  return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9');
}


void fsl_os_str_free(void *pOld){
#if defined(_WIN32)
  fsl_free(pOld);
#elif (defined(__APPLE__) && !defined(WITHOUT_ICONV)) || defined(__CYGWIN__)
  fsl_free(pOld);
#else
  (void)pOld;
  /* No-op on all other unix */
#endif
}

char *fsl_filename_to_utf8(const void *zFilename){
#if defined(_WIN32)
  int nByte = WideCharToMultiByte(CP_UTF8, 0, zFilename, -1, 0, 0, 0, 0);
  char *zUtf = fsl_malloc( nByte );
  char *pUtf, *qUtf;
  if( zUtf==0 ){
    return 0;
  }
  WideCharToMultiByte(CP_UTF8, 0, zFilename, -1, zUtf, nByte, 0, 0);
  pUtf = qUtf = zUtf;
  while( *pUtf ) {
    if( *pUtf == (char)0xef ){
      wchar_t c = ((pUtf[1]&0x3f)<<6)|(pUtf[2]&0x3f);
      /* Only really convert it when the resulting char is in range. */
      if ( c && ((c < ' ') || wcschr(L"\"*:<>?|", c)) ){
        *qUtf++ = c; pUtf+=3; continue;
      }
    }
    *qUtf++ = *pUtf++;
  }
  *qUtf = 0;
  return zUtf;
#elif defined(__CYGWIN__)
  char *zOut;
  zOut = fsl_strdup(zFilename)
    /*
      Required for consistency with fsl_utf8_to_filename(),
      so that fsl_os_str_free() can DTRT.
    */;
  return zOut;
#elif defined(__APPLE__) && !defined(WITHOUT_ICONV)
  char *zIn = (char*)zFilename;
  char *zOut;
  iconv_t cd;
  size_t n, x;
  for(n=0; zIn[n]>0 && zIn[n]<=0x7f; n++){}
  if( zIn[n]!=0 && (cd = iconv_open("UTF-8", "UTF-8-MAC"))!=(iconv_t)-1 ){
    char *zOutx;
    char *zOrig = zIn;
    size_t nIn, nOutx;
    nIn = n = fsl_strlen(zIn);
    nOutx = nIn+100;
    zOutx = zOut = (char *)fsl_malloc( nOutx+1 );
    if(!zOutx) return NULL;
    x = iconv(cd, &zIn, &nIn, &zOutx, &nOutx);
    if( x==(size_t)-1 ){
      fsl_free(zOut);
      zOut = fsl_strdup(zOrig);
    }else{
      zOut[n+100-nOutx] = 0;
    }
    iconv_close(cd);
  }else{
    zOut = fsl_strdup(zFilename);
  }
  return zOut;
#else
  return (char *)zFilename;  /* No-op on non-mac unix */
#endif
}

void *fsl_utf8_to_filename(const char *zUtf8){
#ifdef _WIN32
  /**
     Maintenance note 2021-03-24: fossil's counterpart of this has
     been extended since this code was ported:

     void *fossil_utf8_to_path(const char *zUtf8, int isDir)

     That isDir param is only for Windows and its only purpose is to
     ensure that the translated path is not within 12 bytes of
     MAX_PATH. That same effect can be had by simply always assuming
     that bool is true and sacrificing those 12 bytes and that
     far-edge (literally) case.

     Also, the newer code jumps through many hoops which seem
     unimportant for fossil, e.g. handling UNC-style paths.

     Porting that latter bit over requires someone who can at least
     test whether it compiles.
  */
  int nChar = MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, 0, 0);
  wchar_t *zUnicode = fsl_malloc( nChar * 2 );
  wchar_t *wUnicode = zUnicode;
  if( zUnicode==0 ){
    return 0;
  }
  MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, zUnicode, nChar);
  /* If path starts with "<drive>:/" or "<drive>:\", don't translate the ':' */
  if( fsl_isalpha(zUtf8[0]) && zUtf8[1]==':'
           && (zUtf8[2]=='\\' || zUtf8[2]=='/')) {
    zUnicode[2] = '\\';
    wUnicode += 3;
  }
  while( *wUnicode != '\0' ){
    if ( (*wUnicode < ' ') || wcschr(L"\"*:<>?|", *wUnicode) ){
      *wUnicode |= 0xF000;
    }else if( *wUnicode == '/' ){
      *wUnicode = '\\';
    }
    ++wUnicode;
  }
  return zUnicode;
#elif defined(__CYGWIN__)
  char *zPath, *p;
  if( fsl_isalpha(zUtf8[0]) && (zUtf8[1]==':')
      && (zUtf8[2]=='\\' || zUtf8[2]=='/')) {
    /* win32 absolute path starting with drive specifier. */
    int nByte;
    wchar_t zUnicode[2000];
    wchar_t *wUnicode = zUnicode;
    MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, zUnicode,
                        sizeof(zUnicode)/sizeof(zUnicode[0]));
    while( *wUnicode != '\0' ){
      if( *wUnicode == '/' ){
        *wUnicode = '\\';
      }
      ++wUnicode;
    }
    nByte = cygwin_conv_path(CCP_WIN_W_TO_POSIX, zUnicode, NULL, 0);
    zPath = (char *)fsl_malloc(nByte);
    if(!zPath) return NULL;
    cygwin_conv_path(CCP_WIN_W_TO_POSIX, zUnicode, zPath, nByte);
  }else{
    zPath = fsl_strdup(zUtf8);
    if(!zPath) return NULL;
    zUtf8 = p = zPath;
    while( (*p = *zUtf8++) != 0){
      if( *p++ == '\\' ) {
        p[-1] = '/';
      }
    }
  }
  return zPath;
#elif defined(__APPLE__) && !defined(WITHOUT_ICONV)
  return fsl_strdup(zUtf8)
    /* Why? Why not just act like Unix?
       Much later: so that fsl_os_str_free() can DTRT. */;
#else
  return (void *)zUtf8;  /* No-op on unix */
#endif
}


char *fsl_getenv(const char *zName){
#ifdef _WIN32
  wchar_t *uName = (wchar_t *)fsl_utf8_to_unicode(zName);
  void *zValue = uName ? (void*)_wgetenv(uName) : NULL;
  fsl_free(uName);
#else
  char *zValue = (char *)getenv(zName);
#endif
  if( zValue ) zValue = fsl_filename_to_utf8(zValue);
  return zValue;
}

fsl_size_t fsl_strlen_utf8( char const * str, fsl_strlen_t len ){
  if( !str || 0==len ) return 0;
  len = fsl_nstrlen(str, len);
  if( len<=0 ) return 0;
  char unsigned const * x = (char unsigned const *)str;
  char unsigned const * end = x + len;
  fsl_size_t rc = 0;
  /* Derived from:
     http://www.daemonology.net/blog/2008-06-05-faster-utf8-strlen.html
  */
  for( ; x < end; ++x, ++rc ){
    switch(0xF0 & *x) {
      case 0xF0: /* length 4 */
        x += 3;
        break;
      case 0xE0: /* length 3 */
        x+= 2;
        break;
      case 0xC0: /* length 2 */
        x += 1;
        break;
      default:
        break;
    }
  }
  return rc;
}
/* end of file src/utf8.c */
/* start of file src/vfile.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/************************************************************************
  This file contains some of the APIs dealing with the checkout state.
*/
#include <assert.h>
#include <time.h>

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

int fsl_vfile_load(fsl_cx * const f, fsl_id_t vid,
                   bool clearOtherVersions,
                   uint32_t * missingCount){
  fsl_db * dbC = f ? fsl_needs_ckout(f) : NULL;
  fsl_db * dbR = dbC ? fsl_needs_repo(f) : NULL;
  fsl_deck d = fsl_deck_empty;
  fsl_stmt qIns = fsl_stmt_empty;
  fsl_stmt qRid = fsl_stmt_empty;
  int rc;
  bool alreadyHad = false;
  fsl_card_F const * fc;
  assert(dbC && "Must only be called when a checkout is opened.");
  assert(dbR && "Must only be called when a repo is opened.");
  if(!dbC) return FSL_RC_NOT_A_CKOUT;
  else if(!dbR) return FSL_RC_NOT_A_REPO;
  if(vid<=0) vid = f->db.ckout.rid;
  assert(vid>=0);

  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc) return rc;
  rc = fsl_db_exists2(dbC, &alreadyHad,
                      "SELECT 1 FROM {{dbname.ckout}}.vfile "
                      "WHERE vid=%" FSL_ID_T_PFMT,
                      vid);
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, dbC, rc);
    goto end;
  }
  if(clearOtherVersions){
    /* Reminder to self: DO NOT clear vmerge here. Doing so will break
       merge tracking in the checkin process. */
    rc = fsl_vfile_unload_except(f, vid);
    if(rc) goto end;
  }
  if(alreadyHad){
    /* Already done. */
    rc = 0;
    goto end;
  }
  assert(0==rc);
  if(0==vid){
    /* This is either misuse or an empty/initial repo with no
       checkins. Let's assume the latter, since that's what triggered
       the addition of this check. */
    goto end;
  }

  rc = fsl_deck_load_rid(f, &d, vid, FSL_SATYPE_CHECKIN);
  if(rc) goto end;
  assert(d.rid==vid);
  rc = fsl_deck_F_rewind(&d);
  if(rc) goto end;
  rc = fsl_db_prepare(dbC, &qIns,
                      "INSERT INTO {{dbname.ckout}}.vfile"
                      "(vid,isexe,islink,rid,mrid,pathname,mhash) "
                      "VALUES(:vid,:isexe,:islink,:id,:id,:name,null)"
                      /* 2021-10-15: why do we not set mtime here? */);
  if(rc) goto end;
  rc = fsl_db_prepare(dbR, &qRid,
                      "SELECT rid,size FROM {{dbname.repo}}.blob WHERE uuid=?");
  if(rc) goto end;
  rc = fsl_stmt_bind_id_name(&qIns, ":vid", vid);
  fsl_deck_F_each(&d, fc, rc){
    fsl_id_t rid;
    int64_t size;
    assert(fc->uuid &&
           "We should never see F-card deletions "
           "via fsl_deck_F_next()");
    if(fsl_uuid_is_shunned(f,fc->uuid)) continue;
    rc = fsl_stmt_bind_text(&qRid, 1, fc->uuid, -1, 0);
    if(rc) break;
    rc = fsl_stmt_step(&qRid);
    if(FSL_RC_STEP_ROW==rc){
      rid = fsl_stmt_g_id(&qRid,0);
      size = fsl_stmt_g_int64(&qRid,1);
    }else if(FSL_RC_STEP_DONE==rc){
      rid = 0;
      size = 0;
    }else{
      assert(qRid.db->error.code);
      rc = fsl_cx_uplift_db_error(f, qRid.db);
      break;
    }
    fsl_stmt_reset(&qRid);
    if( !rid || size<0 ){
      if(missingCount) ++*missingCount;
      continue;
    }
    fsl_stmt_bind_int32_name(&qIns, ":isexe",
                             (FSL_FILE_PERM_EXE & fc->perm) ? 1 : 0);
    fsl_stmt_bind_int32_name(&qIns, ":islink",
                             (FSL_FILE_PERM_LINK & fc->perm) ? 1 : 0);
    fsl_stmt_bind_id_name(&qIns, ":id", rid);
    rc = fsl_stmt_bind_text_name(&qIns, ":name", fc->name, -1, 0);
    if(rc) break;
    rc = fsl_stmt_step(&qIns);
    if(FSL_RC_STEP_DONE!=rc) break;
    else rc = 0;
    fsl_stmt_reset(&qIns);
  }

end:
  fsl_stmt_finalize(&qIns);
  fsl_stmt_finalize(&qRid);
  /* Update f->ckout state and some db bits we need
     when changing the checkout. */
  if(!rc && vid>0){
    if(!alreadyHad){
      assert(d.rid>0);
    }
  }
  fsl_deck_finalize(&d);
  if(rc) fsl_cx_txn_end(f, true);
  else rc = fsl_cx_txn_end(f, false);
  if(rc && !f->error.code){
    if(dbC->error.code) fsl_cx_uplift_db_error(f, dbC);
    else if(dbR->error.code) fsl_cx_uplift_db_error(f, dbR);
  }
  return rc;
}

static int fsl_vfile_unload_impl(fsl_cx * const f, fsl_id_t vid,
                                 bool oneVersion){
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return FSL_RC_NOT_A_CKOUT;
  if(vid<=0) vid = f->db.ckout.rid;
  int const rc = fsl_db_exec(db, "DELETE FROM {{dbname.ckout}}.vfile "
                             "WHERE vid%s%" FSL_ID_T_PFMT
                             " /* %s() */",
                             oneVersion ? "=" : "<>",
                             vid, __func__);
  return rc ? fsl_cx_uplift_db_error2(f, db, rc) : 0;
}
int fsl_vfile_unload(fsl_cx * const f, fsl_id_t vid){
  return fsl_vfile_unload_impl(f, vid, true);
}
int fsl_vfile_unload_except(fsl_cx * const f, fsl_id_t vid){
  return fsl_vfile_unload_impl(f, vid, false);
}

/**
   Internal code de-duplifier for places which need to re-check a
   file's hash in order to be sure whether it was really
   modified. hashLen must be the length of the previous (db-side) hash
   of the file. This routine will hash that file using the same hash
   type. The new hash is appended to pTgt.

   If isLink is true, zName is a symlink and the name it points to is
   hashed, as fossil(1) hashes symlinks when the allow-symlinks
   setting is on, else the file's content (following any symlink) is
   hashed.

   Returns 0 on success.
*/
static int fsl_vfile_recheck_file_hash( fsl_cx * const f, const char * const zName,
                                        fsl_size_t hashLen, bool isLink,
                                        fsl_b * const pTgt ){
  bool errReported = false;
  int rc = 0;
  if(isLink){
    fsl_b * const target = fsl_cx_b_borrow(f);
    if(!target) return f->error.code;
    rc = fsl__cfs_symlink_read(f, target, zName);
    if(0==rc){
      if((fsl_size_t)FSL_STRLEN_SHA1==hashLen){
        rc = fsl_sha1sum_buffer(target, pTgt);
      }else{
        rc = fsl_sha3sum_buffer(target, pTgt);
      }
    }
    fsl_cx_b_return(f, target);
  }else if((fsl_size_t)FSL_STRLEN_SHA1==hashLen){
    rc = fsl__cfs_sha1sum(f, zName, pTgt);
  }else if((fsl_size_t)FSL_STRLEN_K256==hashLen){
    rc = fsl__cfs_sha3sum(f, zName, pTgt);
  }else{
    assert(!"This \"cannot happen\".");
    rc = fsl_cx_err_set(f, FSL_RC_CHECKSUM_MISMATCH,
                        "Cannot determine which hash to use for file: %s",
                        zName);
    errReported = true;
  }
  if(rc && !errReported && FSL_RC_OOM != rc){
    rc = fsl_cx_err_set(f, rc, "Error %s while hashing file: %s",
                        fsl_rc_cstr(rc), zName);
  }
  return rc;
}


int fsl_vfile_changes_scan(fsl_cx * const f, fsl_id_t vid, unsigned cksigFlags){
  fsl_stmt * stUpdate = NULL;
  fsl_stmt q = fsl_stmt_empty;
  int rc = 0;
  fsl_fstat fst = fsl_fstat_empty;
  fsl_size_t rootLen;
  const fsl_time_t currentSysTime = (fsl_time_t)time(0);
  fsl_b * const fileCksum = fsl__cx_scratchpad(f);
  bool const useMtime = (cksigFlags & FSL_VFILE_CKSIG_HASH)==0
    && fsl_config_get_bool(f, FSL_CONFDB_REPO, true, "mtime-changes");
  bool allowSymlinks;
  if(!fsl_needs_ckout(f)){
    fsl__cx_scratchpad_yield(f, fileCksum);
    return FSL_RC_NOT_A_CKOUT;
  }
  assert(f->db.ckout.dir);
  if(vid<=0) vid = f->db.ckout.rid;
  assert(vid>=0);
  rootLen = fsl_strlen(f->db.ckout.dir);
  assert(rootLen);
  allowSymlinks = fsl_cx_allows_symlinks(f, false);

  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if(rc){
    fsl__cx_scratchpad_yield(f, fileCksum);
    return rc;
  }
  if(f->db.ckout.rid != vid){
    rc = fsl_vfile_load(f, vid,
                        (FSL_VFILE_CKSIG_KEEP_OTHERS & cksigFlags)
                        ? false : true, NULL);
  }
  if(rc) goto end;

#if 0
  MARKER(("changed/deleted vfile contents post load-from-rid:\n"));
  fsl_db_each( fsl_cx_db_ckout(f), fsl_stmt_each_f_dump, f,
               "SELECT vf.id, substr(b.uuid,0,8) hash, chnged, "
               "deleted, vf.pathname "
               "FROM {{dbname.ckout}}.vfile vf LEFT JOIN {{dbname.repo}}.blob b "
               "ON b.rid=vf.rid "
               "WHERE vf.vid=%"FSL_ID_T_PFMT" "
               "AND (chnged<>0 OR pathname<>origname OR deleted<>0)"
               "ORDER BY vf.id", vid);
#endif

  rc = fsl_cx_prepare(f, &q, "SELECT "
                      /*0*/"id,"
                      /*1*/"%Q || pathname,"
                      /*2*/"vfile.mrid,"
                      /*3*/"deleted,"
                      /*4*/"chnged,"
                      /*5*/"uuid,"
                      /*6*/"size,"
                      /*7*/"mtime,"
                      /*8*/"isexe,"
                      /*9*/"islink, "
                      /*10*/"CASE WHEN isexe THEN %d "
                            "WHEN islink THEN %d ELSE %d END "
                      "FROM {{dbname.ckout}}.vfile AS vfile LEFT JOIN {{dbname.repo}}.blob AS blob ON vfile.mrid=blob.rid "
                      "WHERE vid=%"FSL_ID_T_PFMT,
                      f->db.ckout.dir,
                      FSL_FILE_PERM_EXE, FSL_FILE_PERM_LINK,
                      FSL_FILE_PERM_REGULAR,
                      (fsl_id_t)vid);
  if(rc) goto end;
  while( fsl__cx_stmt_step_each(f, &q, &rc) ){
    fsl_id_t id, rid;
    char const * zName;
#ifndef _WIN32
    //char const * relName;
#endif
    fsl_size_t nName = 0;
    int isDeleted;
    int64_t currentSize;
    int64_t origSize;
    int changed, oldChanged;
    //int isExe;
    fsl_time_t oldMtime, currentMtime;
#if !defined(_WIN32)
    int origPerm;
    int currentPerm;
#endif
    id = fsl_stmt_g_id(&q, 0);
    assert(id>0);
    zName = fsl_stmt_g_text(&q, 1, &nName);
    rid = fsl_stmt_g_id(&q, 2);
    isDeleted = fsl_stmt_g_int32(&q, 3);
    oldChanged = changed = fsl_stmt_g_int32(&q, 4);
    origSize = fsl_stmt_g_int64(&q, 6);
    oldMtime = (fsl_time_t)fsl_stmt_g_int64(&q, 7);
    //isExe = fsl_stmt_g_int32(&q, 8);
    /* As in fossil(1)'s fossil_stat() for RepoFILE: with symlinks
       allowed, a symlink is seen as itself (its size is that of the
       name it points to), else as the file it points to. */
    fst = fsl_fstat_empty;
    rc = fsl__cfs_stat(f, zName, &fst, !allowSymlinks);
    currentSize = rc ? -1 : (int64_t)fst.size;
    currentMtime = rc ? 0 : fst.mtime;
    if(rc){
      fsl_cx_err_reset(f);
      rc = 0;
    }
    bool const isLink = currentSize>=0 && allowSymlinks
      && FSL_FSTAT_TYPE_LINK==fst.type;
#if !defined(_WIN32)
    //relName = zName + rootLen;
    origPerm = fsl_stmt_g_int32(&q, 10);
    currentPerm = currentSize>=0
      ? (int)fsl__fstat_perm(&fst, allowSymlinks)
      : FSL_FILE_PERM_REGULAR;
#endif
    if(!changed && (isDeleted || !rid)){
      /* ADD and REMOVE operations always change the file */
      changed = FSL_VFILE_CHANGE_MOD;
    }
    else if( currentSize>=0
             && !(FSL_FSTAT_TYPE_FILE==fst.type
                  || FSL_FSTAT_TYPE_LINK==fst.type)){
      if( FSL_VFILE_CKSIG_ENOTFILE & cksigFlags ){
        rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                            "Not an ordinary file or symlink: %s",
                            zName);
        goto end;
      }
      changed = FSL_VFILE_CHANGE_MOD;
    }
    if(origSize!=currentSize){
      changed = FSL_VFILE_CHANGE_MOD;
      /* A file size change is definitive - the file has changed. No
         need to check the mtime or hash */
    }else if( changed==FSL_VFILE_CHANGE_MOD && rid!=0 && !isDeleted ){
      /* File is believed to have changed but it is the same size.
         Double check that it really has changed by looking at its
         content. */
      fsl_size_t nUuid = 0;
      char const * uuid;
      fsl_b_reuse(fileCksum);
      assert( origSize==currentSize );
      uuid = fsl_stmt_g_text(&q, 5, &nUuid);
      assert(uuid && fsl_is_uuid_len((int)nUuid));
      rc = fsl_vfile_recheck_file_hash(f, zName, (int)nUuid, isLink,
                                       fileCksum);
      if(rc) goto end;
      assert(fsl_is_uuid_len((int)fileCksum->used));
      if( 0 == fsl_uuidcmp(fsl_b_cstr(fileCksum), uuid) ){
        changed = 0;
      }
    }else if( (changed==FSL_VFILE_CHANGE_NONE
               || changed==FSL_VFILE_CHANGE_MERGE_MOD
               || changed==FSL_VFILE_CHANGE_INTEGRATE_MOD)
              && (!useMtime || currentMtime!=oldMtime
                  || currentMtime==currentSysTime)
    ){
      /* For files that were formerly believed to be unchanged or that
         were changed by merging, if their mtime changes, or
         unconditionally if FSL_VFILE_CKSIG_SETMTIME is used, check to
         see if they have been edited by looking at their hash sum */
      fsl_size_t nUuid = 0;
      char const * uuid;
      assert( origSize==currentSize );
      uuid = fsl_stmt_g_text(&q, 5, &nUuid);
      assert(uuid && fsl_is_uuid_len((int)nUuid));
      fsl_b_reuse(fileCksum);
      rc = fsl_vfile_recheck_file_hash(f, zName, nUuid, isLink, fileCksum);
      if(rc) goto end;
      assert(fsl_is_uuid_len((int)fileCksum->used));
      if( fsl_uuidcmp(fsl_b_cstr(fileCksum), uuid) ){
        changed = FSL_VFILE_CHANGE_MOD;
      }
      /* MARKER(("SHA compare says %d: %s\n", changed, zName)); */
    }
    if( (cksigFlags & FSL_VFILE_CKSIG_SETMTIME)
        && (changed==FSL_VFILE_CHANGE_NONE
            || changed==FSL_VFILE_CHANGE_MERGE_MOD
            || changed==FSL_VFILE_CHANGE_INTEGRATE_MOD) ){
      fsl_time_t desiredMtime = 0;
      if( 0==fsl_mtime_of_manifest_file(f, vid, rid, &desiredMtime)){
        if( currentMtime != desiredMtime ){
          fsl__cfs_mtime_set(f, zName, desiredMtime);
          currentMtime = fsl__cfs_mtime(f, zName);
        }
      }else{
        /* Leaving the mtime as-is is harmless, but an error left on f
           would make later fsl_cx_b_borrow() calls fail. */
        fsl_cx_err_reset(f);
      }
    }
    /* Check for perms differences. */
#if !defined(_WIN32)
    if( origPerm!=FSL_FILE_PERM_LINK && currentPerm==FSL_FILE_PERM_LINK ){
       /* Changing to a symlink takes priority over all other change types. */
       changed = FSL_VFILE_CHANGE_BECAME_SYMLINK;
    }else if( origPerm==FSL_FILE_PERM_LINK && currentPerm!=FSL_FILE_PERM_LINK ){
      /* As does no longer being one, as in fossil(1). */
      changed = FSL_VFILE_CHANGE_NOT_SYMLINK;
    }else if( changed==0
              || changed==FSL_VFILE_CHANGE_IS_EXEC
              || changed==FSL_VFILE_CHANGE_BECAME_SYMLINK
              || changed==FSL_VFILE_CHANGE_NOT_EXEC
              || changed==FSL_VFILE_CHANGE_NOT_SYMLINK ){
       /* Confirm metadata change types. */
      if( origPerm==currentPerm ){
        changed = 0;
      }else if( currentPerm==FSL_FILE_PERM_EXE ){
        changed = FSL_VFILE_CHANGE_IS_EXEC;
      }else if( origPerm==FSL_FILE_PERM_EXE ){
        changed = FSL_VFILE_CHANGE_NOT_EXEC;
      }else if( origPerm==FSL_FILE_PERM_LINK ){
        changed = FSL_VFILE_CHANGE_NOT_SYMLINK;
      }
    }
#endif
    if( currentMtime!=oldMtime || changed!=oldChanged ){
      if(!stUpdate){
        rc = fsl_cx_prepare_cached(f, &stUpdate,
                                   "UPDATE {{dbname.ckout}}.vfile SET "
                                   "mtime=?1, chnged=?2 "
                                   "WHERE id=?3 "
                                   "/*%s()*/",__func__);
        if(rc) goto end;
      }
      rc = fsl_stmt_bind_step(stUpdate, "IiR", currentMtime, changed, id);
      if(rc) goto end;
      /* MARKER(("UPDATED vfile.(mtime,chnged) for: %s\n", zName)); */
    }
  }/*while(step)*/

#if 0
  MARKER(("changed/deleted vfile contents post vfile scan:\n"));
  fsl_db_each( fsl_cx_db_ckout(f), fsl_stmt_each_f_dump, f,
               "SELECT vf.id, substr(b.uuid,0,8) hash, chnged, "
               "deleted, vf.pathname "
               "FROM {{dbname.ckout}}.vfile vf LEFT JOIN {{dbname.repo}}.blob b "
               "ON b.rid=vf.rid "
               "WHERE vf.vid=%"FSL_ID_T_PFMT" "
               "AND (chnged<>0 OR pathname<>origname OR deleted<>0)"
               "ORDER BY vf.id", vid);
#endif
  end:
  fsl__cx_scratchpad_yield(f, fileCksum);
  if(rc && !f->error.code){
    /* fsl_stmt_bind_step() leaves its error on the db handle. */
    rc = fsl_cx_uplift_db_error2(f, NULL, rc);
  }
  if(!rc){
    rc = fsl__ckout_clear_merge_state(f, FSL__MERGE_CLEAR_SCAN);
  }
  if(!rc && (cksigFlags & FSL_VFILE_CKSIG_WRITE_CKOUT_VERSION)
     && (f->db.ckout.rid != vid)){
    rc = fsl__ckout_version_write(f, vid, 0);
  }
  if(rc) {
    fsl_cx_txn_end(f, true);
  }else{
    rc = fsl_cx_txn_end(f, false);
  }
  fsl_stmt_cached_yield(stUpdate);
  fsl_stmt_finalize(&q);
  return rc;
}

int fsl__vfile_to_ckout(fsl_cx * const f, fsl_id_t vfileId,
                        int * wasWritten){
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return FSL_RC_NOT_A_CKOUT;
  fsl_b * const content = fsl_cx_b_borrow(f);
  if( !content ) return FSL_RC_OOM;
  int rc = 0;
  fsl_stmt q = fsl_stmt_empty;
  int counter = 0;
  char const * sql;
  fsl_id_t qArg;
  fsl_fstat * const fst = &f->cache.fstat;
  assert(f->db.ckout.rid);
  if(vfileId){
    sql = "SELECT v.id, "
      "%Q || v.pathname, "
      "v.mrid, "
      "v.isexe, v.islink, b.uuid, b.size "
      "FROM {{dbname.ckout}}.vfile v, {{dbname.repo}}.blob b"
      " WHERE v.id=%" FSL_ID_T_PFMT
      " AND v.mrid>0 "
      " AND v.mrid=b.rid /*%s()*/";
    qArg = vfileId;
  }else{
    sql = "SELECT v.id, "
      "%Q || v.pathname, "
      "v.mrid, "
      "v.isexe, v.islink, b.uuid, b.size "
      "FROM {{dbname.ckout}}.vfile v, {{dbname.repo}}.blob b"
      " WHERE v.vid=%" FSL_ID_T_PFMT
      " AND v.mrid>0 "
      " AND v.mrid=b.rid /*%s()*/";
    qArg = f->db.ckout.rid;
  }
  assert(qArg>=0);
  rc = fsl_db_prepare(db, &q, sql, f->db.ckout.dir, qArg, __func__);
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, db, rc);
    goto end;
  }
  while(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q))){
    //fsl_id_t const id = fsl_stmt_g_id(&q, 0);
    fsl_id_t const rid = fsl_stmt_g_id(&q, 2);
    int32_t const isExe = fsl_stmt_g_int32(&q, 3);
    int32_t const isLink = fsl_stmt_g_int32(&q, 4);
    int64_t const sz = fsl_stmt_g_int64(&q, 6);
    fsl_size_t nameLen = 0;
    char const * zName = fsl_stmt_g_text(&q, 1, &nameLen);
    fsl_size_t hashLen = 0;
    char const * zHash = fsl_stmt_g_text(&q, 5, &hashLen);
    char const * zRelName = &zName[f->db.ckout.dirLen];
    int isMod = 0;
    ++counter;
    assert(nameLen > f->db.ckout.dirLen);
    rc = fsl__ckout_safe_file_check(f, zName);
    if(rc) break;
    assert(fsl_is_uuid_len(hashLen));
    f->cache.fstat = fsl_fstat_empty;
    rc = fsl__is_locally_modified(f, zName, sz, zHash,
                                 (fsl_int_t)hashLen,
                                 isExe ? FSL_FILE_PERM_EXE :
                                 (isLink
                                  ? FSL_FILE_PERM_LINK
                                  : FSL_FILE_PERM_REGULAR),
                                 &isMod)
      /* that updates f->cache.fstat */;
    //MARKER(("isMod=%d zName=%s\n", isMod, zName));
    if(rc) break;
    else if(FSL_FSTAT_TYPE_DIR==fst->type){
      /* Fossil checks for this but if this happens then
         we have an invalid vfile entry or someone replaced
         a file with a dir. */
      rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                          "Cannot overwrite a directory: %s",
                          zRelName);
      break;
    }
    else if(!isMod) continue;
    else if((rc=fsl__cfs_mkdir_for_file(f, zName, true))){
      rc = fsl_cx_err_set(f, rc, "Error %R creating directory "
                          "for file: %s", rc, zName);
      break;
    }
    //assert(!"cannot happen");
    if(FSL__LOCALMOD_LINK & isMod){
      assert(((isLink && FSL_FSTAT_TYPE_LINK!=fst->type)
              ||(!isLink && FSL_FSTAT_TYPE_LINK==fst->type))
             && "Expected fsl__is_locally_modified() to set this.");
      rc = fsl__cfs_unlink(f, zName);
      if(rc){
        rc = fsl_cx_err_set(f, rc,
                            "Error %R removing file to replace it: %s",
                            rc, zRelName);
        break;
      }
    }
    bool const writeFile = !isLink
      && (isMod & (FSL__LOCALMOD_NOTFOUND | FSL__LOCALMOD_CONTENT));
    if(!writeFile && (isLink || (isMod & FSL__LOCALMOD_LINK))){
      /* switched link type. A file to write gets its content from
         fsl__cfs_write_blob() below. */
      rc = fsl_content_get(f, rid, content);
      if(rc) break;
    }
    if(isLink){
      /* content holds the link target and zName is the link. */
      rc = fsl__ckout_symlink_create(f, fsl_b_cstr(content), zName);
      if(wasWritten && !rc) *wasWritten = 2;
    }else if(writeFile){
      /* Not found locally or its contents differ. */
      bool writeFailed = false;
      rc = fsl__cfs_write_blob(f, zName, rid, content, false,
                               &writeFailed);
      if(rc){
        if(writeFailed){
          rc = fsl_cx_err_set(f, rc, "Error %R writing to file: %s",
                              rc, zRelName);
        }
      }else if(wasWritten){
        *wasWritten = 2;
      }
    }else if(wasWritten && (isMod & FSL__LOCALMOD_PERM)){
      *wasWritten = 1;
    }
    if(rc) break;
    fsl__cfs_exec_set(f, zName, !!isExe);
    fsl_b_reuse(content);
  }/*step() loop*/
  switch(rc){
    case FSL_RC_STEP_DONE:
      if(counter){
        rc = 0;
      }else{
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "No entry found: vfile.id=%" FSL_ID_T_PFMT,
                            vfileId);
      }
      break;
    default:
      /* A failed fsl_stmt_step() leaves its error on the db handle. */
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      break;
  }
  end:
  fsl_cx_b_return(f, content);
  fsl_stmt_finalize(&q);
  return rc;
}

int fsl_vfile_pathname(fsl_cx * const f, fsl_id_t vfid, bool absolute, char **zOut){
  assert(f->db.ckout.dir);
  fsl_db * const db = fsl_cx_db_ckout(f);
  assert(db);
  int const rc = fsl_db_get_text(db, zOut, NULL,
                                 "SELECT %Q || pathname FROM {{dbname.ckout}}.vfile "
                                 "WHERE id=%"FSL_ID_T_PFMT,
                                 absolute ? f->db.ckout.dir : "",
                                 vfid);
  if(rc) fsl_cx_uplift_db_error(f, db);
  return rc;
}

#undef MARKER
/* end of file src/vfile.c */
/* start of file src/vpath.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**********************************************************************
  This file contains routines related to working with "paths" through
  Fossil SCM version history.
*/
#include <assert.h>

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


static const fsl_vpath_node fsl_vpath_node_empty = {0,0,0,0,0,{0},0};
const fsl_vpath fsl_vpath_empty = fsl_vpath_empty_m;

void fsl_vpath_clear(fsl_vpath *path){
  fsl_vpath_node * p;
  while(path->pAll){
    p = path->pAll;
    path->pAll = p->pAll;
    fsl_free(p);
  }
  fsl_id_bag_clear(&path->seen);
  *path = fsl_vpath_empty;
}

fsl_vpath_node * fsl_vpath_first(fsl_vpath *p){
  return p->pStart;
}

fsl_vpath_node * fsl_vpath_last(fsl_vpath *p){
  return p->pEnd;
}

int fsl_vpath_length(fsl_vpath const * p){
  return p->nStep;
}

fsl_vpath_node * fsl_vpath_next(fsl_vpath_node *p){
  return p->u.pTo;
}

fsl_vpath_node * fsl_vpath_midpoint(fsl_vpath * path){
  if( path->nStep<2 ) return 0;
  else{
    fsl_vpath_node *p;
    int i;
    int const max = path->nStep/2;
    for(p=path->pEnd, i=0; p && i<max; p=p->pFrom, i++){}
    return p;
  }
}


void fsl_vpath_reverse(fsl_vpath * path){
  fsl_vpath_node *p;
  assert( path->pEnd!=0 );
  for(p=path->pEnd; p && p->pFrom; p = p->pFrom){
    p->pFrom->u.pTo = p;
  }
  path->pEnd->u.pTo = 0;
  assert( p==path->pStart );
}

/**
   Adds a new node to path and returns it. Returns 0 on allocation error.
   path must not be 0. rid must be greater than 0. pFrom may be 0. If
   pFrom is not 0 then isParent must be true if pFrom is a parent of
   rid.

   On success, sets the returned node as path->pCurrent, sets its
   pFrom to the given pFrom, and sets rc->u.pPeer to the prior
   path->pCurrent value.
*/
static fsl_vpath_node * fsl_vpath_new_node(fsl_vpath * path, fsl_id_t rid,
                                         fsl_vpath_node * pFrom, bool isParent){
  fsl_vpath_node * rc = 0;
  assert(path);
  assert(rid>0);
  if(0 != fsl_id_bag_insert(&path->seen, rid)) return 0;
  rc = (fsl_vpath_node*)fsl_malloc(sizeof(fsl_vpath_node));
  if(!rc){
    fsl_id_bag_remove(&path->seen, rid);
    return 0;
  }
  *rc = fsl_vpath_node_empty;
  rc->rid = rid;
  rc->fromIsParent = pFrom ? isParent : 0;
  rc->pFrom = pFrom;
  rc->u.pPeer = path->pCurrent;
  path->pCurrent = rc;
  rc->pAll = path->pAll;
  path->pAll = rc;
  return rc;
}

int fsl_vpath_shortest( fsl_cx * const f, fsl_vpath * const path,
                        fsl_id_t iFrom, fsl_id_t iTo,
                        bool directOnly, bool oneWayOnly ){
  fsl_stmt s = fsl_stmt_empty;
  fsl_db * db = fsl_needs_repo(f);
  int rc = 0;
  fsl_vpath_node * pPrev;
  fsl_vpath_node * p;
  assert(db);
  if(!db) return FSL_RC_NOT_A_REPO;
  else if(iFrom<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid 'from' RID: %"FSL_ID_T_PFMT, iFrom);
  }else if(iTo<=0){
    /*
      Possible TODO: if iTo==0, use... what? Checkout? Tip of current
      checkout branch? Trunk? The multitude of options make it impossible
      to decide :/.
    */
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid 'to' RID: %"FSL_ID_T_PFMT, iTo);
  }

  fsl_vpath_clear(path);
  path->pStart = fsl_vpath_new_node(path, iFrom, 0, 0);
  if(!path->pStart){
    return fsl_cx_err_set(f, FSL_RC_OOM, 0);
  }
  if( iTo == iFrom ){
    path->pEnd = path->pStart;
    return 0;
  }

  if( oneWayOnly ){
    if(directOnly){
      rc = fsl_db_prepare(db, &s,
                          "SELECT cid, 1 FROM {{dbname.repo}}.plink WHERE pid=?1 AND isprim");
    }else{
      rc = fsl_db_prepare(db, &s,
                          "SELECT cid, 1 FROM {{dbname.repo}}.plink WHERE pid=?1");
    }
  }else if( directOnly ){
    rc = fsl_db_prepare(db, &s,
                        "SELECT cid, 1 FROM {{dbname.repo}}.plink WHERE pid=?1 AND isprim "
                        "UNION ALL "
                        "SELECT pid, 0 FROM {{dbname.repo}}.plink WHERE cid=?1 AND isprim");
  }else{
    rc = fsl_db_prepare(db, &s,
                        "SELECT cid, 1 FROM {{dbname.repo}}.plink WHERE pid=?1 "
                        "UNION ALL "
                        "SELECT pid, 0 FROM {{dbname.repo}}.plink WHERE cid=?1");
  }
  if(rc){
    fsl_cx_uplift_db_error(f, db);
    assert(f->error.code);
    goto end;
  }

  while(path->pCurrent){
    ++path->nStep;
    pPrev = path->pCurrent;
    path->pCurrent = 0;
    while( pPrev ){
      rc = fsl_stmt_bind_id(&s, 1, pPrev->rid);
      assert(0==rc);
      while( fsl__cx_stmt_step_each(f, &s, &rc) ){
        fsl_id_t const cid = fsl_stmt_g_id(&s, 0);
        int const isParent = fsl_stmt_g_int32(&s, 1);
        assert((cid>0) && "fsl_id_bag_find() asserts this.");
        if( fsl_id_bag_contains(&path->seen, cid) ) continue;
        p = fsl_vpath_new_node(path, cid, pPrev, isParent ? 1 : 0);
        if(!p){
          rc = fsl_cx_err_set(f, FSL_RC_OOM, 0);
          goto end;
        }
        if( cid == iTo ){
          fsl_stmt_finalize(&s);
          path->pEnd = p;
          fsl_vpath_reverse( path );
          return 0;
        }
      }
      if(rc) goto end;
      fsl_stmt_reset(&s);
      pPrev = pPrev->u.pPeer;
    }
  }
  end:
  fsl_stmt_finalize(&s);
  fsl_vpath_clear(path);
  return rc;
}

/**
   Creates, if needed, the [ancestor] table, else clears its
   contents. Returns 0 on success, non-0 on db error (in which case
   f's error state is updated).
*/
static int fsl__init_ancestor(fsl_cx * const f){
  return fsl_cx_db_repo(f)
    ? fsl_cx_exec_multi(f,
                        "CREATE TEMP TABLE IF NOT EXISTS {{temp.ancestor}}("
                        "  rid INT UNIQUE,"
                        "  generation INTEGER PRIMARY KEY"
                        ");"
                        "DELETE FROM {{temp.ancestor}};")
    : fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                     "Cannot compute ancestors without an "
                     "opened repository.");
}

int fsl_compute_direct_ancestors(fsl_cx * const f, fsl_id_t rid){
  int rc = fsl__init_ancestor(f);
  if( 0==rc ){
    rc = fsl_cx_exec_multi(f,
      "WITH RECURSIVE g(x,i) AS ("
      "  VALUES(%" FSL_ID_T_PFMT ",1)"
      "  UNION ALL"
      "  SELECT plink.pid, g.i+1 FROM {{dbname.repo}}.plink AS plink, g"
      "   WHERE plink.cid=g.x AND plink.isprim)"
      "INSERT INTO {{temp.ancestor}}(rid,generation) SELECT x,i FROM g;",
      rid
    );
  }
  return rc;
}

int fsl_vpath_shortest_store_in_ancestor(fsl_cx * const f,
                                         fsl_id_t iFrom,
                                         fsl_id_t iTo,
                                         uint32_t *pSteps){
  int rc;
  fsl_vpath path = fsl_vpath_empty;
  fsl_stmt ins = fsl_stmt_empty;
  fsl_db * const db = fsl_needs_repo(f);
  fsl_vpath_node * node;
  int32_t gen = 0;
  if(!db) return FSL_RC_NOT_A_REPO;
  rc = fsl_vpath_shortest(f, &path, iFrom, iTo, true, false);
  if(rc) goto end;
  rc = fsl__init_ancestor(f);
  if(rc) goto end;
  rc = fsl_cx_prepare(f, &ins,
                      "INSERT INTO {{temp.ancestor}}(rid, generation) "
                      "VALUES(?,?)");
  for(node = fsl_vpath_first(&path);
      0==rc && node; node = fsl_vpath_next(node)){
    rc = fsl_stmt_bind_step(&ins, "Ri", node->rid, ++gen);
    if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  }
  end:
  if(0==rc && pSteps) *pSteps = (uint32_t)gen;
  fsl_stmt_finalize(&ins);
  fsl_vpath_clear(&path);
  return rc;
}

/*
** A record of a file rename operation.
*/
typedef struct NameChange NameChange;
struct NameChange {
  fsl_id_t origName;        /* Original name of file */
  fsl_id_t curName;         /* Current name of the file */
  fsl_id_t newName;         /* Name of file in next version */
  NameChange *pNext;   /* List of all name changes */
};

int fsl__find_filename_changes(
  fsl_cx * const f,
  fsl_id_t iFrom,          /* Ancestor check-in */
  fsl_id_t iTo,            /* Recent check-in */
  bool revOK,              /* OK to move backwards (child->parent) if true */
  uint32_t *pnChng,        /* Number of name changes along the path */
  fsl_id_t **aiChng        /* Name changes */
){
  fsl_vpath_node *p = 0;   /* For looping over path from iFrom to iTo */
  NameChange *pAll = 0;    /* List of all name changes seen so far */
  NameChange *pChng = 0;   /* For looping through the name change list */
  uint32_t nChng = 0;       /* Number of files whose names have changed */
  fsl_id_t *aChng = 0;     /* Two integers per name change */
  fsl_stmt q1 = fsl_stmt_empty; /* Query of name changes */
  fsl_db * const db = fsl_needs_repo(f);
  fsl_vpath path = fsl_vpath_empty;
  int rc = 0;

  if(!db) return FSL_RC_NOT_A_REPO;
  *pnChng = 0;
  *aiChng = 0;
  if(iFrom<=0){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Invalid 'from' RID: %" FSL_ID_T_PFMT, iFrom);
  }else if(0==iTo){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Invalid 'to' RID: %" FSL_ID_T_PFMT, iTo);
  }
  if( iFrom==iTo ) return 0;
  rc = fsl_vpath_shortest(f, &path, iFrom, iTo, true, !revOK);
  if(rc) goto end;
  else if(!path.pStart){
    goto end;
  }
  fsl_vpath_reverse(&path);
  rc = fsl_db_prepare(db, &q1,
     "SELECT pfnid, fnid FROM {{dbname.repo}}.mlink"
     " WHERE mid=?1 AND (pfnid>0 OR fid==0)"
     " ORDER BY pfnid"
  );
  if(rc) goto dberr;
  for(p=path.pStart; p; p=p->u.pTo){
    fsl_id_t fnid = 0, pfnid = 0;
    if( !p->fromIsParent && (p->u.pTo==0 || p->u.pTo->fromIsParent) ){
      /* Skip nodes where the parent is not on the path */
      continue;
    }
    rc = fsl_stmt_bind_id(&q1, 1, p->rid);
    if(rc) goto dberr;
    while( fsl__cx_stmt_step_each(f, &q1, &rc) ){
      pfnid = fsl_stmt_g_id(&q1, 0);
      fnid = fsl_stmt_g_id(&q1, 1);
      if( pfnid==0 ){
        pfnid = fnid;
        fnid = 0;
      }
      if( !p->fromIsParent ){
        fsl_id_t const t = fnid;
        fnid = pfnid;
        pfnid = t;
      }
#if 0
      if( zDebug ){
        fossil_print("%s at %d%s %.10z: %d[%z] -> %d[%z]\n",
           zDebug, p->rid, p->fromIsParent ? ">" : "<",
           db_text(0, "SELECT uuid FROM {{dbname.repo}}.blob WHERE rid=%d", p->rid),
           pfnid,
           db_text(0, "SELECT name FROM {{dbname.repo}}.filename WHERE fnid=%d", pfnid),
           fnid,
           db_text(0, "SELECT name FROM {{dbname.repo}}.filename WHERE fnid=%d", fnid));
      }
#endif
      for(pChng=pAll; pChng; pChng=pChng->pNext){
        if( pChng->curName==pfnid ){
          pChng->newName = fnid;
          break;
        }
      }
      if( pChng==0 && fnid>0 ){
        pChng = (NameChange*)fsl_malloc( sizeof(NameChange) );
        if(!pChng){
          rc = FSL_RC_OOM;
          goto end;
        }
        pChng->pNext = pAll;
        pAll = pChng;
        pChng->origName = pfnid;
        pChng->curName = pfnid;
        pChng->newName = fnid;
        ++nChng;
      }
    }
    if(rc) goto end;
    for(pChng=pAll; pChng; pChng=pChng->pNext){
      pChng->curName = pChng->newName;
    }
    fsl_stmt_reset(&q1);
  }
  if( nChng ){
    /* Count effective changes. */
    uint32_t n;
    for(pChng=pAll, n=0; pChng; pChng=pChng->pNext){
      if( pChng->newName==0 ) continue;
      if( pChng->origName==0 ) continue;
      ++n;
    }
    nChng = n;
  }
  if(nChng){
    uint32_t i;
    aChng = (fsl_id_t*)fsl_malloc( nChng*2*sizeof(fsl_id_t) );
    if(!aChng){
      rc = FSL_RC_OOM;
      goto end;
    }
    for(pChng=pAll, i=0; pChng; pChng=pChng->pNext){
      if( pChng->newName==0 ) continue;
      if( pChng->origName==0 ) continue;
      aChng[i] = pChng->origName;
      aChng[i+1] = pChng->newName;
#if 0
      if( zDebug ){
        fossil_print("%s summary %d[%z] -> %d[%z]\n",
           zDebug,
           aChng[i],
           db_text(0, "SELECT name FROM {{dbname.repo}}.filename WHERE fnid=%d", aChng[i]),
           aChng[i+1],
           db_text(0, "SELECT name FROM {{dbname.repo}}.filename WHERE fnid=%d", aChng[i+1]));
      }
#endif
      i += 2;
    }
    assert(nChng==i/2);
    *pnChng = i/2;
    *aiChng = aChng;
    while( pAll ){
      pChng = pAll;
      pAll = pAll->pNext;
      fsl_free(pChng);
    }
  }else{
    *pnChng = 0;
    *aiChng = 0;
  }
  end:
  fsl_stmt_finalize(&q1);
  if(rc){
    assert(!aChng);
  }
  while( pAll ){
    pChng = pAll;
    pAll = pAll->pNext;
    fsl_free(pChng);
  }
  fsl_vpath_clear(&path);
  return rc;
  dberr:
  assert(rc);
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  goto end;
}

#undef MARKER
/* end of file src/vpath.c */
/* start of file src/wiki.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*************************************************************************
  This file implements wiki-related parts of the library.
*/
#include <assert.h>

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


int fsl_wiki_names_get( fsl_cx * const f, fsl_list * const tgt ){
  fsl_db * db = fsl_needs_repo(f);
  if(!f) return FSL_RC_MISUSE;
  else if(!tgt){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "%s() requires a target list.", __func__);
  }
  else if(!db) return FSL_RC_NOT_A_REPO;
  else {
    int rc = fsl_db_select_slist( db, tgt,
                                  "SELECT substr(tagname,6) AS name "
                                  "FROM {{dbname.repo}}.tag "
                                  "WHERE tagname GLOB 'wiki-*' "
                                  "ORDER BY lower(name)");
    if(rc && db->error.code && !f->error.code){
      fsl_cx_uplift_db_error(f, db);
    }
    return rc;
  }
}

int fsl_wiki_latest_rid( fsl_cx * const f, char const * pageName, fsl_id_t * const rid ){
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  if(!f) return FSL_RC_MISUSE;
  else if(!pageName){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "%s() requires a page name.", __func__);
  }
  else if(!*pageName){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Wiki page name may not be empty.");
  }
  else if(!db) return FSL_RC_NOT_A_REPO;
  else{
    int const rc = fsl_db_get_id(db, rid,
                            "SELECT x.rid FROM {{dbname.repo}}.tag t, {{dbname.repo}}.tagxref x "
                            "WHERE x.tagid=t.tagid "
                            "AND t.tagname='wiki-%q' "
                            "AND TYPEOF(x.value+0)='integer' "
                            // ^^^^ only 'wiki-%' tags which are wiki pages
                            "ORDER BY mtime DESC LIMIT 1",
                            pageName);
    return rc ? fsl_cx_uplift_db_error2(f, db, rc) : 0;
  }
}

bool fsl_wiki_page_exists(fsl_cx * const f, char const * pageName){
  fsl_id_t rid = 0;
  return pageName && *pageName
    && (0==fsl_wiki_latest_rid(f, pageName, &rid))
    && (rid>0);
}

int fsl_wiki_load_latest( fsl_cx * const f, char const * pageName, fsl_deck * d ){
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  if(!f) return FSL_RC_MISUSE;
  else if(!pageName || !d){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "%s() requires a page name and a deck.",
                          __func__);
  }
  else if(!*pageName){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Wiki page name may not be empty.");
  }
  else if(!db) return FSL_RC_NOT_A_REPO;
  else{
    fsl_id_t rid = 0;
    int rc = fsl_wiki_latest_rid(f, pageName, &rid);
    if(rc) return rc;
    else if(0==rid){
      return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "No such wiki page: %s", pageName);
    }
    return fsl_deck_load_rid( f, d, rid, FSL_SATYPE_WIKI);
  }
}

int fsl_wiki_foreach_page( fsl_cx * const f, fsl_deck_visitor_f cb, void * state ){
  if(!cb){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "%s() requires a callback.", __func__);
  }
  else if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  else{
    fsl_stmt st = fsl_stmt_empty;
    fsl_stmt names = fsl_stmt_empty;
    int rc;
    bool doBreak = false;
    rc = fsl_cx_prepare(f, &names,
                        "SELECT substr(tagname,6) AS name "
                        "FROM {{dbname.repo}}.tag "
                        "WHERE tagname GLOB 'wiki-*' "
                        "ORDER BY lower(name)");
    if(rc) return rc;
    while( !doBreak && !rc
           && (fsl__cx_stmt_step_each(f, &names, &rc))){
      fsl_size_t nameLen = 0;
      char const * pageName = fsl_stmt_g_text(&names, 0, &nameLen);
      if(!st.stmt){
        rc = fsl_cx_prepare(f, &st,
                            "SELECT x.rid AS mrid FROM {{dbname.repo}}.tag t, {{dbname.repo}}.tagxref x "
                            "WHERE x.tagid=t.tagid "
                            "AND t.tagname='wiki-'||?1 "
                            "AND TYPEOF(x.value+0)='integer' "
                            // ^^^^ only 'wiki-%' tags which are wiki pages
                            "ORDER BY x.mtime DESC LIMIT 1");
        if(rc) goto end;
      }
      rc = fsl_stmt_bind_step(&st, "s", pageName);
      if(rc!=FSL_RC_STEP_ROW) continue;
      fsl_deck d = fsl_deck_empty;
      fsl_id_t const rid = fsl_stmt_g_id(&st, 0);
      rc = fsl_deck_load_rid( f, &d, rid, FSL_SATYPE_WIKI);
      if(!rc){
        assert(d.rid==rid);
        rc = cb(f, &d, state);
        if(FSL_RC_BREAK==rc){
          rc = 0;
          doBreak = true;
        }
      }
      fsl_deck_finalize(&d);
      fsl_stmt_reset(&st);
    }

    end:
    if(rc) rc = fsl_cx_uplift_db_error2(f, names.db, rc);
    fsl_stmt_finalize(&st);
    fsl_stmt_finalize(&names);
    return rc;
  }
}

bool fsl_wiki_name_is_wellformed(char const *z, fsl_int_t n){
  unsigned char const *u = (unsigned char const *)z;
  fsl_int_t i;
  if(!z) return false;
  if(n<0) n = (fsl_int_t)fsl_strlen(z);
  if(n<1 || n>100 || u[0]<=0x20) return false;
  for(i=1; i<n; ++i){
    if(u[i]<0x20) return false;
    if(u[i]==0x20 && u[i-1]==0x20) return false;
  }
  return u[n-1]!=0x20;
}

int fsl_wiki_save(fsl_cx * f, char const * pageName,
                  fsl_b const * b,
                  char const * userName,
                  char const * mimeType,
                  fsl_wiki_save_mode_t createPolicy ){
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  if(!f) return FSL_RC_MISUSE;
  else if(!pageName || !b){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "%s() requires a page name and content.",
                          __func__);
  }
  else if(!*pageName){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Wiki page name may not be empty.");
  }
  else if(!fsl_wiki_name_is_wellformed(pageName, -1)){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Wiki page name is not well-formed: it must be "
                          "1 to 100 bytes long, with no byte below "
                          "0x20, no leading or trailing space and "
                          "no two spaces in a row: %s", pageName);
  }
  else if(!db) return FSL_RC_NOT_A_REPO;
  else{
    fsl_deck d = fsl_deck_empty;
    fsl_id_t parentRid = 0;
    int rc = fsl_wiki_latest_rid(f, pageName, &parentRid);
    double mtime;
    if(rc) return rc;
    else if((FSL_WIKI_SAVE_MODE_UPDATE==createPolicy)
            && !parentRid){
      return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "No such wiki page: %s",
                            pageName);
    }
    else if((FSL_WIKI_SAVE_MODE_CREATE==createPolicy)
            && (parentRid>0)){
      return fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                            "Wiki page already exists: %s",
                            pageName);
    }
    mtime = fsl_db_julian_now(db);
    fsl_deck_init(f, &d, FSL_SATYPE_WIKI);
    rc = fsl_deck_D_set(&d, mtime);
    assert(!rc);
    rc = fsl_deck_L_set(&d, pageName, -1);
    if(!rc && mimeType && *mimeType){
      rc = fsl_deck_N_set(&d, mimeType, -1);
    }
    if( !rc && parentRid ){
      char * zUuid = fsl_rid_to_uuid(f, parentRid);
      if(!zUuid){
        rc = f->error.code ? f->error.code : FSL_RC_OOM;
      }else{
        rc = fsl_deck_P_add(&d,zUuid);
        fsl_free(zUuid);
      }
    }
    if(rc) goto end;
    {
      char * u = NULL;
      if(!userName) userName = fsl_cx_user_get(f);
      if(!userName){
        u = fsl_user_name_guess();
        if(!u) rc = FSL_RC_OOM;
      }
      if(!rc) rc = fsl_deck_U_set(&d, u ? u : userName);
      if(u) fsl_free(u);
      if(rc) goto end;
    }
    rc = fsl_deck_W_set(&d, fsl_b_cstr(b), (fsl_int_t)b->used);
#if 0
    fsl_deck_output(f, &d, fsl_output_f_FILE, stdout);
#endif
    if(!rc) rc = fsl_deck_save(&d, 0);
    end:
    fsl_deck_finalize(&d);
    return rc;
  }
}

#undef MARKER
/* end of file src/wiki.c */
/* start of file src/xfer.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2025 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2025 The Libfossil Authors
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**
  This file contains the library internals of the sync transport layer.
*/

#include <stdbool.h>
#include <stdio.h> /* FILE class */
#include <assert.h>
#include <stdlib.h> /* bsearch() */
#include <string.h> /* memcpy() */

#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

const fsl_xfer_config fsl_xfer_config_empty =
  fsl_xfer_config_empty_m;
const fsl_xfer_metrics fsl_xfer_metrics_empty =
  fsl_xfer_metrics_empty_m;

const fsl_sc fsl_sc_empty =
  fsl_sc_empty_m;

const fsl_xfer_dbg fsl_xfer_dbg_empty =
  fsl_xfer_dbg_empty_m;

#if 0
const fsl_sync_config fsl_sync_config_empty =
  fsl_sync_config_empty_m;
#endif

const fsl_clone_config fsl_clone_config_empty =
  fsl_clone_config_empty_m;

const fsl_xfer fsl_xfer_empty = {
  .f = 0,
  .ch = 0,
  .config = 0,
  .rc = 0,
  .line = {
    .b = fsl_b_empty_m,
    .bRaw = fsl_b_empty_m,
    .aToken  = {0,0,0,0,0,0},
    .aTokLen = {0,0,0,0,0,0},
    .nToken  = 0
  },
  .buf = {
    .uresp = fsl_b_empty_m,
    .hash = fsl_b_empty_m,
    .scratch = fsl_b_empty_m,
    .cardPayload = fsl_b_empty_m
  },
  .q = {
    .igotInsert   = fsl_stmt_empty_m,
    .igotHasRid   = fsl_stmt_empty_m,
    .gimmeInsert  = fsl_stmt_empty_m,
    //.gimmeDelete = fsl_stmt_empty_m,
    .remoteUnkUuid = fsl_stmt_empty_m,

  },
  .flag = {
    .configRcvMask = 0,
    .configSendMask = 0,
    .zAltPCode = 0,
    .syncPrivate = false,
    .nextIsPrivate = false,
    .peerError = false,
    .fatalError = false
  },
  .gimmePending = fsl_id_bag_empty_m,
  .privateIgot = fsl_id_bag_empty_m,
  .unsentPending = fsl_id_bag_empty_m,
  .xlinked = fsl_id_bag_empty_m,
  .replyErr = fsl_error_empty_m,
  .remote = {
    .releaseVersion = 0,
    .manifestDate = 0,
    .manifestTime = 0,
    .clockSkewSeen = 0
  },
  .clientVersion = {
    .number = FOSSIL_RELEASE_VERSION_NUMBER,
    .date = FOSSIL_MANIFEST_NUMERIC_DATE,
    .time = FOSSIL_MANIFEST_NUMERIC_TIME,
    .projCodeMatch = -1
  },
  .clone = {
    .protocolVersion = 0,
    .seqNo = 0,
    .pushSeen = false
  },
  .user = {
    .name = 0, .password = 0,
    .passwordToFree = 0,
    .perm = fsl_uperm_empty_m
  },
  .chz = fsl_sc_empty_m,
  .n = fsl_xfer_metrics_empty_m,
  .request = {
    .sha1 = fsl_sha1_cx_empty_m,
    .loginCard = fsl_b_empty_m,
    .nBytes = 0,
    .body = fsl_b_empty_m
  },
  .response = {
    .httpVersion = 0,
    .httpCode = 0
  }
};

/**
   Lowest-valued legal identifier character in a sync card name.  This
   plays a role in the hash.
*/
#define fsl_xfcard_LowestIdChar '$'
#define fsl_xfcard_MaxCardNameLen 11 /*==strlen("clone_seqno")*/

/** @internal

   Internal impl for one hash step of fsl_xfcard_hash() and the HASH#()
   family of macros (for compile-time hashes). Arguments:

   - H is the current hash value (starting at 0)
   - I is the char index into the word we're hashing.
   - CHAR is the character at index I of the word.

   Reminder to self:

   collision with "else" and "eval":
   h = (h << 1) + (++i) * (CHAR - 35)
*/
#if 1
#define fsl_xfcard_hash_step_ch(H,I,CHAR)  \
  (((((fsl_xfcard_hash_t)H << 1) + (I+1)) * (CHAR - fsl_xfcard_LowestIdChar-1)) ^ CHAR)
#elif 0
#define fsl_xfcard_hash_step_ch(H,I,CHAR)  \
  ((((H << 1) + (45*I) + CHAR - fsl_xfcard_LowestIdChar-1)) ^ CHAR)
#else
#define fsl_xfcard_hash_step_ch(H,I,CHAR)  \
  ((H << 1) + 113*I + (CHAR - fsl_xfcard_LowestIdChar-1))
#endif

/** @internal

   Very simple hash which has proven to be collision-free for
   several dozen keywords in a live scripting engine.

   This hash is used to generate ids for limited keyword lists such
   that we can verify, via assert(), that the hash iscollision-free
   for the full input set.

   Aside from the current implementation, these variations of
   fsl_xfcard_hash_step_ch() have worked out in prior testing:

   - ((H << 1) + 100*I + I*CHAR - I* (fsl_xfcard_LowestIdChar - 1))
   - ((H << 1) + 45*I + CHAR - fsl_xfcard_LowestIdChar - 1)

   Design note: this takes an unsigned string because its argument is
   invariably from fsl_xfer::line::aToken.
*/
static fsl_xfcard_hash_t fsl_xfcard_hash( unsigned const char * word );

/** Non-unsigned-qualified C-string convenience form of fsl_xfcard_hash(). */
#define fsl_xfcard_hashS(WORD) fsl_xfcard_hash((unsigned const char *)WORD)

#define fsl__xfer__check_rc if(xf->rc) return xf->rc

/** @internal

   Runs xf->ch->submit(). If a compressed response is expected then it
   fetches all of the content in a single go to keep the xf->ch impl
   from having to deal with compression.

   On success, before returning, it calls xf->ch->init() with a second
   value of FSL_SC_INIT_REQUEST so that xf can immediately be used for
   generating follow-up output.
*/
static int fsl__xfer_submit(fsl_xfer * const xf);
static int fsl__xfer_unsent_forget(fsl_xfer * const xf);

/** @internal

   Updates xf->count and returns the value of xf->ch->append(p,n).
*/
static int fsl__xfer_append(fsl_xfer * const xf, void const * p, fsl_size_t n);

#if 0
/** @internal

   Equivalent to fsl__sc_appendln() except that (A) it adds a newline
   to the output if it does not already have one and (B) it updates
   xf->count.
*/
static int fsl__xfer_appendln(fsl_xfer * const xf, char const * zMsg);
#endif

/** @internal

   Variadic form of fsl__xfer_appendln().
*/
static int fsl__xfer_appendlnf(fsl_xfer * const xf, char const * zFmt, ...);

/** @internal

   va_list form of fsl__xfer_appendln().
*/
static int fsl__xfer_appendlnv(fsl_xfer * const xf, char const * zFmt, va_list args);


/** @internal

   fsl__xfer_appendln() wrapper which prefixes the line with the appropriate
   card name and increments the outbound card count.
*/
static int fsl__xfer_appendcard(fsl_xfer * const xf, fsl_xfcard_e card,
                                char const * zFmt, ...);

static int fsl__xfer_send_file(fsl_xfer * const xf,
                               char const * zUuid,
                               bool isPrivate,
                               fsl_b const * content);


/** @internal

   Reads n bytes from xf->ch into dest. On success it updates
   xf->count and returns 0. n must not be 0 (and that's assert()ed).
*/
static int fsl__xfer_read(fsl_xfer * const xf, fsl_b * dest, fsl_size_t n);

/** @internal

   Reads one line of input from xf->ch into xf->line.b and tokenizes
   it into the other xf->line state. On success it updates xf->line
   and xf->count then returns 0.
*/
static int fsl__xfer_readln(fsl_xfer * const xf);

/**
   If xf->rc is not 0 this is a proxy for fsl_cx_emit(), else it
   returns xf->rc without side-effects. This is a no-op if xf->f
   does not have a fsl_msg_listener installed.
*/
static int fsl__xfer_emit(fsl_xfer *xf, fsl_msg_e type, void const * payload){
  if( xf->f->cxConfig.listener.callback ){
    int const rc = fsl_cx_emit(xf->f, type, payload);
    if( rc && 0==xf->rc ) xf->rc = rc;
  }
  return xf->rc;
}

/**
   Emits a FSL_MSG_XFER message with xf's current metrics. zDone and
   zRemote are as documented for fsl_msg_xfer.
*/
static void fsl__xfer_emit_progress(fsl_xfer * const xf,
                                    char const * zDone,
                                    char const * zRemote){
  fsl_msg_xfer const m = {
    .metrics = &xf->n,
    .trips = xf->n.trips - 1 /* n.trips already counts the next request */,
    .zDone = zDone, .zRemote = zRemote
  };
  fsl__xfer_emit(xf, FSL_MSG_XFER, &m);
}

static int fsl__xfer_emitf(fsl_xfer *xf, fsl_msg_e type,
                           char const * zFmt, ...){
  if( xf->f->cxConfig.listener.callback ){
    va_list args;
    va_start(args, zFmt);
    int const rc = fsl_cx_emitfv(xf->f, type, zFmt, args);
    if( rc && 0==xf->rc ) xf->rc = rc;
    va_end(args);
  }
  return xf->rc;
}


void fsl_xfer_debug_f_FILE(fsl_xfer * const xf, char const * const zMsg){
  assert(xf->config->debug.state);
  (void)fprintf(xf->config->debug.state, "%s sync debug: %s", xf->ch->name, zMsg);
}

void fsl_xfer_debug_f_buffer(fsl_xfer * const xf, char const * const zMsg){
  assert(xf->config->debug.state);
  (void)fsl_b_appendf(fsl_b_reuse(xf->config->debug.state),
                           "%s sync debug: %s", xf->ch->name, zMsg);
}

fsl_cx * fsl_xfer_cx(fsl_xfer * xf){
  return xf->f;
}

void fsl_xfer_dbg_cleanup( fsl_xfer_dbg * const p ){
  fsl_b_clear(&p->b);
}

void fsl_xfer_config_cleanup( fsl_xfer_config * p ){
  fsl_b_clear(&p->url);
  fsl_xfer_dbg_cleanup(&p->debug);
}

void fsl_clone_config_cleanup(fsl_clone_config *c){
  fsl_xfer_config_cleanup(&c->xfer);
}

int fsl_xfer_errorfv(fsl_xfer * const xf, int code,
                     char const * zFmt, va_list args){
  fsl_error * const err = fsl_cx_err_e(xf->f);
  fsl_b * const b = fsl_b_reuse(&err->msg);
  if( !code ){
    code = FSL_RC_ERROR /* Don't allow this routine to clear
                           xf->rc */;
  }
  fsl_b_appendf(b, "fsl_sc<%s> error %R: ", xf->ch->name, code);
  fsl_b_appendfv(b, zFmt, args);
  return xf->rc = err->code = code;
}

int fsl_xfer_errorf(fsl_xfer * const xf, int code, char const * zFmt, ...){
  va_list args;
  assert( xf->f );
  va_start(args,zFmt);
  fsl_xfer_errorfv(xf, code, zFmt, args);
  va_end(args);
  return xf->rc;
}

int fsl_xfer_error(fsl_xfer * const xf, int code, char const * zMsg){
  return FSL_RC_OOM==code
    ? fsl_xfer_errorf(xf, code, "%s", "")
    : fsl_xfer_errorf(xf, code, "%s", zMsg ? zMsg : "");
}

/**
   Settles the result rc of the channel method named zMethod, which
   was called through fsl__xfer_ch_call(). A method has failed if it
   left an error in the transfer's error state (see
   fsl_xfer_error()), whatever it returned, and that error stands. If
   it returned non-0 without setting one, we set one which names the
   channel and the method, so that the caller never sees an empty
   message or a failure blamed on the remote. FSL_RC_BREAK from
   read() is the end of the input, not a failure, and FSL_RC_OOM
   carries no message.
*/
static int fsl__xfer_ch_result(fsl_xfer * const xf, char const * zMethod,
                               int rc){
  fsl_error const * const err = fsl_cx_err_e(xf->f);
  if( err->code ){
    return xf->rc = err->code;
  }
  if( rc && FSL_RC_OOM!=rc && !(FSL_RC_BREAK==rc && 0==strcmp(zMethod, "read")) ){
    return fsl_xfer_errorf(xf, rc, "%s() failed and set no error message",
                           zMethod);
  }
  return rc;
}

/**
   Evaluates CALL, a call of one of xf's channel methods, with a clear
   error state and settles its result with fsl__xfer_ch_result(). The
   result is an expression and is not assigned to xf->rc.
*/
#define fsl__xfer_ch_call(XF, METHOD, CALL) \
  (fsl_cx_err_reset((XF)->f), fsl__xfer_ch_result((XF), METHOD, (CALL)))

/**
   Calls rch->read(), via fsl__xfer_ch_call(), and checks that it
   delivered what was asked for, which the channel is trusted to do
   only so far: a sized read must append exactly howMuch bytes and a
   line read must append something. Returns the result.
*/
static int fsl__xfer_ch_read(fsl_xfer * const xf, fsl_sc * const rch,
                             fsl_b * const tgt, fsl_int_t howMuch){
  fsl_size_t const nBefore = tgt->used;
  int rc = fsl__xfer_ch_call(xf, "read", rch->read(rch, tgt, howMuch));
  if( 0==rc ){
    fsl_size_t const nGot = tgt->used>=nBefore ? tgt->used - nBefore : 0;
    if( howMuch>0 && nGot!=(fsl_size_t)howMuch ){
      rc = fsl_xfer_errorf(xf, FSL_RC_MISUSE,
                           "read() reported success but appended %"
                           FSL_SIZE_T_PFMT " of %" FSL_SIZE_T_PFMT
                           " requested bytes", nGot, (fsl_size_t)howMuch);
    }else if( FSL_SC_READ_LINE==howMuch && !nGot ){
      rc = fsl_xfer_errorf(xf, FSL_RC_MISUSE,
                           "read(FSL_SC_READ_LINE) reported success but "
                           "appended no data");
    }
  }
  return rc;
}

void fsl_xfer_debug(fsl_xfer * const xf, char const * zMsg){
  if( xf->config->debug.callback ){
    xf->config->debug.callback(xf, zMsg);
  }
}

int fsl_xfer_debugfv(fsl_xfer * const xf, char const * zFmt, va_list args){
  int rc = 0;
  assert( xf->f );
  if( xf->config->debug.callback ){
    fsl_b * const b = fsl_b_reuse(&xf->config->debug.b);
    if( b->used<128 ) fsl_b_reserve(b, 128);
    fsl_b_appendf(b, "# DEBUG fsl_sc<%s>: ", xf->ch->name);
    fsl_b_appendfv(b, zFmt, args);
    fsl_b_ensure_eol(b);
    assert( b->errCode || b->mem[b->used-1]=='\n' );
    //MARKER(("debugging buffer(rc=%d): len=%d <<%.*s>>\n", b->rc,
    //        (int)b->used, (int)b->used, (char const*)b->mem));
    if( !(rc = b->errCode) ){
      xf->config->debug.callback(xf, fsl_b_cstr(b));
      rc = xf->f->error.code;
    }
    fsl_b_reuse(b);
  }
  return rc;
}

int fsl_xfer_debugf(fsl_xfer * const xf, char const * zFmt, ...){
  int rc = 0;
  if( xf->config->debug.callback ){
    va_list args;
    va_start(args,zFmt);
    rc = fsl_xfer_debugfv(xf, zFmt, args);
    va_end(args);
  }
  return rc;
}

static char const * fsl__xfer_projcode(fsl_xfer * const xf){
  char const * z = 0;
  if( 0==xf->rc ){
    int const rc = fsl_repo_project_code(xf->f, &z);
    if( FSL_RC_NOT_FOUND==rc ){
      fsl_cx_err_reset(xf->f);
    }
  }
  return z;
}

/**
   Populates xf->buf.scratch with a saved-password lookup key for xf's
   URL. Returns &xf->buf.scratch on success, NULL on allocation error.
   If pUrl is not NULL, then on success *pUrl points to the part of
   the output buffer immediately after the "libfossil-sync-pw:"
   prefix.
*/
static fsl_b * fsl__xfer_pw_key(fsl_xfer * const xf, char const **pUrl){
  assert( !xf->rc );
  fsl_b * const b = fsl_b_reuse(&xf->buf.scratch);
  fsl_b_append(b, "libfossil-sync-pw:", 18);
  fsl_url_render(&xf->ch->self(xf->ch)->url, b,
                 FSL_URL_RENDER_NO_PASSWORD);
  xf->rc = b->errCode;
  if( pUrl ){
    if( xf->rc ){
      *pUrl = 0;
    }else{
      *pUrl = strstr(fsl_b_cstr(b),":");
      assert( *pUrl );
      ++*pUrl /* skip the colon */;
    }
  }
  return b->errCode ? NULL : b;
}

/**
   Returns true if xf->user.password is either "" or "?", else returns
   false.
*/
static inline bool fsl__xfer_pw_wants_prompt(fsl_xfer const * const xf){
  return xf->user.password &&
    (!*xf->user.password || 0==fsl_strcmp("?", xf->user.password));
}

void fsl_xfer_pw_lookup(fsl_xfer * const xf, bool usePrompt){
  /** Look for a password hash in the login table. */
  if( xf->rc ) return;
  char const *zUrl = 0;
  char *zPW = 0;
  fsl_b * const bKey = fsl__xfer_pw_key(xf, &zUrl);
  if( !bKey ) return;

  if( xf->user.password && xf->user.password==xf->user.passwordToFree ){
    xf->user.password = 0;
  }
  fsl_free( xf->user.passwordToFree );
  xf->user.passwordToFree = 0;
  //MARKER(("bKey=%s\n", (char*)bKey->mem));
  //MARKER(("xf->user.password=[%s] usePrompt=%d\n",
  //xf->user.password, (int)usePrompt));
  if( usePrompt ){
    if( !xf->config->password.callback ){
      fsl_xfer_errorf(xf, FSL_RC_ACCESS,
                      "missing or incorrect password for user \"%s\" "
                      "at [%s]: the URL asks for a password prompt "
                      "and this application has no password callback",
                      xf->user.name, zUrl);
      return;
    }
    goto prompt;
  }

  if( 0!=(xf->rc = fsl_config_open(xf->f, NULL)) ){
    return;
  }

  zPW = fsl_config_get_text(xf->f, FSL_CONFDB_GLOBAL,
                            fsl_b_cstr(bKey), NULL);
  if( !zPW ){
    fsl_cx_err_reset(xf->f)
      /* clear FSL_RC_NOT_FOUND. And any other error, for that matter,
         but a password lookup failure is not sync-fatal at this point
         in the process. */;
    fsl_db * const db = fsl_cx_db_repo(xf->f);
    if( db ){
      /* fossil(1) stores last-sync-pw obscured (fossil src/url.c), with a
         different algorithm than user.pw, so it must be unobscured here and
         cannot be folded into the UNION below. */
      char * zObscured = fsl_db_g_text(
          db, NULL,
          "SELECT c1.value FROM {{dbname.repo}}.config c1, {{dbname.repo}}.config c2 WHERE "
          " c1.name='last-sync-pw' AND c2.name='last-sync-url' "
          " AND c2.value=%Q" /* fossil(1) convention */,
          zUrl);
      if( zObscured ){
        zPW = fsl_unobscure(zObscured);
        fsl_free(zObscured);
        if( !zPW ) xf->rc = FSL_RC_OOM;
      }else{
        zPW = fsl_db_g_text(
          db, NULL,
          "SELECT pw FROM {{dbname.repo}}.user WHERE login=%Q"
          " AND login NOT IN ('anonymous','nobody','developer','reader')",
          xf->user.name);
      }
    }
  }
  if( zPW && !*zPW ){
    /* An empty stored password is no password. Using it would make
       fsl__xfer_pw_wants_prompt() ask for a prompt on the next
       round trip. */
    fsl_free(zPW);
    zPW = 0;
  }
  if( zPW ){
    xf->user.password = xf->user.passwordToFree = zPW;
    fsl__xfer_emitf(xf, FSL_MSG_VERBOSE,
                    "Using saved password for [%b]", bKey);
    xf->config->password.save = false
      /* So fsl__xfer_pw_save() does not re-save it */;
  }else if( xf->config->password.callback ){
  prompt: ;
    fsl_b bpw = fsl_b_empty;
    xf->user.password = 0;
    xf->rc =
      xf->config->password.callback(xf->f, zUrl, &bpw,
                                    xf->config->password.state);
    if( 0==xf->rc ){
      xf->user.password = xf->user.passwordToFree =
        (char*)bpw.mem/*transfer ownership*/;
    }else{
      fsl_b_clear(&bpw);
    }
  }
  //MARKER(("xf->user.password=[%s]\n", xf->user.password));
}

/**
   Returns true if xf's URL is ssh: or file: because these channels do not
   use a fossil login. The user of an ssh URL is the ssh login, and
   ssh does the authentication using any of its many many auth mechanisms.
*/
static bool fsl__xfer_url_skips_login(fsl_xfer * const xf){
  char const * const zScheme = xf->ch->self(xf->ch)->url.scheme;
  return 0==fsl_strcmp("ssh", zScheme) || 0==fsl_strcmp("file", zScheme);
}

/**
   If xf->user.name is not empty, xf->user.password is empty, and the URL
   is not ssh: and not file:, try to fetch the password using the fossil
   login card process. Otherwise return having done nothing.

   If that finds no password, xf has no password callback, and the user
   is not one of the unauthenticated "anonymous" and "nobody", xf's
   error state is set to FSL_RC_ACCESS, as fossil(1) does when it
   cannot prompt (url.c:url_prompt_for_password_local()). Without
   this, no login card would be sent and the remote would treat the
   request as user "nobody".
*/
static void fsl__xfer_pw_setup(fsl_xfer * const xf){
  if( 0==xf->rc && xf->user.name && !fsl__xfer_url_skips_login(xf) ){
    //char const * const zPc = fsl__xfer_projcode(xf);
    bool const ignoreSaved = xf->config->password.ignoreSaved;
    bool const usePrompt = fsl__xfer_pw_wants_prompt(xf)
      || (ignoreSaved && !xf->user.password
          && xf->config->password.callback);
    if( !xf->user.password || usePrompt ){
      if( usePrompt || !ignoreSaved ){
        fsl_xfer_pw_lookup(xf, usePrompt);
      }
      if( 0==xf->rc && !xf->user.password
          && !xf->config->password.callback
          && *xf->user.name
          && fsl_strcmp("anonymous", xf->user.name)
          && fsl_strcmp("nobody", xf->user.name) ){
        char const * zUrl = 0;
        if( fsl__xfer_pw_key(xf, &zUrl) ){
          fsl_xfer_errorf(xf, FSL_RC_ACCESS,
                          "missing or incorrect password for user "
                          "\"%s\" at [%s]", xf->user.name, zUrl);
        }
      }
    }
  }
}

static int fsl__xfer_pw_save(fsl_xfer * const xf){
  if( 0==xf->rc
      && xf->config
      && xf->config->password.save
      && xf->user.name
      && xf->user.password
      && xf->ch ){
    char const * myPC = 0;
    if( fsl_config_open(xf->f, NULL) ) goto not_saved;
    myPC = fsl__xfer_projcode(xf);
    if( myPC ) {
      fsl_b * const b = fsl__xfer_pw_key(xf, NULL);
      char * zPW = b
        ? fsl_sha1_shared_secret2(xf->f, xf->user.name,
                                  xf->user.password, myPC)
        : NULL;
      if( zPW ){
        xf->rc = fsl_config_set_text(xf->f, FSL_CONFDB_GLOBAL,
                                     fsl_b_cstr(b), zPW);
        if( 0==xf->rc ){
          /* Reminder to self: in dry-run testing this won't
             be saved. */
          fsl__xfer_emitf(xf, FSL_MSG_INFO,
                         "Password saved under [%b]", b);
        }
      }/* else: we're going to treat this as innocuous for now */
      fsl_free(zPW);
      if( xf->rc && FSL_RC_OOM!=xf->rc ) goto not_saved;
    }/* else: without a project code we can't save the password, as
        the project code is part of the hash. */
  }
  return xf->rc;
not_saved:
  /* This runs after a successful sync, whose result does not depend
     on the password being saved. The failure is reported as INFO
     and f's error state is cleared. */
  {
    char const * zMsg = 0;
    fsl_cx_err_get(xf->f, &zMsg, NULL);
    xf->rc = 0;
    fsl__xfer_emitf(xf, FSL_MSG_INFO, "Password not saved: %s",
                    zMsg ? zMsg : "");
    fsl_cx_err_reset(xf->f);
  }
  return xf->rc;
}

/**
   For a URL which fsl_url_parse() could not parse, so cannot be
   rendered with FSL_URL_RENDER_MASK_PASSWORD, finds the password in
   "scheme://user:password@host...". Sets *pBegin and *pEnd to the
   offsets of the password's first byte and of the byte after it, or
   both to 0 if z has no password.
*/
static void fsl__xfer_url_pw_span(char const * z, int * pBegin,
                                  int * pEnd){
  char const * zAuth = strstr(z, "//");
  *pBegin = *pEnd = 0;
  if( !zAuth ) return;
  zAuth += 2;
  char const * const zAt = strchr(zAuth, '@');
  if( !zAt ) return;
  for( char const * zc = zAuth; zc<zAt; ++zc ){
    if( '/'==*zc ) return;
    if( ':'==*zc ){
      *pBegin = (int)(zc + 1 - z);
      *pEnd = (int)(zAt - z);
      return;
    }
  }
}

static int fsl__xfer_init_url(fsl_xfer * const xf){
  fsl_xfer_config * const xc = xf->config;
  fsl_url * const url = &xf->ch->self(xf->ch)->url;
  char const *zXFUrl = xc->url.used
    ? fsl_b_cstr(&xc->url) : 0;
  assert( 0==xf->rc );
  xf->rc = fsl_url_parse( url, zXFUrl );
  if( xf->rc ){
    if( zXFUrl ){
      int b = 0, e = 0;
      fsl__xfer_url_pw_span(zXFUrl, &b, &e);
      return fsl_xfer_errorf(xf, xf->rc, "Error %R parsing URL: %.*s%s%s",
                             xf->rc, e>b ? b : (int)xc->url.used,
                             zXFUrl, e>b ? "****" : "",
                             e>b ? zXFUrl + e : "");
    }else{
      return fsl_xfer_errorf(xf, xf->rc,
                             "Cannot sync with an empty URL.");
    }
  }
  if( 0==xf->rc && xf->config->listener.callback ){
    fsl_b * const bUrl = fsl_b_reuse(&xf->buf.scratch);
    fsl_url_render(url, bUrl, FSL_URL_RENDER_NO_PASSWORD);
    fsl__xfer_emitf(xf, FSL_MSG_INFO, "Sync URL: %b", bUrl);
  }
  xf->user.name = url->username;
  /* If a password isn't present no login card is sent. */
  xf->user.password = fsl__xfer_url_skips_login(xf) ? NULL : url->password;
  return xf->rc;
}

/**
   (Re)creates temp tables used by xf.
*/
static int fsl__xfer_init_tables(fsl_xfer *xf){
#if 0
  if( 0==xf->rc ){
    xf->rc = fsl_cx_exec_multi(xf->f,
                               "DROP TABLE IF EXISTS {{temp.xfigot}};"
                               "DROP TABLE IF EXISTS {{temp.xfgimme}};"
                               "CREATE TEMP TABLE {{temp.xfigot}}"
                               "(rid INTEGER PRIMARY KEY);"
                               "CREATE TEMP TABLE {{temp.xfgimme}}"
                               "(uuid TEXT NOT NULL, CHECK( length(uuid)>=40 ));",
                               //"INSERT INTO {{temp.xfigot}} SELECT rid FROM %!Q.blob;",
                               /* TODO: delay the INSERT until needed
                                  (if it's needed at all). We don't need it unless
                                  we're going to deal with igots from the remote. */
                               fsl_db_role_name(FSL_DBROLE_REPO));
  }
#endif
  return xf->rc;
}

/**
   Initializes xf's core-most state. Returns 0 on success. On
   error, the sync must be aborted.

   Even on failure, fsl__xfer_cleanup() must eventually be called.

   For round-trip connections (cloning), this must be once at the
   onset and fsl__xfer_start() must be called at the start of each
   round-trip, before attempting to create a request payload.
*/
int fsl__xfer_setup(fsl_cx * const f,
                   fsl_xfer * const xf,
                   fsl_xfer_config * xc,
                   fsl_sc * const channel){
  assert( !channel->xfer );
  assert( channel->self );
  xf->f = f;
  xf->rc = 0;
  xf->ch = channel;
  channel->xfer = xf;
  xf->config = xc;
  fsl_sc * const chSelf = channel->self(channel);
  if( xc->compressTraffic ) chSelf->flags |= FSL_SC_F_COMPRESSED;
  else chSelf->flags &= ~FSL_SC_F_COMPRESSED;
  if( xc->leaveTempFiles ) chSelf->flags |= FSL_SC_F_LEAVE_TEMP_FILES;
  else chSelf->flags &= ~FSL_SC_F_LEAVE_TEMP_FILES;
  if( xc->acceptAnyCert ) chSelf->flags |= FSL_SC_F_TLS_ACCEPT_ANY_CERT;
  else chSelf->flags &= ~FSL_SC_F_TLS_ACCEPT_ANY_CERT;

  if( !xc->listener.callback ){
    xc->listener = f->cxConfig.listener;
  }

  fsl__xfer_init_url(xf);
  /*
    Reminder to self: we can't call fsl__xfer_init_tables(xf) from here
    because f is, in the case of a clone op, not yet opened.
  */
  if( 0==xf->rc ){
    /* Alloc errors here can be ignored. They'll be caught later if
       they continue to happen. */
    fsl_b_reserve(&xf->line.b, 128);
    fsl_b_reserve(&xf->line.bRaw, xf->line.b.capacity);
    fsl_b_reserve(
      &xf->ch->requestHeaders,
      (xf->ch->flags & FSL_SC_F_REQUEST_HEADERS) ? 1024 : 256
      /* We (ab)use this in fsl__xfer_append_prologue() even if
         !(xf->ch->flags & FSL_SC_F_REQUEST_HEADERS). */
    );
    fsl_b_reserve(&xf->line.bRaw, xf->line.b.capacity);
    fsl_b_reserve(&xf->buf.hash, FSL_STRLEN_SHA1+1);
    if( fsl__xfer_projcode(xf) ){
      fsl__xfer_pw_setup(xf);
    }
  }
  return xf->rc
    ? xf->rc
    : (xf->rc = fsl__xfer_ch_call(xf, "init",
                                 xf->ch->init(xf->ch, FSL_SC_INIT_INITIAL)));
}

/** Modes for use with fsl__xfer_start(). */
enum fsl__xfer_e {
  /** (Re)Initialize the response-related state. */
  FSL__XFER_START_RESPONSE = 0x1000,
  /** (Re)Initialize the request-related state. */
  FSL__XFER_START_REQUEST  = 0x2000
};


static int fsl__xfer_start(fsl_xfer * const xf, enum fsl__xfer_e initMode){
  fsl__xfer__check_rc;
  assert( xf->ch );
  assert( xf->f );

  switch( initMode ){
    case FSL__XFER_START_RESPONSE:
      xf->response.httpVersion = xf->response.httpCode = 0;
      fsl_b_reuse(&xf->buf.uresp);
      fsl_b_reserve(fsl_b_reuse(&xf->line.b), 160);
      fsl_b_reserve(fsl_b_reuse(&xf->line.bRaw),
                         xf->line.b.capacity);
      fsl_sc_cleanup(&xf->chz);
      xf->chz = fsl_sc_empty;
      break;
    case FSL__XFER_START_REQUEST:
      ++xf->n.trips;
      xf->request.nBytes = 0;
      fsl_b_reuse(&xf->request.body);
      fsl_sha1_init(&xf->request.sha1);
      fsl__xfer_init_tables(xf);
      break;
#if !defined(NDEBUG)
    default: /* can't happen */
      fsl__fatal(FSL_RC_ERROR, "Unhandled fsl__xfer_start() initMode");
#endif
  }
  //MARKER(("init mode=%02x rc=%d\n", mode, xf->rc));
  return xf->rc;
}


/** @internal

   Cleans up all state owned by xf (which must not be NULL).  If
   xf->ch is not 0, xf->ch->close() is called.
*/
static void fsl__xfer_cleanup(fsl_xfer * const xf, int theRc){
  if( 0==theRc ){
    fsl__xfer_pw_save(xf);
  }
  fsl_sc_cleanup(xf->ch);
#define fbc fsl_b_clear
  fbc(&xf->line.b);
  fbc(&xf->line.bRaw);
  fbc(&xf->buf.uresp);
  fbc(&xf->buf.hash);
  fbc(&xf->buf.cardPayload);
  fbc(&xf->buf.scratch);
  fbc(&xf->request.loginCard);
  fbc(&xf->request.body);
#undef fbc
  fsl_free( xf->user.passwordToFree );
  fsl_id_bag_clear(&xf->gimmePending);
  fsl_id_bag_clear(&xf->privateIgot);
  fsl_id_bag_clear(&xf->unsentPending);
  fsl_error_clear(&xf->replyErr);
  fsl_id_bag_clear(&xf->xlinked);
#define ST(M) fsl_stmt_finalize(&xf->q.M)
  ST(igotInsert);
  ST(igotHasRid);
  ST(gimmeInsert);
  //ST(gimmeDelete);
  ST(remoteUnkUuid);
#undef ST
  if( xf->config && xf->config->metrics.callback ){
    xf->ch = 0;
    xf->user.name = xf->user.password = xf->user.passwordToFree = 0;
    xf->config->metrics.callback( &xf->n, xf->config->metrics.state,
                                  theRc ? theRc : xf->rc );
  }
  if( xf->f ){
    fsl__cx_caches_reset(xf->f, 0==theRc);
  }
  *xf = fsl_xfer_empty;
}

static inline void fsl__xfer_countRead( char mode, fsl_size_t * const pOut, fsl_size_t n ){
  /*MARKER(("update '%c' read: %u + %u = %u\n", mode, (unsigned) n, (unsigned)*pOut,
    (unsigned)(n + *pOut)));*/
  (void)mode;
  *pOut += n;
}

#define fsl__xfer__rch_decl \
  fsl_sc * const rch = xf->chz.xfer ? &xf->chz : xf->ch

static int fsl__xfer_read(fsl_xfer * const xf, fsl_b * const dest,
                          fsl_size_t n){
  if( 0==xf->rc ){
    assert( n > 0 );
    fsl__xfer__rch_decl;
    fsl_timer_scope(&xf->n.timer.read,{
        xf->rc = fsl__xfer_ch_read(xf, rch, dest, (fsl_int_t)n);
      });
    if( 0==xf->rc ){
      fsl__xfer_countRead('u', &xf->n.bytesReadUncompressed, n);
    }
  }
  return xf->rc;
}

static int fsl__xfer_readln(fsl_xfer * const xf){
  fsl_b * const bLn = &xf->line.b;
  fsl_b * const bLnRaw = &xf->line.bRaw;
  fsl__xfer__check_rc;
  fsl__xfer__rch_decl;
again: ;
  fsl_timer_scope(&xf->n.timer.read,{
      xf->rc = fsl__xfer_ch_read(xf, rch, fsl_b_reuse(bLn),
                                 FSL_SC_READ_LINE);
    });

  /*MARKER(("rc=%d line=<<%.*s>>\n", rc,
    (int)(bLn->used ? bLn->used-1 : 0), (char const *)bLn->mem));*/
  if( 0==xf->rc ){
    fsl__xfer_countRead('u', &xf->n.bytesReadUncompressed, bLn->used);
    //assert( bLn->used );
    if( !bLn->used ){
      /* This shouldn't be possible at this point but we could account
         here for a broken fsl_sc impl which doesn't return EOF
         properly. */
      fsl_xfer_errorf(xf, FSL_RC_RANGE, "No more lines in input");
    }else if( '\n'!=bLn->mem[bLn->used-1] ){
      fsl_xfer_error(xf, FSL_RC_SYNTAX,
                     "Input does not end with a newline");
    }else if( 1==bLn->used ){
      /* Skip blank lines */
      assert( '\n'==bLn->mem[0] );
      /* Empty line - skip it */
      goto again;
    }else if( '#'==bLn->mem[0] ){
      /* Comment lines - skip it */
      if( 0 ){
        fsl_xfer_debugf(xf, "%s() got comment line:\n%b",
                      __func__, bLn);
      }
      goto again;
    }else{
      /** Populate xf->line.aToken and aTokLen */
      fsl__tokenizer src = {
        .z = bLn->mem, .zEnd = bLn->mem + bLn->used, .atEol = false
      };
      xf->line.nToken = 0;
      fsl_b_reuse(bLnRaw);
      fsl_b_append( bLnRaw, bLn->mem, (fsl_int_t)bLn->used )
        /* Alloc failure here should be benign. */;
      /*MARKER(("read line = <<%.*s>>\n",
        (int)bLn->used, (char const *)(bLn->mem)));*/
      while( (xf->line.nToken < fsl__xfer_max_tokens)
             && 0!=(xf->line.aToken[xf->line.nToken] =
                    fsl__tokenizer_next(
                      &src, &xf->line.aTokLen[xf->line.nToken]
                    )) ){
        ++xf->line.nToken;
      }
      /* A line from the remote with more tokens than a card can have
         (ie 6) stops the loop above before the end of the line */
      if( !src.atEol ) {
        xf->rc = fsl_cx_err_set(xf->f, FSL_RC_RANGE,
                                     "Unexpected stuff after token #%d: %b",
                                     (int)xf->line.nToken+1,
                                     bLnRaw);
      }
    }
  }
  return xf->rc;
}

/**
   Internal helper which uses src as a fsl_sc read source.
*/
static int fsl__xfer_rdbuf(fsl_sc * const ch, fsl_b * const tgt,
                          fsl_b * const src, fsl_int_t howMuch){
  int rc = FSL_RC_CANNOT_HAPPEN;
  assert( 0==ch->xfer->rc );
  switch( howMuch ){

    case FSL_SC_READ_ALL:
      fsl_b_swap(src, tgt);
      rc = 0;
      break;

    case FSL_SC_READ_LINE:{
      fsl_size_t const cu = src->cursor;
      rc = fsl_b_copy_lines(tgt, src, 1);
      if( !rc && cu==src->cursor ){
        /* End of input */
        rc = FSL_RC_BREAK;
      }
      break;
    }

    default:
      assert( howMuch>0 );
      if( src->cursor + howMuch > src->used ){
        rc = fsl_xfer_errorf(ch->xfer, FSL_RC_RANGE,
                             "Not enough buffered to read %" FSL_INT_T_PFMT
                             " bytes", howMuch);
      }else{
        rc = fsl_b_append(tgt, src->mem+src->cursor, (fsl_size_t)howMuch);
        if( 0==rc ){
          src->cursor += howMuch;
        }
      }
      break;
  }
  return rc;
}

static int fsl__rbuf_xRead(fsl_sc * const ch, fsl_b * tgt, fsl_int_t howMuch){
  return fsl__xfer_rdbuf(ch, tgt, &ch->xfer->buf.uresp, howMuch);
}

static fsl_sc * fsl__rbuf_xSelf(fsl_sc *ch){
  assert( ch->xfer->ch );
  assert( ch->xfer->ch != ch );
  return ch->xfer->ch;
}

/**
   A partial (read()-only) fsl_sc impl to support fsl_xfer's ability
   to read fossil-compressed responses.
 */
static const fsl_sc fsl_sc__xfer_rbuf = {
  .xfer = 0,
  .impl = {.p = 0, .type= &fsl_xfer_empty},
  .name = "fsl_xfer:rbuf",
  .init  = 0,
  .append  = 0,
  .submit  = 0,
  .read = fsl__rbuf_xRead,
  .cleanup = 0,
  .self = fsl__rbuf_xSelf
};

/**
   Guesses whether xf's state is such that a pending request may
   include login info.
*/
static inline bool fsl__xfer_may_attempt_login(fsl_xfer * const xf){
  if(xf->rc
     || !xf->user.password
     || !xf->f->cache.projectCode
     || (xf->config->op.clone
         && xf->clientVersion.projCodeMatch<=0)
     || !xf->user.name || !*xf->user.name
     || 0==fsl_strcmp("anonymous",xf->user.name)
     || 0==fsl_strcmp("nobody",xf->user.name)
  ) return false;
  return true;
}

/**
   May construct a login card for xf->user, (re)populating
   xf->request.loginCard with the result. Returns 0 on success. On
   success it may or may not populate the login card, depending on
   $REASONS. It is not an error for no login card to be created, but
   it will mean that sync operations which require remote write acces
   won't work.

   Login cards look like:

     login LOGIN NONCE SIGNATURE

   The LOGIN is xf->user.name.  NONCE is the SHA1 checksum of all
   request payload (stored in xf->buf.hash).  SIGNATURE is the SHA1
   checksum of the NONCE followed by xf->user.password (or, if the
   password is not an itself an SHA1 hash, its fossil-encrypted form).
*/
static int fsl__xfer_build_login_card(fsl_xfer * const xf){
  fsl__xfer__check_rc;
  fsl_b const * const nonce = &xf->buf.hash;
  fsl_b * const sig = fsl_b_reuse(&xf->buf.scratch);
  char const * const zPw = xf->user.password;
  fsl_size_t nPw = 0;
  int rc = 0;

  fsl_b_reuse(&xf->request.loginCard);
#if !defined(NDEBUG)
  assert( fsl__xfer_may_attempt_login(xf) );
#else
  if( ! fsl__xfer_may_attempt_login(xf) ) return 0;
#endif
  assert( FSL_STRLEN_SHA1 == nonce->used );
  assert( zPw );
  nPw = fsl_strlen(zPw);
  /* At this point fossil(1) also returns 0 for ssh:// URLs. */
  assert( nonce->used == FSL_STRLEN_SHA1 /* payload hash */ );

  fsl_b_copy(sig, nonce);

  /* The login card wants the SHA1 hash of the password (as computed by
  ** fsl_sha1_shared_secret2()), not the original password.  So convert the
  ** password to its SHA1 encoding if it isn't already a SHA1 hash.
  **
  ** We assume that a hexadecimal string of exactly 40 characters is a
  ** SHA1 hash, not an original password.  If a user has a password which
  ** just happens to be a 40-character hex string, then this routine won't
  ** be able to distinguish it from a hash, the translation will not be
  ** performed, and the sync won't work.
  */
  if( sig->errCode ) goto end;
  assert( sig->used == FSL_STRLEN_SHA1 /* payload hash */ );
  if( (FSL_STRLEN_SHA1!=nPw
       || FSL_HTYPE_ERROR==fsl_validate_hash(zPw, FSL_STRLEN_SHA1)) ){
    char const *zPC = fsl__xfer_projcode(xf)
      /* TODO: a way to tell it to use some other project code,
         e.g. parent-project-code. */;
    assert( zPC );
    char * zSSS = fsl_sha1_shared_secret2(xf->f, xf->user.name, zPw, zPC);
    if( !zSSS ){
      if( xf->f->cache.projectCode ){
        fsl_report_oom;
      }else{
        assert(!"Not an OOM. Probably missing project-code");
      }
      rc = FSL_RC_OOM;
      goto end;
    }
    /* TODO: optionally save pw. See fossil(1)
       src/http.c:http_build_login_card(). We need a fsl_xfer flag
       to tell us whether this is okay. */
    assert( !zSSS[FSL_STRLEN_SHA1] && !!zSSS[FSL_STRLEN_SHA1-1] );
    fsl_b_append(sig, zSSS, FSL_STRLEN_SHA1);
    //fsl_b_append(sig, zSSS, -1);
    fsl_free( zSSS );
  }else{
    assert( zPw );
    fsl_b_append(sig, zPw, nPw);
  }

  if( 0==(rc = sig->errCode) ){
    fsl_sha1sum_buffer(sig, sig)
      /* Cannot fail - no alloc needed */;
    rc = fsl_b_appendf(&xf->request.loginCard, "login %F %b %b",
                            xf->user.name, nonce, sig);
  }

end:
  return xf->rc = rc;
}

/**
   Appends zPath to b as the target of an HTTP request line. Characters
   outside the RFC 3986 path grammar are percent-encoded. Existing
   well-formed %XX escapes are kept as they are.
*/
static void fsl__xfer_append_request_target(fsl_b * const b,
                                            char const *zPath){
  static char const zHex[] = "0123456789abcdefABCDEF";
  static char const zPchar[] = "-._~!$&'()*+,;=:@/";
  for( ; *zPath; ++zPath ){
    unsigned char const c = (unsigned char)*zPath;
    if( '%'==c && zPath[1] && zPath[2]
        && strchr(zHex, zPath[1]) && strchr(zHex, zPath[2]) ){
      fsl_b_append(b, zPath, 3);
      zPath += 2;
    }else if( c<0x80 && (fsl_isalnum(c) || strchr(zPchar, c)) ){
      fsl_b_appendch(b, (char)c);
    }else{
      fsl_b_appendf(b, "%%%02X", (unsigned)c);
    }
  }
}

static inline bool fsl__xfer_login_header_supported(fsl_xfer const * const xf){
  return xf->remote.releaseVersion>22700
    || (xf->remote.manifestDate > 20250727
        || (xf->remote.manifestDate == 20250727
            && xf->remote.manifestTime >= 110500));
}

static int fsl__xfer_login_version_check(fsl_xfer * const xf){
  if( xf->remote.releaseVersion
      && !fsl__xfer_login_header_supported(xf) ){
    return fsl_xfer_errorf(
      xf, FSL_RC_UNSUPPORTED,
      "Remote Fossil %d (%d@%06d) does not support login-card cookies; "
      "authenticated sync requires Fossil 2.27 or later",
      xf->remote.releaseVersion,
      xf->remote.manifestDate,
      xf->remote.manifestTime);
  }
  return 0;
}

static int fsl__xfer_prepare_req_headers(fsl_xfer * const xf){
  fsl__xfer__check_rc;
  unsigned char digest[FSL_STRLEN_SHA1/2];
  char hex[FSL_STRLEN_SHA1+1];
  bool const doLogin = fsl__xfer_may_attempt_login(xf);
  fsl_b * const bHash = fsl_b_reuse( &xf->buf.hash );
  fsl_b_reuse( &xf->request.loginCard );
  if( doLogin && fsl__xfer_login_version_check(xf) ) goto end;
  if( doLogin ){
    /* Add some entropy to the request, as a comment line, before
       submitting it so that the login-card nonce is different for
       otherwise identical requests. We don't do this for
       unauthenticated requests because there's no need to harden
       those this way, as the login nonce won't be used. */
    fsl_randomness(sizeof(digest), digest);
    fsl_to_hex(digest, sizeof(digest), hex);
    fsl__xfer_appendlnf(xf, "# entropy %s", hex);
  }

  { /* Add a # timestamp comment line. We really only need this in
       server mode, as it's the client who detects time skews.
       Potential TODO: simplify this in fossil to use a Unix-epoch
       time instead of ISO-8601. And it really should be its own
       card, even if it has to be a pragma for backwards compatibility
       (unknown pragmas are ignored). */
    char tmStamp[30];
    time_t const tt = time(0);
    fsl_strftime( tmStamp, sizeof(tmStamp),
                  "%Y-%m-%dT%H:%M:%S", gmtime(&tt) );
    fsl__xfer_appendlnf(xf, "# timestamp %s", tmStamp);
    fsl__xfer_appendcard(xf, fsl_xfcard_e_pragma,
                         "time %" FSL_TIME_T_PFMT, (fsl_time_t)tt);
  }

  if( doLogin && 0==xf->rc ){
    fsl_sha1_final(&xf->request.sha1, digest);
    xf->rc = fsl_b_reserve(bHash, FSL_STRLEN_SHA1+1);
    if( 0==xf->rc ){
      fsl_sha1_digest_to_base16(digest, (char *)bHash->mem);
      bHash->used = FSL_STRLEN_SHA1;
      bHash->mem[bHash->used] = 0;
    }
  }
  if( xf->rc ) goto end;
  assert( bHash->used == (doLogin ? FSL_STRLEN_SHA1 : 0) );
  fsl_size_t nWire = xf->request.nBytes /* Content-Length */;
  if( FSL_SC_F_COMPRESSED & xf->ch->flags ){
    /* The body is complete: compress it into the container the
       Content-Type promises (sync draft section 4.1) and hand it to
       the channel. The login card above hashes the uncompressed
       body, as fossil(1)'s does. */
    fsl_b * const z = fsl__cx_scratchpad(xf->f);
    xf->rc = fsl_b_compress(&xf->request.body, z);
    if( 0==xf->rc ){
      xf->rc = fsl__xfer_ch_call(xf, "append",
                                 xf->ch->append(xf->ch, z->mem, z->used));
    }
    nWire = z->used;
    fsl__cx_scratchpad_yield(xf->f, z);
    if( xf->rc ) goto end;
  }
  if( 0 ){
     MARKER(( "Request payload size=%" FSL_SIZE_T_SFMT "  sha1=%s\n",
             xf->request.nBytes, fsl_b_cstr(bHash) ));
  }

  if( bHash->used && fsl__xfer_build_login_card(xf) ){
    goto end;
  }
  //MARKER(("Login card=%s\n", fsl_b_cstr(&xf->request.loginCard)));
  fsl_sc * const chSelf = xf->ch->self(xf->ch);
  if( FSL_SC_F_REQUEST_HEADERS & chSelf->flags ){
    /* Emit HTTP headers to chSelf->requestHeaders */
    fsl_url const * const url = &chSelf->url;
    fsl_b * const b = fsl_b_reuse( &chSelf->requestHeaders );
#define fba fsl_b_append
#define fbaf fsl_b_appendf
#define CRNL "\r\n"
    fba(b, "POST ", 5);
    fsl__xfer_append_request_target(b, url->path && *url->path
                                    ? url->path : "/");
    fba(b, " HTTP/1.0" CRNL, -1);
    if( url->port>0 ){
      fbaf(b, "Host: %s:%d" CRNL, url->host ? url->host : "localhost",
           url->port);
    }else{
      fbaf(b, "Host: %s" CRNL, url->host ? url->host : "localhost" );
    }
    if( 1 ){
      fbaf(b, "X-Fossil-Client: libfossil %s" CRNL,
           FSL_LIBRARY_VERSION);
    }
    fba(b, (FSL_SC_F_COMPRESSED & xf->ch->flags)
        ? "Content-Type: application/x-fossil" CRNL
        : "Content-Type: application/x-fossil-uncompressed" CRNL,
        -1);
    if( xf->request.loginCard.used ){
      fbaf(b, "Cookie: x-f-l-c=%t\r\n",
           fsl_b_cstr(&xf->request.loginCard));

    }
    fbaf(b, "Content-Length: %" FSL_SIZE_T_PFMT CRNL, nWire);
    fba(b, CRNL, 2);
    if( xf->config->verbosity ){
      MARKER(("FSL_SC_F_REQUEST_HEADERS:\n"));
      fsl_output(xf->f, b->mem, b->used);
    }
    xf->rc = b->errCode;
  }
end:
  return xf->rc;
#undef CRNL
#undef fba
#undef fbaf
}

/**
   Parse xf's HTTP response headers. Write the Content-Length to
   *contentLength. Set *expectCompressedResponse to be true if the
   response body is expected to be compressed, false if it's not.

   0 on success and all that. This is a no-op if xf->rc
   and this always sets xf->rc on error.
*/
static int fsl__xfer_parse_http_headers( fsl_xfer * const xf,
                                         fsl_size_t * contentLength,
                                         /* Content-Length HTTP header value */
                                         bool * expectCompressedResponse ){
  /* Consume input until the end of the headers (\r\n\r\n).  Look
     for HTTP errors and the like. */
  fsl__xfer__check_rc;
  fsl__xfer__rch_decl;
  fsl_b * const bLine = &xf->line.b;
  fsl_size_t nLine = 0;
  int hc = 0;
  bool haveLength = false;
  int nBlank = 0;
  *contentLength = 0;
  while( 1 ){
    fsl_timer_scope(&xf->n.timer.read,{
        xf->rc = fsl__xfer_ch_read(xf, rch, fsl_b_reuse(bLine),
                                   FSL_SC_READ_LINE)
          /* reminder to self: don't use fsl__xfer_readln() because
             it does validation and empty line skipping which is not
             appropriate here. */;
      });
    if( FSL_RC_BREAK==xf->rc ){
      fsl_xfer_error(xf, FSL_RC_SYNTAX, nLine
                     ? "HTTP response ended before the end of its headers"
                     : "server did not reply");
    }
    if( xf->rc ) break;
    ++nLine;
    fsl__xfer_countRead('u', &xf->n.bytesReadUncompressed,
                        bLine->used);
    if( (2==bLine->used
         && (unsigned char)'\r'==bLine->mem[0]
         && (unsigned char)'\n'==bLine->mem[1])
        || (1==bLine->used && (unsigned char)'\n'==bLine->mem[0]) ){
      /* An empty line, ended by CRLF or by a bare LF, which RFC 9112
         section 2.2 lets a recipient accept, ends the headers. */
      if( 1==nLine && ++nBlank<=4 ){
        /* Some servers send an empty line after an interim reply,
           before the next status line. */
        nLine = 0;
        continue;
      }
      break;
    }
    fsl_xfer_debugf(xf, "Response HTTP header #%d: %b",
                    (int)nLine, bLine);
    char const * const zLine = fsl_b_cstr(bLine);
    {
      /* A CR is allowed only as part of the CRLF which ends the line
         (RFC 9112 section 2.2). */
      char const * const zCr = memchr(zLine, '\r', bLine->used);
      if( zCr && zCr != zLine + bLine->used - 2 ){
        fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                        "HTTP response line %d contains a bare CR",
                        (int)nLine);
        break;
      }
    }
    if( nLine>1 ){
      char const * z = zLine;
      /* RFC 9112 section 5.2 has a user agent replace obsolete line
         folding with spaces. Folding is rejected here because a
         continuation line can change Content-Length or another framing
         field. */
      if( ' '==*z || '\t'==*z ){
        fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                        "Obsolete folded HTTP header line: %b", bLine);
        break;
      }
      /* A header line starts with a field name, a token, followed
         directly by a colon (RFC 9110 section 5.1, RFC 9112 section
         5.1). */
      while( *z && (fsl_isalnum(*z) || strchr("!#$%&'*+-.^_`|~", *z)) ){
        ++z;
      }
      if( z==zLine || ':'!=*z ){
        fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                        "Malformed HTTP header line: %b", bLine);
        break;
      }
    }
    if( xf->config->verbosity ){
      fsl_xfer_debugf(xf, "Response header #%d: %b",
                    (int)nLine, bLine);
    }
    if( 1==nLine ){
      /* status-line = HTTP-version SP status-code SP [reason-phrase],
         with a status code of exactly three digits (RFC 9112 section
         4). */
      if( !(bLine->used>=14 && 0==memcmp(zLine, "HTTP/1.", 7)
            && fsl_isdigit(zLine[7]) && ' '==zLine[8]
            && fsl_isdigit(zLine[9]) && fsl_isdigit(zLine[10])
            && fsl_isdigit(zLine[11])
            && (' '==zLine[12] || '\r'==zLine[12]
                || '\n'==zLine[12])) ){
        fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                        "Expecting \"HTTP/1.X NNN\" in the "
                        "first HTTP result line: %b", bLine);
        break;
      }
      xf->response.httpVersion = zLine[7] - '0';
      xf->response.httpCode = (zLine[9] - '0') * 100
        + (zLine[10] - '0') * 10 + (zLine[11] - '0');
      hc = xf->response.httpCode;
      if( hc/100==1 ){
        /* Discard HTTP/1.1 interim replies such as "100 Continue". */
        do{
          fsl_timer_scope(&xf->n.timer.read,{
              xf->rc = fsl__xfer_ch_read(xf, rch, fsl_b_reuse(bLine),
                                         FSL_SC_READ_LINE);
            });
          if( FSL_RC_BREAK==xf->rc ){
            fsl_xfer_error(xf, FSL_RC_SYNTAX,
                           "Connection dropped after interim HTTP response");
          }
          if( xf->rc ) break;
          fsl__xfer_countRead('u', &xf->n.bytesReadUncompressed,
                              bLine->used);
        }while( !((2==bLine->used
                   && (unsigned char)'\r'==bLine->mem[0]
                   && (unsigned char)'\n'==bLine->mem[1])
                  || (1==bLine->used
                      && (unsigned char)'\n'==bLine->mem[0])) );
        if( xf->rc ) break;
        nLine = 0;
        xf->response.httpVersion = -1;
        xf->response.httpCode = 0;
        hc = 0;
        continue;
      }
      if( hc!=200 && hc!=301 && hc!=302 && hc!=307 && hc!=308 ){
        int ii; /* Skip HTTP/1.X prefix */
        for(ii=7; zLine[ii] && zLine[ii]!=' '; ii++){}
        while( zLine[ii]==' ' ) ii++;
        fsl_xfer_errorf(xf, FSL_RC_ERROR,
                        "Error #%d from remote: %s",
                        hc, &zLine[ii]);
        break;
      }
      continue;
    }/*1==nLine*/
    if( hc==301 || hc==302 || hc==307 || hc==308 ){
      if( 0==fsl_strnicmp(zLine, "location:", 9) ){
        int i = 9, n = (int)bLine->used;
        while( zLine[i]==' ' || zLine[i]=='\t' ) ++i;
        while( n>i && (zLine[n-1]=='\r' || zLine[n-1]=='\n') ) --n;
        fsl_xfer_errorf(xf, FSL_RC_NYI,
                        "redirect with status %d to %.*s is not "
                        "supported: use that URL instead",
                        hc, n-i, zLine+i);
        break;
      }
      continue;
    }
    if( bLine->used>15
        && 0==fsl_strnicmp("content-length:", zLine, 15) ){
      /* The value is one or more digits (RFC 9110 section 8.6), with
         optional spaces or tabs around it, and must fit in a
         fsl_size_t. A second Content-Length with another value makes
         the length of the reply ambiguous, which RFC 9112 section 6.3
         treats as an error. */
      char const * zVal = zLine + 15;
      fsl_size_t n = 0;
      bool ok;
      while( ' '==*zVal || '\t'==*zVal ) ++zVal;
      ok = fsl_isdigit(*zVal);
      for( ; ok && fsl_isdigit(*zVal); ++zVal ){
        unsigned const d = (unsigned)(*zVal - '0');
        if( n > (((fsl_size_t)-1) - d) / 10u ) ok = false;
        else n = n*10u + d;
      }
      while( ' '==*zVal || '\t'==*zVal || '\r'==*zVal || '\n'==*zVal ){
        ++zVal;
      }
      if( !ok || *zVal ){
        fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                        "Malformed content-length header: %s",
                        zLine);
        break;
      }
      if( haveLength && n!=*contentLength ){
        fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                        "Reply has two different Content-Length "
                        "values: %" FSL_SIZE_T_PFMT " and %s",
                        *contentLength, zLine);
        break;
      }
      *contentLength = n;
      haveLength = true;
    }
    if( bLine->used>13
        && 0==fsl_strnicmp("content-type:", zLine, 13) ){
      /* HTTP allows spaces and tabs after the colon. */
      char const * zVal = zLine + 13;
      while( ' '==*zVal || '\t'==*zVal ) ++zVal;
      if( 0==fsl_strnicmp("application/x-fossil", zVal, 20) ){
        /* x-fossil-uncompressed or x-fossil-debug */
        *expectCompressedResponse = !(strstr( zVal+20, "uncompressed" )
                                      || strstr( zVal+20, "debug" ));
      }
    }
  }/* while line */
  if( 0==xf->rc ){
    if( hc==301 || hc==302 || hc==307 || hc==308 ){
      fsl_xfer_errorf(xf, FSL_RC_ERROR,
                      "\"location:\" missing from %d redirect reply", hc);
    }else if( 200!=hc ){
      fsl_xfer_errorf(xf, FSL_RC_ERROR,
                      "HTTP error response #%d", hc);
    }else if( !*contentLength ){
      fsl_xfer_errorf(xf, FSL_RC_RANGE, haveLength
                      ? "Empty HTTP reply (Content-Length: 0)"
                      : "No Content-Length found in response headers");
    }
  }
  return xf->rc;
}

/**
   Reports a response body of nGot bytes whose Content-Length header
   gave nWant, as fossil(1) does for a truncated reply.
*/
static int fsl__xfer_body_length_error(fsl_xfer * const xf,
                                       fsl_size_t nGot,
                                       fsl_size_t nWant){
  return fsl_xfer_errorf(xf, FSL_RC_IO,
                         "Response %s: got %" FSL_SIZE_T_PFMT
                         " bytes of %" FSL_SIZE_T_PFMT,
                         nGot<nWant ? "truncated" : "longer than "
                         "its Content-Length", nGot, nWant);
}

fsl_size_t fsl_xfer_max_response(fsl_xfer const * const xf){
  int32_t const n = (xf && xf->config) ? xf->config->maxResponseBytes : 0;
  return n>0 ? (fsl_size_t)n : (fsl_size_t)256 * 1024 * 1024;
}

int fsl_xfer_socket_timeout(fsl_xfer const * const xf){
  int32_t const n = (xf && xf->config) ? xf->config->socketTimeoutSeconds : 0;
  return n>0 ? (int)n : 120;
}

/**
   fsl_b_uncompress(b) in place.
*/
static int fsl__xfer_unz(fsl_xfer * const xf, fsl_b * const b){
  if( 0==xf->rc ){
    int rc;
    fsl_int_t const nUncompressed = fsl_b_uncompressed_size(b);
    fsl_size_t const maxBytes = fsl_xfer_max_response(xf);
    if( nUncompressed>(fsl_int_t)maxBytes ){
      return fsl_xfer_errorf(
        xf, FSL_RC_RANGE,
        "Uncompressed response exceeds limit of %" FSL_SIZE_T_PFMT
        " bytes", maxBytes);
    }
    fsl_timer_scope(&xf->n.timer.uncompress, {
        rc = fsl_b_uncompress(b, b);
      });
    if( rc ){
      fsl_xfer_errorf(xf, rc, "Error decompressing %" FSL_SIZE_T_PFMT
                      " bytes of %s", b->used,
                      &xf->buf.uresp==b ? "response" : "card payload");
    }
  }
  return xf->rc;
}
/**
   Expects xf->ch to have responded with a compressed response.  We
   read the whole thing, decompress it, and install a small proxy
   fsl_sc to handle the reading from that point on so that concrete
   fsl_sc impls don't need to know how to deal with
   that. contentLength must be the response body length.
*/
static int fsl__xfer_response_unz(fsl_xfer * const xf,
                                  fsl_size_t contentLength){
  fsl_b * const b = fsl_b_reuse(&xf->buf.uresp);
  assert( 0==xf->rc );
  if( !contentLength ) return 0;
  /**
     Set up xf->chz with a partial fsl_sc impl which uses
     xf->buf.uresp as state and supports (only) the fsl_sc::read()
     API. Populate xf->buf.uresp with the uncompressed response
     body. fsl__xfer_read() and fsl__xfer_readln() will use
     xf->chz in place of xf->ch.
  */
  fsl_timer_scope(&xf->n.timer.read,{
      xf->rc = fsl__xfer_ch_read(xf, xf->ch, b, FSL_SC_READ_ALL);
    });
  //MARKER(("xf->rc=%s compressed size=%u\n",fsl_rc_cstr(xf->rc),
  //  (unsigned)b->used));

  if( 0==xf->rc && b->used!=contentLength ){
    fsl__xfer_body_length_error(xf, b->used, contentLength);
  }
  if( 0==xf->rc ){
    fsl__xfer_countRead('c', &xf->n.bytesReadCompressed,
                        b->used);
    if( 0==fsl__xfer_unz(xf, b) ){
      fsl_size_t const maxBytes = fsl_xfer_max_response(xf);
      if( 0==xf->rc && b->used>maxBytes ){
        fsl_xfer_errorf(
          xf, FSL_RC_RANGE,
          "Uncompressed response exceeds limit of %" FSL_SIZE_T_PFMT
          " bytes", maxBytes);
      }
      if( xf->n.largestDecompressedResponse < b->capacity ){
        xf->n.largestDecompressedResponse = b->capacity;
      }
      /* Install a fsl_sc proxy which reads the response content from
         b. */
      xf->chz = fsl_sc__xfer_rbuf;
      xf->chz.xfer = xf;
      xf->chz.impl.p = b;
      xf->chz.impl.type = &fsl_sc__xfer_rbuf;
    }
  }
  return xf->rc;
}

static int fsl__xfer_parse_payload(fsl_xfer * const xf);

int fsl__xfer_submit( fsl_xfer * const xf ){
  fsl__xfer__check_rc;
  fsl_size_t contentLength = 0 /* Content-Length HTTP header value */;
  bool expectCompressedResponse = (3==xf->config->op.clone)
    ? false
    : 0!=(FSL_SC_F_COMPRESSED & xf->ch->flags);

  /* If this sync owns the outermost transaction, commit it before the
     exchange and take the write lock again once the reply is here, so
     that no lock is held while the request goes out and the reply
     comes back. A clone keeps one transaction: it skips
     verify-at-commit and checks hashes in its rebuild instead. Inside
     a caller's transaction there is no lock to give back. */
  bool const splitTxn = !xf->config->op.clone && xf->flag.ownsTxn;
  bool unz = false;
  fsl__xfer_prepare_req_headers(xf);
  fsl__xfer_start(xf, FSL__XFER_START_RESPONSE);
  if( 0==xf->rc && splitTxn ){
    int rc2 = fsl__crosslink_end(xf->f, 0);
    if( 0==rc2 ) rc2 = fsl_cx_txn_end_v2(xf->f, true, false);
    assert( rc2 || 0==fsl_cx_txn_level(xf->f) );
    if( rc2 ) xf->rc = rc2;
  }
  if( 0==xf->rc ){
    fsl_timer_scope(&xf->n.timer.submit,{
        xf->rc = fsl__xfer_ch_call(
          xf, "submit", xf->ch->submit(xf->ch, xf->request.loginCard.used
                                       ? &xf->request.loginCard : NULL));
      });
    fsl_sc const * const chSelf = xf->ch->self(xf->ch);
    if( 0==(FSL_SC_F_NO_HTTP & chSelf->flags) ){
      fsl__xfer_parse_http_headers( xf, &contentLength,
                                    &expectCompressedResponse );
    }else if( 0==xf->rc ){
      contentLength = chSelf->reply.length;
      expectCompressedResponse = chSelf->reply.compressed;
      if( !contentLength ){
        fsl_xfer_error(xf, FSL_RC_RANGE, "Channel reported an empty reply");
      }
    }
    if( 0==xf->rc ) xf->n.bytesReadWire += contentLength;
    if( 0==xf->rc && contentLength>fsl_xfer_max_response(xf) ){
      fsl_xfer_errorf(
        xf, FSL_RC_RANGE,
        "Response exceeds limit of %" FSL_SIZE_T_PFMT " bytes",
        fsl_xfer_max_response(xf));
    }
    unz = 0==xf->rc && contentLength && expectCompressedResponse;
    if( unz ){
      fsl__xfer_response_unz(xf, contentLength);
    }
  }
  if( splitTxn && 0==fsl_cx_txn_level(xf->f) ){
    /* Reopen even after a failed exchange: the caller ends the
       transaction. */
    int rc2 = fsl_cx_txn_begin_write(xf->f, FSL_DBROLE_REPO);
    if( 0==rc2 ) rc2 = fsl__crosslink_begin(xf->f);
    if( rc2 && 0==xf->rc ) xf->rc = rc2;
  }
  if( 0==fsl__xfer_start(xf, FSL__XFER_START_REQUEST) ){
    fsl_size_t const nRead0 = xf->n.bytesReadUncompressed;
    fsl_timer_scope(&xf->n.timer.process,{
        fsl__xfer_parse_payload(xf);
      });
    /* The payload parser reads an uncompressed body to its end. */
    if( 0==xf->rc && !unz
        && xf->n.bytesReadUncompressed - nRead0 != contentLength ){
      fsl__xfer_body_length_error(
        xf, xf->n.bytesReadUncompressed - nRead0, contentLength);
    }
    if( xf->rc && FSL_RC_OOM!=xf->rc && FSL_RC_DB!=xf->rc
        && !xf->flag.fatalError ){
      xf->flag.peerError = true;
    }
  }
  /* Only a reply which parsed without error, e.g. no "error login
     failed", means that the peer took the pushed artifacts. With a
     split transaction an earlier forget would already be committed. */
  if( 0==xf->rc ) xf->rc = fsl__xfer_unsent_forget(xf);
  else fsl_id_bag_reuse(&xf->unsentPending);
  return xf->rc;
}

/**
   Write n bytes of p to xf->ch and update xf's related state.
   Is a no-op if called when xf->rc is non-0.
*/
static void fsl__xfer_append_direct(fsl_xfer * const xf, void const * const p,
                                    fsl_size_t n){
  if( 0==xf->rc ){
    /* A compressed body is collected and sent whole: see
       fsl__xfer_prepare_req_headers(). */
    xf->rc = (FSL_SC_F_COMPRESSED & xf->ch->flags)
      ? fsl_b_append(&xf->request.body, p, n)
      : fsl__xfer_ch_call(xf, "append", xf->ch->append(xf->ch, p, n));
    if( 0==xf->rc ){
      xf->n.bytesWritten += n;
      xf->request.nBytes += n;
      fsl_sha1_update(&xf->request.sha1, p, n);
    }
  }
}

/**
   Appends a prologue series of common cards to the request if the
   request is empty, else this is a no-op.  Is a no-op if called when
   xf->rc is non-0.

   This must only be called from fsl__xfer_append() and only when no
   content has been submitted to the request body. An assert() to that
   effect is in place.
*/
static void fsl__xfer_append_prologue(fsl_xfer * const xf){
  assert( !xf->request.nBytes );
  if( 0==xf->rc ){
    fsl_b * const b = fsl_b_reuse(
      &xf->ch->requestHeaders
      /* using requestHeaders here is a bit of a hack. We can't use
         xf->buf.scratch because this call is made in a context where
         that buffer is already in use. requestHeaders may be
         re-used via fsl__xfer_submit(). */
    );
    /*
      Reminder: we cannot call back into the other
      fsl__xfer_append...() from here or we'll get in a loop until one
      of the buffers gets too big to grow further or we stack
      overflow. The one exception is fsl__xfer_append_direct(), which
      will not loop.
    */
    char const * zPC = fsl__xfer_projcode(xf);
    /* A modern clone sends no pull or push card in any round (sync
       draft sections 8.2 and 8.5), as fossil(1) does. */
    bool const modernClone = xf->config->op.clone>=2;
    if( xf->config->op.privateContent
        && (!xf->config->op.clone
            || xf->clientVersion.projCodeMatch>0) ){
      fsl_b_append(b, "pragma send-private\n", 20);
      ++xf->n.cardsTx[fsl_xfcard_e_pragma];
      xf->flag.syncPrivate = true;
    }
    if( xf->config->op.verily ){
      fsl_b_append(b, "pragma send-catalog\n", 20);
      ++xf->n.cardsTx[fsl_xfcard_e_pragma];
    }
    fsl_b_appendf(b, "pragma client-version %d %d %d\n",
                       xf->clientVersion.number,
                       xf->clientVersion.date,
                       xf->clientVersion.time);
    ++xf->n.cardsTx[fsl_xfcard_e_pragma];
    if( zPC && !modernClone ){
      if( xf->config->op.pull || xf->config->op.clone ){
        fsl_b_appendf(b, "pull ignored-servercode %s\n", zPC)
          /* fossil(1) ignores gimme cards if no pull card was sent, so
             pull must precede any gimme cards. */;
        ++xf->n.cardsTx[fsl_xfcard_e_pull];
      }
      if( xf->config->op.push
          || (xf->config->op.clone
              && fsl__xfer_may_attempt_login(xf)) ){
        fsl_b_appendf(b, "push ignored-servercode %s\n", zPC);
        ++xf->n.cardsTx[fsl_xfcard_e_push];
      }
    }
    xf->rc = b->errCode;
    fsl__xfer_append_direct(xf, b->mem, b->used);
    fsl_b_reuse(b);
  }
}

/**
   Write n bytes of p to xf->ch and update xf's related state.
   Returns xf->rc. Is a no-op if called when xf->rc is
   non-0. Initializes xf->ch if we've not yet sent any output.
*/
int fsl__xfer_append(fsl_xfer * const xf, void const * const p,
                     fsl_size_t n){
  if( 0==xf->rc ){
    if( !xf->request.nBytes ){
      /* Delay (re-)init of the request state until we know we're
         going to post another request (i.e. when we start writing the
         request). */
      xf->rc = fsl__xfer_ch_call(xf, "init",
                                 xf->ch->init(xf->ch, FSL_SC_INIT_REQUEST));
      fsl__xfer_append_prologue(xf);
    }
    fsl__xfer_append_direct(xf, p, n);
  }
  return xf->rc;
}

#if 0
int fsl__xfer_appendln(fsl_xfer * const xf, char const * zMsg){
  if( 0==xf->rc ){
    fsl_b * const b = fsl_b_reuse(&xf->buf.scratch);
    fsl_b_append(b, zMsg, -1);
    fsl_b_ensure_eol(b);
    if( 0==(xf->rc = b->errCode) ){
      fsl__xfer_append(xf, b->mem, b->used);
    }
  }
  return xf->rc;
}
#endif

int fsl__xfer_appendlnv(fsl_xfer * const xf, char const * zFmt, va_list args){
  fsl__xfer__check_rc;
  fsl_b * const b = fsl_b_reuse(&xf->buf.scratch);
  fsl_b_appendfv(b, zFmt, args);
  fsl_b_ensure_eol(b);
  if( 0==(xf->rc = b->errCode) ){
    fsl__xfer_append(xf, b->mem, b->used);
  }
  return xf->rc;
}

int fsl__xfer_appendlnf(fsl_xfer * const xf, char const * zFmt, ...){
  fsl__xfer__check_rc;
  va_list args;
  va_start(args,zFmt);
  fsl__xfer_appendlnv(xf, zFmt, args);
  va_end(args);
  return xf->rc;
}

int fsl__xfer_appendcard(fsl_xfer * const xf, fsl_xfcard_e card,
                         char const * zFmt, ...){
  fsl__xfer__check_rc;
  fsl_b * const b = fsl_b_reuse(&xf->buf.scratch);
  char const * z = 0;
  fsl_int_t n = 0;
  switch( (int)card ){
#define E(T,LEN) case fsl_xfcard_e_ ## T: z = #T; n = LEN; break;
    fsl_xfcard_map(E)
#undef E
      }
  assert( z );
  assert( n );
  fsl_b_append(b, z, n);
  if( zFmt && *zFmt ){
    va_list args;
    fsl_b_appendch(b, ' ');
    va_start(args,zFmt);
    fsl_b_appendfv(b, zFmt, args);
    va_end(args);
  }
  fsl_b_ensure_eol(b);
  ++xf->n.cardsTx[card];
  if( 0==(xf->rc = b->errCode) ){
    fsl__xfer_append(xf, b->mem, b->used);
  }
  return xf->rc;
}

static void fsl__xfer_phantom_new(fsl_xfer *xf, fsl_uuid_cstr zUuid,
                                 bool isPrivate, fsl_id_t *ridOut){
  if( 0==xf->rc ){
    xf->rc = fsl__phantom_new(xf->f, zUuid, isPrivate, ridOut);
  }
}

/**

   Most of what follows will eventually be moved into the library, and
   is currently in this file to expedite development and testing.
*/

/**
   Returns true if z is parsable as a 32-bit integer, else false.  If
   it returns true, *pVal is set to the parsed value.
*/
static bool fsl__is_int32(char const * z, int *pVal){
  char * zEnd = 0;
  long const l = strtol(z, &zEnd, 10);
  if( zEnd && !*zEnd && l==(long)((int)l)/*else overflow*/ ){
    *pVal = (int)l;
    return true;
  }
  return false;
}

/**
   Confirms whether integer-shaped value z is consistent with
   size-typed card arguments. If so, returns true and sets *pVal to
   the size. On error, returns false.
*/
static bool fsl__is_card_size(unsigned char const * z, bool zeroIsLegal,
                              fsl_size_t *pVal){
  int i = 0;
  bool rv = false;
  if( fsl__is_int32((char const *)z, &i) &&
      (zeroIsLegal ? i>=0 : i>0) ){
    *pVal = (fsl_size_t)i;
    rv = true;
  }
  return rv;
}

/**
   Extract xf->line.aToken[tokNdx] for use with fsl__is_card_size().
   If tokNdx is in range and the token is-a size then returns 0 and
   sets *pOut to the size. On error, updates xf->f's error state
   and returns non-0.
*/
static int fsl__xfer_card_size(fsl_xfer * const xf,
                                unsigned char tokNdx, bool zeroIsLegal,
                                fsl_size_t * pOut){
  fsl__xfer__check_rc;
  if( tokNdx>=xf->line.nToken ){
    fsl_xfer_errorf(xf, FSL_RC_SYNTAX, "Malformed card: %b",
                    &xf->line.bRaw);
  }else if( !fsl__is_card_size(xf->line.aToken[tokNdx],
                               zeroIsLegal, pOut) ){
    fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                    "Not a valid %s card size: %s",
                    xf->line.aToken[0],
                    xf->line.aToken[tokNdx]);
  }
  return xf->rc;
}


static inline unsigned char fsl__xfer_ntok(fsl_xfer const * const xf){
  return xf->line.nToken;
}

/**
   If tokNdx is in bounds for xf->line.nToken, that token's memory is
   returned, else NULL is returned.
*/
static inline unsigned char * fsl__xfer_toku(fsl_xfer const * const xf,
                                             unsigned char tokNdx){
  return (tokNdx<fsl__xfer_ntok(xf))
    ? xf->line.aToken[tokNdx] : NULL;
}

/** Not-unsigned counterpart of fsl__xfer_toku(). */
static inline char * fsl__xfer_tokn(fsl_xfer const * const xf,
                                    unsigned char tokNdx){
  return (char *)fsl__xfer_toku(xf, tokNdx);
}

static char const * fsl__xfer_uchomp(unsigned char *z, fsl_size_t *n){
  while( *n>0 && (z[*n - 1]=='\n') ) z[--*n] = 0;
  z[*n] = 0;
  return (char const *)z;
}

/**
   Uses fsl__xfer_toku() to fetch the token at tokNdx. If it's not
   NULL then it is defossilized in-place and returned, else NULL is
   returned.
*/
static char const * fsl__xfer_tokn_defos(fsl_xfer const * const xf,
                                         unsigned char tokNdx){
  unsigned char * z =  fsl__xfer_toku(xf, tokNdx);
  if( z ){
    fsl_size_t n = 0;
    fsl_bytes_defossilize(z, &n)
      /* Fossil-ized error card messages sometimes have a trailing \n
         encoded in them. */;
    return fsl__xfer_uchomp(z, &n);
  }
  return 0;
}

/**
   Returns true if 0==xf->rc and xf->line.aToken[tokNdx] matches the
   given string.
*/
static inline bool fsl__xfer_tok_match(fsl_xfer const * const xf,
                                       unsigned char tokNdx,
                                       char const * zStr){
  return 0==xf->rc && 0==fsl_strcmp(fsl__xfer_tokn(xf, tokNdx), zStr);
}

/**
   If xf->line.nToken is within the range of minArg..maxArg, return
   true, else set xf's error state and return false.  Returns false,
   and is a no-op, if xf->rc is non-0 when this is called.
*/
static bool fsl__xfer_argc_check(fsl_xfer * const xf,
                                 fsl_xfcard const * const card,
                                 unsigned char minArg,
                                 unsigned char maxArg){
  if( 0==xf->rc
      && (fsl__xfer_ntok(xf)<minArg || fsl__xfer_ntok(xf)>maxArg) ) {
    fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                    "Expecting %d-%d token(s) in %s card, but got %d",
                    (int)minArg, (int)maxArg, card->name,
                    (int)fsl__xfer_ntok(xf));
  }
  return xf->rc==0;
}

/** Returns true if the token at tokNdx is a hash, as per
    fsl_validate_hash(), else false. */
static bool fsl__xfer_is_hash(fsl_xfer * const xf, unsigned char tokNdx){
  char const * const z = fsl__xfer_tokn(xf, tokNdx);
  return z
    && FSL_HTYPE_ERROR!=fsl_validate_hash(z, xf->line.aTokLen[tokNdx]);
}

/**
   If xf's error state is not set and xf token #tokNdx is not a valid
   SHA1 or SHA3 hash, set xf's error state to describe the
   problem. Returns xf->rc.
*/
static int fsl__xfer_check_card_hash(fsl_xfer * const xf,
                                     fsl_xfcard const * const card,
                                     unsigned char tokNdx){
  if( 0==xf->rc && !fsl__xfer_is_hash(xf, tokNdx) ){
    char const * const z = fsl__xfer_tokn(xf, tokNdx);
    fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                    "Invalid hash [%s] in %s card index %d",
                    z ? z : "", card->name, (int)tokNdx);
  }
  return xf->rc;
}

/**
   Uncompresses xf->buf.cardPayload, expecting it to have a size
   equal to that set in xf->line.aToken[uszNdx].
*/
static int fsl__payload_unz(fsl_xfer * const xf, unsigned char uszNdx){
  if( 0==xf->rc ){
    fsl_b * const b = &xf->buf.cardPayload;
    fsl_size_t usz = 0;
    assert( uszNdx );
    if( 0==fsl__xfer_card_size(xf, uszNdx, true, &usz) ){
      if( usz ){
        /* Reminder: fossil(1) artifact da39a3ee5e6b4b0d3255bfef95601890afd80709
           has a usz=0 and sz=12. */
        fsl__xfer_unz(xf, b);
      }else{
        fsl_b_reuse(b);
      }
    }
  }
  return xf->rc;
}

/**
   Reads the payload for xf's current card line. The payload's size
   must be encoded in xf->line.aToken[szNdx]. If uszNdx is not 0 then
   the payload is assumed to be compressed, its uncompressed size is
   assumed to be in xf->line.aToken[uszNdx], and it is uncompressed
   in-place.

   The payload is placed in xf->buf.cardPayload.

   Sidebar: it is legal for the uncompressed version to be smaller
   than the compressed one. This will happen for all cards below a
   certain size.
*/
static int fsl__payload_read(fsl_xfer * const xf, unsigned char szNdx,
                             unsigned char uszNdx){
  fsl__xfer__check_rc;
  fsl_b * const b = fsl_b_reuse(&xf->buf.cardPayload);
  fsl_size_t sz = 0;
  fsl__xfer_card_size(xf, szNdx, true, &sz);
  if( sz ){
    fsl__xfer_read(xf, b, sz);
    if( xf->n.largestCardPayload < sz ){
      xf->n.largestCardPayload = sz;
    }
    if( uszNdx ){
      fsl__payload_unz(xf, uszNdx);
    }
  }
  return xf->rc;
}

static int fsl__rcv_config(fsl_xfer * const xf,
                           fsl_xfcard const * const card){
  /* From fossil:
  **
  ** Config card:
  **
  **   config NAME SIZE \n CONTENT
  **
  ** NAME is one of:
  **
  **     "/config", "/user",  "/shun", "/reportfmt", "/concealed",
  **     "/subscriber"
  **
  ** NAME indicates the table that holds the configuration information being
  ** transferred.  pContent is a string that consist of alternating Fossil
  ** and SQL tokens.  The First token is a timestamp in seconds since 1970.
  ** The second token is a primary key for the table identified by NAME.  If
  ** The entry with the corresponding primary key exists and has a more recent
  ** mtime, then nothing happens.  If the entry does not exist or if it has
  ** an older mtime, then the content described by subsequent token pairs is
  ** inserted.  The first element of each token pair is a column name and
  ** the second is its value.
  **
  ** In overview, we have:
  **
  **    NAME        CONTENT
  **    -------     -----------------------------------------------------------
  **    /config     $MTIME $NAME value $VALUE
  **    /user       $MTIME $LOGIN pw $VALUE cap $VALUE info $VALUE photo $VALUE
  **    /shun       $MTIME $UUID scom $VALUE
  **    /reportfmt  $MTIME $TITLE owner $VALUE cols $VALUE sqlcode $VALUE jx $JSON
  **    /concealed  $MTIME $HASH content $VALUE
  **    /subscriber $SMTIME $SEMAIL suname $V ...
  **
  ** NAME-specific notes:
  **
  **  - /reportftm's $MTIME is in Julian, not the Unix epoch.
  */
  fsl__xfer__check_rc;
  if( !fsl__xfer_argc_check(xf, card, 3, 3) ) return xf->rc;
  char const *zName = fsl__xfer_tokn(xf,1);
  if( fsl__payload_read(xf, 2, 0) ) return xf->rc;

  assert( 3==fsl__xfer_ntok(xf) );
  /* The parse/apply engine lives in config.c so that it is testable
     without a network. It skips (rather than errors on) card names and
     columns it does not support, so a newer server cannot break us. */
  xf->rc = fsl__config_receive(xf->f, zName, &xf->buf.cardPayload,
                               (int)xf->flag.configRcvMask);
  fsl__xfer_emit( xf, FSL_MSG_RCV_CONFIG, zName );
  return xf->rc;
}

static int fsl__rcv_pragma(fsl_xfer * const xf){
  fsl__xfer__check_rc;
  if( fsl__xfer_ntok(xf)>2 ){
    if( fsl__xfer_tok_match(xf, 1, "server-version")
        || fsl__xfer_tok_match(xf, 1, "client-version") ){
      /* pragma server-version VERSION ?DATE? ?TIME? */
      /* pragma client-version VERSION ?DATE? ?TIME? */
      /* DATE and TIME are only missing from very old clients */
      /* DATE and TIME may be absent (old peers). Read each token
      ** only when present: atoi(NULL) is a null deref, and the
      ** protocol says a short pragma updates VERSION alone and
      ** keeps the prior DATE/TIME. */
      char const * const zVers = fsl__xfer_tokn(xf, 2);
      char const * const zDate = fsl__xfer_tokn(xf, 3);
      char const * const zTime = fsl__xfer_tokn(xf, 4);
      if( zVers ) xf->remote.releaseVersion = atoi(zVers);
      if( zDate ) xf->remote.manifestDate = atoi(zDate);
      if( zTime ) xf->remote.manifestTime = atoi(zTime);
      if( xf->request.loginCard.used
          && fsl__xfer_login_version_check(xf) ){
        /* We have a login cookie but the remote does not support
           logging in this way. This error is now propagating via
           xf->rc. */
      }else if( 2==xf->n.trips  /* 2 == we've initialized the 2nd
                   request while reading the first response */ ){
        fsl__xfer_emitf(xf, FSL_MSG_VERBOSE,
                       "Remote fossil version is %d %d %06d",
                       xf->remote.releaseVersion,
                       xf->remote.manifestDate,
                       xf->remote.manifestTime);
      }
    }
  }else{
    /* draft-fossil-sync-protocol-00 section 9: unknown pragmas, and known
       ones this client does not act on, are silently ignored. */
    fsl_xfer_debugf(xf, "Ignoring pragma: %b", &xf->line.bRaw);
  }
  return xf->rc;
}


/** Emits a FSL_MSG_RCV_BLOB message with the given hash as its
    payload. */
static int fsl__xfer_emit_blob(fsl_xfer * xf, char const * zHash,
                               fsl_size_t size){
  if( 0==xf->rc && xf->f->cxConfig.listener.callback ){
    fsl_msg_blob const blob = { .hash = zHash, .size = size };
    xf->rc = fsl_cx_emit( xf->f, FSL_MSG_RCV_BLOB, &blob );
  }
  return xf->rc;
}

/**
   Populates xf->buf.cardPayload from xf->line, which is known to be a
   cfile- or file-card, then processes that card.
*/
static void fsl__rcv_file(fsl_xfer * const xf,
                          fsl_xfcard const * const card){
  if( xf->rc ) return;
  char const * zUuid = fsl__xfer_tokn(xf,1);
  char const * zDeltaSrcUuid = 0;
  fsl_id_t deltaSrcRid = 0;
  fsl_id_t newRid = 0;
  fsl_size_t usz = 0 /* decompressed size */;
  unsigned char uszNdx = 0 /* arg index of usz */;
  unsigned char const nTok = fsl__xfer_ntok(xf);
  unsigned char const szNdx = nTok - 1 /* arg index of payload size */;
  bool const isPrivate = xf->flag.nextIsPrivate;

  assert( fsl_xfcard_e_cfile==card->type
          || fsl_xfcard_e_file==card->type );
  xf->flag.nextIsPrivate = false;
  /* draft-fossil-sync-protocol-00 sections 7.1 and 7.2: file takes
     2 or 3 arguments, cfile 3 or 4. */
  if( fsl_xfcard_e_file==card->type
      ? !fsl__xfer_argc_check(xf, card, 3, 4)
      : !fsl__xfer_argc_check(xf, card, 4, 5) ) return;
  assert( zUuid );
  if( !fsl_is_uuid(zUuid) ){
    /* The card target hash comes from the remote. Validate it, as
    ** the delta-source hash below already is, so a malformed hash is
    ** rejected here instead of reaching fsl__content_put_ex(), whose
    ** assert(!zUuid || zUuidLen) would otherwise abort the client. */
    fsl_xfer_errorf(xf, FSL_RC_SYNTAX, "Malformed UUID [%s] in %s card",
                    zUuid, card->name);
    return;
  }

  //fsl_xfer_debugf(ch, "Got %s: %b", card->name, &xf->line.bRaw);
  switch( nTok ) {
    case 3:
      /* file uuid size */
        break;
    case 4:
      /* file uuid delta-uuid size */
      /* cfile uuid usize size */
      if( fsl_xfcard_e_file==card->type ){
        zDeltaSrcUuid = fsl__xfer_tokn(xf,2);
      }else{
        uszNdx = nTok - 2;
      }
      break;
    case 5:
      /* cfile uuid delta-uuid usize size */
      assert( fsl_xfcard_e_cfile==card->type );
      uszNdx = nTok - 2;
      zDeltaSrcUuid = fsl__xfer_tokn(xf,2);
      break;
    default:
      fsl__fatal(FSL_RC_CANNOT_HAPPEN, "Malformed %s card", card->name);
  }
  fsl__payload_read(xf, szNdx, 0/*uszNdx*/);
  if( 0==xf->rc && uszNdx
      && !fsl_b_is_compressed(&xf->buf.cardPayload) ){
    fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                    "Malformed compressed %s payload", card->name);
    return;
  }
  if( 0==xf->rc && fsl_is_shunned_uuid(xf->f, zUuid) ){
    /* The payload has been read, so the next card starts on the next
       line. */
    return;
  }
  if( isPrivate && !xf->config->op.privateContent ){
    /* Private content the client did not ask for is discarded, as in
       fossil(1)'s xfer_accept_file(). */
    return;
  }

  if( zDeltaSrcUuid && 0==xf->rc ){
    /* Ensure that we have a blob for zDeltaSrcUuid, even if it's
       just a phantom. zDeltaSrcUuid comes from the remote, so this
       validates it. */
    if( fsl_is_uuid(zDeltaSrcUuid)
        && 0==fsl_strcmp(zUuid, zDeltaSrcUuid) ){
      /* A delta against itself can never be expanded. */
      fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                      "Artifact [%s] is its own delta source in %s card",
                      zUuid, card->name);
    }else if( fsl_is_uuid(zDeltaSrcUuid) ){
      deltaSrcRid = fsl__uuid_to_rid2(xf->f, zDeltaSrcUuid, isPrivate
                                      ? FSL_PHANTOM_PRIVATE
                                      : FSL_PHANTOM_PUBLIC);
      assert( 0!=deltaSrcRid );
      if( deltaSrcRid<0 ){
        if( FSL_RC_SHUNNED==xf->f->error.code ){
          /* The delta source is shunned: unavailable, not an error.
          ** A well-behaved fossil(1) server never sends a delta against
          ** a shunned source (it falls back to full content instead),
          ** but tolerate it here rather than aborting the transfer if
          ** one ever does. */
          fsl_cx_err_reset(xf->f);
          deltaSrcRid = 0;
        }else{
          xf->rc = xf->f->error.code;
          assert( xf->rc );
        }
      }
    }else{
      fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                      "Malformed UUID [%s] in %s card",
                      zDeltaSrcUuid, card->name);
    }
  }
  if( uszNdx ){
    fsl__xfer_card_size(xf, uszNdx, true, &usz);
    if( 0==xf->rc && 0==usz ){
      /* A cfile with usize 0 is the empty artifact. Store it as the
         empty raw content it decompresses to, because
         fsl__content_put_ex() treats a 0 uncompSize as "not
         compressed". The hash check below catches a payload that
         claims usize 0 for anything else. */
      fsl_b_reuse(&xf->buf.cardPayload);
    }
  }
  if( 0==xf->rc ){
    xf->rc = fsl__content_put_ex(xf->f, &xf->buf.cardPayload,
                                 zUuid, deltaSrcRid, usz, isPrivate,
                                 &newRid);
    if( 0==xf->rc && !isPrivate ){
      /* The sender holds the artifact as public, so it is public
         here too, as in fossil(1)'s xfer_accept_file(). */
      xf->rc = fsl_content_make_public(xf->f, newRid);
    }
    if( 0==xf->rc ){
      xf->rc = fsl_cx_exec(
        xf->f, "DELETE FROM {{dbname.repo}}.unsent WHERE rid=%" FSL_ID_T_PFMT,
        newRid);
    }
    if( 0==xf->rc ){
      /* Sync draft section 10.1: content which does not match its
         hash, or cannot be reconstructed at all, is an integrity
         error which must fail the session now, before another round
         starts, rather than at commit time.  A delta whose source has
         not arrived cannot be checked yet and is left to
         verify-at-commit. */
      xf->rc = fsl__repo_verify_rid(xf->f, newRid);
      if( xf->rc ){
        xf->flag.fatalError = true;
      }
    }
    if( xf->rc ){
      MARKER(("cx rc=%s\n",
              fsl_rc_cstr(fsl_cx_err_get(xf->f,NULL,NULL))));
      MARKER(("xf.rc=%s\n", fsl_rc_cstr(xf->rc)));
    }
  }
  fsl__xfer_emit_blob(xf, zUuid, usz ? usz : xf->buf.cardPayload.used);
}

#if 0
static void fsl__rcv_igot_add(fsl_xfer *xf, fsl_id_t rid){
  assert( rid > 0 );
  if( 0==xf->rc ){
    xf->rc = fsl__rid_insert(xf->f, &xf->q.igotInsert,
                             FSL_DBROLE_TEMP, "xfigot", rid);
  }
}
#endif

#if 0
static bool fsl__xfer_have_igot( fsl_xfer *xf, fsl_id_t rid ){
  assert( rid > 0 );
  fsl_stmt * const q = &xf->q.igotHasRid;
  bool rv = false;
  if( 0==xf->rc ){
    if( !q->stmt ){
      xf->rc = fsl_cx_prepare(xf->f, q,
                              "SELECT 1 FROM {{dbname.repo}}.blob "
                              "WHERE rid=?1 /*%s()*/",
                              __func__);
    }
    if( 0==xf->rc ){
      int const rc = fsl_stmt_bind_step_v2(q, "R", rid);
      switch( rc ){
        case FSL_RC_STEP_ROW: rv = true; break;
        case FSL_RC_STEP_DONE: break;
        default:
          xf->rc = fsl_cx_uplift_db_error2(xf->f, NULL, rc);
          break;
      }
      fsl_stmt_reset(q);
    }
  }
  return rv;
}
#endif

static bool fsl__xfer_have_igot( fsl_xfer *xf, fsl_uuid_cstr zUuid ){
  assert( zUuid );
  bool rv = false;
  if( 0==xf->rc ){
    /* "Have it" means we hold the content, i.e. a non-phantom blob row
    ** (size>=0). A phantom (size<0) is a placeholder for content we do
    ** NOT have and must still request, so it must not suppress the gimme.
    ** fossil's request_phantoms() sends a gimme for every phantom; the
    ** uuid-exists test alone would wrongly treat a phantom as held. Use
    ** the rid+size lookup and require size>=0. */
    fsl_stmt * const q = fsl__cx_stmt(xf->f, fsl__cx_stmt_e_blobRidSize);
    if( q ){
      int const rc = fsl_stmt_bind_step_v2(q, "s", zUuid);
      switch( rc ){
        case FSL_RC_STEP_ROW:
          rv = (fsl_stmt_g_int64(q, 1) >= 0);
          fsl_stmt_reset(q);
          break;
        case FSL_RC_STEP_DONE: break;
        default:
          xf->rc = fsl_cx_uplift_db_error2(xf->f, q->db, rc);
          break;
      }
      fsl__cx_stmt_yield(xf->f, q);
    }else{
      xf->rc = xf->f->error.code;
    }
  }
  return rv;
}

static void fsl__gimme_queue(fsl_xfer *xf, fsl_uuid_cstr zUuid){
  assert(zUuid);
  if( !fsl__xfer_have_igot(xf, zUuid)
      && 0==xf->rc /* have_igot() can change it */){
    fsl__xfer_appendcard(xf, fsl_xfcard_e_gimme, zUuid);
  }
}

#if 0
/* Not useful unless we're going queue up gimmes in a table
   rather than emit gimme cards at the earliest opportunity. */
static void fsl__gimme_delete(fsl_xfer *xf, fsl__uuid_cstr zUuid){
  assert( rid > 0 );
  if( 0==xf->rc ){
    xf->rc = fsl_cx_exec(xf->f,
                         "DELETE FROM %!Q.xfgimme WHERE uuid=%Q",
                         fsl_db_role_name(FSL_DBROLE_TEMP),
                         zUuid);
  }
}
#endif

static void fsl__rcv_igot(fsl_xfer * const xf,
                         fsl_xfcard const * const card){
  assert( fsl_xfcard_e_igot==card->type );
  if( xf->rc || fsl__xfer_check_card_hash(xf, card, 1) ){
    return;
  }
  /* igot artifact-id ?flags? ...ignored... */
  assert( fsl__xfer_ntok(xf)>1 );
  char const *zUuid = fsl__xfer_tokn(xf, 1);
  if( fsl_is_shunned_uuid(xf->f, zUuid) ){
    /* The server's igot blast is not filtered by its own shun list, so
    ** once our shun table is populated mid-clone (see /shun reqconfig)
    ** we can be told about an artifact we must not create even a
    ** phantom placeholder for. fsl__phantom_new() correctly refuses
    ** shunned uuids, but that refusal is fatal to the whole transfer
    ** if it escapes this handler -- so skip it here, the same way an
    ** actual file/cfile card for a shunned uuid is skipped above. */
    return;
  }
  bool const isPrivate = fsl__xfer_ntok(xf)>2
    ? fsl__xfer_tok_match(xf, 2, "1")
    : false;
  fsl_id_t rid = fsl_uuid_to_rid(xf->f, zUuid);
  xf->flag.nextIsPrivate = isPrivate;
  if( rid<0 ){
    /* fsl_uuid_to_rid() has set f's error state. */
    xf->rc = xf->f->error.code ? xf->f->error.code : FSL_RC_ERROR;
  }else if( rid>0 ){ /* We already have this */
    xf->rc = isPrivate
      ? fsl__private_rid_add(xf->f, rid)
      : fsl__private_rid_delete(xf->f, rid);
    if( -1==fsl_content_size(xf->f, rid) ){
      /* fossil(1) version 1 clone response #2 and later send
         file-cards for what it can, up to its limit, then sends igots
         to indicate that there's still more to fetch. */
      //fsl__xfer_appendcard(xf, fsl_xfcard_e_gimme, zUuid);
      /* However, we can get into a loop of receiving/sending
         the same igot/gimme cards, so we need to keep more
         precise track of them. */
    }
    //fsl__gimme_delete(xf, zUuid);
  }else if( isPrivate && !xf->config->op.privateContent ){
    /* Ignore private files */
    //fsl__gimme_delete(xf, zUuid);
  }else if( xf->config->op.clone>=2 ){
    /* Clone protocol 2/3: the server's initial igot blast (fossil
    ** send_all()) exists only to populate our phantom set; content
    ** arrives via the clone_seqno cfile stream, in monotonic rid order.
    ** Create the phantom but do NOT gimme. Gimme-ing makes the server
    ** delta-encode the artifact against an arbitrary peer in the gimme
    ** batch, which can yield two contradictory delta edges and a
    ** delta-table cycle that wedges reconstruction ("Infinite loop in
    ** delta table"). fossil's protocol-3 clone client sends no gimme. */
    fsl__xfer_phantom_new(xf, zUuid, isPrivate, &rid);
  }else if( xf->config->op.clone>0 || xf->config->op.pull ){
    /* Clone protocol 1 delivers some file-cards then announces the
    ** remainder via igot, expecting a gimme for each; pull works the same
    ** way. Create the phantom and request it. */
    fsl__xfer_phantom_new(xf, zUuid, isPrivate, &rid);
    fsl__gimme_queue(xf, zUuid);
    if( 0==xf->rc && rid>0 ){
      xf->rc = fsl_id_bag_insert(&xf->gimmePending, rid);
    }
  }
}

/**
   To be called immediately after xf->ch->submit() has been called, to
   parse its response.

   Reminder to self: we eventually need to distinguish between
   received-from-client and received-from-server payloads, as card
   handling can differ between the two (e.g. "igot" cards). We
   currently only handle the latter case.
*/
static int fsl__xfer_parse_payload(fsl_xfer * const xf){
  fsl__xfer__check_rc;
  unsigned nLine = 0;
  unsigned char * const * aTok = xf->line.aToken;
  //fsl_b * const bLn = &xf->line.b;
  fsl_b * const bLnRaw = &xf->line.bRaw;
  fsl_b * const bPay = &xf->buf.cardPayload;

  xf->flag.nextIsPrivate = false;
  xf->clone.pushSeen = false;
  for( ; 0==xf->rc; ++nLine ){
    fsl_b_reuse(bPay);
    fsl__xfer_readln(xf);
    if( xf->rc ){
      //MARKER(("xfer_readln() xf->rc=%s\n", fsl_rc_cstr(xf->rc)));
      if( FSL_RC_BREAK==xf->rc ) xf->rc = 0 /* EOF */;
      break;
    }
    if( !fsl__xfer_ntok(xf) ){
      if( 0==nLine ){
        fsl_xfer_error(xf, FSL_RC_ERROR, "Got an empty response");
      }else{
        assert(!"should not be possible");
        fsl_xfer_error(xf, FSL_RC_ERROR,
                       "FIXME: empty lines should be "
                       "skipped (elsewhere)");
      }
      break;
    }
    unsigned char const nTok = fsl__xfer_ntok(xf);

    /* Bails if nTok is not have between MIN and MAX
       arguments. If MAX<0 then any number, up to
       fsl__xfer_max_tokens, is fine. */
#define argcCheck2(MIN,MAX)                                     \
    if( !fsl__xfer_argc_check(xf, card, (MIN), (MAX)) ) break

#define argcCheck(N) argcCheck2(N,N)

    if( xf->config->verbosity>1 && xf->config->debug.callback ){
      MARKER(("line = %s", fsl_b_cstr(bLnRaw)));
      fsl_xfer_debugf( xf, "line #%u: %b", nLine, bLnRaw );
    }
    fsl_xfcard const * const card =
      fsl__xfcard_search(aTok[0]);
    if( 0 ){
      MARKER(("ntoken=%d search(%s) => %p\n", (int)nTok,
              (char const *)aTok[0], (void*)card));
    }

#define readPayload(N)                          \
    if( N ){                                    \
      fsl__xfer_read(xf, fsl_b_reuse(bPay), N); \
      if( xf->rc ) break;                       \
      else if( xf->n.largestCardPayload < N ){  \
        xf->n.largestCardPayload = N;           \
      }                                         \
    }

#define readPayloadTok(TOKNDX,SZVAR)                           \
    if( fsl__xfer_card_size(xf, TOKNDX, true, &SZVAR) ) break; \
    readPayload(SZVAR)

    if( card ){
      ++xf->n.cardsRx[card->type];
    }
    if( 0 ){
      MARKER(("line=%s", fsl_b_cstr(bLnRaw)));
    }

    switch( card ? card->type : fsl_xfcard_e_unknown ){
#define CASE(X) case fsl_xfcard_e_ ## X

      CASE(cfile): /* cfile uuid ?delta-uuid? usize size\n<PAYLOAD> */
      CASE(file):{ /* file uuid ?delta-uuid? size\n<PAYLOAD> */
        fsl__rcv_file(xf, card);
        xf->flag.nextIsPrivate = false;
        break;
      }

      CASE(clone):{
        /* clone
           clone protocol-version sequence-number */
        if( 3==nTok ){
          fsl_size_t n = 0;
          fsl__xfer_card_size(xf, 1, false, &n);
          if( 0==xf->rc ){
            xf->clone.protocolVersion = (int)n;
            fsl__xfer_card_size(xf, 2, true, &xf->clone.seqNo);
          }
        }else if( 1==nTok ){
          xf->clone.protocolVersion = 1;
        }else{
          fsl_xfer_errorf(xf, FSL_RC_SYNTAX,
                          "clone card expects 1 or 3 arguments "
                          "but got %d", (int)nTok);
        }
        break;
      }

      CASE(clone_seqno):{ /* clone_seqno number */
        if( fsl__xfer_card_size(xf, 1, true, &xf->clone.seqNo) ){
          /* Without a valid cursor the clone cannot go on, so this is
             fatal even in the first clone reply. */
          xf->flag.fatalError = true;
        }
        /* a seqno of 0 is sent at the end of the cloning
           round-trips. */
        break;
      }

      CASE(config):{ /* config name size \n content */
        fsl__rcv_config(xf, card);
        break;
      }

      CASE(error):    /* error fossilized-msg */
      CASE(message):{ /* message fossilized-msg */
        argcCheck(2);
        if( fsl_xfcard_e_error==card->type ){
          char const * z = fsl__xfer_tokn_defos(xf, 1);
          if( xf->config->op.clone>0 && 2==xf->n.trips ){
            /* Mirrors fossil(1)'s client_sync(): a login-required
            ** server rejects the unauthenticated first clone request,
            ** but the project code (needed to build a login card at
            ** all) typically arrives in a "push" card in this same
            ** response. Treat this one error, on this one round, as
            ** informational rather than fatal, so parsing continues
            ** and the project code (if present) still gets cached.
            ** fsl__xfer_should_continue() already forces a second
            ** round for any clone, and by then the cached project
            ** code lets fsl__xfer_may_attempt_login() succeed. A
            ** second rejection (xf->n.trips!=2 here) still aborts
            ** normally, so this is a one-shot carve-out, not a retry
            ** loop. */
            fsl__xfer_emitf(xf, FSL_MSG_INFO,
                           "Ignoring remote error on clone round 1 "
                           "(retrying with credentials): %s", z);
          }else{
            fsl__xfer_emit(xf, FSL_MSG_ERROR, z);
            fsl_xfer_errorf(xf, FSL_RC_REMOTE,
                            "Error from remote: %s", z);
          }
        }else if( xf->config->listener.callback ){
          fsl__xfer_emit(xf, FSL_MSG_RCV_MESSAGE,
                         fsl__xfer_tokn_defos(xf, 1));
        }
        break;
      }

      CASE(igot):{/* igot artifact-id ?flags? */
        /* Further tokens are ignored, as fossil(1) does. */
        argcCheck2(2,-1);
        fsl__rcv_igot(xf, card);
        break;
      }

      CASE(gimme):{/* gimme artifact-id */
        argcCheck2(2,2);
        /* A client answers gimme only when pushing, as fossil(1)
           does: a pull must not send content to the server. */
        if( 0==fsl__xfer_check_card_hash(xf, card, 1)
            && xf->config->op.push ){
          char const * const zUuid = fsl__xfer_tokn(xf, 1);
          if( fsl__xfer_have_igot(xf, zUuid) ){
            bool const isShunned = fsl_is_shunned_uuid(xf->f, zUuid);
            fsl_id_t const rid = isShunned
              ? 0 : fsl_uuid_to_rid(xf->f, zUuid);
            bool const isPrivate = rid>0
              && fsl_content_is_private(xf->f, rid);
            if( isShunned ){
              /* A shunned artifact is never sent, as in fossil(1)'s
                 send_file(), though its blob stays until a rebuild. */
            }else if( rid<=0 ){
              xf->rc = xf->f->error.code
                ? xf->f->error.code
                : fsl_xfer_errorf(xf, FSL_RC_NOT_FOUND,
                                  "Cannot find gimme artifact %s",
                                  zUuid);
            }else if( !isPrivate || xf->config->op.privateContent ){
              fsl_b content = fsl_b_empty;
              xf->rc = fsl_content_get(xf->f, rid, &content);
              if( 0==xf->rc ){
                xf->rc = fsl__xfer_send_file(
                  xf, zUuid, isPrivate, &content);
              }
              fsl_b_clear(&content);
            }else if( xf->remote.manifestDate>=20200413 ){
              /* Sync draft section 8.6: without private sync, answer
                 with "igot HASH 1", as fossil(1) does, but only to a
                 peer dated 2020-04-13 or later. The card goes into
                 the next request, if there is one. */
              xf->rc = fsl_id_bag_insert(&xf->privateIgot, rid);
            }
          }
        }
        break;
      }

      CASE(uvigot) : { /* uvigot name mtime hash size */
        fsl_size_t sz = 0;
        argcCheck(5);
        readPayloadTok(4, sz);
        break;
      }

      CASE(pragma):{
        argcCheck2(2,-1);
        //fsl_xfer_debugf(ch, "Got pragma: %b", bLnRaw);
        fsl__rcv_pragma(xf);
        break;
      }

      CASE(private):{
        /* Tokens after the card name are ignored, as fossil(1) does. */
        argcCheck2(1,-1);
        xf->flag.nextIsPrivate = true;
        break;
      }

      CASE(pull):  /* pull serverCode(IGNORED) projectCode */
      CASE(push):{ /* push serverCode(IGNORED) projectCode */
        argcCheck(3);
        char const * theirPC = fsl__xfer_tokn(xf, 2);
        char const * myPC = fsl__xfer_projcode(xf);
        //MARKER(("project code rc=%s %s\n", fsl_rc_cstr(rc), myPC));
        if( 0==xf->rc ){
          if( xf->clientVersion.projCodeMatch<0
              && xf->config->op.clone>0
              && !myPC ){
            /* Assume we just got our new project code via a clone */
            fsl_cx_err_reset(xf->f);
            fsl__xfer_emitf(xf, FSL_MSG_INFO,
                           "Got new project code: %s", theirPC);
            xf->clientVersion.projCodeMatch = 1;
            xf->rc = fsl_config_set_text(xf->f, FSL_CONFDB_REPO,
                                         "project-code", theirPC);
          }else{
            xf->clientVersion.projCodeMatch =
              myPC && (0==fsl_strcmp(theirPC, myPC));
            if( !xf->clientVersion.projCodeMatch ){
              /* Sync draft section 8.5: this is fatal. */
              xf->flag.fatalError = true;
              fsl_xfer_errorf(
                xf, FSL_RC_CONSISTENCY,
                "Project code mismatch: this=%s remote=%s",
                myPC ? myPC : "(missing)", theirPC);
            }
          }
        }
        if( 0==xf->rc && fsl_xfcard_e_push==card->type ){
          xf->clone.pushSeen = true;
        }
        break;
      }

      default:{
        /* For an unknown card, fossil(1) xfer.c and
           draft-fossil-sync-protocol-00 section 5.2 use "unknown
           command: [LINE]". */
        int const nLn = (int)(bLnRaw->used ? bLnRaw->used-1 : 0);
        if( card ){
          fsl_xfer_errorf(xf, FSL_RC_NYI,
                          "Don't yet know how to handle %s card: [%.*s]",
                          card->name, nLn, (char const *)bLnRaw->mem);
        }else{
          fsl_xfer_errorf(xf, FSL_RC_NYI, "unknown command: [%.*s]",
                          nLn, (char const *)bLnRaw->mem);
        }
        break;
      }
    }/* switch( card->type ) */
  }/* while(0==rc) */
#undef CASE
#undef readPayload
#undef readPayloadTok
#undef argcCheck
#undef argcCheck2
  //end:
  return xf->rc;
//bad_card:
//  fsl_xfer_errorf(xf, FSL_RC_SYNTAX, "Malformed card: %b", bLnRaw);
//  goto end;
}

fsl_xfcard_hash_t fsl_xfcard_hash( unsigned const char * word ){
  fsl_xfcard_hash_t H = 0;
  uint8_t I = 0;
  for( unsigned char const * x = word; *x; ++x, ++I ){
#if 1
    if( *x < fsl_xfcard_LowestIdChar || I>fsl_xfcard_MaxCardNameLen ){
      /* Reminder to self: this is a use-case-specific optimization
         and may not be appropriate when carrying this code forward
         into other trees. You remind yourself of that because _this_
         copy (sans this block) was carried forward from the sewal
         experiment. */
      H = 0;
      break;
    }
#endif
    H = fsl_xfcard_hash_step_ch(H,I,*x);
  }
  return H;
}

/**
   qsort()/bsearch() cmp function for (fsl_xfcard*), ordering on their
   hash values.
*/
static int fsl__xfcard_cmp_hash(void const *lhs, void const *rhs){
  fsl_xfcard_hash_t const l = ((fsl_xfcard const *)lhs)->hash;
  fsl_xfcard_hash_t const r = ((fsl_xfcard const *)rhs)->hash;
  //assert( l==0 ? l==r : l!=r );
  return (l<r) ? -1 : l!=r;
}

fsl_xfcard const * fsl__xfcard_search(unsigned char const * z){
  /**
     All sync protocol card types, initially sorted by name but will
     be sorted (once) by hash the first time this is called.
  */
  static fsl_xfcard obh[fsl_xfcard_e_COUNT] = {
    /* !!! Must be in fsl_xfcard_e order !!! */
    {.type=fsl_xfcard_e_unknown, .name="<unknown>", .hash=0},
    /* .hash is filled in below, on first use: a hash computed from
       a string literal at compile time is not a constant expression
       in ISO C, and MSVC rejects it. */
#define E(T,LEN) {.type=fsl_xfcard_e_ ## T, .name=#T, .hash=0},
    fsl_xfcard_map(E)
#undef E
  };
  static bool once = false;
  /* Two threads syncing at once must not both sort obh, or search it
     while the other sorts it. The first sorts it under SQLite's static
     main mutex, as fsl__libinit() uses: fsl__mutex_enter() is a no-op
     unless the library is built with FSL_ENABLE_MUTEX, which normal
     builds do not define. Readers load the flag with acquire semantics
     so that, having seen it set, they also see the sorted table. */
#if defined(__GNUC__) || defined(__clang__)
#  define FSL__XFCARD_ONCE_GET __atomic_load_n(&once, __ATOMIC_ACQUIRE)
#  define FSL__XFCARD_ONCE_SET __atomic_store_n(&once, true, __ATOMIC_RELEASE)
#else
#  define FSL__XFCARD_ONCE_GET false /* always take the lock */
#  define FSL__XFCARD_ONCE_SET once = true
#endif
  bool const locked = !FSL__XFCARD_ONCE_GET;
  sqlite3_mutex * const mx = locked
    ? fsl__sq3_mutex_alloc(SQLITE_MUTEX_STATIC_MAIN)
    : NULL /* NULL if SQLite has no mutexes, and then a no-op */;
  fsl__sq3_mutex_enter(mx);
  if( locked && !once ){
    /* obh = Ordered By Hash, so sort obh by hash value... */
    assert( fsl_xfcard_e_COUNT == sizeof(obh)/sizeof(obh[0]) );
    assert( fsl_xfcard_e_uvigot==obh[fsl_xfcard_e_COUNT-1].type );
    assert( 0==fsl_strcmp("clone_seqno", obh[fsl_xfcard_e_clone_seqno].name) );
    assert( fsl_xfcard_MaxCardNameLen == fsl_strlen(obh[fsl_xfcard_e_clone_seqno].name) );
    assert( fsl_xfcard_e_unknown==obh[0].type );
    assert( 0==obh[0].hash );
    for(int i = 1; i < fsl_xfcard_e_COUNT; ++i){
      obh[i].hash = fsl_xfcard_hash((unsigned char const *)obh[i].name);
    }

    qsort( obh, fsl_xfcard_e_COUNT, sizeof(obh[0]), fsl__xfcard_cmp_hash);

    assert( fsl_xfcard_e_unknown==obh[0].type );
    assert( 0==obh[0].hash );

    FSL__XFCARD_ONCE_SET;
#if !defined(NDEBUG)
    /* Assert that there are no duplicate hashes. If there are,
       we need to tweak the hash algo until there are none. */
    for(int i = 0; i < fsl_xfcard_e_COUNT; ++i){
      assert( fsl_strlen(obh[i].name) <= fsl_xfcard_MaxCardNameLen );
      assert( i ? (obh[i-1].hash < obh[i].hash) : 1 );
    }
    assert( 0 == fsl_xfcard_hashS("abc!nope") );
#  if 0
    MARKER(("fsl_xfcards sorted by hash:\n"));
    for(int i = 0; i < fsl_xfcard_e_COUNT; ++i){
      printf("%-12s # %2d 0x%08" PRIx32 "\n",  obh[i].name, obh[i].type, obh[i].hash);
    }
#  endif
#endif
  }/*one-time setup*/
  fsl__sq3_mutex_leave(mx);
#undef FSL__XFCARD_ONCE_GET
#undef FSL__XFCARD_ONCE_SET
  if( !z ) return NULL;
  fsl_xfcard const key = {
    fsl_xfcard_e_unknown,
    (char const *)z,
    fsl_xfcard_hash(z)
  };
  fsl_xfcard const * scc = bsearch( &key, obh, fsl_xfcard_e_COUNT,
                                    sizeof(fsl_xfcard),
                                    fsl__xfcard_cmp_hash );
  /*MARKER(("Searching for 0x%08" PRIx32 " [%s] candidate=%p\n",
    key.hash, z, (void*)scc));*/
  return scc
    ? (fsl_strcmp((char const *)scc->name, (char const *)z)
       ? 0
       : (scc->type==fsl_xfcard_e_unknown ? 0 : scc))
    : 0;
}

/**
   Reports, via err, whichever members the caller's channel ch lacks
   of those a channel needs: init(), append(), submit(), read() and a
   non-NULL impl.p. (cleanup() is optional and self() defaults.)
   Returns 0 if it lacks none, else FSL_RC_MISUSE.
*/
static int fsl__xfer_channel_check(fsl_sc const * const ch,
                                   fsl_error * const err){
  fsl_b b = fsl_b_empty;
  int rc = 0;
#define MISSING(COND, NAME) \
  if( COND ) fsl_b_appendf(&b, "%s%s", b.used ? ", " : "", NAME)
  MISSING(!ch->init, "init()");
  MISSING(!ch->append, "append()");
  MISSING(!ch->submit, "submit()");
  MISSING(!ch->read, "read()");
  MISSING(!ch->impl.p, "impl.p");
#undef MISSING
  if( b.used ){
    rc = fsl_error_set(err, FSL_RC_MISUSE,
                       "Sync channel '%s' is not usable: missing %b",
                       ch->name ? ch->name : "unnamed", &b);
  }
  fsl_b_clear(&b);
  return rc;
}

/**
   Populate pSc and pPopenState from config->channel or, if that is NULL,
   based on config->url. Report errors via err.
*/
static int fsl__xfer_sc_init(fsl_xfer_config const * const config,
                             fsl_sc * const pSc,
                             fsl_sc_popen_state * const pPopenState,
                             fsl_error * const err){
  int rc = 0;
  fsl_url url = fsl_url_empty;
  char const * const zUrl = fsl_b_cstr(&config->url);
  assert( zUrl && *zUrl );
  rc = fsl_url_parse(&url, zUrl);
  if( 0==rc ){
    assert( url.raw );
    if( config->channel ){
      /* The caller's channel. The URL is parsed into it by
         fsl__xfer_init_url(). */
      rc = fsl__xfer_channel_check(config->channel, err);
      if( 0==rc ){
        *pSc = *config->channel;
        if( !pSc->self ) pSc->self = fsl_sc_self;
        *pPopenState = fsl_sc_popen_state_empty;
      }
    }else if( 0==fsl_strcmp("http", url.scheme)
        || 0==fsl_strcmp("https", url.scheme) ){
      /* Native socket. Allocates and installs heap-owned
         per-channel state. */
      *pSc = fsl_sc_socket;
      *pPopenState = fsl_sc_popen_state_empty;
      assert(!pPopenState->impl.init);
      rc = fsl_sc_socket_state_init(pSc);
      if( 0==rc ){
        fsl_url_swap(&url, &pSc->url);
      }
    }else if( 0==fsl_strcmp("file", url.scheme) ){
      *pSc = fsl_sc_popen_fth;
      *pPopenState = fsl_sc_popen_state_fth;
      pSc->impl.p = pPopenState;
    }else if( 0==fsl_strcmp("ssh", url.scheme) ){
      *pSc = fsl_sc_popen_ssh;
      *pPopenState = fsl_sc_popen_state_ssh;
      pSc->impl.p = pPopenState;
    }else{
      rc = fsl_error_set(err, FSL_RC_TYPE,
                         "Cannot determine which sync channel to use "
                         "for URL ");
      fsl_url_render(&url, &err->msg,
                     FSL_URL_RENDER_MASK_PASSWORD);
    }
  }else if( FSL_RC_OOM!=rc ){
    int b = 0, e = 0;
    fsl__xfer_url_pw_span(zUrl, &b, &e);
    rc = fsl_error_set(err, rc, "Error parsing URL: %.*s%s%s",
                       e>b ? b : (int)config->url.used,
                       zUrl, e>b ? "****" : "",
                       e>b ? zUrl + e : "");
  }
  fsl_url_cleanup(&url);
  return rc;
}

/**
   Applies clone destination checks, then initializes its channel.
*/
static int fsl__clone_sc_init(fsl_clone_config const * const c,
                              fsl_sc * const pSc,
                              fsl_sc_popen_state * const pPos,
                              fsl_error * const err){
  int rc = 0;
  assert( c );
  assert( c->xfer.url.used );
  assert( c->repo.filename );
  if( fsl_file_size(c->repo.filename)>=0 ){
    if( c->repo.allowOverwrite ){
      if( 0!=fsl_file_unlink(c->repo.filename) ){
        rc = fsl_error_set(err, FSL_RC_ACCESS,
                           "Cannot delete file %s", c->repo.filename);
      }
    }else{
      rc = fsl_error_set(err, FSL_RC_ALREADY_EXISTS,
                         "Cowardly refusing to overwrite %s",
                         c->repo.filename);
    }
  }
  return rc ? rc : fsl__xfer_sc_init(&c->xfer, pSc, pPos, err);
}

/** Number of file and cfile cards received, per metrics M. */
#define fsl__xfer_nfiles(M) \
  ((M)->cardsRx[fsl_xfcard_e_file] + (M)->cardsRx[fsl_xfcard_e_cfile])

/**
   SQL condition, against blob aliased as b, for a phantom a pull may
   request: not shunned and, unless syncing private content, not
   private. Takes one %d: xf->flag.syncPrivate.

   It keys on blob.size<0 rather than the phantom table so that it
   also finds phantoms which older builds recorded in [unclustered]
   instead.
*/
#define FSL__XFER_WANTED_PHANTOM \
  "b.size<0" \
  " AND NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.shun WHERE uuid=b.uuid)" \
  " AND (%d OR NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.private WHERE rid=b.rid))"

static bool fsl__xfer_has_phantoms(fsl_xfer const * const xf){
  return fsl_db_exists(fsl_cx_db_repo(xf->f),
                       "SELECT 1 FROM {{dbname.repo}}.blob b WHERE "
                       FSL__XFER_WANTED_PHANTOM,
                       (int)xf->flag.syncPrivate);
}

/**
   Port of fossil(1)'s request_phantoms(): queues a gimme for up to
   maxReq wanted phantoms which are not already requested in the
   pending request.
*/
static int fsl__xfer_request_phantoms(fsl_xfer * const xf,
                                      fsl_size_t maxReq){
  fsl_db * const db = fsl_cx_db_repo(xf->f);
  fsl_stmt q = fsl_stmt_empty;
  int rc = fsl_db_prepare(db, &q,
                          "SELECT b.rid, b.uuid FROM {{dbname.repo}}.blob b WHERE "
                          FSL__XFER_WANTED_PHANTOM,
                          (int)xf->flag.syncPrivate);
  if( rc ) rc = fsl_cx_uplift_db_error2(xf->f, db, rc);
  while( 0==rc && maxReq>0 ){
    int const stepRc = fsl_stmt_step(&q);
    if( FSL_RC_STEP_DONE==stepRc ) break;
    else if( FSL_RC_STEP_ROW!=stepRc ){
      rc = fsl_cx_uplift_db_error2(xf->f, db, stepRc);
      break;
    }
    fsl_id_t const rid = fsl_stmt_g_id(&q, 0);
    if( fsl_id_bag_contains(&xf->gimmePending, rid) ) continue;
    rc = fsl__xfer_appendcard(xf, fsl_xfcard_e_gimme, "%s",
                              fsl_stmt_g_text(&q, 1, NULL));
    if( 0==rc ) rc = fsl_id_bag_insert(&xf->gimmePending, rid);
    --maxReq;
  }
  fsl_stmt_finalize(&q);
  return rc ? (xf->rc = rc) : 0;
}

/**
   Crosslinks everything received so far which this transfer has not
   already crosslinked. fossil(1) crosslinks each file as it arrives;
   doing it after each trip is what turns a received cluster into
   phantoms before deciding whether another trip is needed.

   Crosslinking may add entries to toVerify. An insertion can resize
   and rehash the bag, even when the inserted RID is already present,
   invalidating an active iteration and potentially skipping entries.
   Iterate over a snapshot so that mutations of toVerify cannot affect
   traversal. Do not swap or otherwise drain toVerify: it must remain
   populated for fsl__repo_verify_at_commit().

   Caveat: an application callback that imports a genuinely new,
   uncrosslinked artifact during this pass would add it only to
   toVerify, not the snapshot. Supporting that case fully would
   require a dedicated crosslink queue.
*/
static int fsl__xfer_crosslink_rcvd(fsl_xfer * const xf){
  fsl_cx * const f = xf->f;
  fsl_id_bag snap = fsl_id_bag_empty;
  fsl_id_t rid;
  int rc;
  if( f->cache.ignoreDephantomizations ) return 0;
  rc = fsl_id_bag_copy(fsl__cx_ptl_bag(f, fsl__ptl_e_toVerify), &snap);
  for( rid = fsl_id_bag_first(&snap);
       0==rc && rid>0;
       rid = fsl_id_bag_next(&snap, rid) ){
    if( fsl_id_bag_contains(&xf->xlinked, rid) ) continue;
    if( !fsl__content_is_available(f, rid) ){
      /* A delta whose source has not arrived yet, which fossil(1)
         calls dangling. A later trip crosslinks it once the source
         is here. */
      continue;
    }
    rc = fsl_id_bag_insert(&xf->xlinked, rid);
    if( 0==rc ) rc = fsl__after_dephantomize(f, rid, true);
  }
  fsl_id_bag_clear(&snap);
  return rc ? (xf->rc = rc) : 0;
}

/**
   To be called after fsl__xfer_submit(). Tries to guess whether another
   request should be sent as a follow-up.
*/
static bool fsl__xfer_should_continue(fsl_xfer const * const xf,
                                      fsl_xfer_metrics const * const prev,
                                      fsl_size_t nOldCloneSeq){
  if( xf->request.nBytes ) return true;
  if( prev->cardsTx[fsl_xfcard_e_gimme]
      < xf->n.cardsTx[fsl_xfcard_e_gimme] ){
    /* We can't just compare prev/xf->n.sentCard because some cards
       are innocuous and should not trigger a new trip. */
    return true;
  }
  if( 2==xf->n.trips && xf->privateIgot.entryCount ){
    /* Sync draft section 3.7 limb (c): the first reply asked for
       private content, which the next request answers. */
    return true;
  }
  if( xf->config->op.clone
      && xf->clone.seqNo
      && nOldCloneSeq<xf->clone.seqNo ) return true;
  if( xf->config->op.clone
      && fsl__xfer_nfiles(&xf->n) > fsl__xfer_nfiles(prev) ){
    /* fossil(1) and sync draft section 3.7(e): a clone round which
       stored files is followed by another. */
    return true;
  }
  if( xf->config->op.clone && !xf->flag.configReqSent ){
    /* The config request is only emitted from the second trip onwards
       (see fsl_clone()), so a repo small enough to clone in a single
       trip would otherwise never be asked for its shun list. fossil's
       clone always runs at least two cycles; make ours do the same
       rather than silently skipping the request. */
    return true;
  }
  if( xf->config->op.privateContent
      && xf->clientVersion.projCodeMatch>0
      && !xf->flag.syncPrivate ){
    return true;
  }
  if( xf->config->op.push && !xf->replyErr.code
      && fsl_db_exists(
        fsl_cx_db_repo(xf->f),
        "SELECT 1 FROM {{dbname.repo}}.unsent u"
        " WHERE %d OR NOT EXISTS("
          "SELECT 1 FROM {{dbname.repo}}.private p WHERE p.rid=u.rid)",
        (int)xf->config->op.privateContent) ){
    return true;
  }
  if( xf->config->op.pull && !xf->config->op.clone
      && fsl__xfer_nfiles(&xf->n) > fsl__xfer_nfiles(prev)
      && fsl__xfer_has_phantoms(xf) ){
    /* fossil(1): keep going while files arrive and phantoms remain. */
    return true;
  }
  return false;
}

static int fsl__xfer_send_file(fsl_xfer * const xf,
                               char const * const zUuid,
                               bool const isPrivate,
                               fsl_b const * const content){
  int rc = 0;
  assert( zUuid );
  assert( content );
  if( isPrivate ){
    rc = fsl__xfer_appendcard(xf, fsl_xfcard_e_private, NULL);
  }
  if( 0==rc ){
    rc = fsl__xfer_appendcard(
      xf, fsl_xfcard_e_file, "%s %" FSL_SIZE_T_PFMT,
      zUuid, content->used);
  }
  if( 0==rc ){
    rc = fsl__xfer_append(xf, content->mem, content->used);
  }
  return rc;
}

/**
   Adds a bounded batch of locally-created artifacts to the current
   request and records them in xf->unsentPending.
   fsl__xfer_unsent_forget() removes them from unsent once the reply
   arrives, in the transaction which processes it, so that they stay
   queued if the exchange or the processing fails.
*/
static int fsl__xfer_send_unsent(fsl_xfer * const xf){
  static fsl_size_t const MaxArtifacts = 200;
  static fsl_size_t const DefaultMaxBytes = 5 * 1024 * 1024;
  fsl_size_t const maxBytes = xf->config->maxResponseBytes>0
    ? (fsl_size_t)xf->config->maxResponseBytes : DefaultMaxBytes;
  bool const sendPrivate = xf->config->op.privateContent
    && (!xf->config->op.clone
        || xf->clientVersion.projCodeMatch>0);
  fsl_stmt q = fsl_stmt_empty;
  fsl_b content = fsl_b_empty;
  fsl_size_t nSent = 0;
  int stepRc = 0;
  int rc = fsl_cx_prepare(
    xf->f, &q,
    "SELECT b.rid, b.uuid,"
    " EXISTS(SELECT 1 FROM {{dbname.repo}}.private p WHERE p.rid=b.rid)"
    " FROM {{dbname.repo}}.unsent u JOIN {{dbname.repo}}.blob b USING(rid)"
    " WHERE b.size>=0"
    " AND (%d OR NOT EXISTS("
      "SELECT 1 FROM {{dbname.repo}}.private p WHERE p.rid=b.rid))"
    " ORDER BY b.rid LIMIT %" FSL_SIZE_T_PFMT,
    (int)sendPrivate, MaxArtifacts);
  while( 0==rc && FSL_RC_STEP_ROW==(stepRc=fsl_stmt_step(&q)) ){
    fsl_id_t const rid = fsl_stmt_g_id(&q, 0);
    char const * const zUuid = fsl_stmt_g_text(&q, 1, NULL);
    bool const isPrivate = 0!=fsl_stmt_g_int32(&q, 2);
    if( fsl_is_shunned_uuid(xf->f, zUuid) ){
      /* A shunned artifact is never sent, as in fossil(1)'s
         send_file(). It leaves unsent with the batch, as fossil(1)'s
         send_unsent() empties unsent, so that it does not hold the
         sync open for another round. */
      rc = fsl_id_bag_insert(&xf->unsentPending, rid);
      continue;
    }
    fsl_b_reuse(&content);
    rc = fsl_content_get(xf->f, rid, &content);
    if( rc ) break;
    if( nSent
        && xf->request.nBytes + content.used + 100 > maxBytes ){
      break;
    }
    rc = fsl__xfer_send_file(xf, zUuid, isPrivate, &content);
    if( 0==rc ) rc = fsl_id_bag_insert(&xf->unsentPending, rid);
    if( 0==rc ) ++nSent;
  }
  if( 0==rc && FSL_RC_STEP_DONE!=stepRc
      && FSL_RC_STEP_ROW!=stepRc ){
    rc = fsl_cx_uplift_db_error2(xf->f, q.db, stepRc);
  }
  fsl_stmt_finalize(&q);
  fsl_b_clear(&content);
  return rc;
}

/**
   Removes the artifacts pushed by the request just sent from the
   unsent table. See fsl__xfer_send_unsent().
*/
static int fsl__xfer_unsent_forget(fsl_xfer * const xf){
  int rc = 0;
  for( fsl_id_t rid = fsl_id_bag_first(&xf->unsentPending);
       0==rc && rid>0;
       rid = fsl_id_bag_next(&xf->unsentPending, rid) ){
    rc = fsl_cx_exec(
      xf->f, "DELETE FROM {{dbname.repo}}.unsent WHERE rid=%" FSL_ID_T_PFMT,
      rid);
  }
  fsl_id_bag_reuse(&xf->unsentPending);
  return rc;
}

/**
   Sync draft section 8.6: when private sync is in effect, every
   request which carries push lists the private inventory, as
   fossil(1)'s send_private() does, as "igot HASH 1" cards. Phantoms
   are not inventory and are not listed.
*/
static int fsl__xfer_send_private_igots(fsl_xfer * const xf){
  fsl_stmt q = fsl_stmt_empty;
  int stepRc = 0;
  int rc = fsl_cx_prepare(
    xf->f, &q,
    "SELECT b.uuid FROM {{dbname.repo}}.private p JOIN {{dbname.repo}}.blob b USING(rid)"
    " WHERE b.size>=0 ORDER BY b.rid");
  while( 0==rc && FSL_RC_STEP_ROW==(stepRc=fsl_stmt_step(&q)) ){
    rc = fsl__xfer_appendcard(xf, fsl_xfcard_e_igot, "%s 1",
                              fsl_stmt_g_text(&q, 0, NULL));
  }
  if( 0==rc && FSL_RC_STEP_DONE!=stepRc
      && FSL_RC_STEP_ROW!=stepRc ){
    rc = fsl_cx_uplift_db_error2(xf->f, q.db, stepRc);
  }
  fsl_stmt_finalize(&q);
  return rc;
}

/**
   Lists the unclustered inventory as "igot HASH" cards, as fossil(1)'s
   send_unclustered() does in every request which carries push. The
   peer asks with gimme for any it lacks. Without this, an artifact
   whose unsent entry a push to one peer cleared is never offered to
   another. Shunned, phantom and private artifacts are not listed.
*/
static int fsl__xfer_send_unclustered(fsl_xfer * const xf){
  fsl_stmt q = fsl_stmt_empty;
  int stepRc = 0;
  int rc = fsl_cx_prepare(
    xf->f, &q,
    "SELECT b.uuid FROM {{dbname.repo}}.unclustered u"
    " JOIN {{dbname.repo}}.blob b USING(rid)"
    " WHERE b.size>=0"
    " AND NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.shun s"
    " WHERE s.uuid=b.uuid)"
    " AND NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.private p"
    " WHERE p.rid=b.rid)"
    " ORDER BY b.rid");
  while( 0==rc && FSL_RC_STEP_ROW==(stepRc=fsl_stmt_step(&q)) ){
    rc = fsl__xfer_appendcard(xf, fsl_xfcard_e_igot, "%s",
                              fsl_stmt_g_text(&q, 0, NULL));
  }
  if( 0==rc && FSL_RC_STEP_DONE!=stepRc
      && FSL_RC_STEP_ROW!=stepRc ){
    rc = fsl_cx_uplift_db_error2(xf->f, q.db, stepRc);
  }
  fsl_stmt_finalize(&q);
  return rc;
}

/**
   To be called when fsl__xfer_submit() fails with a reply error (see
   xf->flag.peerError). Sync draft section 10.1: such an error ends
   only the reply-card loop. What the reply delivered before it is
   kept, and the session goes on to decide whether another round
   follows. This clears xf's error state, keeping the error in
   xf->replyErr to become the session's result. An error in the first
   clone reply is ignored instead (sync draft section 8.3), so that
   the mandatory second round still happens.

   Only the first reply error is absorbed this way. A second one, or
   one in a later clone reply, ends the session, so that a peer which
   fails the same way every round cannot keep it going. A sync session
   then reports the first error.
*/
static void fsl__xfer_absorb_reply_error(fsl_xfer * const xf){
  fsl_error * const err = fsl_cx_err_e(xf->f);
  assert( xf->rc && xf->flag.peerError );
  if( xf->config->op.clone ){
    if( 2==xf->n.trips ){
      xf->rc = 0;
      xf->flag.peerError = false;
      fsl__xfer_emitf(xf, FSL_MSG_INFO,
                      "Ignoring error in first clone reply: %b",
                      &err->msg);
      fsl_error_reset(err);
    }
  }else if( !xf->replyErr.code ){
    xf->rc = 0;
    xf->flag.peerError = false;
    fsl_error_propagate(err, &xf->replyErr);
  }else{
    fsl__xfer_emitf(xf, FSL_MSG_INFO, "Reply processing stopped: %b",
                    &err->msg);
    fsl_error_propagate(&xf->replyErr, err);
    xf->rc = err->code;
  }
}

/**
   Returns true if xf's URL, rendered without its password, is the
   repository's last-sync-url. fossil(1) syncs with last-sync-url when
   its sync command is given no URL.
*/
static bool fsl__xfer_url_is_last_sync(fsl_xfer * const xf){
  bool rv = false;
  char * zLast;
  fsl_b * const b = fsl_cx_b_borrow(xf->f);
  if( !b ) return false;
  zLast = fsl_config_get_text(xf->f, FSL_CONFDB_REPO, "last-sync-url",
                              NULL);
  if( zLast ){
    rv = 0==fsl_url_render(&xf->ch->self(xf->ch)->url, b,
                           FSL_URL_RENDER_NO_PASSWORD)
      && 0==fsl_strcmp(zLast, fsl_b_cstr(b));
    fsl_free(zLast);
  }else{
    fsl_cx_err_reset(xf->f);
  }
  fsl_cx_b_return(xf->f, b);
  return rv;
}

static int fsl__xfer_client_run(fsl_xfer * const xf,
                                fsl_error * const err){
  fsl_xfer_metrics prevMetrics = fsl_xfer_metrics_empty_m;
  fsl_size_t cloneSeqNo = 0;
  int rc = 0;
  assert( xf );
  assert( xf->f );
  assert( xf->config );
  assert( 1==xf->n.trips );
again:
  assert( !rc );
  if( xf->config->op.pull && !xf->config->op.clone
      && (1==xf->n.trips
          || fsl__xfer_nfiles(&xf->n) > fsl__xfer_nfiles(&prevMetrics)) ){
    /* As fossil(1) does: request phantoms on the first trip and after
       any trip which received files, asking for more as more arrive.
       This happens before prevMetrics is taken so that these gimmes
       do not count as new work in fsl__xfer_should_continue(). */
    fsl_size_t const n = 2 * (fsl__xfer_nfiles(&xf->n)
                              - fsl__xfer_nfiles(&prevMetrics));
    rc = fsl__xfer_request_phantoms(xf, n>200 ? n : 200);
    if( rc ) return rc;
  }
  prevMetrics = xf->n;
  rc = fsl__xfer_emit(xf, FSL_MSG_CONNECT, &xf->n.trips);
  assert( xf->rc == rc );
  if( 0==rc ){
    fsl__xfer_pw_setup(xf);
    if( 0==xf->rc && xf->config->op.clone ){
      /* The request prologue already sent client-version. */
      if( 1!=xf->n.trips ){
        cloneSeqNo = xf->clone.seqNo;
        /* The project code normally arrived in the first reply's push
           card, but a first reply which is only an error has none, and
           the second round is still required (sync draft section
           8.3). */
        if( 0==rc && !xf->flag.configReqSent ){
          xf->flag.configReqSent = true;
          xf->flag.configRcvMask = FSL_CONFIGSET_ALL;
          rc = xf->rc = fsl__xfer_appendcard(
            xf, fsl_xfcard_e_reqconfig, "/all");
        }
      }
    }else if( 0==xf->rc && xf->config->op.pull
              && !xf->flag.configReqSent
              && fsl_config_get_bool(xf->f, FSL_CONFDB_REPO, true,
                                     "auto-shun")
              && fsl__xfer_url_is_last_sync(xf) ){
      /* As fossil(1) does while its auto-shun setting is on. */
      xf->flag.configReqSent = true;
      xf->flag.configRcvMask = FSL_CONFIGSET_SHUN;
      xf->rc = fsl__xfer_appendcard(xf, fsl_xfcard_e_reqconfig, "/shun");
    }
    rc = xf->rc;
  }
  switch( rc ? 0 : xf->config->op.clone ){
    case 0: break;
    case 1:
      if( 1==xf->n.trips ){
        rc = fsl__xfer_appendcard(xf, fsl_xfcard_e_clone, NULL);
      }
      break;
    case 2:
    case 3:
      xf->clone.protocolVersion = xf->config->op.clone;
      if( 1==xf->n.trips ){
        /* The sequence starts at 1 (sync draft section 8.2), so that
           a first reply holding a push card but no clone_seqno, as a
           login-required server sends, is followed by clone 3 1. */
        xf->clone.seqNo = 1;
      }
      /* Ask for more only if the last reply had a push card and a
         positive sequence number (sync draft section 8.2). Otherwise
         this round is the draft's operation-less cleanup. */
      if( 1==xf->n.trips
          || (xf->clone.pushSeen && xf->clone.seqNo) ){
        rc = fsl__xfer_appendcard(xf, fsl_xfcard_e_clone,
                                  "%d %" FSL_SIZE_T_PFMT,
                                  xf->clone.protocolVersion,
                                  xf->clone.seqNo
                                  ? xf->clone.seqNo : 1);
      }
      break;
    default:
      rc = xf->rc = fsl_error_set(
        err, FSL_RC_MISUSE,
        "Don't know how to handle clone protocol version #%d",
        (int)xf->config->op.clone);
      break;
  }
  if( 0==rc && xf->config->op.push
      && xf->config->op.privateContent
      && (!xf->config->op.clone
          || xf->clientVersion.projCodeMatch>0) ){
    /* This comes after the fsl__xfer_should_continue() decision, so
       these cards never cause another round (sync draft section 3.7
       limb (c)). */
    rc = xf->rc = fsl__xfer_send_private_igots(xf);
  }
  for( fsl_id_t rid = fsl_id_bag_first(&xf->privateIgot);
       0==rc && rid>0;
       rid = fsl_id_bag_next(&xf->privateIgot, rid) ){
    fsl_uuid_str const zUuid = fsl_rid_to_uuid(xf->f, rid);
    rc = zUuid
      ? fsl__xfer_appendcard(xf, fsl_xfcard_e_igot, "%s 1", zUuid)
      : (xf->f->error.code ? xf->f->error.code : FSL_RC_NOT_FOUND);
    xf->rc = rc;
    fsl_free(zUuid);
  }
  fsl_id_bag_reuse(&xf->privateIgot);
  if( 0==rc && xf->config->op.push && !xf->replyErr.code ){
    /* After a reply error, push no more batches: the peer may be
       refusing them, and each one sent leaves the unsent table. */
    rc = xf->rc = fsl__xfer_send_unsent(xf);
    if( 0==rc ) rc = xf->rc = fsl__xfer_send_unclustered(xf);
  }
  if( rc ) return rc;
  fsl_id_bag_reuse(&xf->gimmePending);
  if( fsl__xfer_submit(xf) && xf->flag.peerError ){
    fsl__xfer_absorb_reply_error(xf);
  }
  if( 0==xf->rc ){
    if( fsl__xfer_crosslink_rcvd(xf) ) return xf->rc;
    fsl__xfer_emit_progress(xf, NULL, NULL);
    if( fsl__xfer_should_continue(xf, &prevMetrics, cloneSeqNo) ){
      if( !xf->config->op.clone ){
        /* Commit this round and open a new transaction, as fossil(1)'s
           client_sync() does, so the write lock is free while the next
           request goes out and the reply comes back. fsl_clone() keeps
           one transaction: it skips verify-at-commit and checks hashes
           in its rebuild instead. */
        fsl_cx * const f = xf->f;
        int rc2 = fsl__crosslink_end(f, 0);
        if( 0==rc2 ) rc2 = fsl_cx_txn_end_v2(f, true, false);
        if( 0==rc2 ) rc2 = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
        if( 0==rc2 ) rc2 = fsl__crosslink_begin(f);
        if( rc2 ) return xf->rc = rc2;
      }
      if( xf->n.trips>=1000 ){
        return xf->rc = fsl_error_set(
          err, FSL_RC_RANGE,
          "Sync exceeded the 1000-round safety limit.");
      }
      goto again;
    }
  }
  if( 0==xf->rc && xf->replyErr.code ){
    /* The session ended normally after a reply error: report it. */
    fsl_error * const err = fsl_cx_err_e(xf->f);
    fsl_error_propagate(&xf->replyErr, err);
    xf->rc = err->code;
    xf->flag.peerError = true;
  }
  return xf->rc;
}

int fsl_sync_client(fsl_cx * const f,
                    fsl_xfer_config const * const config_,
                    fsl_error * const err_){
  fsl_error * const err = err_ ? err_ : (f ? &f->error : NULL);
  fsl_xfer_config config = fsl_xfer_config_empty;
  fsl_xfer xf = fsl_xfer_empty;
  fsl_sc chBase;
  fsl_sc chTrace;
  fsl_sc * ch = &chBase;
  fsl_sc_popen_state st;
  bool crosslinkStarted = false;
  bool keepReceived = false;
  int rc = 0;
  bool openedTxn = false;
    /* content.c */;
  if( !f || !config_ ){
    return fsl_error_set(err, FSL_RC_MISUSE,
                         "fsl_sync_client() requires non-NULL "
                         "context and configuration arguments.");
  }
  fsl_error_reset(err);
  if( !fsl_cx_db_repo(f) ){
    return fsl_error_set(err, FSL_RC_NOT_A_REPO,
                         "fsl_sync_client() requires an open repository.");
  }
#if 0
  /* Historically (pre-mid-2026) we could not sync during a transaction
     because we had to shell out to fossil(1) and our transaction locked
     the db. */
  else if( fsl_cx_txn_level(f) ){
    return fsl_error_set(err, FSL_RC_LOCKED,
                         "Sync cannot run inside an open transaction.");
  }
#endif
  else if( config_->op.clone ){
    return fsl_error_set(err, FSL_RC_MISUSE,
                         "fsl_sync_client() does not accept clone mode.");
  }else if( config_->op.autosync ){
    return fsl_error_set(err, FSL_RC_NYI,
                         "Automatic sync direction is not implemented.");
  }else if( config_->maxResponseSeconds>=0 ){
    return fsl_error_set(err, FSL_RC_NYI,
                         "Sync response time limits are not implemented.");
  }else if( !config_->op.pull && !config_->op.push ){
    return fsl_error_set(err, FSL_RC_MISUSE,
                         "Sync requires pull, push, or both.");
  }else if( !config_->url.used ){
    return fsl_error_set(err, FSL_RC_MISUSE,
                         "Sync requires a peer URL.");
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if( rc ) goto end;
  openedTxn = true;
  fsl__xfer_config_almost_copy(config_, &config);
  rc = fsl__xfer_sc_init(&config, &chBase, &st, err);
  if( rc ) goto end;
  assert( chBase.impl.p );
  /* not all channels do this assert( chBase.url.raw ); */
  if( config.trace.mask ){
    if( fsl_sc_tracer_init(&chTrace, &chBase,
                           config.trace.mask,
                           &config.trace.outputer) ){
      ch = &chTrace;
      chBase.xfer = &xf;
      assert( chTrace.impl.p );
      assert( chTrace.impl.p!=&ch );
    }else{
      fsl_report_oom;
      rc = FSL_RC_OOM;
      goto end;
    }
  }
  rc = fsl__xfer_setup(f, &xf, &config, ch);
  if( rc ) goto end;
  xf.flag.ownsTxn = 1==fsl_cx_txn_level(f) /* just our own */;
  rc = fsl__crosslink_begin(f);
  if( rc ) goto end;
  crosslinkStarted = true;
  rc = fsl__xfer_start(&xf, FSL__XFER_START_REQUEST);
  if( 0==rc ) rc = fsl__xfer_client_run(&xf, err);
end:
  if( crosslinkStarted && !f->cache.isCrosslinking ){
    /* A round boundary failed after ending the crosslink and before
       starting the next one, e.g. because another connection held
       the write lock past the busy timeout. */
    crosslinkStarted = false;
  }
  if( rc && crosslinkStarted && xf.flag.peerError ){
    /* A reply held an error card, or something we could not handle.
       As fossil(1) does, and as the sync draft requires (sections 5.2
       and 10.1), keep what was received. The error itself is still
       returned. */
    fsl_error peerErr = fsl_error_empty;
    int rc2;
    fsl_error_propagate(&f->error, &peerErr);
    rc2 = fsl__xfer_crosslink_rcvd(&xf);
    crosslinkStarted = false;
    rc2 = fsl__crosslink_end(f, rc2);
    keepReceived = 0==rc2;
    if( keepReceived ){
      fsl_error_propagate(&peerErr, &f->error);
    }/* else report the crosslink error, which is now in f */
    else rc = rc2;
    fsl_error_clear(&peerErr);
  }
  if( crosslinkStarted ){
    int const rc2 = fsl__crosslink_end(f, rc);
    if( 0==rc ) rc = rc2;
  }
  if( 0==rc ){
    fsl__xfer_emit_progress(&xf, config.op.pull
                            ? (config.op.push ? "Sync" : "Pull")
                            : "Push", chBase.url.host);
  }
  fsl__xfer_cleanup(&xf, rc);
  fsl_xfer_config_cleanup(&config);
  if( openedTxn && fsl_cx_txn_level(f) ){
    /* The level is 0 if a round boundary committed and then could
       not start the next transaction. */
    int const rc2 = fsl_cx_txn_end_v2(f, 0==rc || keepReceived, false);
    if( 0==rc ) rc = rc2;
  }
  if( rc && err!=&f->error && !err->code && f->error.code ){
    /* The sync and channel code report their errors via f. */
    fsl_error_propagate(&f->error, err);
  }
  return rc;
}

/**
   Calculates the total sent or received card counts.
*/
static fsl_size_t fsl_xfer_metrics_ntx(fsl_xfer_metrics const * const m,
                                       bool sent){
  fsl_size_t n = 0;
  for( int i = fsl_xfcard_e_unknown + 1; i < fsl_xfcard_e_COUNT; ++i){
    n += sent ? m->cardsTx[i] : m->cardsRx[i];
  }
  return n;
}

int fsl_clone( fsl_clone_config const * const cc_, fsl_error * const err_ ){
  fsl_url url = fsl_url_empty;
  int rc = 0;
  fsl_cx f_ = fsl__cx_empty;
  fsl_cx * f = &f_;
  fsl_sc chBase;
  fsl_sc chTrace;
  fsl_sc *ch = &chBase;
  fsl_sc_popen_state st;
  fsl_clone_config ccc = fsl_clone_config_empty_m;
  fsl_xfer_config * const cxf = &ccc.xfer;
  fsl_cx_config fCfg = fsl_cx_config_empty_m;
  fsl_xfer xf = fsl_xfer_empty;
  bool createdRepo = false;
  fsl_error * err = err_ ? err_ : &f_.error;

  ccc = *cc_;
  ccc.xfer = fsl_xfer_config_empty/*undo memory damage*/;
  fsl__xfer_config_almost_copy(&cc_->xfer, cxf);
  if( !cxf->op.clone ){
    rc = fsl_error_set(err_, FSL_RC_MISUSE,
                       "Expecting fsl_clone_config::xfer::op.clone "
                       "to be true.");
    goto end;
  }
  fsl_error_reset(err);
  fCfg.listener = cxf->listener;
  rc = fsl__clone_sc_init(&ccc, &chBase, &st, err);
  if( rc ) goto end;
  /* The popen channels point impl.p at the stack-local `st`; the native
     socket channel owns heap-allocated state of a different type and
     frees it in its cleanup(). Either way impl.p must be set. */
  assert( chBase.impl.p );
  //fCfg.traceSql = 1;
  rc = fsl_cx_init(&f, &fCfg);
  if( rc ) goto end;
  f->cache.ignoreDephantomizations = true;
  if( 1 ){
    /* 2026-07-25 (a year later): what was this for? */
    f->output.out = fsl_output_f_FILE;
    f->output.flush = fsl_flush_f_FILE;
    f->output.state = stdout;
  }
  if( cxf->trace.mask ){
    if( fsl_sc_tracer_init(&chTrace, &chBase,
                           cxf->trace.mask,
                           &cxf->trace.outputer) ){
      ch = &chTrace;
      chBase.xfer = &xf;
      assert(chTrace.impl.p);
      assert(chTrace.impl.p!=&ch);
    }else{
      fsl_report_oom;
      rc = FSL_RC_OOM;
      goto end;
    }
  }
  assert( !xf.f );
  rc = fsl__xfer_setup(f, &xf, cxf, ch);
  assert( f==xf.f );
  assert( rc==xf.rc );
  if( 0==rc ){
    /* Create the repo */
    ccc.repo.elideProjectCode = true;
    ccc.repo.commitMessage =
      /* A clone must not seed an initial commit: the artifact set comes
         entirely from the server. A default commitMessage would create
         a spurious manifest not present on the remote, so suppress it
         (NULL => no initial check-in). */
      NULL;
    if( !ccc.repo.username ) ccc.repo.username = xf.user.name;
    rc = fsl_repo_create(f, &ccc.repo);
    if( 0==rc ){
      createdRepo = true;
      if( 0==(rc = fsl_cx_txn_begin(f)) ){
        rc = fsl__xfer_start(&xf, FSL__XFER_START_REQUEST);
      }
    }else{
      createdRepo = FSL_RC_ALREADY_EXISTS!=rc;
    }
  }
  if( rc ) goto end;

  rc = fsl__xfer_client_run(&xf, err);
  if( 0==rc ) fsl__xfer_emit_progress(&xf, "Clone", chBase.url.host);
  if( 0==rc
      && fsl_db_g_int64(fsl_cx_db_repo(f), 0,
                        "SELECT count(*) FROM {{dbname.repo}}.blob")<=0 ){
    rc = fsl_error_set(err, FSL_RC_RANGE,
                       "Clone received no artifacts.");
  }
  if( 0==rc ){
    fsl_size_t const nArt = fsl_xfer_metrics_ntx(&xf.n, false);
    if( nArt > 10/*kinda arbitrary*/ ){
      rc = fsl__xfer_emitf(&xf, FSL_MSG_INFO,
                           "Validating %" FSL_SIZE_T_PFMT
                           " blobs. Please be patient.", nArt);
    }
  }
  if( 0==rc ){
    /* We need to commit before the rebuild is run so that
       dephantomization happens. If we run fsl_rebuild() while this
       level is active, that won't happen until after rebuild. (A year
       later: and that presumably breaks all the things, but my memory
       is fuzzy on it.)

       Hashes are not checked at commit: most of a clone arrives as
       deltas whose sources come later, so verify-at-commit would
       expand and hash nearly every artifact in one long silent pass.
       The rebuild expands every artifact anyway, so it checks the
       hashes instead, under its own progress messages. fossil(1)'s
       clone skips this check entirely (verify_cancel() in
       clone_cmd()). */
    fsl__repo_verify_cancel(f);
    rc = fsl_cx_txn_end_v2(f, true, false);
    if( 0==rc ){
      fsl_rebuild_opt ropt = fsl_rebuild_opt_empty;
      ropt.verifyHashes = true;
      rc = fsl_repo_rebuild(f, &ropt);
    }
  }

end:
  if( !rc ) rc = xf.rc;
  if( f->error.code ){
    fsl_error_propagate(&f->error, err);
  }else if( !err->code && rc ){
    err->code = rc;
  }
  if( err->code && xf.config ){
    assert( xf.f );
    if( err->msg.used ){
      fsl__xfer_emit(&xf, FSL_MSG_ERROR,
                     fsl_b_cstr(&err->msg));
    }else{
      fsl__xfer_emitf(&xf, FSL_MSG_ERROR,
                     "Sync failed with code %R", err->code);
    }
  }
  fsl_url_cleanup(&url);
  fsl_clone_config_cleanup(&ccc);
  fsl__xfer_cleanup(&xf, rc);
  while( fsl_cx_txn_level(f)!=0 ){
    fsl_cx_txn_end_v2(f, false, true);
  }
  if( 0 && 0==rc ){
    if( f->output.out ){
      fsl_db * const db = fsl_cx_db(f);
      fsl_outputf(f, "****** debugging counts:\n");
      fsl_db_each( db, fsl_stmt_each_f_dump,
                   f, "SELECT COUNT(*) nPhantom FROM {{dbname.repo}}.blob WHERE size<0");
      fsl_db_each( db, fsl_stmt_each_f_dump,
                   f, "SELECT COUNT(*) nNonPhantom FROM {{dbname.repo}}.blob WHERE size>=0");
      fsl_db_each( db, fsl_stmt_each_f_dump,
                   f, "SELECT COUNT(*) nDelta FROM {{dbname.repo}}.delta");

#if 0
      MARKER(("All delta chains:\n"));
      fsl_db_each(
        db, fsl_stmt_each_f_dump, f,
        "SELECT d.rid, d.srcid, b.size "
        "from {{dbname.repo}}.delta d, {{dbname.repo}}.blob b where d.rid=b.rid "
        "order by d.rid"
      );
      MARKER(("Non-deltified roots of deltas:\n"));
      fsl_db_each(
        db, fsl_stmt_each_f_dump, f,
        "SELECT d.srcid, b.size "
        "FROM {{dbname.repo}}.delta d, {{dbname.repo}}.blob b WHERE d.srcid=b.rid "
        "AND d.srcid NOT IN (SELECT rid FROM {{dbname.repo}}.delta) "
        "ORDER BY d.rid"
      );
#endif
#if 0
      MARKER(("Delta chains:\n"));
      fsl_db_each(
        db, fsl_stmt_each_f_dump, f,
        "WITH RECURSIVE "
        "roots(rid,bsz) AS ( "
        "  SELECT DISTINCT d.srcid rid, b.size bsz "
        "  FROM {{dbname.repo}}.delta d, {{dbname.repo}}.blob b "
        "  WHERE b.rid=d.srcid "
        "  AND d.srcid NOT IN (SELECT rid FROM {{dbname.repo}}.delta) "
        "  ORDER BY d.rid"
        "), "
        "dchain(level,srcid,rid,bsz) AS ( "
        "  SELECT 0 level, 0 srcid, r.rid rid, r.bsz "
        "    FROM roots r "
        "  UNION ALL "
        "  SELECT dchain.level+1, delta.srcid, delta.rid, blob.size "
        "    FROM {{dbname.repo}}.delta AS delta, dchain, {{dbname.repo}}.blob AS blob "
        "    WHERE delta.srcid=dchain.rid "
        "    AND delta.rid=blob.rid "
        "  ORDER BY 1, 2 "
        ") "
        "SELECT "
        "substr('..........',1,level*2) || "
        "format('%%d [%%d]->%%d', rid, bsz, srcid) as 'Delta chains'"
        "FROM dchain"
      );
      if( db->error.code ){
        MARKER(("db says: %s: %s\n", fsl_rc_cstr(db->error.code),
                fsl_b_cstr(&db->error.msg)));
      }
#endif
      fsl_db_each( db, fsl_stmt_each_f_dump,
                   f, "SELECT rid,uuid,size, "
                   "octet_length(content), "
                   "octet_length(fsl_uncompress(content)) "
                   "from {{dbname.repo}}.blob order by rid desc" );
    }
  }/*debug output*/
  fsl_cx_finalize(f);
  if( rc && createdRepo ){
    /* Has to wait until after fsl_cx_finalize(). Willfully
       ignoring unlink error. */
    fsl_file_unlink(ccc.repo.filename);
  }
  fsl_xfer_config_cleanup(cxf);
  return rc;
}

void fsl_xfer_metrics_f_dup(fsl_xfer_metrics const *m, void*dest, int theRc){
  (void)theRc;
  *((fsl_xfer_metrics *) dest) = *m;
}

void fsl_xfer_metrics_f_outputer(fsl_xfer_metrics const * const m, void *state,
                                 int theRc){
  if( theRc ) return;
  char const * cardNames[] ={
    NULL,
#define E(T,N) # T,
    fsl_xfcard_map(E)
#undef E
  };
  fsl_outputer * const fo = state;
  assert( fo );


#define out(msg) fo->out(fo->state, msg, sizeof(msg)-1)
#define outf(msg,...) fsl_appendf(fo->out, fo->state, msg, __VA_ARGS__)

  out("fsl_xfer metrics:\n");

  fsl_size_t n = fsl_xfer_metrics_ntx(m, false);
  outf("Cards read:      %," FSL_SIZE_T_PFMT "\n", n);
  if( n ){
    for( int i = fsl_xfcard_e_unknown + 1; i < fsl_xfcard_e_COUNT; ++i){
      if( m->cardsRx[i] ){
        outf("    %-12s %," FSL_SIZE_T_PFMT "\n",
              cardNames[i], m->cardsRx[i]);
      }
    }
    out("\n");
  }
  n = fsl_xfer_metrics_ntx(m, true);
  outf("Cards written:   %," FSL_SIZE_T_PFMT "\n", n);
  if( n ){
    for( int i = fsl_xfcard_e_unknown + 1; i < fsl_xfcard_e_COUNT; ++i){
      if( m->cardsTx[i] ){
        outf("    %-12s %," FSL_SIZE_T_PFMT "\n",
             cardNames[i], m->cardsTx[i]);
      }
    }
    out("\n");
  }

  if( m->bytesWritten ){
    outf("Bytes written:           %," FSL_SIZE_T_PFMT "\n",
          m->bytesWritten);
  }
  if(m->bytesReadUncompressed){
    outf("Bytes read uncompressed: %," FSL_SIZE_T_PFMT "\n",
          m->bytesReadUncompressed);
  }
  if(m->bytesReadCompressed){
    outf("Bytes read compressed:   %," FSL_SIZE_T_PFMT "\n",
          m->bytesReadCompressed);
  }
  if(m->bytesReadWire){
    outf("Bytes read from wire:    %," FSL_SIZE_T_PFMT "\n",
          m->bytesReadWire);
  }
  if( m->largestDecompressedResponse ){
    outf("Largest decompr. buffer: %," FSL_SIZE_T_PFMT "\n",
          m->largestDecompressedResponse);
  }
  if( m->largestCardPayload ){
    outf("Largest card payload:    %," FSL_SIZE_T_PFMT "\n",
          m->largestCardPayload);
  }

  fsl_timer tmt = {.user=0,.system=0,.wall=0};
  int nTimers = 0;
  char const * zTimerFmt =
    "    %-18s %-10.3lf %-10.3lf %-10.3lf %-10.3lf\n"
    /*   label  wall     CPU      user      system */
    ;

  for( unsigned j = 0; j < sizeof(m->timer)/sizeof(m->timer.submit); ++j ){
    /* m->timer... */
    fsl_timer const * tm = 0;
    char const * zPre = 0;
    switch(j){
      case 0:
        tm = &m->timer.submit;
        zPre = "fsl_sc::submit()";
        break;
      case 1:
        tm = &m->timer.read;
        zPre = "fsl_sc::read()";
        break;
      case 2:
        tm = &m->timer.uncompress;
        zPre = "blob uncompress()";
        break;
      case 3:
        tm = &m->timer.process;
        zPre = "processing";
        break;
    }
    assert( tm );
    if( tm->user || tm->system || tm->wall ){
      if( 1==++nTimers ){
        out("\nfsl_xfer timers (ms):\n");
        outf("    %-18s %-10s %-10s %-10s %-10s\n",
               "Purpose", "Wall", "CPU", "User", "System");
      }
      tmt.user += tm->user;
      tmt.system += tm->system;
      tmt.wall += tm->wall;
      outf( zTimerFmt, zPre,
             (double)(tm->wall / 1000.0),
             (double)((tm->user + tm->system) / 1000.0),
             (double)(tm->user / 1000.0),
             (double)(tm->system / 1000.0) );
    }
  }
  if( nTimers>1 ){
    outf( "    %.80c\n", '-');
    outf( zTimerFmt, "                 =",
            (double)(tmt.wall / 1000.0),
            (double)((tmt.user + tmt.system) / 1000.0),
            (double)(tmt.user / 1000.0),
            (double)(tmt.system / 1000.0) );
  }

#undef out
#undef outf
}

static fsl_flag32_t fsl__autosync_ops(fsl_cx *f, fsl_flag32_t ops){
  char * z;
  if( fsl_config_open(f, NULL) ){
    /* The "g" lookups below need the global config db, which may not
       be opened yet. If it cannot be opened, treat its settings as
       unset. */
    fsl_cx_err_reset(f);
  }
  if( 0==(ops & FSL_SYNC_FULL) ){
    /* FSL_SYNC_AUTO alone asks for a full sync. */
    ops |= FSL_SYNC_FULL;
  }
  z = fsl_configs_get_text(
    f, "crg", "libfossil.autosync", 0
  );
  if(!z){
    z = fsl_configs_get_text(f, "crg", "autosync", 0);
  }
  /* No setting means autosync=on, fossil(1)'s default: the requested
     ops stand. */
  if( z ){
    if(!fsl_str_bool(z)){
      ops &= ~FSL_SYNC_FULL;
    }else if(0==fsl_strcmp(z, "pullonly")){
      ops &= ~FSL_SYNC_PUSH;
    }
    fsl_free(z);
  }
  if( fsl_configs_get_bool(f, "crg", false, "dont-push") ){
    ops &= ~FSL_SYNC_PUSH;
  }
  return ops;
}

static int fsl_msg_f__devnull(fsl_msg const *msg, void *state){
  (void)msg; (void)state;
  return 0;
}

fsl_flag32_t fsl_xfer_config_from_flags(fsl_cx * f,
                                        fsl_xfer_config *xc,
                                        fsl_flag32_t flags){
  if(FSL_SYNC_AUTO & flags){
    if( !fsl_needs_repo(f) ) return -1;
    flags = fsl__autosync_ops(f, flags);
    if( f->error.code ) return -1;
  }
  if( !xc->url.used && fsl_cx_last_sync_url(f, &xc->url) ){
    return -1;
  }
  xc->op.pull = !!(FSL_SYNC_PULL & flags);
  xc->op.push = !!(FSL_SYNC_PUSH & flags);
  xc->password.save = !(FSL_SYNC_NO_PW_SAVE & flags);
  xc->password.ignoreSaved = !!(FSL_SYNC_NO_SAVED_PASSWORD & flags);
  if( FSL_SYNC_NO_OUTPUT & flags ){
    xc->listener.callback = fsl_msg_f__devnull;
    xc->listener.state = NULL;
  }
  return flags;
}

void fsl__xfer_config_almost_copy(fsl_xfer_config const *src,
                                  fsl_xfer_config *dest){
  fsl_xfer_config_cleanup(dest);
  *dest = *src;
  /* Undo memory damage that copy does... */
  dest->debug.b = dest->url = fsl_b_empty;
  if( src->url.used ){
    fsl_b_external(&dest->url, src->url.mem, src->url.used);
  }
}


#undef MARKER
#undef fsl__sc_popen_init
#undef fsl__xfer__rch_decl
#undef fsl_xfcard_LowestIdChar
#undef fsl_xfcard_MaxCardNameLen
#undef fsl_xfcard_hash_step_ch
#undef fsl_xfcard_hashS
#undef fsl__xfer__check_rc
/* end of file src/xfer.c */
/* start of file src/zip.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
** Copyright (c) 2017 D. Richard Hipp
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
** known as the "2-Clause License" or "FreeBSD License".)
**
** This program is distributed in the hope that it will be useful,
** but without any warranty; without even the implied warranty of
** merchantability or fitness for a particular purpose.
**
** Author contact information:
**   [email protected]
**   http://www.hwaci.com/drh/
**
*/
/**
   This copy has been modified slightly, and expanded, for use
   with the libfossil project.
*/
#include <assert.h>
#include <zlib.h>
#include <stdlib.h> /* atoi() and friends */
#include <memory.h> /* memset() */

/*
   Write a 16- or 32-bit integer as little-endian into the given buffer.
*/
static void fzip__put16(char *z, int v){
  z[0] = v & 0xff;
  z[1] = (v>>8) & 0xff;
}
static void fzip__put32(char *z, uint32_t v){
  z[0] = v & 0xff;
  z[1] = (v>>8) & 0xff;
  z[2] = (v>>16) & 0xff;
  z[3] = (v>>24) & 0xff;
}

/**
    Set the date and time values from an ISO8601 date string.
 */
static void fzip__timestamp_from_str(fsl_zip_writer *z, const char *zDate){
  int y, m, d;
  int H, M, S;

  y = atoi(zDate);
  m = atoi(&zDate[5]);
  d = atoi(&zDate[8]);
  H = atoi(&zDate[11]);
  M = atoi(&zDate[14]);
  S = atoi(&zDate[17]);
  if( y<1980 ){
    /* The DOS date field cannot hold a date before 1980. */
    y = 1980; m = 1; d = 1; H = 0; M = 0; S = 0;
  }else if( y>2107 ){
    /* The DOS year field is 7 bits wide: 1980 to 2107. */
    y = 2107; m = 12; d = 31; H = 23; M = 59; S = 58;
  }
  z->dosTime = (H<<11) + (M<<5) + (S>>1);
  z->dosDate = ((y-1980)<<9) + (m<<5) + d;
}

fsl_b const * fsl_zip_body( fsl_zip_writer const * const z ){
  return &z->body;
}

void fsl_zip_timestamp_set_julian(fsl_zip_writer * const z, double rDate){
  char buf[20] = {0};
  fsl_julian_to_iso8601(rDate, buf, 0);
  fzip__timestamp_from_str(z, buf);
  z->unixTime = (fsl_time_t)((rDate - 2440587.5)*86400.0);
}

void fsl_zip_timestamp_set_unix(fsl_zip_writer * const z, fsl_time_t epochTime){
  char buf[20] = {0};
  fsl_julian_to_iso8601(fsl_unix_to_julian(epochTime), buf, 0);
  fzip__timestamp_from_str(z, buf);
  z->unixTime = epochTime;
}

/**
    Adds all directories for the given file to the zip if they are not
    in there already. Returns 0 on success, non-0 on error (namely
    OOM).
 */
static int fzip__mkdir(fsl_zip_writer * const z, char const *zName);

/**
    Adds a file entry to zw's zip output. zName is the virtual name of
    the file or directory. If pSrc is NULL then it is assumed that we
    are creating a directory, otherwise the zip's entry is populated
    from pSrc. mPerms specify the fossil-specific permission flags
    from the fsl_fileperm_e enum. If doMkDirs is true then fzip__mkdir()
    is called to create the directory entries for zName, otherwise
    they are not.
 */
static int fzip__file_add(fsl_zip_writer * const zw, char const * zName,
                          fsl_b const * pSrc, int mPerm,
                          char doMkDirs){
  int rc = 0;
  z_stream stream;
  fsl_size_t nameLen;
  int toOut = 0;
  fsl_size_t iStart;
  unsigned int iCRC = 0;
  fsl_size_t nByte = 0;
  fsl_size_t nByteCompr = 0;
  fsl_size_t nBlob;          /* Size of the blob */
  int iMethod;               /* Compression method. */
  int iMode = 0644;          /* Access permissions */
  char *z;
  char zHdr[30];
  char zExTime[13];
  /* The "UT" extra field holds a signed 32-bit Unix time. It is left
     out for times it cannot hold. */
  int const hasExTime = zw->unixTime>=INT32_MIN && zw->unixTime<=INT32_MAX;
  char zBuf[100];
  char zOutBuf[/*historical: 100000*/ 1024 * 32];

  /* Fill in as much of the header as we know.
  */
  if( pSrc && pSrc->used>UINT32_MAX ){
    /* The size fields are 32 bits. */
    return FSL_RC_RANGE;
  }
  nBlob = pSrc ? pSrc->used : 0;
  if( pSrc ){ /* a file entry */
    iMethod = pSrc->used ? 8 : 0 /* don't compress 0-byte files */;
    switch( mPerm ){
      case FSL_FILE_PERM_LINK:  iMode = 0120755;   break;
      case FSL_FILE_PERM_EXE:   iMode = 0100755;   break;
      default:         iMode = 0100644;   break;
    }
  }else{ /* a directory entry */
    iMethod = 0;
    iMode = 040755;
  }
  if(doMkDirs){
    rc = fzip__mkdir(zw, zName)
      /* This causes an extraneous run of fzip__mkdir(),
         but it is harmless other than the waste of search
         time */;
    if(rc) return rc;
  }

  if(zw->rootDir){
    fsl_b_reuse(&zw->scratch);
    rc = fsl_b_appendf(&zw->scratch, "%s%s", zw->rootDir, zName);
    if(rc) return rc;
    zName = fsl_b_cstr(&zw->scratch);
  }

  nameLen = fsl_strlen(zName);
  if( nameLen>0xffff || zw->body.used>UINT32_MAX ){
    /* The name length field is 16 bits and the entry offset
       field is 32 bits. */
    return FSL_RC_RANGE;
  }
  memset(zHdr, 0, sizeof(zHdr));
  fzip__put32(&zHdr[0], 0x04034b50);
  fzip__put16(&zHdr[4], 0x000a);
  fzip__put16(&zHdr[6], 0x0800);
  fzip__put16(&zHdr[8], iMethod);
  fzip__put16(&zHdr[10], zw->dosTime);
  fzip__put16(&zHdr[12], zw->dosDate);
  fzip__put16(&zHdr[26], nameLen);
  fzip__put16(&zHdr[28], hasExTime ? 13 : 0);

  fzip__put16(&zExTime[0], 0x5455);
  fzip__put16(&zExTime[2], 9);
  zExTime[4] = 3;
  fzip__put32(&zExTime[5], zw->unixTime);
  fzip__put32(&zExTime[9], zw->unixTime);


  /* Write the header and filename. */
  iStart = zw->body.used;
  fsl_b_append(&zw->body, zHdr, 30);
  fsl_b_append(&zw->body, zName, nameLen);
  if( hasExTime ) fsl_b_append(&zw->body, zExTime, 13);

  if(zw->body.errCode) return zw->body.errCode;
  else if( nBlob>0 ){
    /* Write the compressed file.  Compute the CRC as we progress. */
    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
    stream.opaque = 0;
    stream.avail_in = pSrc->used;
    stream.next_in = /* (unsigned char*) */pSrc->mem;
    stream.avail_out = sizeof(zOutBuf);
    stream.next_out = (unsigned char*)zOutBuf;
    deflateInit2(&stream, 9, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
    iCRC = crc32(0, stream.next_in, stream.avail_in);
    while( stream.avail_in>0 ){
      deflate(&stream, 0);
      toOut = sizeof(zOutBuf) - stream.avail_out;
      fsl_b_append(&zw->body, zOutBuf, toOut);
      stream.avail_out = sizeof(zOutBuf);
      stream.next_out = (unsigned char*)zOutBuf;
    }
    do{
      stream.avail_out = sizeof(zOutBuf);
      stream.next_out = (unsigned char*)zOutBuf;
      deflate(&stream, Z_FINISH);
      toOut = sizeof(zOutBuf) - stream.avail_out;
      fsl_b_append(&zw->body, zOutBuf, toOut);
    }while( stream.avail_out==0 && 0==zw->body.errCode );
    if(zw->body.errCode) return zw->body.errCode;
    nByte = stream.total_in;
    nByteCompr = stream.total_out;
    deflateEnd(&stream);

    /* Go back and write the header, now that we know the compressed
       file size. */
    z = (char *)zw->body.mem + iStart;
    fzip__put32(&z[14], iCRC);
    fzip__put32(&z[18], nByteCompr);
    fzip__put32(&z[22], nByte);
  }

  /* Make an entry in the tables of contents */
  memset(zBuf, 0, sizeof(zBuf));
  fzip__put32(&zBuf[0], 0x02014b50);
  fzip__put16(&zBuf[4], 0x0317);
  fzip__put16(&zBuf[6], 0x000a);
  fzip__put16(&zBuf[8], 0x0800);
  fzip__put16(&zBuf[10], iMethod);
  fzip__put16(&zBuf[12], zw->dosTime);
  fzip__put16(&zBuf[14], zw->dosDate);
  fzip__put32(&zBuf[16], iCRC);
  fzip__put32(&zBuf[20], nByteCompr);
  fzip__put32(&zBuf[24], nByte);
  fzip__put16(&zBuf[28], nameLen);
  fzip__put16(&zBuf[30], hasExTime ? 9 : 0);
  fzip__put16(&zBuf[32], 0);
  fzip__put16(&zBuf[34], 0);
  fzip__put16(&zBuf[36], 0);
  fzip__put32(&zBuf[38], ((unsigned)iMode)<<16);
  fzip__put32(&zBuf[42], iStart);
  fsl_b_append(&zw->toc, zBuf, 46);
  fsl_b_append(&zw->toc, zName, nameLen);
  if( hasExTime ){
    fzip__put16(&zExTime[2], 5);
    fsl_b_append(&zw->toc, zExTime, 9);
  }
  ++zw->entryCount;
  return zw->toc.errCode;
}

int fzip__mkdir(fsl_zip_writer * const z, char const *zName){
  fsl_size_t i;
  fsl_size_t j;
  int rc = 0;
  char const * dirName;
  fsl_size_t nDir = z->dirs.used;
  for(i=0; zName[i]; i++){
    if( zName[i]=='/' ){
      while(zName[i+1]=='/') ++i /* Skip extra slashes */;
      for(j=0; j<nDir; j++){
        /* See if we know this dir already... */
        dirName = (char const *)z->dirs.list[j];
        if( fsl_strncmp(zName, dirName, i+1)==0
            && 0==dirName[i+1] ) break;
      }
      if( j>=nDir ){
        char * cp = fsl_strndup(zName, (fsl_int_t)i+1);
        if(!cp) return FSL_RC_OOM;
        rc = fsl_list_append(&z->dirs, cp);
        if(rc){
          fsl_free(cp);
          return rc;
        }
        rc = fzip__file_add(z, cp, NULL, 0, 0);
        if(rc) return rc;
      }
    }
  }
  return rc;
}

int fsl_zip_file_add(fsl_zip_writer * const z, char const * zName,
                     fsl_b const * pSrc, int mPerm){
  return fzip__file_add(z, zName, pSrc, mPerm, 1);
}

int fsl_zip_root_set(fsl_zip_writer * const z, char const * zRoot ){
  if(!z) return FSL_RC_MISUSE;
  else if(zRoot && *zRoot && fsl_is_absolute_path(zRoot)){
    return FSL_RC_RANGE;
  }else{
    fsl_free(z->rootDir);
    z->rootDir = NULL;
    if(zRoot && *zRoot){
      /*
        Problem: we have to mkdir zRoot before we assign z->rootDir to
        avoid an interesting ROOT/ROOT dir entry on an otherwise empty
        ZIP. We create the dirs here, instead of during the first file
        insertion (after z->rootDir is set), to work around that.
      */
      char * cp;
      fsl_size_t n = fsl_strlen(zRoot);
      if('/'==zRoot[n-1]){
        /* Keep the slash */
        cp = fsl_strndup(zRoot, (fsl_int_t)n);
      }else{
        /* Add a slash to our copy... */
        cp = (char *)fsl_malloc(n+2);
        if(cp){
          memcpy( cp, zRoot, n );
          cp[n] = '/';
          cp[n+1] = 0;
          ++n;
        }
      }
      if(!cp) return FSL_RC_OOM;
      else{
        int rc;
        n = fsl_file_simplify_name(cp, (fsl_int_t)n, 1);
        assert(n);
        assert('/'==cp[n-1]);
        cp[n-1] = 0;
        rc = fsl_is_simple_pathname(cp, 1);
        cp[n-1] = '/';
        rc = rc
          ? fzip__mkdir(z, cp)
          : FSL_RC_RANGE;
        z->rootDir = cp /* transfer ownership on error as well and let
                           normal downstream clean it up. */;
        return rc;
      }
    }
    return 0;
  }
}

static void fsl__zip_finalize(fsl_zip_writer * const z, bool alsoBody){
  if(z){
    fsl_b_clear(&z->toc);
    fsl_b_clear(&z->scratch);
    fsl_list_visit_free(&z->dirs, 1);
    assert(NULL==z->dirs.list);
    fsl_free(z->rootDir);
    if(alsoBody){
      fsl_b_clear(&z->body);
      *z = fsl_zip_writer_empty;
    }else{
      fsl_b cp = z->body;
      *z = fsl_zip_writer_empty;
      z->body = cp;
    }
  }
}

void fsl_zip_finalize(fsl_zip_writer * const z){
  fsl__zip_finalize(z, 1);
}

int fsl_zip_end( fsl_zip_writer * const z ){
  int rc;
  fsl_int_t iTocStart;
  fsl_int_t iTocEnd;
  char zBuf[30];

  iTocStart = (fsl_int_t)z->body.used;
  if( z->entryCount>0xffff || iTocStart>(fsl_int_t)UINT32_MAX ){
    /* The entry count fields are 16 bits and the directory offset
       field is 32 bits. */
    return FSL_RC_RANGE;
  }
  rc = fsl_b_append(&z->body, z->toc.mem, z->toc.used);
  if(rc) return rc;
  fsl_b_clear(&z->toc);
  iTocEnd = (fsl_int_t)z->body.used;

  memset(zBuf, 0, sizeof(zBuf));
  fzip__put32(&zBuf[0], 0x06054b50);
  fzip__put16(&zBuf[4], 0);
  fzip__put16(&zBuf[6], 0);
  fzip__put16(&zBuf[8], (int)z->entryCount);
  fzip__put16(&zBuf[10], (int)z->entryCount);
  fzip__put32(&zBuf[12], iTocEnd - iTocStart);
  fzip__put32(&zBuf[16], iTocStart);
  fzip__put16(&zBuf[20], 0);

  rc = fsl_b_append(&z->body, zBuf, 22);
  fsl__zip_finalize(z, 0);
  assert(z->body.used);
  return rc;
}

int fsl_zip_end_take( fsl_zip_writer * const z, fsl_b * dest ){
  if(!z) return FSL_RC_MISUSE;
  else{
    int rc;
    if(!dest){
      rc = FSL_RC_MISUSE;
    }else{
      rc = fsl_zip_end(z);
      if(!rc){
        fsl_b_swap( &z->body, dest );
      }
    }
    fsl_zip_finalize( z );
    return rc;
  }
}

int fsl_zip_end_to_filename( fsl_zip_writer * const z, char const * filename ){
  if(!z) return FSL_RC_MISUSE;
  else{
    int rc;
    if(!filename || !*filename){
      rc = FSL_RC_MISUSE;
    }else{
      rc = fsl_zip_end(z);
      if(!rc){
        rc = fsl_b_to_filename(&z->body, filename);
      }
    }
    fsl_zip_finalize( z );
    return rc;
  }
}

struct ZipState{
  fsl_cx * f;
  fsl_id_t vid;
  fsl_card_F_visitor_f progress;
  void * progressState;
  fsl_zip_writer z;
  fsl_b cbuf;
};
typedef struct ZipState ZipState;
static const ZipState ZipState_empty = {
NULL, 0, NULL, NULL,
fsl_zip_writer_empty_m,
fsl_b_empty_m
};

/**
   Sets zs->f's error state to rc with a message which ends with the
   name of file fc and the hash of the check-in being zipped, prefixed
   by zWhat. Returns rc.
*/
static int fsl__zip_file_err(ZipState * const zs, int rc,
                             fsl_card_F const * const fc,
                             char const * zWhat){
  char * const zCi = fsl_rid_to_uuid(zs->f, zs->vid);
  if(zCi){
    rc = fsl_cx_err_set(zs->f, rc, "%s: file %s of check-in %S",
                        zWhat, fc->name, zCi);
    fsl_free(zCi);
  }else{
    rc = fsl_cx_err_set(zs->f, rc, "%s: file %s of check-in RID %"
                        FSL_ID_T_PFMT, zWhat, fc->name, zs->vid);
  }
  return rc;
}

static int fsl_card_F_visitor_zip(fsl_card_F const * fc,
                                   void * state){
  ZipState * zs = (ZipState *)state;
  fsl_id_t frid;
  int rc = 0;
  if(zs->progress){
    rc = (*zs->progress)(fc, zs->progressState);
    if(rc) return rc;
  }
  frid = fsl_uuid_to_rid(zs->f, fc->uuid);
  if(frid<=0){
    rc = zs->f->error.code;
    if(!rc){
      rc = fsl__zip_file_err(zs, FSL_RC_NOT_FOUND, fc,
                             "artifact not found in repository");
    }
  }else{
    fsl_time_t mTime = 0;
    rc = fsl_mtime_of_manifest_file(zs->f, zs->vid, frid, &mTime);
    if(!rc){
      fsl_zip_timestamp_set_unix(&zs->z, mTime);
      zs->cbuf.used = 0;
      rc = fsl_content_get(zs->f, frid, &zs->cbuf);
      if(!rc){
        rc = fsl_zip_file_add(&zs->z, fc->name, &zs->cbuf,
                              fc->perm);
        if(FSL_RC_RANGE==rc){
          fsl__zip_file_err(zs, rc, fc, "too large for a ZIP "
                            "archive without zip64 extensions");
        }else if(rc && FSL_RC_OOM!=rc){
          fsl__zip_file_err(zs, rc, fc, "cannot add file to ZIP");
        }
      }
    }
  }
  return rc;
}

int fsl_repo_zip_sym_to_filename( fsl_cx * const f, char const * sym,
                                  char const *  rootDir,
                                  char const * fileName,
                                  fsl_card_F_visitor_f progress,
                                  void * progressState ){
  int rc;
  fsl_deck mf = fsl_deck_empty;
  ZipState zs = ZipState_empty;
  if(!f) return FSL_RC_MISUSE;
  else if(!sym || !fileName || !*sym || !*fileName){
    return fsl_cx_err_set(f, FSL_RC_MISUSE, "ZIP requires a check-in "
                          "name and an output file name.");
  }
  else if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;

  rc = fsl_deck_load_sym( f, &mf, sym, FSL_SATYPE_CHECKIN );
  if(rc) goto end;

  if(rootDir && *rootDir){
    fsl_time_t rootTime = 0;
    rc = fsl_mtime_of_manifest_file(f, mf.rid, 0, &rootTime);
    if(rc) goto end;
    fsl_zip_timestamp_set_unix(&zs.z, rootTime);
    rc = fsl_zip_root_set( &zs.z, rootDir );
    if(FSL_RC_RANGE==rc){
      rc = fsl_cx_err_set(f, rc, "invalid ZIP root directory name: %s",
                          rootDir);
    }
    if(rc) goto end;
  }

  rc = fsl_deck_F_rewind(&mf);
  if(rc) goto end;

  zs.f = f;
  zs.vid = mf.rid;
  zs.progress = progress;
  zs.progressState = progressState;
  rc = fsl_deck_F_foreach( &mf, fsl_card_F_visitor_zip, &zs);
  if(!rc){
    if(!zs.z.entryCount){
      if(rootDir && *rootDir){
        rc = fsl_zip_file_add( &zs.z, rootDir, NULL, FSL_FILE_PERM_REGULAR );
      }else{
        rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Cowardly refusing to create "
                            "empty ZIP file for repo version [%s].",
                            sym);
      }
      if(rc) goto end;
    }
  }

  /**
     Always write the manifest files to the zip, regardless of
     the repo-level settings. This decision is up for debate. */
  if(rc) goto end;
  else {
    fsl_b * const bManifest = fsl__cx_content_buffer(f);
    fsl_b * const bHash = fsl__cx_scratchpad(f);
    fsl_b * const bTags = fsl__cx_scratchpad(f);
    fsl_b_reuse(bManifest);
    rc = fsl_repo_manifest_write(f, mf.rid, bManifest, bHash, bTags);
    if(rc) goto mf_end;
    rc = fsl_zip_file_add(&zs.z, "manifest", bManifest,
                          FSL_FILE_PERM_REGULAR);
    if(rc) goto mf_end;
    rc = fsl_zip_file_add(&zs.z, "manifest.uuid", bHash,
                          FSL_FILE_PERM_REGULAR);
    if(rc) goto mf_end;
    rc = fsl_zip_file_add(&zs.z, "manifest.tags", bTags,
                          FSL_FILE_PERM_REGULAR);
    mf_end:
    fsl__cx_content_buffer_yield(f);
    fsl__cx_scratchpad_yield(f, bHash);
    fsl__cx_scratchpad_yield(f, bTags);
  }
  if(rc) goto end;
  rc = fsl_zip_end( &zs.z );
  if(FSL_RC_RANGE==rc){
    rc = fsl_cx_err_set(f, rc, "ZIP of check-in %s exceeds 65535 "
                        "entries or 4GiB, the limits of a ZIP archive "
                        "without zip64 extensions", sym);
    goto end;
  }
  if(!rc){
    rc = fsl_b_to_filename( fsl_zip_body(&zs.z), fileName );
    if(rc && FSL_RC_OOM!=rc){
      rc = fsl_cx_err_set(f, rc, "unable to write ZIP file \"%s\": %R",
                          fileName, rc);
    }
  }

  end:
  if(rc && FSL_RC_OOM!=rc && !f->error.code){
    fsl_cx_err_set(f, rc, "error %R creating ZIP of check-in %s",
                   rc, sym);
  }
  fsl_b_clear(&zs.cbuf);
  fsl_zip_finalize(&zs.z);
  fsl_deck_clean(&mf);
  return rc;
}
/* end of file src/zip.c */
/* start of file src/sqlext.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2026 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2026 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*
  libfossil as a SQLite extension: SQL functions which open a fossil
  repository on the calling connection and read and write it inside the
  caller's transactions.

  SELECT fsl_open('project.fossil');   -- ATTACHes it AS repo
  SELECT hash, comment FROM fsl_timeline WHERE type='ci'
   ORDER BY mtime DESC LIMIT 5;
  SELECT fsl_resolve('trunk');         -- the full hash of trunk's tip
  SELECT fsl_file('trunk', 'README.md');
  SELECT fsl_extract('trunk', '/tmp/trunk');  -- its files, no checkout
  SELECT fsl_zip('trunk', 'trunk.zip', 'project');
  SELECT fsl_rebuild();
  SELECT fsl_wiki_save('Notes', '# Notes', 'text/x-markdown');
  SELECT fsl_technote_save('Shipped.', json_object('comment', 'Release'));
  SELECT fsl_forum_post('Hello', json_object('title', 'First post'));
  SELECT fsl_ticket_new(json_object('title', 'Crash', 'status', 'Open'));
  SELECT filename, uuid FROM fsl_foci('trunk');  -- trunk's files
  SELECT fsl_diff('trunk', 'feature');
  SELECT line_no, user, text FROM fsl_annotate('README.md');
  SELECT fsl_commit(json_object('comment','Add notes'));
  SELECT fsl_tag('trunk', 'release', '1.0');
  SELECT fsl_branch('fix', 'trunk');   -- a new branch at trunk's tip
  SELECT fsl_setting('ignore-glob', '*.o');
  SELECT fsl_sync('https://example.com/project', 'pull');
  SELECT fsl_checkout('work');         -- ATTACHes it AS ckout
  SELECT fsl_add('notes.md'), fsl_status();
  SELECT fsl_commit(json_object('comment','Edit notes'));
  SELECT fsl_update(), fsl_merge('feature');
  SELECT fsl_undo();                   -- takes the merge back
  SELECT fsl_stash_save('wip'), fsl_stash_pop();
  SELECT fsl_close();

  Several repositories may be opened on one connection. Each is
  attached under a schema name of its own, and fsl_use() picks the one
  the other functions act on. Their work commits or rolls back
  together with the caller's transaction:

  SELECT fsl_open('app.fossil'), fsl_open('docs.fossil');
  SELECT name, location FROM fsl_repos; -- repo, repo_2
  SELECT count(*) FROM fsl_timeline_2; -- docs.fossil's timeline
  BEGIN;
  SELECT fsl_commit(json_object('comment','Release 2', ...));
  SELECT fsl_use('repo_2');
  SELECT fsl_wiki_save('Release 2', '...', 'text/x-markdown');
  COMMIT;                              -- both, or neither
  SELECT fsl_close('repo_2');

  The loadable extension needs SQLite 3.44.0 or later.

  A program which links libfossil registers the extension with
  sqlite3_auto_extension((void(*)(void))fsl_sqlext_init). The loadable
  build (src/sqlext-loadable.c) has the entry point
  sqlite3_fossilext_init().

  Every write function is SQLITE_DIRECTONLY and must be the only
  thing its statement does, e.g. a plain SELECT, because SQLite cannot
  open a SAVEPOINT while another statement writes. fsl_open(),
  fsl_checkout(), and fsl_close() must run outside of a transaction,
  as SQLite requires for ATTACH and DETACH. So must fsl_update(),
  fsl_merge(), and fsl_revert(), because a ROLLBACK cannot undo the
  files they write.

  fsl_checkout(), and fsl_open() of a checkout, need the connection's
  main db to be a file, not ":memory:" or "", so that SQLite commits
  the repository and the checkout db together.

  A working copy can also live in tables of the connection's main db
  instead of a directory: fsl_checkout('db:NAME' [, VERSION]), where
  NAME is 1 to 64 of A-Z, a-z, 0-9 and _, without regard to case, as
  SQLite's table names: db:Work is db:work, and the tables' names use
  it in lower case. Its files are the rows of main.fslfiles_NAME(name
  TEXT PRIMARY KEY, content BLOB, uuid TEXT, rid INTEGER, mtime
  INTEGER, isexe INTEGER), named relative to the working copy's top, which fsl_repos
  lists as files_table. They are edited with plain SQL, and every other
  function works on them as on a directory's files:

  SELECT fsl_open('project.fossil');
  SELECT fsl_checkout('db:work', 'trunk');
  UPDATE fslfiles_work SET content='# New title' WHERE name='README.md';
  INSERT INTO fslfiles_work(name, content) VALUES('notes.md', '...');
  SELECT fsl_add('notes.md'), fsl_status();
  SELECT fsl_commit(json_object('comment', 'Edit README'));
  SELECT fsl_close();
  SELECT fsl_open('db:work');  -- later, from any connection on this db

  The working copy is copy-on-write. A row whose content is NULL is a
  reference: the file is the blob of the repository whose hash is
  uuid, which stays there, so checking out or updating writes one
  small row per file and copies no file out. rid caches that blob's
  rid in the repository, which fsl_open() refreshes, but uuid decides,
  so a rid naming another blob (as in another clone) does no harm. A row
  with content owns it (uuid, if not NULL, names the blob it last
  referenced). Its bytes are therefore coalesce(content,
  fsl_content(uuid)), with the working copy's repository in use
  (fsl_use()):

  SELECT name, coalesce(content, fsl_content(uuid)) FROM fslfiles_work;

  libfossil's fsl_content() reads in a savepoint, so it cannot be
  called from a statement which writes (INSERT ... SELECT): copy a
  file by its row instead, which copies the reference:
  INSERT INTO fslfiles_work(name, content, uuid, rid) SELECT
  'copy.txt', content, uuid, rid FROM fslfiles_work WHERE name='a.txt'.
  Writing content (UPDATE ... SET content=...) makes a row own it, and
  UPDATE ... SET content=NULL makes it a reference to the blob it last
  referenced again (a row with neither is refused); both are writes,
  which the change scan sees. Content equal to the blob of uuid goes
  back to the reference: at once when libfossil writes it (revert,
  undo, merge, ...), and when SQL writes it, by the change scan
  (fsl_status(), fsl_commit(), ...) which hashes it next, if it can
  write then. A commit turns the rows of the files it saved into
  references to their new blobs, in its transaction; rows it did not
  save, e.g. of files never added, keep their content. Only a blob
  the repository can give, neither a phantom nor shunned, is
  referenced: bytes equal to another are kept as content, and
  checking out a shunned blob, which libfossil still reads, writes its
  bytes as content, as on disk. Checking out a blob which cannot be
  read (a phantom) fails, as on disk. If a referenced blob is shunned
  later, the file reads as "missing" in fsl_status() and
  fsl_commit() refuses, naming it. If it is a phantom (still in the
  blob table, without content), the change scan cannot hash it, so
  fsl_status() and fsl_commit() fail, naming it, as libfossil does for
  a disk checkout whose file and blob are both missing. Either way,
  fsl_rm() and a DELETE of the row, or writing its content, mend it.
  A working copy made before uuid existed has no such column, and
  fsl_open() refuses it, saying what to do.

  Writing a row does not add the file: fsl_add() does, as on disk, and
  deleting a row leaves a "missing" file until fsl_rm(). Names must be
  simple relative paths ("a/b.txt", not "/a", "a/", "a//b", "./a" or
  "a/../b"), and no file may also be a directory ("a" beside "a/b"):
  the table refuses such rows. Names compare as the repository's
  case-sensitive setting says when the working copy is made (COLLATE
  NOCASE if it is off), and fsl_open() refuses the working copy if
  that setting has changed since. A file's mtime is not a time but
  the value of a counter in main.fslclock_NAME, which the table's
  triggers advance and store on each INSERT or UPDATE of content, so
  that libfossil's change scan sees every edit, however it is
  written. A rename moves the row, so fsl_mv() is followed by an
  UPDATE of name, as fossil(1)'s mv is by a file move. libfossil's own
  tables of the working copy (vfile, vvar, ...) are
  main.fslwc_NAME_vfile and so on; nothing is ATTACHed for it, and
  the host's own tables are left alone. Its checkout directory is the
  name "/db:NAME/", which is never looked up on disk. A real
  directory or repository file whose name starts with "db:" must be
  given to fsl_checkout() and fsl_open() as "./db:...". Each NAME's
  tables belong to one repository, and one host db can hold several, of the
  same or of other repositories; but one NAME may not start with
  another's followed by "_" (e.g. db:a and db:a_b), as libfossil keeps
  its tables' names apart. fsl_close() leaves the tables in place,
  since they are data: to delete a working copy, DROP the tables of
  main named fslfiles_NAME and fslclock_NAME and those whose names
  start with fslwc_NAME_. fsl_checkout('db:NAME') refuses a NAME
  which exists, even in part, and if checking out fails part way it
  drops the tables it made, or says which to drop if it cannot.
  fsl_checkout('db:NAME') and fsl_open('db:NAME') must run outside of
  a transaction, because libfossil sets the repository's PRAGMA
  synchronous then. fsl_checkout('db:NAME') must also be the only
  statement running on the connection, reading no table (a plain
  SELECT), because SQLite cannot DROP a table while a statement reads.

  A repository, too, can live in tables of the connection's main db
  instead of a file of its own: repo:NAME, with NAME as for db:NAME
  (repo:Lib is repo:lib), other than "repo" and "repo_N", which name
  file repositories' schemas. Its tables are main.fslrepo_NAME_blob
  and so on (see fsl_repo_open_host()); nothing is ATTACHed for it, and
  the host's own tables, even one named like a repository table (e.g.
  event), are left alone. A db:NAME working copy of it keeps
  repository, working copy and files in the one host db, and a
  transaction across several repositories, of either kind, commits or
  rolls back together. fsl_repos lists it by NAME, with location
  "host":

  SELECT fsl_open('repo:lib', 'me', json_object('create', 1));
  SELECT fsl_import('other.fossil', 'repo:other');  -- a copy of a file
  SELECT fsl_clone('https://example.org/x', 'repo:x');  -- or a remote
  SELECT fsl_use('lib');
  SELECT fsl_checkout('db:draft');
  UPDATE fslfiles_draft SET content='...' WHERE name='doc.md';
  SELECT fsl_commit(json_object('comment', 'Edit doc'));
  SELECT fsl_export('lib', 'lib.fossil');  -- for fossil(1), a server
  SELECT fsl_close();
  SELECT fsl_open('db:draft');  -- later: with its repo:lib

  One NAME may not start with another's followed by "_" (repo:a and
  repo:a_b), nor overlap a working copy's tables (libfossil keeps the
  names of a host db's repositories and working copies apart).
  fsl_close() leaves the tables in place, since they are data;
  fsl_drop('repo:NAME') drops them. A repo:NAME repository is opened
  with fsl_open() outside of a transaction, as a file one is: there is
  nothing to ATTACH, but a ROLLBACK would take with it the TEMP views
  and libfossil's TEMP state which opening adds. fsl_import() and
  fsl_export() need no transaction either, as they ATTACH the file.
  fsl_clone(URL, 'repo:NAME') makes one from a remote repository, all
  or nothing, through a temporary file beside the host db, so that the
  host is only locked for the final copy.

  See fsl_cx_host_db() for what binding a connection involves.
*/
#include <string.h>

/**
   Per-connection state, owned by the connection's "fsl_sqlext"
   client data.
*/
typedef struct FslExt FslExt;
struct FslExt {
  /** The host connection. */
  sqlite3 * db;
  /** The contexts fsl_open() opened on db, in the order it did. */
  fsl_cx ** a;
  /** For each of a, the number in its views' names (fslext_suffix()). */
  unsigned * aSlot;
  unsigned n;
  unsigned cap;
  /** The one of them the fsl_* functions act on (fsl_use()), or NULL
      when nothing is opened. */
  fsl_cx * f;
  /** The storage of each context whose working copy is db:NAME. */
  struct FslextWc * wc;
};

/*
  The storage (fsl_ckout_fs) of a db:NAME working copy: its files are
  the rows of the host's main."fslfiles_NAME" table, with names
  relative to the working copy's top, and with mtime a counter which
  rises with every write of a file's content, kept in the one row of
  main."fslclock_NAME". The table's triggers bump it, so that a write
  by plain SQL is seen by the change scan as a write through libfossil
  is. A row is a reference to the blob named by uuid (content NULL),
  which xWriteBlob() writes and xStat(), xRead() and xHash() look up
  by uuid in the blob table, or owns its content. xWrite() of a
  usable blob's own bytes keeps or restores the reference, and so does
  xHash() of content equal to its uuid's blob. Directories are implicit: the top, and every leading part of a
  stored name. There are no symlinks. Names compare as the
  repository's case-sensitive setting said when the working copy was
  made, which the name column's collation records.

  The files table is made first, before libfossil makes its own
  tables (main."fslwc_NAME_vfile" and so on): a plain CREATE TABLE
  which only one connection can win, so that a fsl_checkout() which
  fails drops only what it made.

  The library passes absolute names under the synthetic root
  "/db:NAME", which never reaches the filesystem. Every operation runs
  its own statement on the host connection, possibly while libfossil's
  statements step and inside its savepoints, so its writes commit or
  roll back with libfossil's.
*/
typedef struct FslextWc FslextWc;
struct FslextWc {
  /** The context this storage is installed on. */
  fsl_cx * f;
  sqlite3 * db;
  /** "fslwc_NAME_": libfossil's table prefix for the working copy. */
  char * zPre;
  /** "fslfiles_NAME": the files table. */
  char * zFiles;
  /** "/db:NAME": the working copy's root. */
  char * zRoot;
  fsl_size_t nRoot;
  /** True if names compare without regard to (ASCII) case. */
  bool nocase;
  FslextWc * next;
};

/** The longest NAME of a db:NAME working copy or repo:NAME
    repository. */
#define FSLEXT_WC_NAME_MAX 64

/**
   If z is zScheme ("db:" or "repo:") followed by NAME, copies NAME to
   zOut in lower case, since SQLite's table names, which NAME is part
   of, ignore case, and returns 1 if NAME is valid (1 to
   FSLEXT_WC_NAME_MAX of [A-Za-z0-9_]), else -1. Returns 0 if z does
   not start with zScheme.
*/
static int fslext_scheme_name(char const * z, char const * zScheme,
                              char zOut[FSLEXT_WC_NAME_MAX+1]){
  fsl_size_t n = 0;
  fsl_size_t const nScheme = fsl_strlen(zScheme);
  zOut[0] = 0;
  if( !z || 0!=fsl_strncmp(z, zScheme, nScheme) ) return 0;
  z += nScheme;
  for( ; z[n] && ('_'==z[n] || fsl_isalnum(z[n])); ++n ){
    if( n<FSLEXT_WC_NAME_MAX ) zOut[n] = (char)fsl_tolower(z[n]);
  }
  if( !n || n>FSLEXT_WC_NAME_MAX || z[n] ){
    zOut[0] = 0;
    return -1;
  }
  zOut[n] = 0;
  return 1;
}

/** fslext_scheme_name() for a db:NAME working copy. */
static int fslext_wc_name(char const * z,
                          char zOut[FSLEXT_WC_NAME_MAX+1]){
  return fslext_scheme_name(z, "db:", zOut);
}

/**
   fslext_scheme_name() for a repo:NAME repository in the host's main
   db (fsl_repo_open_host()), whose table prefix is "fslrepo_NAME_".
   Also -1 for NAME "repo" or "repo_" followed by digits, the names of
   file repositories' schemas, which fsl_repos lists by the same
   column.
*/
static int fslext_repo_name(char const * z,
                            char zOut[FSLEXT_WC_NAME_MAX+1]){
  int const rc = fslext_scheme_name(z, "repo:", zOut);
  if( rc>0 && 0==fsl_strncmp(zOut, "repo", 4)
      && (!zOut[4] || ('_'==zOut[4] && zOut[5]
                       && strspn(zOut+5, "0123456789")
                       ==fsl_strlen(zOut+5))) ){
    zOut[0] = 0;
    return -1;
  }
  return rc;
}

/** The error message for an invalid repo: name. */
#define FSLEXT_REPO_NAME_ERR \
  "A repo: repository's name must be 1 to 64 of A-Z, a-z, 0-9 and _," \
  " other than repo and repo_N, the names of file repositories' schemas."

/** The error message for an invalid db: name. */
#define FSLEXT_WC_NAME_ERR \
  "A db: working copy's name must be 1 to 64 of A-Z, a-z, 0-9 and _."

/**
   Sets *pRel to zName relative to w's root ("" for the root itself).
   Returns FSL_RC_NOT_FOUND if zName is not under the root.
*/
static int fslext_wc_rel(FslextWc const * const w, char const * zName,
                         char const ** pRel){
  if( 0!=fsl_strncmp(zName, w->zRoot, w->nRoot) ) return FSL_RC_NOT_FOUND;
  zName += w->nRoot;
  if( !*zName ){
    *pRel = zName;
    return 0;
  }else if( '/'!=*zName || !zName[1] ){
    return FSL_RC_NOT_FOUND;
  }
  *pRel = zName + 1;
  return 0;
}

/**
   Prepares zTmpl on w's connection, with each "$F" replaced by the
   files table's qualified name, each "$R.TABLE" by the repository's
   table TABLE (main."PTABLE" for a host repository, see
   fsl_repo_open_host()) and each "$C" by the COLLATE clause its names
   compare with. Returns 0 or a FSL_RC_xxx code, with the error on w's
   context.
*/
static int fslext_wc_prep(FslextWc * const w, sqlite3_stmt ** pQ,
                          char const * zTmpl){
  sqlite3_str * const s = sqlite3_str_new(w->db);
  char * zSql;
  int rc;
  *pQ = NULL;
  for( char const * z = zTmpl; *z; ++z ){
    if( '$'==z[0] && 'F'==z[1] ){
      sqlite3_str_appendf(s, "main.\"%w\"", w->zFiles);
      ++z;
    }else if( '$'==z[0] && 'R'==z[1] && '.'==z[2] ){
      char const * const zPre = fsl__db_repo_prefix(w->f->dbMain);
      fsl_size_t n = 0;
      while( '_'==z[3+n] || fsl_isalnum(z[3+n]) ) ++n;
      if( zPre ){
        sqlite3_str_appendf(s, "main.\"%w%.*s\"", zPre, (int)n, z + 3);
      }else{
        sqlite3_str_appendf(s, "\"%w\".%.*s",
                            fsl__db_schema(w->f->dbMain, FSL_DBROLE_REPO),
                            (int)n, z + 3);
      }
      z += 2 + n;
    }else if( '$'==z[0] && 'C'==z[1] ){
      sqlite3_str_appendall(s, w->nocase ? "COLLATE NOCASE"
                            : "COLLATE BINARY");
      ++z;
    }else{
      sqlite3_str_appendchar(s, 1, *z);
    }
  }
  zSql = sqlite3_str_finish(s);
  if( !zSql ) return fsl_cx_err_set(w->f, FSL_RC_OOM, NULL);
  rc = sqlite3_prepare_v2(w->db, zSql, -1, pQ, NULL);
  sqlite3_free(zSql);
  if( SQLITE_OK!=rc ){
    return fsl_cx_err_set(w->f, FSL_RC_DB, "db:%s storage: %s",
                          w->zRoot + 4, sqlite3_errmsg(w->db));
  }
  return 0;
}

/** Steps q once: returns SQLITE_ROW, SQLITE_DONE, or, with the error
    on w's context, FSL_RC_TYPE for a constraint of the files table
    (a name which is no file name, or a file which would also be a
    directory), else FSL_RC_DB. */
static int fslext_wc_step(FslextWc * const w, sqlite3_stmt * const q){
  int const rc = sqlite3_step(q);
  if( SQLITE_ROW==rc || SQLITE_DONE==rc ) return rc;
  return fsl_cx_err_set(w->f, SQLITE_CONSTRAINT==(rc & 0xff)
                        ? FSL_RC_TYPE : FSL_RC_DB, "db:%s storage: %s",
                        w->zRoot + 4, sqlite3_errmsg(w->db));
}

/** Runs zTmpl (see fslext_wc_prep()) with rel bound to ?1 and, if
    nVal>=0, the nVal bytes at pVal as a BLOB to ?2, to completion.
    Sets *pChanges to the number of rows it changed if not NULL. */
static int fslext_wc_exec(FslextWc * const w, char const * zTmpl,
                          char const * rel, void const * pVal,
                          fsl_int_t nVal, int * pChanges){
  sqlite3_stmt * q = NULL;
  int rc = fslext_wc_prep(w, &q, zTmpl);
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, rel, -1, SQLITE_STATIC);
  if( nVal>=0 ){
    /* A NULL pointer would bind NULL, not an empty BLOB. */
    sqlite3_bind_blob64(q, 2, pVal ? pVal : "", (sqlite3_uint64)nVal,
                        SQLITE_STATIC);
  }
  rc = fslext_wc_step(w, q);
  if( SQLITE_DONE==rc || SQLITE_ROW==rc ){
    if( pChanges ) *pChanges = sqlite3_changes(w->db);
    rc = 0;
  }
  sqlite3_finalize(q);
  return rc;
}

/** Sets *pIs to whether the n bytes at rel are a stored file's name
    (n<0: all of rel). */
static int fslext_wc_isfile(FslextWc * const w, char const * rel,
                            int n, bool * const pIs){
  sqlite3_stmt * q = NULL;
  int rc;
  *pIs = false;
  rc = fslext_wc_prep(w, &q, "SELECT 1 FROM $F WHERE name=?1 $C");
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, rel, n, SQLITE_STATIC);
  rc = fslext_wc_step(w, q);
  if( SQLITE_ROW==rc || SQLITE_DONE==rc ){
    *pIs = SQLITE_ROW==rc;
    rc = 0;
  }
  sqlite3_finalize(q);
  return rc;
}

/** Sets *pIs to whether rel is an implicit directory: a leading part
    of a stored name. */
static int fslext_wc_isdir(FslextWc * const w, char const * rel,
                           bool * const pIs){
  sqlite3_stmt * q = NULL;
  int rc;
  *pIs = false;
  rc = fslext_wc_prep(w, &q, "SELECT 1 FROM $F WHERE name>(?1||'/') $C"
                      " AND name<(?1||'0') $C LIMIT 1");
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, rel, -1, SQLITE_STATIC);
  rc = fslext_wc_step(w, q);
  if( SQLITE_ROW==rc || SQLITE_DONE==rc ){
    *pIs = SQLITE_ROW==rc;
    rc = 0;
  }
  sqlite3_finalize(q);
  return rc;
}

/** Sets *pIs to whether a leading part of rel is a stored file, so
    that rel cannot be created: its directory would be that file. */
static int fslext_wc_under_file(FslextWc * const w, char const * rel,
                                bool * const pIs){
  int rc = 0;
  *pIs = false;
  for( int i = 0; 0==rc && !*pIs && rel[i]; ++i ){
    if( '/'==rel[i] ) rc = fslext_wc_isfile(w, rel, i, pIs);
  }
  return rc;
}

/** FSL_RC_TYPE if rel is the name of an implicit directory or lies
    under a stored file, else 0 (or an error). */
static int fslext_wc_creatable(FslextWc * const w, char const * rel){
  bool is = false;
  int rc = fslext_wc_isdir(w, rel, &is);
  if( 0==rc && !is ) rc = fslext_wc_under_file(w, rel, &is);
  return rc ? rc : (is ? FSL_RC_TYPE : 0);
}

/*
  A blob a reference may use: one which is not a phantom and not
  shunned. B is the blob table's alias. Every lookup of a row's blob
  goes by its uuid, which, unlike the rid, names the same bytes in
  any repository; rid only caches it.
*/
#define FSLEXT_WC_BLOB_OK(B)                                          \
  "(" B ".size>=0 AND NOT EXISTS(SELECT 1 FROM $R.shun s"            \
  " WHERE s.uuid=" B ".uuid))"
/* Joins blob b, usable, to the row f's uuid. */
#define FSLEXT_WC_JOIN_BLOB                                           \
  " LEFT JOIN $R.blob b ON b.uuid=f.uuid AND " FSLEXT_WC_BLOB_OK("b")

/**
   Sets *pSame to whether the n bytes at p are blob rid's content, if
   rid is a usable blob (FSLEXT_WC_BLOB_OK): its size, then, if the
   blob's name is a SHA3 hash, the hash of the bytes, else (SHA1,
   which can collide) the blob's bytes themselves.
*/
static int fslext_wc_is_blob(FslextWc * const w, fsl_id_t rid,
                             void const * p, fsl_size_t n,
                             bool * const pSame){
  sqlite3_stmt * q = NULL;
  int rc;
  *pSame = false;
  rc = fslext_wc_prep(w, &q, "SELECT b.uuid FROM $R.blob b"
                      " WHERE b.rid=?1 AND b.size=?2 AND "
                      FSLEXT_WC_BLOB_OK("b"));
  if( rc ) return rc;
  sqlite3_bind_int64(q, 1, (sqlite3_int64)rid);
  sqlite3_bind_int64(q, 2, (sqlite3_int64)n);
  rc = fslext_wc_step(w, q);
  if( SQLITE_ROW==rc ){
    char const * const zUuid = (char const *)sqlite3_column_text(q, 0);
    fsl_size_t const nUuid = (fsl_size_t)sqlite3_column_bytes(q, 0);
    fsl_b h = fsl_b_empty;
    rc = 0;
    if( FSL_STRLEN_K256==nUuid ){
      fsl_b in = fsl_b_empty;
      fsl_b_external(&in, p ? p : "", (fsl_int_t)n);
      in.used = n;
      rc = fsl_sha3sum_buffer(&in, &h);
      if( 0==rc ) *pSame = h.used==nUuid && 0==memcmp(h.mem, zUuid, nUuid);
    }else{
      rc = fsl_content_get(w->f, rid, &h);
      if( 0==rc ) *pSame = h.used==n && (!n || 0==memcmp(h.mem, p, n));
    }
    fsl_b_clear(&h);
  }else if( SQLITE_DONE==rc ){
    rc = 0;
  }
  sqlite3_finalize(q);
  return rc;
}

/**
   Turns file rel, which holds blob rid's bytes as its own content,
   into a reference to rid, dropping the content. The bytes do not
   change, so neither does its mtime, which the trigger advances: it
   is put back. All or nothing, in a savepoint.
*/
static int fslext_wc_to_ref(FslextWc * const w, char const * rel,
                            fsl_id_t rid){
  sqlite3_stmt * q = NULL;
  sqlite3_int64 mtime = 0;
  int rc = fslext_wc_prep(w, &q, "SELECT mtime FROM $F WHERE name=?1 $C");
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, rel, -1, SQLITE_STATIC);
  rc = fslext_wc_step(w, q);
  if( SQLITE_ROW==rc ) mtime = sqlite3_column_int64(q, 0);
  sqlite3_finalize(q);
  if( SQLITE_DONE==rc ) return FSL_RC_NOT_FOUND;
  if( SQLITE_ROW!=rc ) return rc;
  rc = 0;
  if( SQLITE_OK!=sqlite3_exec(w->db, "SAVEPOINT fslwc_ref", 0, 0, 0) ){
    return fsl_cx_err_set(w->f, FSL_RC_DB, "db:%s storage: %s",
                          w->zRoot + 4, sqlite3_errmsg(w->db));
  }
  for( int i = 0; 0==rc && i < 2; ++i ){
    rc = fslext_wc_prep(w, &q, i
                        ? "UPDATE $F SET mtime=?2 WHERE name=?1 $C"
                        : "UPDATE $F SET content=NULL, rid=?2, uuid="
                          "(SELECT uuid FROM $R.blob WHERE rid=?2)"
                          " WHERE name=?1 $C");
    if( rc ) break;
    sqlite3_bind_text(q, 1, rel, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 2, i ? mtime : (sqlite3_int64)rid);
    rc = fslext_wc_step(w, q);
    sqlite3_finalize(q);
    rc = SQLITE_DONE==rc ? 0 : rc;
  }
  sqlite3_exec(w->db, rc ? "ROLLBACK TO fslwc_ref; RELEASE fslwc_ref"
               : "RELEASE fslwc_ref", 0, 0, 0);
  return rc;
}

/** The error for file rel, a reference to blob zUuid, which cannot
    be read: a phantom, shunned, or not in the repository. */
static int fslext_wc_missing(FslextWc * const w, char const * rel,
                             char const * zUuid, int rc){
  char const * zWhy = NULL;
  fsl_cx_err_get(w->f, &zWhy, NULL);
  return fsl_cx_err_set(w->f, rc ? rc : FSL_RC_PHANTOM, "db:%s: file %s "
                        "cannot be read: its blob %.16s is not available "
                        "in the repository%s%s", w->zRoot + 4, rel,
                        zUuid ? zUuid : "?", zWhy && *zWhy ? ": " : ".",
                        zWhy && *zWhy ? zWhy : "");
}

static int fslext_wc_xStat(void * state, char const * zName,
                           fsl_fstat * tgt, bool derefLinks){
  FslextWc * const w = state;
  char const * rel = NULL;
  sqlite3_stmt * q = NULL;
  bool isDir = false;
  int rc = fslext_wc_rel(w, zName, &rel);
  (void)derefLinks;
  if( rc ) return rc;
  *tgt = fsl_fstat_empty;
  if( !*rel ){
    tgt->type = FSL_FSTAT_TYPE_DIR;
    return 0;
  }
  /* A reference's size is its blob's, without reading the blob. One
     whose blob is not available reads as missing, as a deleted file
     does, so that the change scan reports it and nothing reads it as
     empty. */
  rc = fslext_wc_prep(w, &q, "SELECT CASE WHEN f.content IS NOT NULL"
                      " THEN length(CAST(f.content AS BLOB)) ELSE b.size END,"
                      " f.mtime, f.isexe,"
                      " f.content IS NOT NULL OR b.rid IS NOT NULL"
                      " FROM $F f" FSLEXT_WC_JOIN_BLOB
                      " WHERE f.name=?1 $C");
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, rel, -1, SQLITE_STATIC);
  rc = fslext_wc_step(w, q);
  if( SQLITE_ROW==rc && !sqlite3_column_int(q, 3) ){
    rc = FSL_RC_NOT_FOUND;
  }else if( SQLITE_ROW==rc ){
    tgt->type = FSL_FSTAT_TYPE_FILE;
    tgt->size = (fsl_size_t)sqlite3_column_int64(q, 0);
    tgt->mtime = tgt->ctime = (fsl_time_t)sqlite3_column_int64(q, 1);
    if( sqlite3_column_int(q, 2) ) tgt->perm = FSL_FSTAT_PERM_EXE;
    rc = 0;
  }else if( SQLITE_DONE==rc ){
    rc = fslext_wc_isdir(w, rel, &isDir);
    if( 0==rc ){
      if( isDir ) tgt->type = FSL_FSTAT_TYPE_DIR;
      else rc = FSL_RC_NOT_FOUND;
    }
  }
  sqlite3_finalize(q);
  return rc;
}

static int fslext_wc_xRead(void * state, char const * zName, fsl_b * tgt){
  FslextWc * const w = state;
  char const * rel = NULL;
  sqlite3_stmt * q = NULL;
  int rc = fslext_wc_rel(w, zName, &rel);
  if( rc ) return rc;
  if( !*rel ) return FSL_RC_TYPE;
  rc = fslext_wc_prep(w, &q, "SELECT f.content, b.rid, f.uuid"
                      " FROM $F f" FSLEXT_WC_JOIN_BLOB
                      " WHERE f.name=?1 $C");
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, rel, -1, SQLITE_STATIC);
  rc = fslext_wc_step(w, q);
  if( SQLITE_ROW==rc && SQLITE_NULL!=sqlite3_column_type(q, 0) ){
    void const * const p = sqlite3_column_blob(q, 0);
    int const n = sqlite3_column_bytes(q, 0);
    rc = fsl_b_append(tgt, p ? p : "", n);
  }else if( SQLITE_ROW==rc ){
    /* A reference: the blob, straight from the repository. */
    char const * const zUuid = (char const *)sqlite3_column_text(q, 2);
    if( SQLITE_NULL==sqlite3_column_type(q, 1) ){
      fsl_cx_err_reset(w->f);
      rc = fslext_wc_missing(w, rel, zUuid, 0);
    }else{
      rc = fsl_content_get(w->f, (fsl_id_t)sqlite3_column_int64(q, 1), tgt);
      if( rc ) rc = fslext_wc_missing(w, rel, zUuid, rc);
    }
  }else if( SQLITE_DONE==rc ){
    bool isDir = false;
    rc = fslext_wc_isdir(w, rel, &isDir);
    if( 0==rc ) rc = isDir ? FSL_RC_TYPE : FSL_RC_NOT_FOUND;
  }
  sqlite3_finalize(q);
  return rc;
}

/** Sets *pRid to file rel's blob, if it is usable: the one it
    references, or, if it has its own content, the one it last
    referenced, else 0; and *pRef to whether it is a reference. */
static int fslext_wc_rid(FslextWc * const w, char const * rel,
                         fsl_id_t * const pRid, bool * const pRef){
  sqlite3_stmt * q = NULL;
  int rc = fslext_wc_prep(w, &q, "SELECT coalesce(b.rid, 0),"
                          " f.content IS NULL FROM $F f" FSLEXT_WC_JOIN_BLOB
                          " WHERE f.name=?1 $C");
  *pRid = 0;
  *pRef = false;
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, rel, -1, SQLITE_STATIC);
  rc = fslext_wc_step(w, q);
  if( SQLITE_ROW==rc ){
    *pRid = (fsl_id_t)sqlite3_column_int64(q, 0);
    *pRef = 0!=sqlite3_column_int(q, 1);
  }
  sqlite3_finalize(q);
  return (SQLITE_ROW==rc || SQLITE_DONE==rc) ? 0 : rc;
}

static int fslext_wc_xWrite(void * state, char const * zName,
                            void const * src, fsl_size_t n){
  FslextWc * const w = state;
  char const * rel = NULL;
  fsl_id_t rid = 0;
  bool isRef = false, same = false;
  int rc = fslext_wc_rel(w, zName, &rel);
  if( rc ) return FSL_RC_ACCESS /* outside of the working copy */;
  if( !*rel ) return FSL_RC_TYPE;
  rc = fslext_wc_creatable(w, rel);
  if( 0==rc ) rc = fslext_wc_rid(w, rel, &rid, &isRef);
  if( 0==rc && rid>0 ) rc = fslext_wc_is_blob(w, rid, src, n, &same);
  if( rc ) return rc;
  if( same ){
    /* The bytes of the usable blob the file references, or last
       referenced: keep (or go back to) the reference rather than a
       copy. Writing a reference's own bytes back changes nothing,
       not even its mtime, so the file reads as unchanged, as such a
       write does on disk to fossil(1)'s hash check. Going back from
       other content does change the file, so the trigger advances
       its mtime. A blob which is not usable keeps the bytes as
       content, so that nothing written is lost. */
    return isRef ? 0 : fslext_wc_exec(w, "UPDATE $F SET content=NULL"
                                      " WHERE name=?1 $C", rel, NULL, -1,
                                      NULL);
  }
  /* The triggers set mtime. An existing file keeps its executable
     bit, as on disk, and uuid and rid, the blob it last referenced. */
  return fslext_wc_exec(w, "INSERT INTO $F(name, content) VALUES(?1, ?2)"
                        " ON CONFLICT(name) DO UPDATE"
                        " SET content=excluded.content",
                        rel, src, (fsl_int_t)n, NULL);
}

static int fslext_wc_xWriteBlob(void * state, char const * zName,
                                fsl_id_t rid){
  FslextWc * const w = state;
  char const * rel = NULL;
  sqlite3_stmt * q = NULL;
  int rc = fslext_wc_rel(w, zName, &rel);
  if( rc ) return FSL_RC_ACCESS;
  if( !*rel ) return FSL_RC_TYPE;
  rc = fslext_wc_creatable(w, rel);
  if( rc ) return rc;
  /* Only the reference: the blob stays in the repository. Setting
     content, even to NULL, fires the trigger which advances the
     clock and the file's mtime, as any write does. A blob which is
     not usable as a reference (see FSLEXT_WC_BLOB_OK) but can be
     read, i.e. a shunned one, is written as content, as on disk; one
     which cannot be read is refused, as writing it to disk fails. */
  rc = fslext_wc_prep(w, &q, "INSERT INTO $F(name, content, rid, uuid)"
                      " SELECT ?1, NULL, b.rid, b.uuid FROM $R.blob b"
                      " WHERE b.rid=?2 AND " FSLEXT_WC_BLOB_OK("b")
                      " ON CONFLICT(name) DO UPDATE"
                      " SET content=NULL, rid=excluded.rid,"
                      " uuid=excluded.uuid");
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, rel, -1, SQLITE_STATIC);
  sqlite3_bind_int64(q, 2, (sqlite3_int64)rid);
  rc = fslext_wc_step(w, q);
  sqlite3_finalize(q);
  if( SQLITE_DONE!=rc ) return rc;
  if( 0==sqlite3_changes(w->db) ){
    fsl_b b = fsl_b_empty;
    rc = fsl_content_get(w->f, rid, &b);
    if( 0==rc ){
      rc = fslext_wc_xWrite(w, zName, b.mem, b.used);
    }else{
      char * const zUuid = fsl_rid_to_uuid(w->f, rid);
      fsl_cx_err_reset(w->f);
      rc = fslext_wc_missing(w, rel, zUuid, rc);
      fsl_free(zUuid);
    }
    fsl_b_clear(&b);
    return rc;
  }
  return 0;
}

static int fslext_wc_xHash(void * state, char const * zName, bool sha3,
                           fsl_b * tgt){
  FslextWc * const w = state;
  char const * rel = NULL;
  sqlite3_stmt * q = NULL;
  fsl_size_t const nWant = sha3 ? FSL_STRLEN_K256 : FSL_STRLEN_SHA1;
  int rc = fslext_wc_rel(w, zName, &rel);
  if( rc ) return rc;
  if( !*rel ) return FSL_RC_TYPE;
  rc = fslext_wc_prep(w, &q, "SELECT f.content, b.rid, b.uuid"
                      " FROM $F f" FSLEXT_WC_JOIN_BLOB
                      " WHERE f.name=?1 $C");
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, rel, -1, SQLITE_STATIC);
  rc = fslext_wc_step(w, q);
  if( SQLITE_ROW==rc ){
    char const * const zUuid = (char const *)sqlite3_column_text(q, 2);
    bool const isRef = SQLITE_NULL==sqlite3_column_type(q, 0);
    fsl_id_t const rid = (fsl_id_t)sqlite3_column_int64(q, 1);
    bool const uuidFits = zUuid
      && (fsl_size_t)sqlite3_column_bytes(q, 2)==nWant;
    if( isRef && uuidFits ){
      /* A reference's hash is its blob's name: no read. */
      rc = fsl_b_append(tgt, zUuid, (fsl_int_t)nWant);
    }else if( isRef ){
      /* The blob has a hash of the other kind, or is missing. */
      fsl_b b = fsl_b_empty;
      rc = fslext_wc_xRead(w, zName, &b);
      if( 0==rc ){
        rc = sha3 ? fsl_sha3sum_buffer(&b, tgt) : fsl_sha1sum_buffer(&b, tgt);
      }
      fsl_b_clear(&b);
    }else{
      fsl_b in = fsl_b_empty;
      void const * const p = sqlite3_column_blob(q, 0);
      fsl_size_t const n = (fsl_size_t)sqlite3_column_bytes(q, 0);
      bool same = false;
      fsl_b_external(&in, p ? p : "", (fsl_int_t)n);
      in.used = n;
      rc = sha3 ? fsl_sha3sum_buffer(&in, tgt) : fsl_sha1sum_buffer(&in, tgt);
      if( 0==rc && uuidFits && tgt->used==nWant
          && 0==memcmp(tgt->mem, zUuid, nWant)
          && fslext_wc_is_blob(w, rid, p, n, &same) ){
        fsl_cx_err_reset(w->f) /* not restored, which is harmless */;
        same = false;
      }
      if( same ){
        /* Content written back by SQL as its blob's bytes: the change
           scan turns it back into the reference. That is a
           convenience, so a failure to write (e.g. a read-only
           connection) leaves the content and the scan goes on, with
           the hash it asked for. */
        char * const zRel = sqlite3_mprintf("%s", rel);
        sqlite3_finalize(q);
        q = NULL;
        if( !zRel || fslext_wc_to_ref(w, zRel, rid) ){
          fsl_cx_err_reset(w->f);
        }
        sqlite3_free(zRel);
      }
    }
  }else if( SQLITE_DONE==rc ){
    rc = FSL_RC_NOT_FOUND;
  }
  sqlite3_finalize(q);
  return rc;
}

static int fslext_wc_xCopy(void * state, char const * zFrom,
                           char const * zTo){
  FslextWc * const w = state;
  char const * relFrom = NULL, * relTo = NULL;
  sqlite3_stmt * q = NULL;
  bool is = false;
  int rc = fslext_wc_rel(w, zFrom, &relFrom);
  if( rc ) return rc;
  if( fslext_wc_rel(w, zTo, &relTo) || !*relTo ) return FSL_RC_ACCESS;
  if( !*relFrom ) return FSL_RC_TYPE;
  rc = fslext_wc_isfile(w, relFrom, -1, &is);
  if( 0==rc && !is ){
    rc = fslext_wc_isdir(w, relFrom, &is);
    if( 0==rc ) rc = is ? FSL_RC_TYPE : FSL_RC_NOT_FOUND;
  }
  if( 0==rc ) rc = fslext_wc_creatable(w, relTo);
  if( rc ) return rc;
  /* As fsl_file_copy(): the bytes, and the executable bit if the
     source has it. A reference copies as the reference. */
  rc = fslext_wc_prep(w, &q, "INSERT INTO $F(name, content, rid, uuid,"
                      " isexe) SELECT ?2, content, rid, uuid, isexe FROM $F"
                      " WHERE name=?1 $C ON CONFLICT(name) DO UPDATE"
                      " SET content=excluded.content, rid=excluded.rid,"
                      " uuid=excluded.uuid, isexe=max(isexe, excluded.isexe)");
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, relFrom, -1, SQLITE_STATIC);
  sqlite3_bind_text(q, 2, relTo, -1, SQLITE_STATIC);
  rc = fslext_wc_step(w, q);
  sqlite3_finalize(q);
  return SQLITE_DONE==rc ? 0 : rc;
}

/** Runs zTmpl with rel as ?1. Returns FSL_RC_NOT_FOUND if it changed
    no row, FSL_RC_TYPE if rel is the root or an implicit directory. */
static int fslext_wc_file_exec(FslextWc * const w, char const * zName,
                               char const * zTmpl){
  char const * rel = NULL;
  int nChanged = 0;
  int rc = fslext_wc_rel(w, zName, &rel);
  if( rc ) return rc;
  if( !*rel ) return FSL_RC_TYPE;
  rc = fslext_wc_exec(w, zTmpl, rel, NULL, -1, &nChanged);
  if( 0==rc && !nChanged ){
    bool isDir = false;
    rc = fslext_wc_isdir(w, rel, &isDir);
    if( 0==rc ) rc = isDir ? FSL_RC_TYPE : FSL_RC_NOT_FOUND;
  }
  return rc;
}

static int fslext_wc_xUnlink(void * state, char const * zName){
  return fslext_wc_file_exec(state, zName,
                             "DELETE FROM $F WHERE name=?1 $C");
}

static int fslext_wc_xRename(void * state, char const * zFrom,
                             char const * zTo){
  FslextWc * const w = state;
  char const * relFrom = NULL, * relTo = NULL;
  sqlite3_stmt * q = NULL;
  bool is = false;
  int rc = fslext_wc_rel(w, zFrom, &relFrom);
  if( rc ) return rc;
  if( fslext_wc_rel(w, zTo, &relTo) || !*relTo ) return FSL_RC_ACCESS;
  if( !*relFrom ) return FSL_RC_TYPE;
  rc = fslext_wc_isfile(w, relFrom, -1, &is);
  if( 0==rc && !is ){
    rc = fslext_wc_isdir(w, relFrom, &is);
    if( 0==rc ) rc = is ? FSL_RC_TYPE : FSL_RC_NOT_FOUND;
  }
  if( 0==rc && 0==fsl_strcmp(relFrom, relTo) ) return 0;
  /* As on disk, a file replaces a file but not a directory, and
     cannot go under a file. */
  if( 0==rc ) rc = fslext_wc_creatable(w, relTo);
  if( rc ) return rc;
  /* A rename keeps the file's content, mtime and executable bit, as
     on disk. A name differing only in case, where names ignore it, is
     the same row. */
  rc = fslext_wc_prep(w, &q, "DELETE FROM $F WHERE name=?2 $C"
                      " AND NOT name=?1 $C");
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, relFrom, -1, SQLITE_STATIC);
  sqlite3_bind_text(q, 2, relTo, -1, SQLITE_STATIC);
  rc = fslext_wc_step(w, q);
  sqlite3_finalize(q);
  if( SQLITE_DONE!=rc && SQLITE_ROW!=rc ) return rc;
  rc = fslext_wc_prep(w, &q, "UPDATE $F SET name=?2 WHERE name=?1 $C");
  if( rc ) return rc;
  sqlite3_bind_text(q, 1, relFrom, -1, SQLITE_STATIC);
  sqlite3_bind_text(q, 2, relTo, -1, SQLITE_STATIC);
  rc = fslext_wc_step(w, q);
  sqlite3_finalize(q);
  return (SQLITE_DONE==rc || SQLITE_ROW==rc) ? 0 : rc;
}

static int fslext_wc_xMkdir(void * state, char const * zName){
  FslextWc * const w = state;
  char const * rel = NULL;
  bool is = false;
  int rc;
  if( fslext_wc_rel(w, zName, &rel) ) return FSL_RC_ACCESS;
  if( !*rel ) return 0;
  /* Directories are implicit: one exists once a file is written in
     it. A file of that name, or above it, is in the way. */
  rc = fslext_wc_isfile(w, rel, -1, &is);
  if( 0==rc && !is ) rc = fslext_wc_under_file(w, rel, &is);
  return rc ? rc : (is ? FSL_RC_TYPE : 0);
}

static int fslext_wc_xRmdir(void * state, char const * zName){
  FslextWc * const w = state;
  char const * rel = NULL;
  bool isDir = false;
  int rc = fslext_wc_rel(w, zName, &rel);
  if( rc ) return rc;
  if( !*rel ){
    /* The top: removable only when empty, and it stays anyway. */
    sqlite3_stmt * q = NULL;
    rc = fslext_wc_prep(w, &q, "SELECT 1 FROM $F LIMIT 1");
    if( rc ) return rc;
    rc = fslext_wc_step(w, q);
    sqlite3_finalize(q);
    if( SQLITE_ROW==rc ) return FSL_RC_ACCESS /* not empty */;
    return SQLITE_DONE==rc ? 0 : rc;
  }
  /* An implicit directory which exists has files in it. */
  rc = fslext_wc_isdir(w, rel, &isDir);
  if( rc ) return rc;
  return isDir ? FSL_RC_ACCESS : FSL_RC_NOT_FOUND;
}

static int fslext_wc_xDirList(void * state, char const * zDir,
                              fsl_ckout_fs_dir_f cb, void * cbState){
  FslextWc * const w = state;
  char const * rel = NULL;
  sqlite3_stmt * q = NULL;
  fsl_b prev = fsl_b_empty;
  bool any = false;
  int rc = fslext_wc_rel(w, zDir, &rel);
  if( rc ) return rc;
  if( *rel ){
    rc = fslext_wc_prep(w, &q, "SELECT substr(name, length(?1)+2)"
                        " FROM $F WHERE name>(?1||'/') $C"
                        " AND name<(?1||'0') $C ORDER BY name $C");
  }else{
    rc = fslext_wc_prep(w, &q, "SELECT name FROM $F ORDER BY name $C");
  }
  if( rc ) return rc;
  if( *rel ) sqlite3_bind_text(q, 1, rel, -1, SQLITE_STATIC);
  while( SQLITE_ROW==(rc = fslext_wc_step(w, q)) ){
    /* The entry is the name's first part. Names sharing it are
       adjacent in name order, so each entry is reported once. */
    char const * const z = (char const *)sqlite3_column_text(q, 0);
    fsl_size_t n = 0;
    any = true;
    if( !z ) continue;
    while( z[n] && '/'!=z[n] ) ++n;
    if( prev.used==n && 0==(w->nocase
                            ? fsl_strnicmp((char const *)prev.mem, z,
                                           (fsl_int_t)n)
                            : memcmp(prev.mem, z, n)) ){
      continue;
    }
    fsl_b_reuse(&prev);
    rc = fsl_b_append(&prev, z, (fsl_int_t)n);
    if( 0==rc ) rc = cb(cbState, fsl_b_cstr(&prev));
    if( rc ) break;
  }
  if( SQLITE_DONE==rc && *rel && !any ){
    bool is = false;
    rc = fslext_wc_isfile(w, rel, -1, &is);
    if( 0==rc ) rc = is ? FSL_RC_TYPE : FSL_RC_NOT_FOUND;
  }else if( SQLITE_DONE==rc ){
    rc = 0;
  }
  sqlite3_finalize(q);
  fsl_b_clear(&prev);
  return rc;
}

static int fslext_wc_xExecSet(void * state, char const * zName,
                              bool isExec){
  return fslext_wc_file_exec(state, zName, isExec
                             ? "UPDATE $F SET isexe=1 WHERE name=?1 $C"
                             : "UPDATE $F SET isexe=0 WHERE name=?1 $C");
}

static int fslext_wc_xMtimeSet(void * state, char const * zName,
                               fsl_time_t mtime){
  FslextWc * const w = state;
  char * const zSql = sqlite3_mprintf("UPDATE $F SET mtime=%lld"
                                      " WHERE name=?1 $C",
                                      (long long)mtime);
  int rc;
  if( !zSql ) return FSL_RC_OOM;
  /* The given time, which the library reads back: a later write sets
     the counter, which differs from it. */
  rc = fslext_wc_file_exec(w, zName, zSql);
  sqlite3_free(zSql);
  return rc;
}

/** Fills *fs with w's storage. */
static void fslext_wc_fs(FslextWc * const w, fsl_ckout_fs * const fs){
  *fs = fsl_ckout_fs_empty;
  fs->iVersion = 2;
  fs->xStat = fslext_wc_xStat;
  fs->xRead = fslext_wc_xRead;
  fs->xWrite = fslext_wc_xWrite;
  fs->xUnlink = fslext_wc_xUnlink;
  fs->xRename = fslext_wc_xRename;
  fs->xMkdir = fslext_wc_xMkdir;
  fs->xRmdir = fslext_wc_xRmdir;
  fs->xDirList = fslext_wc_xDirList;
  fs->xExecSet = fslext_wc_xExecSet;
  fs->xMtimeSet = fslext_wc_xMtimeSet;
  fs->xCopy = fslext_wc_xCopy;
  fs->xHash = fslext_wc_xHash;
  fs->xWriteBlob = fslext_wc_xWriteBlob;
  fs->state = w;
}

/** w's storage, installed on f, or NULL. */
static FslextWc * fslext_wc_of(FslExt const * const ext,
                               fsl_cx const * const f){
  FslextWc * w = ext->wc;
  while( w && w->f!=f ) w = w->next;
  return w;
}

static void fslext_wc_delete(FslextWc * const w){
  if( w ){
    sqlite3_free(w->zPre);
    sqlite3_free(w->zFiles);
    sqlite3_free(w->zRoot);
    sqlite3_free(w);
  }
}

/**
   Creates the storage of working copy db:zName (lower case), whose
   names ignore case if nocase is true, and installs it on f. Returns
   0 or a FSL_RC_xxx code, with f's error state set.
*/
static int fslext_wc_install(FslExt * const ext, fsl_cx * const f,
                             char const * zName, bool nocase){
  fsl_ckout_fs fs;
  FslextWc * const w = sqlite3_malloc(sizeof(*w));
  int rc;
  if( !w ) return fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  memset(w, 0, sizeof(*w));
  w->f = f;
  w->db = ext->db;
  w->nocase = nocase;
  w->zPre = sqlite3_mprintf("fslwc_%s_", zName);
  w->zFiles = sqlite3_mprintf("fslfiles_%s", zName);
  w->zRoot = sqlite3_mprintf("/db:%s", zName);
  if( !w->zPre || !w->zFiles || !w->zRoot ){
    fslext_wc_delete(w);
    return fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  }
  w->nRoot = fsl_strlen(w->zRoot);
  fslext_wc_fs(w, &fs);
  rc = fsl_cx_ckout_fs(f, &fs, NULL);
  if( rc ){
    fslext_wc_delete(w);
    return fsl_cx_err_set(f, rc, "Cannot install the working copy's "
                          "storage.");
  }
  w->next = ext->wc;
  ext->wc = w;
  return 0;
}

/** Frees the storage of f. Call it while f is still alive, once
    nothing uses its storage (e.g. after fsl_close_dbs()). */
static void fslext_wc_free(FslExt * const ext, fsl_cx const * const f){
  for( FslextWc ** pp = &ext->wc; *pp; pp = &(*pp)->next ){
    FslextWc * const w = *pp;
    if( w->f==f ){
      *pp = w->next;
      fslext_wc_delete(w);
      return;
    }
  }
}

/**
   Returns true if the calling function's statement is the only one
   running on ext's connection and reads no table, else sets an error
   on cx naming zFunc and returns false. Making a db: working copy
   needs that, so that it can DROP the tables it made if it fails,
   which SQLite refuses while any statement reads.
*/
static bool fslext_wc_alone(sqlite3_context * const cx,
                            FslExt * const ext, char const * zFunc){
  int nBusy = 0;
  bool ok;
  char * z;
  for( sqlite3_stmt * q = sqlite3_next_stmt(ext->db, NULL); q;
       q = sqlite3_next_stmt(ext->db, q) ){
    if( sqlite3_stmt_busy(q) ) ++nBusy;
  }
  /* Only the calling statement is running, but it may read a table
     (SELECT fsl_checkout(...) FROM t): try what the cleanup does. */
  ok = nBusy<=1
    && SQLITE_OK==sqlite3_exec(ext->db, "SAVEPOINT fslext_probe;"
                               "CREATE TEMP TABLE fslext_drop_probe(x);"
                               "DROP TABLE temp.fslext_drop_probe;"
                               "RELEASE fslext_probe;", 0, 0, 0);
  if( ok ) return true;
  if( nBusy<=1 ){
    sqlite3_exec(ext->db, "ROLLBACK TO fslext_probe;"
                 " RELEASE fslext_probe;", 0, 0, 0);
  }
  z = sqlite3_mprintf("%s() of a db: working copy must be the only "
                      "statement running on the connection, and may "
                      "not read a table, e.g. a plain SELECT.", zFunc);
  sqlite3_result_error(cx, z ? z : "Another statement is running.", -1);
  sqlite3_free(z);
  return false;
}

/**
   Sets *pFiles and *pVvar to whether the host's main db has working
   copy db:zName's files table and libfossil's vvar table. Returns 0
   or SQLITE_NOMEM or another SQLite error code.
*/
static int fslext_wc_tables(sqlite3 * const db, char const * zName,
                            bool * const pFiles, bool * const pVvar){
  sqlite3_stmt * q = NULL;
  char * const zSql = sqlite3_mprintf(
    "SELECT (SELECT count(*) FROM main.sqlite_schema WHERE type='table'"
    "  AND name='fslfiles_'||?1 COLLATE NOCASE),"
    " (SELECT count(*) FROM main.sqlite_schema WHERE type='table'"
    "  AND name='fslwc_'||?1||'_vvar' COLLATE NOCASE)");
  int rc;
  *pFiles = *pVvar = false;
  if( !zSql ) return SQLITE_NOMEM;
  rc = sqlite3_prepare_v2(db, zSql, -1, &q, NULL);
  sqlite3_free(zSql);
  if( SQLITE_OK!=rc ) return rc;
  sqlite3_bind_text(q, 1, zName, -1, SQLITE_STATIC);
  rc = sqlite3_step(q);
  if( SQLITE_ROW==rc ){
    *pFiles = sqlite3_column_int(q, 0)>0;
    *pVvar = sqlite3_column_int(q, 1)>0;
    rc = 0;
  }
  sqlite3_finalize(q);
  return rc;
}

/** Sets f's error for db:zName having only some of its tables: as
    another connection's fsl_checkout() has them while it runs, and as
    one which could not clean up leaves them. */
static int fslext_wc_incomplete(fsl_cx * const f, char const * zName,
                                bool hasFiles){
  return fsl_cx_err_set(f, FSL_RC_CONSISTENCY, "Working copy db:%s is "
                        "incomplete: this database has %s but not %s. "
                        "Another connection may still be creating it: "
                        "try again. If none is, remove it: DROP the "
                        "tables of main named fslfiles_%s, fslclock_%s "
                        "and fslwc_%s_*.",
                        zName, hasFiles ? "its files table" : "its "
                        "checkout tables", hasFiles ? "its checkout "
                        "tables" : "its files table", zName, zName, zName);
}

/**
   Creates working copy db:zName's files and clock tables and their
   triggers, in one savepoint. The files table's names ignore case if
   nocase. Fails, creating nothing, if the files table exists. Returns
   0 or a FSL_RC_xxx code, with f's error state set.
*/
static int fslext_wc_create(sqlite3 * const db, fsl_cx * const f,
                            char const * zName, bool nocase){
  /* The files table first: if it exists, nothing else is made. The
     CHECK takes only simple relative names. The "dir" triggers refuse
     a file whose name is a directory of another's, or the other way
     around, with lookups of the primary key only: each leading
     directory of the new name by equality, and the names under it as
     one range. The others make every write of a file's content,
     through libfossil or by plain SQL, advance the clock and give the
     file the clock's value as its mtime. Turning a file into a
     reference sets content (to NULL), so it is such a write too. If the clock's row is gone,
     they put it back, at the newest mtime, so that it never goes
     back. */
  char const * const zC = nocase ? "COLLATE NOCASE" : "COLLATE BINARY";
  char const * const zDirConflict =
    "SELECT RAISE(ABORT, 'a file cannot also be a directory')"
    " WHERE EXISTS(SELECT 1 FROM \"fslfiles_%s\" WHERE %s"
    "  name>(new.name||'/') %s AND name<(new.name||'0') %s)"
    " OR EXISTS(SELECT 1 FROM \"fslfiles_%s\" WHERE %s name IN"
    "  (WITH RECURSIVE p(i) AS (SELECT instr(new.name, '/')"
    "   UNION ALL SELECT i+instr(substr(new.name, i+1), '/') FROM p"
    "   WHERE instr(substr(new.name, i+1), '/')>0)"
    "   SELECT substr(new.name, 1, i-1) FROM p WHERE i>0));";
  char const * const zOther = "rowid<>old.rowid AND";
  char * const zIns = sqlite3_mprintf(zDirConflict, zName, "", zC, zC,
                                      zName, "");
  char * const zUpd = sqlite3_mprintf(zDirConflict, zName, zOther, zC, zC,
                                      zName, zOther);
  char * const zTick = sqlite3_mprintf(
    "INSERT INTO \"fslclock_%s\"(n) SELECT (SELECT coalesce(max(mtime), 0)"
    " FROM \"fslfiles_%s\") WHERE NOT EXISTS(SELECT 1 FROM \"fslclock_%s\");"
    " UPDATE \"fslclock_%s\" SET n=n+1;"
    " UPDATE \"fslfiles_%s\" SET mtime=(SELECT max(n) FROM \"fslclock_%s\")"
    " WHERE rowid=new.rowid;", zName, zName, zName, zName, zName, zName);
  char * zSql = (zIns && zUpd && zTick) ? sqlite3_mprintf(
    "SAVEPOINT fslwc_create;"
    "CREATE TABLE main.\"fslfiles_%s\"("
    " name TEXT PRIMARY KEY %s CHECK(typeof(name)='text' AND name<>''"
    "  AND instr(CAST(name AS BLOB), x'00')=0"
    "  AND substr(name, 1, 1)<>'/' AND substr(name, -1)<>'/'"
    "  AND instr(name, '//')=0 AND name NOT IN ('.', '..')"
    "  AND NOT (name GLOB './*' OR name GLOB '../*' OR name GLOB '*/./*'"
    "   OR name GLOB '*/../*' OR name GLOB '*/.' OR name GLOB '*/..')),"
    " content BLOB, uuid TEXT, rid INTEGER,"
    " mtime INTEGER NOT NULL DEFAULT 0, isexe INTEGER NOT NULL DEFAULT 0,"
    " CHECK(content IS NOT NULL OR uuid IS NOT NULL));"
    "CREATE TABLE main.\"fslclock_%s\"(n INTEGER NOT NULL);"
    "INSERT INTO main.\"fslclock_%s\" VALUES(0);"
    "CREATE TRIGGER main.\"fsltrig_%s_dir\" BEFORE INSERT"
    " ON \"fslfiles_%s\" BEGIN %s END;"
    "CREATE TRIGGER main.\"fsltrig_%s_dirmv\" BEFORE UPDATE OF name"
    " ON \"fslfiles_%s\" BEGIN %s END;"
    "CREATE TRIGGER main.\"fsltrig_%s_ins\" AFTER INSERT"
    " ON \"fslfiles_%s\" BEGIN %s END;"
    "CREATE TRIGGER main.\"fsltrig_%s_upd\" AFTER UPDATE OF content"
    " ON \"fslfiles_%s\" BEGIN %s END;"
    "RELEASE fslwc_create;",
    zName, zC, zName, zName,
    zName, zName, zIns, zName, zName, zUpd,
    zName, zName, zTick, zName, zName, zTick) : NULL;
  int rc = 0;
  sqlite3_free(zIns);
  sqlite3_free(zUpd);
  sqlite3_free(zTick);
  if( !zSql ){
    rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  }else if( SQLITE_OK!=sqlite3_exec(db, zSql, 0, 0, 0) ){
    rc = fsl_cx_err_set(f, FSL_RC_DB, "Cannot create the tables of "
                        "working copy db:%s: %s", zName,
                        sqlite3_errmsg(db));
    sqlite3_exec(db, "ROLLBACK TO fslwc_create; RELEASE fslwc_create;",
                 0, 0, 0);
  }
  sqlite3_free(zSql);
  return rc;
}

/**
   Drops working copy db:zName's files and clock tables, with their
   triggers, and, if ckoutToo, libfossil's tables of it (those of main
   whose names start with "fslwc_" zName "_"), in one savepoint.
   Returns NULL on success, else an error message, to be freed with
   sqlite3_free().
*/
static char * fslext_wc_drop(sqlite3 * const db, char const * zName,
                             bool ckoutToo){
  sqlite3_stmt * q = NULL;
  sqlite3_str * const s = sqlite3_str_new(db);
  char * zSql, * zErr = NULL;
  int rc = SQLITE_OK;
  sqlite3_str_appendf(s, "SAVEPOINT fslwc_drop;"
                      "DROP TABLE IF EXISTS main.\"fslfiles_%w\";"
                      "DROP TABLE IF EXISTS main.\"fslclock_%w\";",
                      zName, zName);
  if( ckoutToo ){
    rc = sqlite3_prepare_v2(db, "SELECT name FROM main.sqlite_schema"
                            " WHERE type='table' AND substr(name, 1,"
                            " length(?1))=?1 COLLATE NOCASE", -1, &q, NULL);
    if( SQLITE_OK==rc ){
      char * const zPre = sqlite3_mprintf("fslwc_%s_", zName);
      sqlite3_bind_text(q, 1, zPre, -1, sqlite3_free);
      while( SQLITE_ROW==(rc = sqlite3_step(q)) ){
        sqlite3_str_appendf(s, "DROP TABLE IF EXISTS main.\"%w\";",
                            sqlite3_column_text(q, 0));
      }
      if( SQLITE_DONE==rc ) rc = SQLITE_OK;
    }
    if( SQLITE_OK!=rc ) zErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
    sqlite3_finalize(q);
  }
  sqlite3_str_appendall(s, "RELEASE fslwc_drop;");
  zSql = sqlite3_str_finish(s);
  if( !zErr && !zSql ){
    zErr = sqlite3_mprintf("out of memory");
  }else if( !zErr && SQLITE_OK!=sqlite3_exec(db, zSql, 0, 0, 0) ){
    zErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
    sqlite3_exec(db, "ROLLBACK TO fslwc_drop; RELEASE fslwc_drop;",
                 0, 0, 0);
  }
  sqlite3_free(zSql);
  return zErr;
}

/**
   Opens on f the repository which a checkout records as zRef
   (fsl__cx_repo_ref()): a file, or tables of the host's main db.
*/
static int fslext_repo_open_ref(fsl_cx * const f, char const * zRef){
  return 0==fsl_strncmp(zRef, FSL__REPO_HOST_REF,
                        sizeof(FSL__REPO_HOST_REF)-1)
    ? fsl_repo_open_host(f, zRef + sizeof(FSL__REPO_HOST_REF)-1)
    : fsl_repo_open(f, zRef);
}

/**
   fsl_open('db:NAME') on the new context f: checks that the working
   copy is whole, opens the repository it records, installs its
   storage and reopens its checkout tables, which libfossil checks
   against the repository.
*/
static int fslext_open_wc(FslExt * const ext, fsl_cx * const f,
                          char const * zName){
  fsl_repo_open_ckout_opt oOpt = fsl_repo_open_ckout_opt_empty;
  sqlite3_stmt * q = NULL;
  char * zRepo = NULL, * zSql = NULL;
  bool hasFiles = false, hasVvar = false, nocase = false;
  FslextWc * w;
  int rc = fslext_wc_tables(ext->db, zName, &hasFiles, &hasVvar);
  if( rc ){
    return fsl_cx_err_set(f, FSL_RC_DB, "%s", sqlite3_errmsg(ext->db));
  }else if( !hasFiles && !hasVvar ){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "This database has no "
                          "working copy db:%s.", zName);
  }else if( !hasFiles || !hasVvar ){
    return fslext_wc_incomplete(f, zName, hasFiles);
  }
  zSql = sqlite3_mprintf("SELECT (SELECT value FROM main.\"fslwc_%w_vvar\""
                         " WHERE name='repository'),"
                         " (SELECT coll FROM pragma_index_xinfo("
                         "'sqlite_autoindex_fslfiles_%w_1', 'main')"
                         " WHERE cid=0),"
                         " EXISTS(SELECT 1 FROM pragma_table_info("
                         "'fslfiles_%w', 'main') WHERE name='uuid')",
                         zName, zName, zName);
  if( !zSql ) return fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  rc = sqlite3_prepare_v2(ext->db, zSql, -1, &q, NULL);
  sqlite3_free(zSql);
  if( SQLITE_OK!=rc || SQLITE_ROW!=sqlite3_step(q) ){
    rc = fsl_cx_err_set(f, FSL_RC_DB, "%s", sqlite3_errmsg(ext->db));
  }else if( SQLITE_NULL==sqlite3_column_type(q, 0)
            || SQLITE_NULL==sqlite3_column_type(q, 1) ){
    rc = fslext_wc_incomplete(f, zName, false);
  }else if( !sqlite3_column_int(q, 2) ){
    rc = fsl_cx_err_set(f, FSL_RC_CONSISTENCY, "Working copy db:%s has "
                        "the files table of an earlier version, with no "
                        "uuid column, which this version cannot open. "
                        "Commit or copy out its changes with that "
                        "version, DROP its tables (fslfiles_%s, "
                        "fslclock_%s and fslwc_%s_*), and check it out "
                        "again.", zName, zName, zName, zName);
  }else{
    nocase = 0==sqlite3_stricmp("NOCASE",
                                (char const *)sqlite3_column_text(q, 1));
    zRepo = sqlite3_mprintf("%s", sqlite3_column_text(q, 0));
    if( !zRepo ) rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  }
  sqlite3_finalize(q);
  if( 0==rc ) rc = fslext_repo_open_ref(f, zRepo);
  if( 0==rc && nocase==fsl_cx_is_case_sensitive(f, false) ){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "Working copy db:%s compares "
                        "file names %s case, but repository %s now says "
                        "they are case-%s.", zName,
                        nocase ? "without regard to" : "by", zRepo,
                        nocase ? "sensitive" : "insensitive");
  }
  sqlite3_free(zRepo);
  if( 0==rc ) rc = fslext_wc_install(ext, f, zName, nocase);
  if( rc ) return rc;
  w = fslext_wc_of(ext, f);
  oOpt.targetDir = w->zRoot;
  oOpt.fileOverwritePolicy = FSL_OVERWRITE_NEVER;
  oOpt.checkForOpenedCkout = false;
  oOpt.hostTablePrefix = w->zPre;
  rc = fsl_repo_open_ckout(f, &oOpt);
  if( 0==rc ){
    /* A row's uuid names its blob; its rid only caches the blob's rid
       in this repository, which differs in another clone of it (or
       after a reconstruct). Refresh the cache, which nothing depends
       on but the documented reads by rid: the storage looks blobs up
       by uuid. Best effort, e.g. on a read-only connection. */
    sqlite3_stmt * qh = NULL;
    if( 0==fslext_wc_prep(w, &qh, "UPDATE $F AS f SET rid=(SELECT b.rid"
                          " FROM $R.blob b WHERE b.uuid=f.uuid)"
                          " WHERE f.uuid IS NOT NULL AND f.rid IS NOT"
                          " (SELECT b.rid FROM $R.blob b WHERE b.uuid=f.uuid)") ){
      sqlite3_step(qh);
    }
    sqlite3_finalize(qh);
    fsl_cx_err_reset(f);
  }
  return rc;
}

/**
   Releases ext's contexts without running SQL on the host connection,
   for use while the connection is closing.
*/
static void fslext_release(FslExt * const ext){
  for( unsigned i = 0; i < ext->n; ++i ){
    fsl_cx_host_db_closing(ext->a[i]);
    fsl_cx_finalize(ext->a[i]);
  }
  while( ext->wc ){
    FslextWc * const w = ext->wc;
    ext->wc = w->next;
    fslext_wc_delete(w);
  }
  sqlite3_free(ext->a);
  ext->a = NULL;
  sqlite3_free(ext->aSlot);
  ext->aSlot = NULL;
  ext->n = ext->cap = 0;
  ext->f = NULL;
}

/** The table prefix of a repo:NAME repository. */
#define FSLEXT_REPO_PREFIX "fslrepo_"

/**
   The name of f's repository, as fsl_repos lists it: the schema name
   of a file repository ("repo", "repo_2", ...), the NAME of a
   repo:NAME one, or the whole table prefix of another host repository,
   which a checkout can record (see fsl_repo_open_host()). Sets *pn to
   its length: a NAME is part of its table prefix, "fslrepo_NAME_",
   and not NUL-terminated.
*/
static char const * fslext_name(fsl_cx * const f, fsl_size_t * const pn){
  char const * const zPre = fsl__db_repo_prefix(f->dbMain);
  char const * z;
  if( zPre ){
    fsl_size_t const n = fsl_strlen(zPre);
    fsl_size_t const nP = sizeof(FSLEXT_REPO_PREFIX)-1;
    if( n>nP+1 && 0==fsl_strncmp(zPre, FSLEXT_REPO_PREFIX, nP) ){
      *pn = n - nP - 1;
      return zPre + nP;
    }
    *pn = n;
    return zPre;
  }
  z = fsl__db_schema(f->dbMain, FSL_DBROLE_REPO);
  *pn = fsl_strlen(z);
  return z;
}

/**
   Writes the suffix of the names of f's views to zOut: "" for the
   first repository fsl_open() opens, "_2" for the second while the
   first is opened, and so on, the lowest number not in use. For file
   repositories alone that is the number of their schema name, which
   libfossil picks the same way ("repo", "repo_2", ...).
*/
static void fslext_suffix(FslExt const * const ext, fsl_cx * const f,
                          char zOut[16]){
  unsigned k = 1;
  for( unsigned i = 0; i < ext->n; ++i ){
    if( ext->a[i]==f ) k = ext->aSlot[i];
  }
  if( k>1 ) fsl_snprintf(zOut, 16, "_%u", k);
  else zOut[0] = 0;
}

/**
   The context whose repository has name zName in fsl_repos, or which
   is repo:zName, without regard to the case of NAME, or NULL.
*/
static fsl_cx * fslext_find(FslExt const * const ext,
                            char const * zName){
  char zRepo[FSLEXT_WC_NAME_MAX+1];
  bool const isHost = fslext_repo_name(zName, zRepo)>0;
  for( unsigned i = 0; zName && i < ext->n; ++i ){
    fsl_size_t n = 0;
    char const * const z = fslext_name(ext->a[i], &n);
    bool const host = !!fsl__db_repo_prefix(ext->a[i]->dbMain);
    if( isHost ? (host && n==fsl_strlen(zRepo)
                  && 0==fsl_strncmp(z, zRepo, n))
        : (host ? (n==fsl_strlen(zName) && 0==fsl_strnicmp(z, zName, n))
           : 0==fsl_strcmp(zName, z)) ){
      return ext->a[i];
    }
  }
  return NULL;
}

/** Makes f (NULL if nothing is opened) the context the fsl_*
    functions, and libfossil's own SQL functions in the host's SQL,
    act on. */
static void fslext_use(FslExt * const ext, fsl_cx * const f){
  ext->f = f;
  fsl__cxreg_default_set(ext->db, f);
}

/** Adds f to ext's contexts. Returns 0 or SQLITE_NOMEM. */
static int fslext_keep(FslExt * const ext, fsl_cx * const f){
  unsigned k = 1;
  if( ext->n==ext->cap ){
    unsigned const cap = ext->cap ? ext->cap * 2 : 4;
    fsl_cx ** const a = sqlite3_realloc64(ext->a, cap * sizeof(fsl_cx*));
    unsigned * aSlot;
    if( !a ) return SQLITE_NOMEM;
    ext->a = a;
    aSlot = sqlite3_realloc64(ext->aSlot, cap * sizeof(unsigned));
    if( !aSlot ) return SQLITE_NOMEM;
    ext->aSlot = aSlot;
    ext->cap = cap;
  }
  for( unsigned i = 0; i < ext->n; ++i ){
    /* The lowest view number not in use (fslext_suffix()). */
    if( ext->aSlot[i]==k ){
      ++k;
      i = (unsigned)-1;
    }
  }
  ext->aSlot[ext->n] = k;
  ext->a[ext->n++] = f;
  return 0;
}

/** Removes f from ext's contexts, without closing it. If it was the
    current one, the first remaining one becomes current. */
static void fslext_forget(FslExt * const ext, fsl_cx * const f){
  for( unsigned i = 0; i < ext->n; ++i ){
    if( ext->a[i]==f ){
      memmove(&ext->a[i], &ext->a[i+1], (ext->n - i - 1) * sizeof(fsl_cx*));
      memmove(&ext->aSlot[i], &ext->aSlot[i+1],
              (ext->n - i - 1) * sizeof(unsigned));
      --ext->n;
      break;
    }
  }
  if( ext->f==f ) fslext_use(ext, ext->n ? ext->a[0] : NULL);
}

/** True if a libfossil context which fsl_open() did not open uses
    ext's connection. */
static bool fslext_foreign(FslExt const * const ext){
  fsl__cxreg const * const r = sqlite3_get_clientdata(ext->db,
                                                      "fsl_cxreg");
  for( unsigned i = 0; r && i < r->n; ++i ){
    unsigned j = 0;
    while( j < ext->n && ext->a[j]!=r->a[i] ) ++j;
    if( j==ext->n ) return true;
  }
  return false;
}

static void fslext_free(void * p){
  FslExt * const ext = p;
  fslext_release(ext);
  sqlite3_free(ext);
}

/*
  The "fsl_sqlext_life" eponymous virtual table holds no rows. Its only
  job is xDisconnect: sqlite3_close() disconnects virtual tables before
  it checks for unfinalized statements, so libfossil can finalize its
  cached statements there and the close succeeds. fsl_open() connects
  it.
*/
typedef struct {
  sqlite3_vtab base;
  FslExt * ext;
} FslExtLife;

static int fslextLifeConnect(sqlite3 *db, void *pAux, int argc,
                             const char *const*argv,
                             sqlite3_vtab **ppVtab, char **pzErr){
  FslExtLife * p;
  int rc;
  (void)argc; (void)argv; (void)pzErr;
  rc = sqlite3_declare_vtab(db, "CREATE TABLE x(x)");
  if( rc ) return rc;
  p = sqlite3_malloc(sizeof(*p));
  if( !p ) return SQLITE_NOMEM;
  memset(p, 0, sizeof(*p));
  p->ext = pAux;
  *ppVtab = &p->base;
  return SQLITE_OK;
}

static int fslextLifeDisconnect(sqlite3_vtab *pVtab){
  FslExtLife * const p = (FslExtLife*)pVtab;
  fslext_release(p->ext);
  sqlite3_free(p);
  return SQLITE_OK;
}

static int fslextLifeBestIndex(sqlite3_vtab *tab,
                               sqlite3_index_info *pIdx){
  (void)tab;
  pIdx->estimatedCost = 1;
  return SQLITE_OK;
}

static int fslextLifeOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCur){
  sqlite3_vtab_cursor * const c = sqlite3_malloc(sizeof(*c));
  (void)p;
  if( !c ) return SQLITE_NOMEM;
  memset(c, 0, sizeof(*c));
  *ppCur = c;
  return SQLITE_OK;
}

static int fslextLifeClose(sqlite3_vtab_cursor *c){
  sqlite3_free(c);
  return SQLITE_OK;
}

static int fslextLifeFilter(sqlite3_vtab_cursor *c, int idxNum,
                            const char *idxStr, int argc,
                            sqlite3_value **argv){
  (void)c; (void)idxNum; (void)idxStr; (void)argc; (void)argv;
  return SQLITE_OK;
}

static int fslextLifeNext(sqlite3_vtab_cursor *c){
  (void)c;
  return SQLITE_OK;
}

static int fslextLifeEof(sqlite3_vtab_cursor *c){
  (void)c;
  return 1;
}

static int fslextLifeColumn(sqlite3_vtab_cursor *c, sqlite3_context *cx,
                            int i){
  (void)c; (void)cx; (void)i;
  return SQLITE_OK;
}

static int fslextLifeRowid(sqlite3_vtab_cursor *c, sqlite3_int64 *pRowid){
  (void)c;
  *pRowid = 0;
  return SQLITE_OK;
}

static sqlite3_module fslextLifeModule = {
  0,                       /* iVersion */
  0,                       /* xCreate: eponymous-only */
  fslextLifeConnect,       /* xConnect */
  fslextLifeBestIndex,     /* xBestIndex */
  fslextLifeDisconnect,    /* xDisconnect */
  0,                       /* xDestroy */
  fslextLifeOpen,          /* xOpen */
  fslextLifeClose,         /* xClose */
  fslextLifeFilter,        /* xFilter */
  fslextLifeNext,          /* xNext */
  fslextLifeEof,           /* xEof */
  fslextLifeColumn,        /* xColumn */
  fslextLifeRowid,         /* xRowid */
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

/**
   Sets cx's error result from f's error state, or from rc if f has
   none, then clears f's error state.
*/
static void fslext_error(sqlite3_context * const cx, fsl_cx * const f,
                         int rc){
  char const * zMsg = NULL;
  if( f ) fsl_cx_err_get(f, &zMsg, NULL);
  if( zMsg && *zMsg ){
    sqlite3_result_error(cx, zMsg, -1);
  }else{
    char * const z = sqlite3_mprintf("libfossil error: %s",
                                     fsl_rc_cstr(rc));
    sqlite3_result_error(cx, z ? z : "libfossil error", -1);
    sqlite3_free(z);
  }
  if( f ) fsl_cx_err_reset(f);
}

/**
   Returns the bound context, or sets an error on cx and returns NULL.
*/
static fsl_cx * fslext_cx(sqlite3_context * const cx){
  FslExt * const ext = sqlite3_user_data(cx);
  if( !ext->f ){
    sqlite3_result_error(cx, "No repository is opened. "
                         "Use fsl_open() first.", -1);
    return NULL;
  }
  if( fsl__cx_host_rollback_check(ext->f) ){
    fslext_error(cx, ext->f, FSL_RC_DB);
    return NULL;
  }
  return ext->f;
}

/**
   Sets cx's result to the hash of rid.
*/
static void fslext_result_hash(sqlite3_context * const cx,
                               fsl_cx * const f, fsl_id_t rid){
  char * const zHash = fsl_rid_to_uuid(f, rid);
  if( zHash ){
    sqlite3_result_text(cx, zHash, -1, SQLITE_TRANSIENT);
    fsl_free(zHash);
  }else{
    fslext_error(cx, f, FSL_RC_NOT_FOUND);
  }
}

/*
  fsl_timeline

  A TEMP view which fsl_open() creates and fsl_close() drops: one row
  per timeline event of the opened repository, in no particular order.
  Each repository gets views of its own, named after its schema:
  fsl_timeline, fsl_history and fsl_branches for "repo",
  fsl_timeline_2 and so on for "repo_2".

  - hash: the event artifact's full hash.
  - type: "ci" (check-in), "w" (wiki), "e" (tech note), "f" (forum
    post), "t" (ticket change) or "g" (tag change).
  - time: UTC, "YYYY-MM-DD HH:MM:SS". mtime: the same as a Julian day.
  - user, comment: as the timeline shows them, i.e. with any edits
    from tags applied.
  - branch: a check-in's branch, else NULL.
  - tags: a check-in's other symbolic tags, comma-separated, or NULL.
  - parents: a check-in's parent hashes, comma-separated, primary
    parent first, or NULL for a root check-in.

  SELECT hash, user, comment FROM fsl_timeline
   WHERE type='ci' AND branch='trunk' ORDER BY mtime DESC LIMIT 10;

  It reads libfossil's event, tagxref and plink tables, which libfossil
  keeps for every artifact, sub-manifest trees included. branch, tags
  and parents are subqueries run per row, so select them only when
  needed on large repositories.

  fsl_history

  A TEMP view like fsl_timeline: one row per change to a file in a
  check-in, from libfossil's mlink table, compared with the check-in's
  primary parent.

  - name: the file's name in that check-in.
  - checkin, time, mtime, user: the check-in, as in fsl_timeline.
  - change: "added", "edited", "deleted", "renamed" (prior_name holds
    the old name; the content may have changed too) or "merged" (added
    by a merge).
  - hash: the file's content hash, or NULL if deleted.

  SELECT time, user, change FROM fsl_history
   WHERE name='src/main.c' ORDER BY mtime DESC;

  fsl_branches

  A TEMP view like fsl_timeline: one row per branch.

  - name: the branch name.
  - tip, time, mtime: the branch's most recent check-in.
  - closed: 1 if that check-in carries the "closed" tag, else 0.
  - checkins: how many check-ins are on the branch.

  SELECT name, time FROM fsl_branches WHERE NOT closed ORDER BY name;

  fsl_foci(VERSION)

  Not this file's: libfossil's own table-valued function (src/foci.c),
  which fsl_open() makes available along with libfossil's other SQL
  functions. One row per file in check-in VERSION:

  - filename: the file's name.
  - uuid: its content hash.
  - perm: "w" (regular), "x" (executable) or "l" (symlink).
  - previousName: its name in the parent check-in if it was renamed
    there, else an empty string.
  - checkinID: the check-in's internal record id (rid), not its hash;
    see fsl_resolve() for that.

  SELECT filename, fsl_content(uuid) FROM fsl_foci('trunk')
   WHERE filename LIKE 'src/%';
*/
static char const zFslextViews[] =
  /* libfossil's fsl__init_ancestor() (vpath.c) creates this TEMP table
     on first use, e.g. by fsl_annotate(). Created then, inside a host
     statement, the schema change aborts that statement when the
     library's savepoint is released. Created here, it is already
     there. The definition must match vpath.c's. */
  "CREATE TEMP TABLE IF NOT EXISTS {{temp.ancestor}}("
  " rid INT UNIQUE, generation INTEGER PRIMARY KEY);"
  "CREATE TEMP VIEW IF NOT EXISTS fsl_timeline%s AS SELECT"
  " b.uuid AS hash, e.type AS type,"
  " datetime(e.mtime) AS time, e.mtime AS mtime,"
  " coalesce(e.euser, e.user) AS user,"
  " coalesce(e.ecomment, e.comment) AS comment,"
  " (SELECT x.value FROM {{dbname.repo}}.tagxref x, {{dbname.repo}}.tag t"
  "   WHERE x.rid=e.objid AND x.tagid=t.tagid AND t.tagname='branch'"
  "   AND x.tagtype>0) AS branch,"
  " (SELECT group_concat(substr(t.tagname,5), ',') FROM {{dbname.repo}}.tagxref x,"
  "   {{dbname.repo}}.tag t WHERE x.rid=e.objid AND x.tagid=t.tagid"
  "   AND x.tagtype>0 AND t.tagname GLOB 'sym-*'"
  "   AND t.tagname<>'sym-'||coalesce((SELECT x2.value"
  "     FROM {{dbname.repo}}.tagxref x2, {{dbname.repo}}.tag t2 WHERE x2.rid=e.objid"
  "     AND x2.tagid=t2.tagid AND t2.tagname='branch'"
  "     AND x2.tagtype>0),'')) AS tags,"
  " (SELECT group_concat(uuid, ',') FROM (SELECT pb.uuid"
  "   FROM {{dbname.repo}}.plink p, {{dbname.repo}}.blob pb"
  "   WHERE p.cid=e.objid AND pb.rid=p.pid"
  "   ORDER BY p.isprim DESC, p.pid)) AS parents"
  " FROM {{dbname.repo}}.event e, {{dbname.repo}}.blob b WHERE b.rid=e.objid;"
  "CREATE TEMP VIEW IF NOT EXISTS fsl_history%s AS SELECT"
  " fn.name AS name, cb.uuid AS checkin,"
  " datetime(e.mtime) AS time, e.mtime AS mtime,"
  " coalesce(e.euser, e.user) AS user,"
  " CASE WHEN ml.fid=0 THEN 'deleted'"
  "  WHEN ml.pid=0 THEN 'added'"
  "  WHEN ml.pid<0 THEN 'merged'"
  "  WHEN ml.pfnid>0 THEN 'renamed'"
  "  ELSE 'edited' END AS change,"
  " fb.uuid AS hash, pfn.name AS prior_name"
  " FROM {{dbname.repo}}.mlink ml JOIN {{dbname.repo}}.filename fn ON fn.fnid=ml.fnid"
  " JOIN {{dbname.repo}}.blob cb ON cb.rid=ml.mid"
  " JOIN {{dbname.repo}}.event e ON e.objid=ml.mid"
  " LEFT JOIN {{dbname.repo}}.blob fb ON fb.rid=ml.fid AND ml.fid>0"
  " LEFT JOIN {{dbname.repo}}.filename pfn ON pfn.fnid=ml.pfnid AND ml.pfnid>0"
  " WHERE NOT ml.isaux;"
  "CREATE TEMP VIEW IF NOT EXISTS fsl_branches%s AS SELECT"
  " br.name AS name, b.uuid AS tip,"
  " datetime(br.mt) AS time, br.mt AS mtime,"
  " EXISTS(SELECT 1 FROM {{dbname.repo}}.tagxref c, {{dbname.repo}}.tag ct"
  "   WHERE c.rid=br.rid AND c.tagid=ct.tagid AND ct.tagname='closed'"
  "   AND c.tagtype>0) AS closed,"
  " br.n AS checkins"
  " FROM (SELECT x.value AS name, x.rid AS rid, max(e.mtime) AS mt,"
  "   count(*) AS n FROM {{dbname.repo}}.tagxref x"
  "   JOIN {{dbname.repo}}.tag t ON t.tagid=x.tagid AND t.tagname='branch'"
  "   JOIN {{dbname.repo}}.event e ON e.objid=x.rid AND e.type='ci'"
  "   WHERE x.tagtype>0 GROUP BY x.value) br"
  " JOIN {{dbname.repo}}.blob b ON b.rid=br.rid;";

/*
  The views fsl_open() creates for a repository, for fsl_close() to
  drop. Like zFslextViews, a format string taking the views' name
  suffix (fslext_suffix()) three times.
*/
static char const zFslextViewsDrop[] =
  "DROP VIEW IF EXISTS temp.fsl_timeline%s;"
  "DROP VIEW IF EXISTS temp.fsl_history%s;"
  "DROP VIEW IF EXISTS temp.fsl_branches%s;";

/** Drops the views of the repository whose views carry suffix zSfx
    (fslext_suffix()). Returns 0 or an SQLite result code. */
static int fslext_views_drop(FslExt * const ext, char const * zSfx){
  char * const zDrop = sqlite3_mprintf(zFslextViewsDrop,
                                       zSfx, zSfx, zSfx);
  int const rc = zDrop ? sqlite3_exec(ext->db, zDrop, 0, 0, 0)
    : SQLITE_NOMEM;
  sqlite3_free(zDrop);
  return rc;
}

/**
   Creates f's views (zFslextViews), with ext's suffix for them, and
   its TEMP table "ancestor",
   through f so that its placeholders expand. Returns 0 or a libfossil
   result code, with f's error state set.
*/
static int fslext_views_create(FslExt const * const ext, fsl_cx * const f){
  char zSfx[16];
  fslext_suffix(ext, f, zSfx);
  return fsl_cx_exec_multi(f, zFslextViews, zSfx, zSfx, zSfx);
}

/**
   The checks fsl_open() and fsl_import() (zFunc) make before they
   open anything: outside of a transaction, and no libfossil context
   which this extension did not open on the connection. Returns true,
   or false with cx's error result set.
*/
static bool fslext_open_ok(sqlite3_context * const cx,
                           FslExt const * const ext, char const * zFunc){
  if( !sqlite3_get_autocommit(ext->db) ){
    /* For a repo:NAME repository there is nothing to ATTACH, but a
       ROLLBACK would take with it the TEMP views and libfossil's TEMP
       state which opening adds. */
    char * const z = sqlite3_mprintf("%s() cannot run inside a "
                                     "transaction.", zFunc);
    sqlite3_result_error(cx, z ? z : "out of memory", -1);
    sqlite3_free(z);
    return false;
  }else if( fslext_foreign(ext) ){
    /* Its schema names would be the "repo" and "ckout" which the
       views and documentation here assume. */
    sqlite3_result_error(cx, "A libfossil context which fsl_open() did "
                         "not open already uses this connection.", -1);
    return false;
  }
  return true;
}

/** Sets cx's error result: repo:zName is opened on this connection. */
static void fslext_already_open(sqlite3_context * const cx,
                                char const * zName){
  char * const z = sqlite3_mprintf("repo:%s is already opened "
                                   "(fsl_repos name '%s').", zName, zName);
  sqlite3_result_error(cx, z ? z : "out of memory", -1);
  sqlite3_free(z);
}

/**
   The rest of fsl_open() and fsl_import() for f, which has opened its
   repository (rc 0) or failed (rc not 0): adds it to ext's contexts,
   current if it is the first, with its views, and sets cx's result to
   vResult. On error, sets cx's error result and closes f.
*/
static void fslext_open_finish(sqlite3_context * const cx,
                               FslExt * const ext, fsl_cx * f, int rc,
                               sqlite3_value * const vResult){
  sqlite3_stmt * q = NULL;
  if( rc ){
    fslext_error(cx, f, rc);
    fsl_close_dbs(f);
    fslext_wc_free(ext, f);
    fsl_cx_finalize(f);
    return;
  }
  rc = fslext_keep(ext, f);
  if( 0==rc && !ext->f ) fslext_use(ext, f);
  /* Connect fsl_sqlext_life so that sqlite3_close() reaches its
     xDisconnect. */
  if( 0==rc ){
    rc = sqlite3_prepare_v2(ext->db, "SELECT 1 FROM fsl_sqlext_life",
                            -1, &q, NULL);
    sqlite3_finalize(q);
  }
  if( 0==rc ){
    rc = sqlite3_exec(ext->db, "CREATE TEMP TABLE IF NOT EXISTS "
                      "fsl_stage(name TEXT PRIMARY KEY, content BLOB,"
                      " perm TEXT)", 0, 0, 0);
  }
  if( rc ){
    sqlite3_result_error(cx, SQLITE_NOMEM==rc
                         ? "out of memory" : sqlite3_errmsg(ext->db), -1);
  }else{
    rc = fslext_views_create(ext, f);
    if( rc ){
      char zSfx[16];
      fslext_error(cx, f, rc);
      fslext_suffix(ext, f, zSfx);
      fslext_views_drop(ext, zSfx);
    }
  }
  if( rc ){
    fslext_forget(ext, f);
    fsl_close_dbs(f);
    fslext_wc_free(ext, f);
    fsl_cx_finalize(f);
    return;
  }
  sqlite3_result_value(cx, vResult);
}

/**
   Opens repo:NAME, the repository whose tables are those of the host's
   main db with prefix "fslrepo_NAME_" (zPre), on the new context f,
   or, if create, creates it first, as fossil(1)'s init does, with the
   initial check-in made by zUser (NULL to guess). A missing one is
   FSL_RC_NOT_A_REPO, with a message which says how to create it.
*/
static int fslext_open_host(fsl_cx * const f, char const * zName,
                            char const * zPre, bool create,
                            char const * zUser){
  int rc;
  if( create ){
    fsl_repo_create_opt cOpt = fsl_repo_create_opt_empty;
    cOpt.hostTablePrefix = zPre;
    cOpt.username = zUser;
    cOpt.commitMessage = "initial empty check-in";
    rc = fsl_repo_create(f, &cOpt);
  }else{
    rc = fsl_repo_open_host(f, zPre);
    if( FSL_RC_NOT_A_REPO==rc ){
      rc = fsl_cx_err_set(f, rc, "This database has no repository "
                          "repo:%s. Create one with fsl_open('repo:%s',"
                          " NULL, json_object('create', 1)), or import "
                          "one with fsl_import(FILE, 'repo:%s').",
                          zName, zName, zName);
    }
  }
  return rc;
}

/*
  fsl_open(PATH [, USER [, OPTIONS]])

  Opens the repository file PATH, or the checkout in directory PATH,
  on this connection: it is ATTACHed as "repo" or, if a repository is
  already opened, as "repo_2", and so on, and a checkout likewise as
  "ckout", "ckout_2", ... (the two numbers need not match); the
  fsl_repos table lists them. USER sets the default
  user for writes; without it, libfossil guesses as fossil(1) does.
  The first repository opened is the one the other functions act on
  until fsl_use() picks another. Returns PATH. It fails if a libfossil
  context which this extension did not open uses the connection.

  PATH 'db:NAME' reopens the working copy fsl_checkout('db:NAME')
  made in this connection's main db (see the top of this file): it
  opens the repository the working copy records, which libfossil
  checks is the working copy's by project-code and version.

  PATH 'repo:NAME' opens the repository whose tables are in this
  connection's main db (see the top of this file). OPTIONS is a JSON
  object: {"create": true} creates it first, empty but for its initial
  check-in (by USER), as fossil(1)'s init does, and fails if repo:NAME
  exists. OPTIONS is only for repo:NAME.
*/
static void fslext_open(sqlite3_context *cx, int argc, sqlite3_value **argv){
  FslExt * const ext = sqlite3_user_data(cx);
  char const * const zPath = (char const *)sqlite3_value_text(argv[0]);
  char const * const zUser = argc>1
    ? (char const *)sqlite3_value_text(argv[1]) : NULL;
  fsl_cx * f = NULL;
  bool create = false;
  int rc;
  char zWc[FSLEXT_WC_NAME_MAX+1], zRepo[FSLEXT_WC_NAME_MAX+1];
  int const wcKind = fslext_wc_name(zPath, zWc);
  int const repoKind = fslext_repo_name(zPath, zRepo);
  if( !zPath || !*zPath ){
    sqlite3_result_error(cx, "fsl_open() requires a path.", -1);
    return;
  }else if( !fslext_open_ok(cx, ext, "fsl_open") ){
    return;
  }else if( wcKind<0 ){
    sqlite3_result_error(cx, FSLEXT_WC_NAME_ERR, -1);
    return;
  }else if( repoKind<0 ){
    sqlite3_result_error(cx, FSLEXT_REPO_NAME_ERR, -1);
    return;
  }else if( repoKind>0 && fslext_find(ext, zPath) ){
    fslext_already_open(cx, zRepo);
    return;
  }else if( 3==argc && SQLITE_NULL!=sqlite3_value_type(argv[2]) ){
    sqlite3_stmt * q = NULL;
    if( !repoKind ){
      sqlite3_result_error(cx, "fsl_open()'s OPTIONS are only for a "
                           "repo:NAME repository.", -1);
      return;
    }
    rc = sqlite3_prepare_v2(ext->db,
           "SELECT coalesce(json_extract(?1,'$.create'),0)", -1, &q, NULL);
    if( 0==rc ){
      sqlite3_bind_value(q, 1, argv[2]);
      rc = sqlite3_step(q);
      rc = SQLITE_ROW==rc ? 0 : rc;
    }
    if( rc ){
      sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
      sqlite3_finalize(q);
      return;
    }
    create = 0!=sqlite3_column_int(q, 0);
    sqlite3_finalize(q);
  }
  rc = fsl_cx_init(&f, NULL);
  if( rc ){
    fslext_error(cx, f, rc);
    fsl_cx_finalize(f);
    return;
  }
  rc = fsl_cx_host_db(f, ext->db);
  if( 0==rc ){
    if( repoKind>0 ){
      char * const zPre = fsl_mprintf(FSLEXT_REPO_PREFIX "%s_", zRepo);
      rc = zPre ? fslext_open_host(f, zRepo, zPre, create, zUser)
        : fsl_cx_err_set(f, FSL_RC_OOM, NULL);
      fsl_free(zPre);
    }else{
      rc = wcKind>0
        ? fslext_open_wc(ext, f, zWc)
        : fsl_dir_check(zPath)>0
        ? fsl_ckout_open_dir(f, zPath, false)
        : fsl_repo_open(f, zPath);
    }
  }
  if( 0==rc && zUser ) rc = fsl_cx_user_set(f, zUser);
  fslext_open_finish(cx, ext, f, rc, argv[0]);
}

/*
  fsl_import(FILE, 'repo:NAME')

  Copies the repository file FILE into this connection's main db as
  repo:NAME (see the top of this file), in one transaction, and opens
  it as fsl_open('repo:NAME') does. Its artifacts are copied as stored
  and nothing is rebuilt; its full-text search indexes are left out
  (see fsl_repo_import()). It fails if repo:NAME exists, and, as
  fsl_open(), inside a transaction. Returns 'repo:NAME'.
*/
static void fslext_import(sqlite3_context *cx, int argc,
                          sqlite3_value **argv){
  FslExt * const ext = sqlite3_user_data(cx);
  char const * const zFile = (char const *)sqlite3_value_text(argv[0]);
  fsl_cx * f = NULL;
  char zRepo[FSLEXT_WC_NAME_MAX+1];
  int rc;
  (void)argc;
  if( !zFile || !*zFile ){
    sqlite3_result_error(cx, "fsl_import() requires a file.", -1);
    return;
  }else if( fslext_repo_name((char const *)sqlite3_value_text(argv[1]),
                             zRepo)<=0 ){
    sqlite3_result_error(cx, "fsl_import() imports into a repo:NAME "
                         "repository: " FSLEXT_REPO_NAME_ERR, -1);
    return;
  }else if( !fslext_open_ok(cx, ext, "fsl_import") ){
    return;
  }else if( fslext_find(ext, (char const *)sqlite3_value_text(argv[1])) ){
    fslext_already_open(cx, zRepo);
    return;
  }
  rc = fsl_cx_init(&f, NULL);
  if( rc ){
    fslext_error(cx, f, rc);
    fsl_cx_finalize(f);
    return;
  }
  rc = fsl_cx_host_db(f, ext->db);
  if( 0==rc ){
    char * const zPre = fsl_mprintf(FSLEXT_REPO_PREFIX "%s_", zRepo);
    rc = zPre ? fsl_repo_import(f, zFile, zPre)
      : fsl_cx_err_set(f, FSL_RC_OOM, NULL);
    fsl_free(zPre);
  }
  fslext_open_finish(cx, ext, f, rc, argv[1]);
}

/*
  fsl_export(REPO, FILE [, OVERWRITE])

  Writes the opened repository REPO (its fsl_repos name, or
  'repo:NAME') to the new repository file FILE, which fossil(1) can
  open, with fsl_repo_export(): a repo:NAME repository with the usual
  table names, a file repository as it is. It fails if FILE exists,
  unless OVERWRITE is true (it never overwrites a db file of this
  connection), and inside a transaction, as SQLite cannot ATTACH FILE
  there. Returns FILE.
*/
static void fslext_export(sqlite3_context *cx, int argc,
                          sqlite3_value **argv){
  FslExt * const ext = sqlite3_user_data(cx);
  char const * const zName = (char const *)sqlite3_value_text(argv[0]);
  char const * const zFile = (char const *)sqlite3_value_text(argv[1]);
  fsl_cx * const f = fslext_find(ext, zName);
  int rc;
  if( !f ){
    char * const z = sqlite3_mprintf("No repository %Q is opened (see "
                                     "fsl_repos).", zName);
    sqlite3_result_error(cx, z ? z : "No such repository.", -1);
    sqlite3_free(z);
    return;
  }else if( !zFile || !*zFile ){
    sqlite3_result_error(cx, "fsl_export() requires a file.", -1);
    return;
  }
  rc = fsl_repo_export(f, zFile, 3==argc && sqlite3_value_int(argv[2]));
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_value(cx, argv[1]);
}

/**
   Appends to s, as a comma-separated list of SQL strings, zPre
   followed by the name of each table which zSchema (fsl_schema_repo1()
   and friends) creates with "CREATE TABLE {{dbname.repo}}.NAME".
*/
static void fslext_schema_tables(sqlite3_str * const s, char const * zPre,
                                 char const * zSchema){
  static char const zKw[] = "CREATE TABLE {{dbname.repo}}.";
  for( char const * z = strstr(zSchema, zKw); z; z = strstr(z, zKw) ){
    fsl_size_t n = 0;
    z += sizeof(zKw) - 1;
    while( '_'==z[n] || fsl_isalnum(z[n]) ) ++n;
    sqlite3_str_appendf(s, ",'%q%.*q'", zPre, (int)n, z);
  }
}

/**
   The objects of the host's main db whose names start with zPre,
   ignoring case, which remain after fsl_drop(), as SQL: with
   bDrop, the DROP statements for its tables and views, separated by
   spaces, else a JSON array of their names. NULL on OOM or error.
*/
static char * fslext_drop_left(sqlite3 * const db, char const * zPre,
                               bool bDrop){
  sqlite3_stmt * q = NULL;
  char * z = NULL;
  char * const zSql = sqlite3_mprintf(bDrop
    ? "SELECT coalesce(group_concat('DROP '||upper(type)||' main.'"
      "||quote(name)||';', ' '), '') FROM main.sqlite_schema"
      " WHERE type IN ('table','view')"
      " AND lower(substr(name, 1, %d))=lower(%Q)"
    : "SELECT json_group_array(name) FROM (SELECT name FROM"
      " main.sqlite_schema WHERE sql IS NOT NULL"
      " AND lower(substr(name, 1, %d))=lower(%Q) ORDER BY name)",
    (int)fsl_strlen(zPre), zPre);
  if( zSql && SQLITE_OK==sqlite3_prepare_v2(db, zSql, -1, &q, NULL)
      && SQLITE_ROW==sqlite3_step(q) ){
    z = sqlite3_mprintf("%s", sqlite3_column_text(q, 0));
  }
  sqlite3_finalize(q);
  sqlite3_free(zSql);
  return z;
}

/*
  fsl_drop('repo:NAME')

  Drops the tables of repository repo:NAME from this connection's main
  db, in one transaction, and returns a JSON object: "dropped", how
  many tables it dropped, and "left", the names of the objects whose
  names start with fslrepo_NAME_ which it left. Only the
  tables a repository has are dropped: those of libfossil's repository
  schemas (fsl_schema_repo1(), fsl_schema_repo2(), fsl_schema_forum()),
  the ticket tables, and fossil(1)'s own which fsl_import() may have
  brought (accesslog, admin_log, alias, chat, modreq, pending_alert,
  purgeevent, purgeitem, subscriber, unversioned), with their indexes
  and triggers, and the "artifact" view; never another table whose name
  merely starts with "fslrepo_NAME_", e.g. an app's, or fossil(1)'s
  fx_ tables, or a custom ticket schema's other objects, which stay,
  listed in "left". As long as any are there, repo:NAME cannot be
  created or imported anew: fsl_drop('repo:NAME') of a NAME with no
  repository but with such objects fails, saying which they are and
  giving the DROP statements for them. It is refused while repo:NAME
  is opened on this
  connection, and while a working copy recorded in the main db (e.g.
  db:NAME) uses it. A checkout db on disk of it cannot be seen from
  here: it no longer opens once the repository is dropped.
*/
static void fslext_drop(sqlite3_context *cx, int argc, sqlite3_value **argv){
  /* The tables of fossil(1)'s own beside libfossil's schemas. */
  static char const * const azFossil[] = {
    "accesslog", "admin_log", "alias", "chat", "modreq", "pending_alert",
    "purgeevent", "purgeitem", "subscriber", "unversioned", NULL
  };
  FslExt * const ext = sqlite3_user_data(cx);
  char const * const zArg = (char const *)sqlite3_value_text(argv[0]);
  char zRepo[FSLEXT_WC_NAME_MAX+1];
  char * zPre = NULL, * zRef = NULL, * zList = NULL, * zSql = NULL;
  char * zWc = NULL;
  sqlite3_stmt * q = NULL;
  int n = 0, rc;
  (void)argc;
  if( fslext_repo_name(zArg, zRepo)<=0 ){
    sqlite3_result_error(cx, "fsl_drop() drops a repo:NAME repository: "
                         FSLEXT_REPO_NAME_ERR, -1);
    return;
  }else if( fslext_find(ext, zArg) ){
    char * const z = sqlite3_mprintf("repo:%s is opened: fsl_close('%s') "
                                     "it first.", zRepo, zRepo);
    sqlite3_result_error(cx, z ? z : "out of memory", -1);
    sqlite3_free(z);
    return;
  }
  zPre = sqlite3_mprintf(FSLEXT_REPO_PREFIX "%s_", zRepo);
  zRef = zPre ? sqlite3_mprintf("%s%s", FSL__REPO_HOST_REF, zPre) : NULL;
  if( zRef ){
    sqlite3_str * const s = sqlite3_str_new(ext->db);
    sqlite3_str_appendf(s, "'%qticket','%qticketchng'", zPre, zPre);
    for( int i = 0; azFossil[i]; ++i ){
      sqlite3_str_appendf(s, ",'%q%q'", zPre, azFossil[i]);
    }
    fslext_schema_tables(s, zPre, fsl_schema_repo1());
    fslext_schema_tables(s, zPre, fsl_schema_repo2());
    fslext_schema_tables(s, zPre, fsl_schema_forum());
    zList = sqlite3_str_finish(s);
  }
  if( !zList ){
    sqlite3_result_error_nomem(cx);
    goto end;
  }
  /* A repository, as libfossil tells one (fsl_repo_open_host()). */
  zSql = sqlite3_mprintf("SELECT count(*) FROM main.sqlite_schema"
                         " WHERE type='table' AND name IN ('%qblob',"
                         "'%qconfig')", zPre, zPre);
  rc = zSql ? sqlite3_prepare_v2(ext->db, zSql, -1, &q, NULL)
    : SQLITE_NOMEM;
  sqlite3_free(zSql);
  zSql = NULL;
  if( 0==rc ) rc = SQLITE_ROW==sqlite3_step(q) ? 0 : sqlite3_errcode(ext->db);
  if( 0==rc && 2!=sqlite3_column_int(q, 0) ){
    char * const zLeft = fslext_drop_left(ext->db, zPre, false);
    char * const zDrop = zLeft && 0!=fsl_strcmp(zLeft, "[]")
      ? fslext_drop_left(ext->db, zPre, true) : NULL;
    char * const z = zDrop
      ? sqlite3_mprintf("This database has no repository repo:%s, but "
                        "objects named with its prefix %s: %s. While "
                        "they are there, repo:%s cannot be made anew. "
                        "To drop them, if they are not the app's: %s",
                        zRepo, zPre, zLeft, zRepo, zDrop)
      : sqlite3_mprintf("This database has no repository repo:%s.",
                        zRepo);
    sqlite3_result_error(cx, z ? z : "out of memory", -1);
    sqlite3_free(z);
    sqlite3_free(zLeft);
    sqlite3_free(zDrop);
    goto end;
  }
  sqlite3_finalize(q);
  q = NULL;
  if( rc ) goto db_err;
  /* A working copy recorded in main which uses it: a table whose name
     ends in vvar, with its "repository" entry. A host's table so named
     need not have those columns. */
  rc = sqlite3_prepare_v2(ext->db, "SELECT name FROM main.sqlite_schema"
                          " WHERE type='table'"
                          " AND lower(substr(name, -4))='vvar'",
                          -1, &q, NULL);
  while( 0==rc && !zWc && SQLITE_ROW==sqlite3_step(q) ){
    char const * const zT = (char const *)sqlite3_column_text(q, 0);
    sqlite3_stmt * qv = NULL;
    char * const z = sqlite3_mprintf("SELECT 1 FROM main.\"%w\""
                                     " WHERE name='repository'"
                                     " AND value=?1", zT);
    if( !z ){
      rc = SQLITE_NOMEM;
    }else if( SQLITE_OK==sqlite3_prepare_v2(ext->db, z, -1, &qv, NULL) ){
      sqlite3_bind_text(qv, 1, zRef, -1, SQLITE_STATIC);
      if( SQLITE_ROW==sqlite3_step(qv) ){
        zWc = sqlite3_mprintf("%.*s", (int)fsl_strlen(zT) - 4, zT);
        if( !zWc ) rc = SQLITE_NOMEM;
      }
    }
    sqlite3_finalize(qv);
    sqlite3_free(z);
  }
  sqlite3_finalize(q);
  q = NULL;
  if( rc ) goto db_err;
  if( zWc ){
    fsl_size_t const nW = fsl_strlen(zWc);
    char * const z = (0==fsl_strncmp(zWc, "fslwc_", 6) && nW>7)
      ? sqlite3_mprintf("Working copy db:%.*s uses repo:%s: drop it "
                        "first.", (int)nW - 7, zWc + 6, zRepo)
      : sqlite3_mprintf("The working copy whose tables are prefixed %s "
                        "uses repo:%s: drop it first.", zWc, zRepo);
    sqlite3_result_error(cx, z ? z : "out of memory", -1);
    sqlite3_free(z);
    goto end;
  }
  /* The tables to drop, those of zList which exist. */
  zSql = sqlite3_mprintf("SELECT name FROM main.sqlite_schema"
                         " WHERE type='table' AND name IN (%s)", zList);
  rc = zSql ? sqlite3_prepare_v2(ext->db, zSql, -1, &q, NULL)
    : SQLITE_NOMEM;
  sqlite3_free(zSql);
  zSql = NULL;
  if( 0==rc ){
    sqlite3_str * const s = sqlite3_str_new(ext->db);
    sqlite3_str_appendall(s, "SAVEPOINT fsl_drop;");
    while( SQLITE_ROW==sqlite3_step(q) ){
      sqlite3_str_appendf(s, "DROP TABLE main.\"%w\";",
                          sqlite3_column_text(q, 0));
      ++n;
    }
    sqlite3_str_appendf(s, "DROP VIEW IF EXISTS main.\"%wartifact\";"
                        "RELEASE fsl_drop;", zPre);
    zSql = sqlite3_str_finish(s);
    sqlite3_finalize(q);
    q = NULL;
    rc = zSql ? sqlite3_exec(ext->db, zSql, 0, 0, 0) : SQLITE_NOMEM;
    if( rc && SQLITE_NOMEM!=rc ){
      char * const zErr = sqlite3_mprintf("%s", sqlite3_errmsg(ext->db));
      sqlite3_exec(ext->db, "ROLLBACK TO fsl_drop; RELEASE fsl_drop;",
                   0, 0, 0);
      sqlite3_result_error(cx, zErr ? zErr : "out of memory", -1);
      sqlite3_free(zErr);
      goto end;
    }
  }
  db_err:
  if( rc ){
    sqlite3_result_error(cx, SQLITE_NOMEM==rc
                         ? "out of memory" : sqlite3_errmsg(ext->db), -1);
  }else{
    char * const zLeft = fslext_drop_left(ext->db, zPre, false);
    char * const z = zLeft
      ? sqlite3_mprintf("{\"dropped\":%d,\"left\":%s}", n, zLeft) : NULL;
    if( z ) sqlite3_result_text(cx, z, -1, sqlite3_free);
    else sqlite3_result_error_nomem(cx);
    sqlite3_free(zLeft);
  }
  end:
  sqlite3_finalize(q);
  sqlite3_free(zPre);
  sqlite3_free(zRef);
  sqlite3_free(zList);
  sqlite3_free(zSql);
  sqlite3_free(zWc);
}

/**
   Closes f, one of ext's contexts: drops its views, DETACHes its dbs
   and forgets it. On error, sets cx's error result, leaves f opened
   and returns non-0.
*/
static int fslext_close_one(sqlite3_context * const cx,
                            FslExt * const ext, fsl_cx * const f){
  char zSfx[16];
  int rc;
  fslext_suffix(ext, f, zSfx);
  rc = fslext_views_drop(ext, zSfx);
  if( rc ){
    sqlite3_result_error(cx, SQLITE_NOMEM==rc
                         ? "out of memory" : sqlite3_errmsg(ext->db), -1);
    return rc;
  }
  rc = fsl_close_dbs(f);
  if( rc ){
    fslext_error(cx, f, rc);
    return rc;
  }
  fslext_forget(ext, f);
  fslext_wc_free(ext, f);
  fsl_cx_finalize(f);
  return 0;
}

/*
  fsl_close([NAME])

  Closes what fsl_open() opened: all of it, or only the repository
  (and its checkout) NAME (its fsl_repos name, or 'repo:NAME').
  Closing DETACHes it (a repo:NAME repository's tables stay),
  drops its views, and, once nothing is left opened, removes
  libfossil's SQL functions other than this extension's. If the
  repository the other functions act on is closed, the first one still
  opened takes its place. Returns 1 if something was closed, else 0.
  It is an error if NAME is not a repository fsl_open() opened.
*/
static void fslext_close(sqlite3_context *cx, int argc, sqlite3_value **argv){
  FslExt * const ext = sqlite3_user_data(cx);
  fsl_cx * f = NULL;
  if( 1==argc ){
    f = fslext_find(ext, (char const *)sqlite3_value_text(argv[0]));
    if( !f ){
      char * const z = sqlite3_mprintf("No repository %Q is opened "
                                       "(see fsl_repos).",
                                       sqlite3_value_text(argv[0]));
      sqlite3_result_error(cx, z ? z : "No such repository.", -1);
      sqlite3_free(z);
      return;
    }
  }
  if( !ext->n ){
    sqlite3_result_int(cx, 0);
    return;
  }else if( !sqlite3_get_autocommit(ext->db) ){
    sqlite3_result_error(cx, "fsl_close() cannot run inside a "
                         "transaction.", -1);
    return;
  }
  if( f ){
    if( fslext_close_one(cx, ext, f) ) return;
  }else{
    while( ext->n ){
      if( fslext_close_one(cx, ext, ext->a[ext->n - 1]) ) return;
    }
  }
  sqlite3_result_int(cx, 1);
}

/*
  fsl_use(NAME)

  Makes the repository NAME (its fsl_repos name, or 'repo:NAME') the
  one the other fsl_* functions and tables act on, and the one
  libfossil's SQL functions, e.g. fsl_content(), use in this
  connection's SQL. The views stay per repository: fsl_timeline for
  the first one opened, fsl_timeline_2 for the second while the first
  is opened, and so on (for file repositories alone, the number of
  schema "repo_2"). Returns NAME.
*/
static void fslext_use_name(sqlite3_context *cx, int argc,
                            sqlite3_value **argv){
  FslExt * const ext = sqlite3_user_data(cx);
  fsl_cx * const f = fslext_find(ext,
                                 (char const *)sqlite3_value_text(argv[0]));
  (void)argc;
  if( !f ){
    char * const z = sqlite3_mprintf("No repository %Q is opened "
                                     "(see fsl_repos).",
                                     sqlite3_value_text(argv[0]));
    sqlite3_result_error(cx, z ? z : "No such repository.", -1);
    sqlite3_free(z);
    return;
  }
  fslext_use(ext, f);
  sqlite3_result_value(cx, argv[0]);
}

/*
  fsl_resolve(SYMBOL)

  Returns the full hash of the artifact SYMBOL names: a hash or hash
  prefix of any artifact, or a name for a check-in, e.g. a branch or
  tag name, "tip", a date, "root:NAME" or, in a checkout, "current".
  fsl_sym_to_rid() lists every form. It is an error if SYMBOL names
  nothing or is an ambiguous prefix.
*/
static void fslext_resolve(sqlite3_context *cx, int argc,
                           sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zSym = (char const *)sqlite3_value_text(argv[0]);
  fsl_id_t rid = 0;
  int rc;
  (void)argc;
  if( !f ) return;
  if( !zSym || !*zSym ){
    sqlite3_result_error(cx, "fsl_resolve() requires a symbol.", -1);
    return;
  }
  rc = fsl_sym_to_rid(f, zSym, FSL_SATYPE_ANY, &rid);
  if( rc ) fslext_error(cx, f, rc);
  else fslext_result_hash(cx, f, rid);
}

/*
  fsl_file(VERSION, NAME)

  Returns the content of file NAME as of check-in VERSION (anything
  fsl_resolve() accepts for a check-in) as a BLOB, or NULL if the
  check-in has no such file. Use CAST(... AS TEXT) for text. NAME is
  matched as the repository's case-sensitivity setting says.
*/
static void fslext_file(sqlite3_context *cx, int argc,
                        sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zVersion = (char const *)sqlite3_value_text(argv[0]);
  char const * const zName = (char const *)sqlite3_value_text(argv[1]);
  fsl_deck d = fsl_deck_empty;
  fsl_card_F const * fc = NULL;
  fsl_b content = fsl_b_empty;
  int rc;
  (void)argc;
  if( !f ) return;
  if( !zVersion || !*zVersion || !zName || !*zName ){
    sqlite3_result_error(cx, "fsl_file() requires a version and a "
                         "file name.", -1);
    return;
  }
  rc = fsl_deck_load_sym(f, &d, zVersion, FSL_SATYPE_CHECKIN);
  if( 0==rc ) rc = fsl_deck_F_search2(&d, zName, &fc);
  if( 0==rc && fc ) rc = fsl_card_F_content(f, fc, &content);
  if( rc ){
    fslext_error(cx, f, rc);
  }else if( fc ){
    sqlite3_result_blob64(cx, content.mem ? (void const *)content.mem : "",
                          content.used, SQLITE_TRANSIENT);
  }else{
    sqlite3_result_null(cx);
  }
  fsl_b_clear(&content);
  fsl_deck_finalize(&d);
}

static bool fslext_autocommit(sqlite3_context * const cx,
                              char const * zFunc);

/** State for fslext_extract_f(). */
typedef struct {
  /** The target directory, with a trailing slash, then each name. */
  fsl_b path;
  fsl_size_t dirLen;
  /** False for the pass which only checks for existing files. */
  bool write;
  bool overwrite;
  bool allowLinks;
  sqlite3_int64 n;
} FslextExtract;

/** fsl_repo_extract() callback for fsl_extract(). */
static int fslext_extract_f(fsl_repo_extract_state const * xs){
  FslextExtract * const p = xs->callbackState;
  fsl_card_F const * const fc = xs->fCard;
  char const * zAbs;
  int rc;
  if( !fsl_is_simple_pathname(fc->name, true) ){
    return fsl_cx_err_set(xs->f, FSL_RC_RANGE,
                          "Refusing to extract unsafe name: %s", fc->name);
  }
  p->path.used = p->dirLen;
  rc = fsl_b_append(&p->path, fc->name, -1);
  if( rc ) return rc;
  zAbs = fsl_b_cstr(&p->path);
  if( !p->write ){
    if( !p->overwrite && 0==fsl_stat(zAbs, NULL, false) ){
      return fsl_cx_err_set(xs->f, FSL_RC_ALREADY_EXISTS,
                            "File already exists: %s", zAbs);
    }
    return 0;
  }
  rc = fsl_mkdir_for_file(zAbs, false);
  if( 0==rc && FSL_FILE_PERM_LINK==fc->perm ){
    fsl_file_unlink(zAbs);
    rc = fsl_symlink_create(fsl_b_cstr(xs->content), zAbs, p->allowLinks);
  }else if( 0==rc ){
    rc = fsl_b_to_filename(xs->content, zAbs);
    if( 0==rc ) rc = fsl_file_exec_set(zAbs, FSL_FILE_PERM_EXE==fc->perm);
  }
  if( rc ){
    return fsl_cx_err_set(xs->f, rc, "Cannot write %s: %s", zAbs,
                          fsl_rc_cstr(rc));
  }
  ++p->n;
  return 0;
}

/*
  fsl_extract(VERSION, DIR [, OVERWRITE])

  Writes the files of check-in VERSION (anything fsl_resolve() accepts
  for a check-in) under directory DIR, creating it and subdirectories
  as needed, without making a checkout of it. Executable bits are set,
  and symlinks are made only if the repository allows them (else the
  file holds the link's target). It refuses, writing nothing, if any
  of the files already exists, unless OVERWRITE is true. Returns the
  number of files written. It must run outside of a transaction.
*/
static void fslext_extract(sqlite3_context *cx, int argc,
                           sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zVersion = (char const *)sqlite3_value_text(argv[0]);
  char const * const zDir = (char const *)sqlite3_value_text(argv[1]);
  fsl_repo_extract_opt opt = fsl_repo_extract_opt_empty;
  FslextExtract st = {0};
  int rc;
  if( !f || !fslext_autocommit(cx, "fsl_extract") ) return;
  if( !zVersion || !*zVersion || !zDir || !*zDir ){
    sqlite3_result_error(cx, "fsl_extract() requires a version and a "
                         "directory.", -1);
    return;
  }
  st.path = fsl_b_empty;
  st.overwrite = argc>2 && sqlite3_value_int(argv[2]);
  st.allowLinks = fsl_cx_allows_symlinks(f, false);
  rc = fsl_b_append(&st.path, zDir, -1);
  if( 0==rc && '/'!=zDir[strlen(zDir)-1] ){
    rc = fsl_b_append(&st.path, "/", 1);
  }
  st.dirLen = st.path.used;
  if( 0==rc ) rc = fsl_sym_to_rid(f, zVersion, FSL_SATYPE_CHECKIN,
                                  &opt.checkinRid);
  if( 0==rc ){
    opt.callback = fslext_extract_f;
    opt.callbackState = &st;
    rc = fsl_repo_extract(f, &opt);
  }
  if( 0==rc ){
    st.write = true;
    opt.extractContent = true;
    rc = fsl_repo_extract(f, &opt);
  }
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_int64(cx, st.n);
  fsl_b_clear(&st.path);
}

/*
  fsl_zip(VERSION, FILE [, ROOT])

  Writes a ZIP of check-in VERSION's files, as fossil(1)'s zip does,
  to FILE, with each name under directory ROOT if it is given and not
  empty. It always adds manifest, manifest.uuid and manifest.tags,
  which fossil(1) adds only if its "manifest" setting asks for them.
  Returns FILE; readfile(FILE) gives the bytes. It must
  run outside of a transaction.
*/
static void fslext_zip(sqlite3_context *cx, int argc, sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zVersion = (char const *)sqlite3_value_text(argv[0]);
  char const * const zFile = (char const *)sqlite3_value_text(argv[1]);
  char const * const zRoot = argc>2
    ? (char const *)sqlite3_value_text(argv[2]) : NULL;
  int rc;
  if( !f || !fslext_autocommit(cx, "fsl_zip") ) return;
  if( !zVersion || !*zVersion || !zFile || !*zFile ){
    sqlite3_result_error(cx, "fsl_zip() requires a version and a file "
                         "name.", -1);
    return;
  }
  rc = fsl_repo_zip_sym_to_filename(f, zVersion, zRoot, zFile, NULL, NULL);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_value(cx, argv[1]);
}

/*
  fsl_rebuild([OPTIONS])

  Rebuilds the opened repository's derived tables (timeline, file
  history, tags, and so on) from its artifacts, as fossil(1)'s rebuild
  does. Like fossil(1)'s, it drops tables in the repository which
  fossil does not know. OPTIONS is a JSON object: {"verifyHashes":
  true} also checks every artifact against its hash. Returns 1.
*/
static void fslext_rebuild(sqlite3_context *cx, int argc,
                           sqlite3_value **argv){
  FslExt * const ext = sqlite3_user_data(cx);
  fsl_cx * const f = fslext_cx(cx);
  fsl_rebuild_opt opt = fsl_rebuild_opt_empty;
  int rc;
  if( !f ) return;
  if( argc>0 && SQLITE_NULL!=sqlite3_value_type(argv[0]) ){
    sqlite3_stmt * q = NULL;
    rc = sqlite3_prepare_v2(ext->db,
           "SELECT coalesce(json_extract(?1,'$.verifyHashes'),0)",
           -1, &q, NULL);
    if( 0==rc ){
      sqlite3_bind_value(q, 1, argv[0]);
      rc = sqlite3_step(q);
      rc = SQLITE_ROW==rc ? 0 : rc;
    }
    if( rc ){
      sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
      sqlite3_finalize(q);
      return;
    }
    opt.verifyHashes = 0!=sqlite3_column_int(q, 0);
    sqlite3_finalize(q);
  }
  rc = fsl_repo_rebuild(f, &opt);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_int(cx, 1);
}

/*
  fsl_wiki(NAME)

  Returns the text of the newest version of wiki page NAME, or NULL if
  there is no such page.
*/
static void fslext_wiki(sqlite3_context *cx, int argc, sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zName = (char const *)sqlite3_value_text(argv[0]);
  fsl_deck d = fsl_deck_empty;
  int rc;
  (void)argc;
  if( !f ) return;
  if( !zName || !*zName ){
    sqlite3_result_error(cx, "fsl_wiki() requires a page name.", -1);
    return;
  }
  if( !fsl_wiki_page_exists(f, zName) ){
    sqlite3_result_null(cx);
    return;
  }
  rc = fsl_wiki_load_latest(f, zName, &d);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_text(cx, d.W.mem ? (char const *)d.W.mem : "",
                           (int)d.W.used, SQLITE_TRANSIENT);
  fsl_deck_finalize(&d);
}

/*
  fsl_wiki_save(NAME, TEXT [, MIMETYPE])

  Saves TEXT as a new version of wiki page NAME, creating the page if
  needed, and returns the new version's hash. MIMETYPE is
  "text/x-markdown", "text/x-fossil-wiki" (fossil(1)'s default) or
  "text/plain". The user is fsl_open()'s USER.
*/
static void fslext_wiki_save(sqlite3_context *cx, int argc,
                             sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zName = (char const *)sqlite3_value_text(argv[0]);
  char const * const zText = (char const *)sqlite3_value_text(argv[1]);
  char const * const zMime = argc>2
    ? (char const *)sqlite3_value_text(argv[2]) : NULL;
  fsl_b body = fsl_b_empty;
  fsl_id_t rid = 0;
  int rc;
  if( !f ) return;
  if( !zName || !*zName || !zText ){
    sqlite3_result_error(cx, "fsl_wiki_save() requires a page name and "
                         "text.", -1);
    return;
  }
  fsl_b_external(&body, zText, sqlite3_value_bytes(argv[1]));
  rc = fsl_wiki_save(f, zName, &body, NULL, zMime,
                     FSL_WIKI_SAVE_MODE_UPSERT);
  if( 0==rc ) rc = fsl_wiki_latest_rid(f, zName, &rid);
  if( rc ) fslext_error(cx, f, rc);
  else fslext_result_hash(cx, f, rid);
}

/**
   Resolves technote id or id prefix zId to the rid of its newest
   version, and sets *pzId to a copy of the full id, which the caller
   must fsl_free(). Returns FSL_RC_NOT_FOUND if no technote has that
   id, or FSL_RC_AMBIGUOUS if more than one does.
*/
static int fslext_technote_rid(fsl_cx * const f, char const * zId,
                               fsl_id_t * const pRid, char ** pzId){
  fsl_stmt q = fsl_stmt_empty;
  int rc, n = 0;
  *pRid = 0;
  *pzId = NULL;
  rc = fsl_cx_prepare(f, &q,
         "SELECT substr(tagname,7), (SELECT x.rid FROM"
         "   {{dbname.repo}}.tagxref x"
         "   WHERE x.tagid=t.tagid ORDER BY x.mtime DESC, x.rid DESC"
         "   LIMIT 1)"
         " FROM {{dbname.repo}}.tag t WHERE tagname GLOB 'event-%q*'", zId);
  while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
    if( ++n>1 ) break;
    *pRid = fsl_stmt_g_id(&q, 1);
    *pzId = fsl_strdup(fsl_stmt_g_text(&q, 0, NULL));
    if( !*pzId ) rc = FSL_RC_OOM;
  }
  fsl_stmt_finalize(&q);
  if( rc ) return rc;
  if( 1!=n || *pRid<=0 ){
    fsl_free(*pzId);
    *pzId = NULL;
    *pRid = 0;
    return n>1
      ? fsl_cx_err_set(f, FSL_RC_AMBIGUOUS, "Ambiguous technote id: %s", zId)
      : fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "No such technote: %s", zId);
  }
  return 0;
}

/*
  fsl_technote(ID)

  Returns the text of the newest version of the technote with id (or
  unique id prefix) ID, or NULL if there is none.
*/
static void fslext_technote(sqlite3_context *cx, int argc,
                            sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zId = (char const *)sqlite3_value_text(argv[0]);
  fsl_deck d = fsl_deck_empty;
  fsl_id_t rid = 0;
  char * zFull = NULL;
  int rc;
  (void)argc;
  if( !f ) return;
  if( !zId || !*zId ){
    sqlite3_result_error(cx, "fsl_technote() requires an id.", -1);
    return;
  }
  rc = fslext_technote_rid(f, zId, &rid, &zFull);
  if( FSL_RC_NOT_FOUND==rc ){
    fsl_cx_err_reset(f);
    sqlite3_result_null(cx);
    return;
  }
  if( 0==rc ) rc = fsl_deck_load_rid(f, &d, rid, FSL_SATYPE_TECHNOTE);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_text(cx, d.W.mem ? (char const *)d.W.mem : "",
                           (int)d.W.used, SQLITE_TRANSIENT);
  fsl_free(zFull);
  fsl_deck_finalize(&d);
}

/*
  fsl_technote_save(TEXT [, OPTIONS])

  Saves TEXT as a technote and returns its id. OPTIONS is a JSON
  object with any of:

  - "comment": the line the timeline shows for it.
  - "time": when it happened, anything julianday() accepts (default
    now). The timeline shows it at that time.
  - "id": the id (or unique prefix) of an existing technote, to save a
    new version of it. The new version keeps the old one's comment,
    time, mimetype and tags unless OPTIONS gives new ones. Without
    "id" a new technote is made.
  - "mimetype": "text/x-markdown", "text/x-fossil-wiki" (default) or
    "text/plain".
  - "tags": an array of tag names to give it.

  The user is fsl_open()'s USER.
*/
static void fslext_technote_save(sqlite3_context *cx, int argc,
                                 sqlite3_value **argv){
  FslExt * const ext = sqlite3_user_data(cx);
  fsl_cx * const f = fslext_cx(cx);
  char const * const zText = (char const *)sqlite3_value_text(argv[0]);
  fsl_deck d = fsl_deck_empty;
  fsl_deck prev = fsl_deck_empty;
  bool tagsGiven = false;
  sqlite3_stmt * q = NULL;
  char * zComment = NULL, * zEditId = NULL, * zMime = NULL;
  char * zId = NULL, * zUser = NULL;
  double tEvent = 0;
  fsl_id_t prevRid = 0;
  int rc = 0;
  if( !f ) return;
  if( !zText ){
    sqlite3_result_error(cx, "fsl_technote_save() requires text.", -1);
    return;
  }
  if( argc>1 && SQLITE_NULL!=sqlite3_value_type(argv[1]) ){
    rc = sqlite3_prepare_v2(ext->db,
           "SELECT json_extract(?1,'$.comment'),"
           " julianday(json_extract(?1,'$.time')),"
           " json_extract(?1,'$.id'), json_extract(?1,'$.mimetype'),"
           " json_extract(?1,'$.time') IS NOT NULL,"
           " json_type(?1,'$.tags') IS NOT NULL", -1, &q, NULL);
    if( 0==rc ){
      sqlite3_bind_value(q, 1, argv[1]);
      rc = sqlite3_step(q);
      rc = SQLITE_ROW==rc ? 0 : rc;
    }
    if( rc ){
      sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
      sqlite3_finalize(q);
      return;
    }
#define COL(N) (sqlite3_column_text(q, N) \
                ? fsl_strdup((char const *)sqlite3_column_text(q, N)) : NULL)
    zComment = COL(0);
    zEditId = COL(2);
    zMime = COL(3);
#undef COL
    if( sqlite3_column_int(q, 4) ){
      if( SQLITE_NULL==sqlite3_column_type(q, 1) ){
        sqlite3_finalize(q);
        sqlite3_result_error(cx, "fsl_technote_save(): \"time\" is not "
                             "a date.", -1);
        goto end;
      }
      tEvent = sqlite3_column_double(q, 1);
    }
    tagsGiven = 0!=sqlite3_column_int(q, 5);
    sqlite3_finalize(q);
    q = NULL;
  }
  if( zEditId ){
    rc = fslext_technote_rid(f, zEditId, &prevRid, &zId);
    if( 0==rc ) rc = fsl_deck_load_rid(f, &prev, prevRid,
                                       FSL_SATYPE_TECHNOTE);
    if( 0==rc ){
      if( tEvent<=0 ) tEvent = prev.E.julian;
      if( !zComment && prev.C ){
        zComment = fsl_strdup(prev.C);
        if( !zComment ) rc = FSL_RC_OOM;
      }
      if( 0==rc && !zMime && prev.N ){
        zMime = fsl_strdup(prev.N);
        if( !zMime ) rc = FSL_RC_OOM;
      }
    }
  }else{
    zId = fsl_db_random_hex(fsl_cx_db_repo(f), 40);
    if( !zId ) rc = FSL_RC_OOM;
  }
  if( rc ) goto err;
  fsl_deck_init(f, &d, FSL_SATYPE_TECHNOTE);
  {
    double const now = fsl_db_julian_now(fsl_cx_db_repo(f));
    rc = fsl_deck_D_set(&d, now);
    if( 0==rc ) rc = fsl_deck_E_set(&d, tEvent>0 ? tEvent : now, zId);
  }
  if( 0==rc && zComment ) rc = fsl_deck_C_set(&d, zComment, -1);
  if( 0==rc && zMime && *zMime ) rc = fsl_deck_N_set(&d, zMime, -1);
  if( 0==rc && prevRid>0 ) rc = fsl_deck_P_add_rid(&d, prevRid);
  for( fsl_size_t i = 0; 0==rc && !tagsGiven && i<prev.T.used; ++i ){
    fsl_card_T const * const t = prev.T.list[i];
    rc = fsl_deck_T_add(&d, t->type, NULL, t->name, t->value);
  }
  if( 0==rc && argc>1 && SQLITE_NULL!=sqlite3_value_type(argv[1]) ){
    rc = sqlite3_prepare_v2(ext->db,
           "SELECT value FROM json_each(?1,'$.tags')"
           " WHERE type='text' ORDER BY value", -1, &q, NULL);
    if( rc ){
      sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
      goto end;
    }
    sqlite3_bind_value(q, 1, argv[1]);
    while( 0==rc && SQLITE_ROW==sqlite3_step(q) ){
      char * const zTag = sqlite3_mprintf("sym-%s",
                                          sqlite3_column_text(q, 0));
      rc = zTag ? fsl_deck_T_add(&d, FSL_TAGTYPE_ADD, NULL, zTag, NULL)
        : FSL_RC_OOM;
      sqlite3_free(zTag);
    }
    sqlite3_finalize(q);
    q = NULL;
  }
  if( 0==rc ){
    char const * zU = fsl_cx_user_get(f);
    if( !zU ){
      zUser = fsl_user_name_guess();
      zU = zUser;
    }
    rc = zU ? fsl_deck_U_set(&d, zU) : FSL_RC_OOM;
  }
  if( 0==rc ) rc = fsl_deck_W_set(&d, zText, sqlite3_value_bytes(argv[0]));
  if( 0==rc ) rc = fsl_deck_save(&d, false);
  err:
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_text(cx, zId, -1, SQLITE_TRANSIENT);
  end:
  fsl_deck_finalize(&d);
  fsl_deck_finalize(&prev);
  fsl_free(zComment);
  fsl_free(zEditId);
  fsl_free(zMime);
  fsl_free(zId);
  fsl_free(zUser);
}

/**
   Resolves zSym (a hash or prefix) to a forum post's rid, or sets an
   error and returns non-0.
*/
static int fslext_forum_rid(fsl_cx * const f, char const * zSym,
                            fsl_id_t * const pRid){
  int rc = fsl_sym_to_rid(f, zSym, FSL_SATYPE_FORUMPOST, pRid);
  if( FSL_RC_NOT_FOUND==rc || (0==rc && *pRid<=0) ){
    fsl_cx_err_reset(f);
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "No such forum post: %s",
                        zSym);
  }
  return rc;
}

/*
  fsl_forum(POST)

  Returns the text of forum post POST (a hash or unique prefix), or
  NULL if there is no such post. The thread structure is in fossil's
  forumpost table: fpid (the post), froot (its thread's first post),
  firt (the post it replies to) and fprev (the version it edits), all
  rids.
*/
static void fslext_forum(sqlite3_context *cx, int argc,
                         sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zSym = (char const *)sqlite3_value_text(argv[0]);
  fsl_deck d = fsl_deck_empty;
  fsl_id_t rid = 0;
  int rc;
  (void)argc;
  if( !f ) return;
  if( !zSym || !*zSym ){
    sqlite3_result_error(cx, "fsl_forum() requires a post hash.", -1);
    return;
  }
  rc = fslext_forum_rid(f, zSym, &rid);
  if( FSL_RC_NOT_FOUND==rc ){
    fsl_cx_err_reset(f);
    sqlite3_result_null(cx);
    return;
  }
  if( 0==rc ) rc = fsl_deck_load_rid(f, &d, rid, FSL_SATYPE_FORUMPOST);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_text(cx, d.W.mem ? (char const *)d.W.mem : "",
                           (int)d.W.used, SQLITE_TRANSIENT);
  fsl_deck_finalize(&d);
}

/*
  fsl_forum_post(TEXT, OPTIONS)

  Saves a forum post and returns its hash. OPTIONS is a JSON object
  which says what the post is, with exactly one of:

  - "title": starts a new thread with this title.
  - "inReplyTo": the hash (or prefix) of the post this replies to.
  - "edits": the hash (or prefix) of a post this is a new version of.
    It stays in the same place in its thread; a thread's first post
    keeps its title unless "title" is also given.

  and optionally "mimetype": "text/x-markdown", "text/x-fossil-wiki"
  (default) or "text/plain". The user is fsl_open()'s USER.
*/
static void fslext_forum_post(sqlite3_context *cx, int argc,
                              sqlite3_value **argv){
  FslExt * const ext = sqlite3_user_data(cx);
  fsl_cx * const f = fslext_cx(cx);
  char const * const zText = (char const *)sqlite3_value_text(argv[0]);
  fsl_deck d = fsl_deck_empty;
  fsl_deck prev = fsl_deck_empty;
  sqlite3_stmt * q = NULL;
  char * zTitle = NULL, * zReply = NULL, * zEdits = NULL, * zMime = NULL;
  char * zUser = NULL;
  fsl_id_t rid = 0;
  int rc = 0;
  (void)argc;
  if( !f ) return;
  if( !zText ){
    sqlite3_result_error(cx, "fsl_forum_post() requires text.", -1);
    return;
  }
  rc = sqlite3_prepare_v2(ext->db,
         "SELECT json_extract(?1,'$.title'), json_extract(?1,'$.inReplyTo'),"
         " json_extract(?1,'$.edits'), json_extract(?1,'$.mimetype')",
         -1, &q, NULL);
  if( 0==rc ){
    sqlite3_bind_value(q, 1, argv[1]);
    rc = sqlite3_step(q);
    rc = SQLITE_ROW==rc ? 0 : rc;
  }
  if( rc ){
    sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
    sqlite3_finalize(q);
    return;
  }
#define COL(N) (sqlite3_column_text(q, N) \
                ? fsl_strdup((char const *)sqlite3_column_text(q, N)) : NULL)
  zTitle = COL(0);
  zReply = COL(1);
  zEdits = COL(2);
  zMime = COL(3);
#undef COL
  sqlite3_finalize(q);
  if( (zReply && zEdits) || (zReply && zTitle)
      || !(zTitle || zReply || zEdits) ){
    sqlite3_result_error(cx, "fsl_forum_post() OPTIONS needs \"title\" "
                         "for a new thread, \"inReplyTo\" for a reply, "
                         "or \"edits\" for a new version.", -1);
    goto end;
  }
  rc = fsl_repo_install_schema_forum(f);
  if( 0==rc ){
    fsl_deck_init(f, &d, FSL_SATYPE_FORUMPOST);
    rc = fsl_deck_D_set(&d, fsl_db_julian_now(fsl_cx_db_repo(f)));
  }
  if( 0==rc && zEdits ){
    /* A new version: same thread and parent, P names the old one. */
    rc = fslext_forum_rid(f, zEdits, &rid);
    if( 0==rc ) rc = fsl_deck_load_rid(f, &prev, rid, FSL_SATYPE_FORUMPOST);
    if( 0==rc ) rc = fsl_deck_P_add_rid(&d, rid);
    if( 0==rc && prev.G ) rc = fsl_deck_G_set(&d, prev.G);
    if( 0==rc && prev.I ) rc = fsl_deck_I_set(&d, prev.I);
    if( 0==rc && !zTitle && prev.H ) rc = fsl_deck_H_set(&d, prev.H, -1);
    if( 0==rc && !zMime && prev.N ){
      zMime = fsl_strdup(prev.N);
      if( !zMime ) rc = FSL_RC_OOM;
    }
  }else if( 0==rc && zReply ){
    /* A reply: I names the parent, G the thread's first post. */
    rc = fslext_forum_rid(f, zReply, &rid);
    if( 0==rc ){
      char * const zParent = fsl_rid_to_uuid(f, rid);
      rc = zParent ? fsl_deck_I_set(&d, zParent) : FSL_RC_OOM;
      fsl_free(zParent);
    }
    if( 0==rc ){
      char * const zRoot = fsl_db_g_text(fsl_cx_db_repo(f), NULL,
        "SELECT uuid FROM {{dbname.repo}}.blob WHERE rid="
        "(SELECT froot FROM {{dbname.repo}}.forumpost"
        " WHERE fpid=%" FSL_ID_T_PFMT ")", rid);
      rc = zRoot ? fsl_deck_G_set(&d, zRoot)
        : fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "Cannot find the thread of "
                         "forum post %s.", zReply);
      fsl_free(zRoot);
    }
  }
  if( 0==rc && zTitle ) rc = fsl_deck_H_set(&d, zTitle, -1);
  if( 0==rc && zMime && *zMime ) rc = fsl_deck_N_set(&d, zMime, -1);
  if( 0==rc ){
    char const * zU = fsl_cx_user_get(f);
    if( !zU ){
      zUser = fsl_user_name_guess();
      zU = zUser;
    }
    rc = zU ? fsl_deck_U_set(&d, zU) : FSL_RC_OOM;
  }
  if( 0==rc ) rc = fsl_deck_W_set(&d, zText, sqlite3_value_bytes(argv[0]));
  if( 0==rc ) rc = fsl_deck_save(&d, false);
  if( rc ) fslext_error(cx, f, rc);
  else fslext_result_hash(cx, f, d.rid);
  end:
  fsl_deck_finalize(&d);
  fsl_deck_finalize(&prev);
  fsl_free(zTitle);
  fsl_free(zReply);
  fsl_free(zEdits);
  fsl_free(zMime);
  fsl_free(zUser);
}

/** State for fslext_diff_f(). */
typedef struct {
  /** Only this file, or every file if NULL. */
  char const * zName;
  /** The unified-diff builder, writing to out. */
  fsl_dibu * db;
  fsl_dibu_opt opt;
  fsl_b out;
} FslextDiff;

/** fsl_cidiff() callback for fsl_diff(): appends one file's diff. */
static int fslext_diff_f(fsl_cidiff_state const * st){
  FslextDiff * const p = st->opt->callbackState;
  fsl_card_F const * const fc1 = st->fc1;
  fsl_card_F const * const fc2 = st->fc2;
  fsl_b lhs = fsl_b_empty, rhs = fsl_b_empty;
  int rc = 0;
  if( FSL_RC_STEP_ROW!=st->stepType
      || !(st->changes & (FSL_CIDIFF_FILE_MODIFIED | FSL_CIDIFF_FILE_ADDED
                          | FSL_CIDIFF_FILE_REMOVED)) ){
    return 0;
  }
  if( p->zName
      && !(fc1 && 0==fsl_strcmp(fc1->name, p->zName))
      && !(fc2 && 0==fsl_strcmp(fc2->name, p->zName)) ){
    return 0;
  }
  if( fc1 ) rc = fsl_card_F_content(st->f, fc1, &lhs);
  if( 0==rc && fc2 ) rc = fsl_card_F_content(st->f, fc2, &rhs);
  if( 0==rc ){
    p->opt.nameLHS = fc1 ? fc1->name : fc2->name;
    p->opt.nameRHS = fc2 ? fc2->name : fc1->name;
    p->opt.hashLHS = fc1 ? fc1->uuid : NULL;
    p->opt.hashRHS = fc2 ? fc2->uuid : NULL;
    rc = fsl_diff_v2(&lhs, &rhs, p->db);
    if( FSL_RC_DIFF_BINARY==rc ){
      /* As fossil(1) reports it. */
      rc = fsl_b_appendf(&p->out, "Index: %s\n%.66c\n"
                         "cannot compute difference between binary "
                         "files\n", p->opt.nameRHS, '=');
    }
  }
  fsl_b_clear(&lhs);
  fsl_b_clear(&rhs);
  return rc;
}

/*
  fsl_diff(FROM, TO [, NAME])

  Returns a unified diff of the files which differ between check-ins
  FROM and TO (anything fsl_resolve() accepts for a check-in), or only
  of file NAME. Added and removed files diff against nothing; a binary
  file gets fossil(1)'s "cannot compute difference between binary
  files" line. Returns an empty string if nothing differs.
*/
static void fslext_diff(sqlite3_context *cx, int argc,
                        sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zFrom = (char const *)sqlite3_value_text(argv[0]);
  char const * const zTo = (char const *)sqlite3_value_text(argv[1]);
  FslextDiff st = {0};
  fsl_cidiff_opt opt = fsl_cidiff_opt_empty;
  int rc;
  if( !f ) return;
  if( !zFrom || !*zFrom || !zTo || !*zTo ){
    sqlite3_result_error(cx, "fsl_diff() requires two versions.", -1);
    return;
  }
  st.zName = argc>2 ? (char const *)sqlite3_value_text(argv[2]) : NULL;
  st.opt = fsl_dibu_opt_empty;
  st.opt.out = fsl_output_f_b;
  st.opt.outState = &st.out;
  st.out = fsl_b_empty;
  rc = fsl_sym_to_rid(f, zFrom, FSL_SATYPE_CHECKIN, &opt.v1);
  if( 0==rc ) rc = fsl_sym_to_rid(f, zTo, FSL_SATYPE_CHECKIN, &opt.v2);
  if( 0==rc ) rc = fsl_dibu_factory(FSL_DIBU_UNIFIED_TEXT, &st.db);
  if( 0==rc ){
    st.db->opt = &st.opt;
    opt.callback = fslext_diff_f;
    opt.callbackState = &st;
    rc = fsl_cidiff(f, &opt);
  }
  if( rc ){
    fslext_error(cx, f, rc);
  }else{
    sqlite3_result_text64(cx, st.out.mem ? (char const *)st.out.mem : "",
                          st.out.used, SQLITE_TRANSIENT, SQLITE_UTF8);
  }
  if( st.db ) st.db->finalize(st.db);
  fsl_b_clear(&st.out);
}

/*
  fsl_annotate(NAME [, VERSION])

  An eponymous table-valued function: one row per line of file NAME
  as of check-in VERSION (default: the checkout's version, or "trunk"
  when only a repository is opened), with the check-in which last
  changed that line.

  - line_no: 1-based line number.
  - text: the line, without its line ending.
  - checkin, user, time, mtime: that check-in, its user (whoever
    merged it, for merged changes) and its time, as in fsl_timeline.

  SELECT line_no, user, text FROM fsl_annotate('src/main.c')
   WHERE text LIKE '%TODO%';

  A binary or empty file is an error.
*/
enum {
  FSLEXT_ANN_LINE_NO, FSLEXT_ANN_TEXT, FSLEXT_ANN_CHECKIN,
  FSLEXT_ANN_USER, FSLEXT_ANN_TIME, FSLEXT_ANN_MTIME,
  FSLEXT_ANN_NAME, FSLEXT_ANN_VERSION
};

/** One fsl_annotate row. */
typedef struct {
  uint32_t lineNo;
  char * zText;
  char * zCheckin;
  char * zUser;
  double mtime;
} FslextAnnRow;

typedef struct {
  sqlite3_vtab base;
  FslExt * ext;
} FslextAnnTab;

typedef struct {
  sqlite3_vtab_cursor base;
  FslextAnnRow * aRow;
  sqlite3_int64 nRow;
  sqlite3_int64 nAlloc;
  sqlite3_int64 i;
} FslextAnnCursor;

static void fslext_ann_reset(FslextAnnCursor * const c){
  for( sqlite3_int64 i = 0; i < c->nRow; ++i ){
    fsl_free(c->aRow[i].zText);
    fsl_free(c->aRow[i].zCheckin);
    fsl_free(c->aRow[i].zUser);
  }
  fsl_free(c->aRow);
  c->aRow = NULL;
  c->nRow = c->nAlloc = c->i = 0;
}

/** fsl_annotate() callback: appends one line to the cursor. */
static int fslext_ann_f(void * state, fsl_annotate_opt const * opt,
                        fsl_annotate_step const * step){
  FslextAnnCursor * const c = state;
  FslextAnnRow * r;
  (void)opt;
  if( FSL_ANNOTATE_STEP_FULL!=step->stepType ) return 0;
  if( c->nRow==c->nAlloc ){
    sqlite3_int64 const n = c->nAlloc ? c->nAlloc*2 : 64;
    FslextAnnRow * const a = fsl_realloc(c->aRow, n*sizeof(*a));
    if( !a ) return FSL_RC_OOM;
    c->aRow = a;
    c->nAlloc = n;
  }
  r = &c->aRow[c->nRow];
  r->lineNo = step->lineNumber;
  r->mtime = step->mtime;
  r->zText = fsl_strndup(step->line, (fsl_int_t)step->lineLength);
  r->zCheckin = fsl_strdup(step->versionHash);
  r->zUser = step->username ? fsl_strdup(step->username) : NULL;
  ++c->nRow;
  return (r->zText && r->zCheckin
          && (r->zUser || !step->username)) ? 0 : FSL_RC_OOM;
}

static int fslextAnnConnect(sqlite3 *db, void *pAux, int argc,
                            const char *const*argv,
                            sqlite3_vtab **ppVtab, char **pzErr){
  FslextAnnTab * p;
  int rc;
  (void)argc; (void)argv; (void)pzErr;
  rc = sqlite3_declare_vtab(db, "CREATE TABLE x(line_no INTEGER,"
                            " text TEXT, checkin TEXT, user TEXT,"
                            " time TEXT, mtime REAL,"
                            " name HIDDEN, version HIDDEN)");
  if( rc ) return rc;
  p = sqlite3_malloc(sizeof(*p));
  if( !p ) return SQLITE_NOMEM;
  memset(p, 0, sizeof(*p));
  p->ext = pAux;
  *ppVtab = &p->base;
  return SQLITE_OK;
}

static int fslextAnnDisconnect(sqlite3_vtab *pVtab){
  sqlite3_free(pVtab);
  return SQLITE_OK;
}

/*
  idxNum bit 1: NAME is argv[0]. Bit 2: VERSION follows it. NAME is
  required.
*/
static int fslextAnnBestIndex(sqlite3_vtab *tab,
                              sqlite3_index_info *pIdx){
  int iName = -1, iVersion = -1;
  (void)tab;
  for( int i = 0; i < pIdx->nConstraint; ++i ){
    struct sqlite3_index_constraint const * const pC =
      &pIdx->aConstraint[i];
    if( SQLITE_INDEX_CONSTRAINT_EQ!=pC->op ) continue;
    if( FSLEXT_ANN_NAME==pC->iColumn ){
      if( !pC->usable ) return SQLITE_CONSTRAINT;
      iName = i;
    }else if( FSLEXT_ANN_VERSION==pC->iColumn ){
      if( !pC->usable ) return SQLITE_CONSTRAINT;
      iVersion = i;
    }
  }
  if( iName<0 ){
    tab->zErrMsg = sqlite3_mprintf("fsl_annotate() requires a file "
                                   "name.");
    return SQLITE_ERROR;
  }
  pIdx->aConstraintUsage[iName].argvIndex = 1;
  pIdx->aConstraintUsage[iName].omit = 1;
  pIdx->idxNum = 1;
  if( iVersion>=0 ){
    pIdx->aConstraintUsage[iVersion].argvIndex = 2;
    pIdx->aConstraintUsage[iVersion].omit = 1;
    pIdx->idxNum |= 2;
  }
  pIdx->estimatedCost = 1000;
  return SQLITE_OK;
}

static int fslextAnnOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCur){
  FslextAnnCursor * const c = sqlite3_malloc(sizeof(*c));
  (void)p;
  if( !c ) return SQLITE_NOMEM;
  memset(c, 0, sizeof(*c));
  *ppCur = &c->base;
  return SQLITE_OK;
}

static int fslextAnnClose(sqlite3_vtab_cursor *cur){
  FslextAnnCursor * const c = (FslextAnnCursor*)cur;
  fslext_ann_reset(c);
  sqlite3_free(c);
  return SQLITE_OK;
}

/** Sets tab's error from f's error state, or from rc. */
static int fslext_vtab_error(sqlite3_vtab * const tab,
                             fsl_cx * const f, int rc){
  char const * zMsg = NULL;
  if( f ) fsl_cx_err_get(f, &zMsg, NULL);
  sqlite3_free(tab->zErrMsg);
  tab->zErrMsg = (zMsg && *zMsg)
    ? sqlite3_mprintf("%s", zMsg)
    : sqlite3_mprintf("libfossil error: %s", fsl_rc_cstr(rc));
  if( f ) fsl_cx_err_reset(f);
  return SQLITE_ERROR;
}

static int fslextAnnFilter(sqlite3_vtab_cursor *cur, int idxNum,
                           const char *idxStr, int argc,
                           sqlite3_value **argv){
  FslextAnnCursor * const c = (FslextAnnCursor*)cur;
  sqlite3_vtab * const tab = cur->pVtab;
  FslExt * const ext = ((FslextAnnTab*)tab)->ext;
  fsl_cx * const f = ext->f;
  fsl_annotate_opt opt = fsl_annotate_opt_empty;
  char const * const zVersion = (idxNum & 2)
    ? (char const *)sqlite3_value_text(argv[1]) : NULL;
  int rc = 0;
  (void)idxStr; (void)argc;
  fslext_ann_reset(c);
  if( !f ){
    sqlite3_free(tab->zErrMsg);
    tab->zErrMsg = sqlite3_mprintf("No repository is opened. "
                                   "Use fsl_open() first.");
    return SQLITE_ERROR;
  }
  if( fsl__cx_host_rollback_check(f) ){
    return fslext_vtab_error(tab, f, FSL_RC_DB);
  }
  opt.filename = (char const *)sqlite3_value_text(argv[0]);
  if( !opt.filename || !*opt.filename ){
    sqlite3_free(tab->zErrMsg);
    tab->zErrMsg = sqlite3_mprintf("fsl_annotate() requires a file "
                                   "name.");
    return SQLITE_ERROR;
  }
  if( zVersion || !fsl_cx_db_ckout(f) ){
    rc = fsl_sym_to_rid(f, zVersion ? zVersion : "trunk",
                        FSL_SATYPE_CHECKIN, &opt.versionRid);
  }
  if( 0==rc ){
    opt.praise = true;
    opt.out = fslext_ann_f;
    opt.outState = c;
    rc = fsl_annotate(f, &opt);
  }
  if( rc ){
    fslext_ann_reset(c);
    return fslext_vtab_error(tab, f, rc);
  }
  return SQLITE_OK;
}

static int fslextAnnNext(sqlite3_vtab_cursor *cur){
  ++((FslextAnnCursor*)cur)->i;
  return SQLITE_OK;
}

static int fslextAnnEof(sqlite3_vtab_cursor *cur){
  FslextAnnCursor * const c = (FslextAnnCursor*)cur;
  return c->i >= c->nRow;
}

static int fslextAnnColumn(sqlite3_vtab_cursor *cur, sqlite3_context *cx,
                           int i){
  FslextAnnRow const * const r =
    &((FslextAnnCursor*)cur)->aRow[((FslextAnnCursor*)cur)->i];
  switch( i ){
    case FSLEXT_ANN_LINE_NO: sqlite3_result_int64(cx, r->lineNo); break;
    case FSLEXT_ANN_TEXT:
      sqlite3_result_text(cx, r->zText, -1, SQLITE_TRANSIENT); break;
    case FSLEXT_ANN_CHECKIN:
      sqlite3_result_text(cx, r->zCheckin, -1, SQLITE_TRANSIENT); break;
    case FSLEXT_ANN_USER:
      if( r->zUser ) sqlite3_result_text(cx, r->zUser, -1,
                                         SQLITE_TRANSIENT);
      break;
    case FSLEXT_ANN_TIME: {
      char z[24];
      if( fsl_julian_to_iso8601(r->mtime, z, false) ){
        z[10] = ' ';
        sqlite3_result_text(cx, z, 19, SQLITE_TRANSIENT);
      }
      break;
    }
    case FSLEXT_ANN_MTIME: sqlite3_result_double(cx, r->mtime); break;
    default: break;
  }
  return SQLITE_OK;
}

static int fslextAnnRowid(sqlite3_vtab_cursor *cur, sqlite3_int64 *pRowid){
  *pRowid = ((FslextAnnCursor*)cur)->i + 1;
  return SQLITE_OK;
}

static sqlite3_module fslextAnnModule = {
  0,                       /* iVersion */
  0,                       /* xCreate: eponymous-only */
  fslextAnnConnect,        /* xConnect */
  fslextAnnBestIndex,      /* xBestIndex */
  fslextAnnDisconnect,     /* xDisconnect */
  0,                       /* xDestroy */
  fslextAnnOpen,           /* xOpen */
  fslextAnnClose,          /* xClose */
  fslextAnnFilter,         /* xFilter */
  fslextAnnNext,           /* xNext */
  fslextAnnEof,            /* xEof */
  fslextAnnColumn,         /* xColumn */
  fslextAnnRowid,          /* xRowid */
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

/**
   Adds one file change to d: zName gets the given content, or is
   removed if pContent is NULL. zPerm is NULL/"" (regular), "x"
   (executable) or "l" (symlink).
*/
static int fslext_commit_file(fsl_deck * const d, char const * zName,
                              fsl_b * const pContent, char const * zPerm){
  fsl_fileperm_e perm = FSL_FILE_PERM_REGULAR;
  if( zPerm && 'x'==*zPerm ) perm = FSL_FILE_PERM_EXE;
  else if( zPerm && 'l'==*zPerm ) perm = FSL_FILE_PERM_LINK;
  if( !pContent ){
    int const rc = fsl_deck_F_set(d, zName, NULL, perm, NULL);
    return FSL_RC_NOT_FOUND==rc
      ? fsl_cx_err_set(d->f, rc, "Cannot remove %s: it is not in "
                       "the parent check-in.", zName)
      : rc;
  }
  return fsl_deck_F_set_content(d, zName, pContent, perm, NULL);
}

/**
   Puts d on new branch zBranch, a child of check-in parentRid: adds
   the branch's T-cards and cancels parentRid's other branch tags, as
   fossil(1)'s commit --branch does. Without the cancellations the new
   check-in would also carry its parent's branch name, e.g. trunk.
*/
static int fslext_branch(fsl_deck * const d, fsl_id_t parentRid,
                         char const * zBranch){
  fsl_stmt q = fsl_stmt_empty;
  int rc = fsl_deck_branch_set(d, zBranch);
  if( 0==rc && parentRid>0 ){
    rc = fsl_cx_prepare(d->f, &q,
           "SELECT tagname FROM {{dbname.repo}}.tagxref AS tagxref,"
           " {{dbname.repo}}.tag AS tag"
           " WHERE tagxref.rid=%" FSL_ID_T_PFMT
           " AND tagxref.tagid=tag.tagid AND tagtype>0"
           " AND tagname GLOB 'sym-*' AND tagname<>'sym-'||%Q"
           " ORDER BY tagname", parentRid, zBranch);
  }
  while( q.stmt && fsl__cx_stmt_step_each(d->f, &q, &rc) ){
    rc = fsl_deck_T_add(d, FSL_TAGTYPE_CANCEL, NULL,
                        fsl_stmt_g_text(&q, 0, NULL), NULL);
  }
  fsl_stmt_finalize(&q);
  return rc;
}

/**
   Adds the file changes listed in zSql's result rows (name, content,
   perm, removed) to d. zSql takes the commit's JSON as ?1.
*/
static int fslext_commit_files(fsl_deck * const d, sqlite3 * const db,
                               char const * zSql, sqlite3_value * json){
  sqlite3_stmt * q = NULL;
  fsl_b content = fsl_b_empty;
  int rc = 0, src;
  if( SQLITE_OK!=sqlite3_prepare_v2(db, zSql, -1, &q, NULL) ){
    return fsl_cx_err_set(d->f, FSL_RC_DB, "%s", sqlite3_errmsg(db));
  }
  if( json ) sqlite3_bind_value(q, 1, json);
  while( 0==rc && SQLITE_ROW==(src = sqlite3_step(q)) ){
    char const * const zName = (char const *)sqlite3_column_text(q, 0);
    bool const removed = sqlite3_column_int(q, 3)
      || SQLITE_NULL==sqlite3_column_type(q, 1);
    if( !zName || !*zName ){
      rc = fsl_cx_err_set(d->f, FSL_RC_MISUSE,
                          "A file in the commit has no name.");
      break;
    }
    fsl_b_reuse(&content);
    if( !removed ){
      rc = fsl_b_append(&content, sqlite3_column_blob(q, 1),
                        sqlite3_column_bytes(q, 1));
    }
    if( 0==rc ){
      rc = fslext_commit_file(d, zName, removed ? NULL : &content,
                              (char const *)sqlite3_column_text(q, 2));
    }
  }
  if( 0==rc && SQLITE_DONE!=src ){
    rc = fsl_cx_err_set(d->f, FSL_RC_DB, "%s", sqlite3_errmsg(db));
  }
  sqlite3_finalize(q);
  fsl_b_clear(&content);
  return rc;
}

/**
   After a commit from db: working copy w, inside its transaction:
   turns each file which holds its own content and was committed
   (vfile, now of the new check-in vid, has it unchanged) back into a
   reference to its new blob, dropping the content. Each is checked
   against the blob's hash first, so only bytes the repository holds
   are dropped. Files not committed, e.g. unmanaged ones, keep their
   content.
*/
static int fslext_wc_committed(FslextWc * const w, fsl_id_t vid){
  sqlite3_stmt * q = NULL;
  sqlite3_str * names = NULL;
  char * zTmpl = sqlite3_mprintf(
    "SELECT f.name, v.mrid, f.content FROM $F f"
    " JOIN main.\"%wvfile\" v ON v.pathname=f.name $C"
    " WHERE f.content IS NOT NULL AND v.vid=?1 AND v.mrid>0"
    " AND v.chnged=0 AND v.deleted=0", w->zPre);
  char * zNames = NULL;
  int rc, nNames = 0;
  if( !zTmpl ) return fsl_cx_err_set(w->f, FSL_RC_OOM, NULL);
  rc = fslext_wc_prep(w, &q, zTmpl);
  sqlite3_free(zTmpl);
  if( rc ) return rc;
  sqlite3_bind_int64(q, 1, (sqlite3_int64)vid);
  names = sqlite3_str_new(w->db);
  /* Collect "RID\0NAME\0" pairs first: the files change after. */
  while( SQLITE_ROW==(rc = fslext_wc_step(w, q)) ){
    fsl_id_t const rid = (fsl_id_t)sqlite3_column_int64(q, 1);
    void const * const p = sqlite3_column_blob(q, 2);
    fsl_size_t const n = (fsl_size_t)sqlite3_column_bytes(q, 2);
    bool same = false;
    rc = fslext_wc_is_blob(w, rid, p, n, &same);
    if( rc ) break;
    if( same ){
      char const * const zName = (char const *)sqlite3_column_text(q, 0);
      sqlite3_str_appendf(names, "%lld", (long long)rid);
      sqlite3_str_append(names, "", 1);
      sqlite3_str_append(names, zName, (int)strlen(zName) + 1);
      ++nNames;
    }
  }
  sqlite3_finalize(q);
  if( SQLITE_DONE==rc ) rc = 0;
  zNames = sqlite3_str_finish(names);
  if( 0==rc && nNames && !zNames ) rc = fsl_cx_err_set(w->f, FSL_RC_OOM, NULL);
  for( char const * z = zNames; 0==rc && nNames--; ){
    char const * const zName = z + strlen(z) + 1;
    rc = fslext_wc_to_ref(w, zName, (fsl_id_t)strtoll(z, NULL, 10));
    z = zName + strlen(zName) + 1;
  }
  sqlite3_free(zNames);
  return rc;
}

/**
   Saves the changes in f's checkout as a new check-in, as fossil(1)'s
   commit does, and moves the checkout to it. On success *pRid is the
   new check-in's rid. fslext_commit() calls this when a checkout is
   opened.
*/
static int fslext_commit_ckout(fsl_cx * const f, FslextWc * const w,
                               char const * zComment,
                               char const * zBranch, char const * zUser,
                               double mtime, fsl_id_t * const pRid){
  fsl_checkin_opt cOpt = fsl_checkin_opt_empty;
  fsl_checkin_queue_opt qOpt = fsl_checkin_queue_opt_empty;
  fsl_uuid_str zNew = NULL;
  fsl_id_t vid = 0;
  int rc;
  cOpt.julianTime = mtime>0 ? mtime : fsl_db_julian_now(fsl_cx_db_repo(f));
  cOpt.message = zComment;
  cOpt.user = zUser;
  cOpt.branch = zBranch;
  cOpt.calcRCard = true;
  cOpt.scanForChanges = false /* fsl_checkin_enqueue() scans */;
  qOpt.filename = ".";
  qOpt.relativeToCwd = false;
  qOpt.scanForChanges = true;
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO | FSL_DBROLE_CKOUT);
  if( rc ) return rc;
  /* Check inside the transaction, which holds the write lock, so that
     no other connection's check-in can come between. Another
     connection may also have moved this checkout. */
  rc = fsl__ckout_version_fetch(f);
  fsl_ckout_version_info(f, &vid, NULL);
  if( 0==rc && vid>0 && !zBranch && !fsl_rid_is_leaf(f, vid) ){
    rc = fsl_cx_err_get(f, NULL, NULL);
    if( !rc ){
      rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "Would fork: the checkout's "
                          "version is not a leaf. Use fsl_update() "
                          "first, or give a \"branch\".");
    }
  }
  if( 0==rc && zBranch
      && fsl_db_exists(fsl_cx_db_repo(f),
           "SELECT 1 FROM {{dbname.repo}}.leaf AS leaf,"
           " {{dbname.repo}}.tagxref AS tagxref"
           " WHERE tagxref.rid=leaf.rid AND tagxref.tagtype>0"
           " AND tagxref.tagid=(SELECT tagid FROM {{dbname.repo}}.tag"
           "  WHERE tagname='sym-'||%Q)"
           " AND NOT EXISTS(SELECT 1 FROM {{dbname.repo}}.tagxref c"
           "  WHERE c.rid=leaf.rid AND c.tagid=%d AND c.tagtype>0)",
           zBranch, FSL_TAGID_CLOSED) ){
    /* As fossil(1)'s commit --branch refuses without --force. */
    rc = fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS, "Branch %s already "
                        "exists and is open.", zBranch);
  }
  if( 0==rc && vid>0 ){
    fsl_deck parent = fsl_deck_empty;
    rc = fsl_deck_load_rid(f, &parent, vid, FSL_SATYPE_CHECKIN);
    if( 0==rc && parent.D >= cOpt.julianTime ){
      rc = fsl_cx_err_set(f, FSL_RC_RANGE, "The checkout's version is "
                          "newer than the check-in's date.");
    }
    fsl_deck_finalize(&parent);
  }
  if( 0==rc ) rc = fsl_checkin_enqueue(f, &qOpt);
  if( 0==rc ) rc = fsl_checkin_commit(f, &cOpt, pRid, &zNew);
  if( 0==rc && w ) rc = fslext_wc_committed(w, *pRid);
  fsl_free(zNew);
  if( 0==rc ){
    rc = fsl_cx_txn_end(f, false);
  }else{
    fsl_cx_txn_end(f, true);
  }
  fsl_checkin_discard(f);
  return rc;
}

/*
  fsl_commit(JSON)

  Saves one check-in and returns its hash. JSON is an object:

  - "comment" (required): the check-in comment.
  - "parent": the symbolic name of the parent (default "trunk"), or
    null to start a new root check-in.
  - "branch": puts the check-in on a new branch of that name.
  - "user": overrides the default user.
  - "date": anything SQLite's julianday() accepts (default now).
  - "files": an array of {"name", "content", "perm", "removed"}.
    "content" is text. "perm" is "x" for executable. "removed": true
    or a null "content" removes the file.

  Rows in the TEMP table fsl_stage(name, content, perm), which
  fsl_open() creates, are added too, and that table is emptied when
  the check-in is saved. There is one per connection, not one per
  repository: rows go to whichever repository's fsl_commit() runs
  next. Use it for BLOB content such as readfile().
  Files not named keep their parent's content.

  When a checkout is opened, the check-in instead saves the changes
  in the checkout's files, as fossil(1)'s commit does, and the
  checkout moves to it. Its parent is the checkout's version, so
  "parent", "files", and fsl_stage rows are errors, and so is a
  check-in which would fork the branch without a "branch", or a
  "branch" which already exists and is open. With the repository's
  manifest setting on, the manifest files it writes into the checkout
  are not undone by a ROLLBACK. In a db: working copy, the rows of
  the files it saves become references to their new blobs, dropping
  their content, in the same transaction.
*/
static void fslext_commit(sqlite3_context *cx, int argc, sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  FslExt * const ext = sqlite3_user_data(cx);
  sqlite3 * const db = ext->db;
  sqlite3_stmt * q = NULL;
  fsl_deck d = fsl_deck_empty;
  char * zParent = NULL, * zComment = NULL, * zBranch = NULL,
       * zUser = NULL;
  bool hasParent = true, parentGiven = false, filesGiven = false;
  double mtime = 0;
  int rc;
  (void)argc;
  if( !f ) return;
  rc = sqlite3_prepare_v2(db,
         "SELECT json_extract(?1,'$.comment'),"
         " json_type(?1,'$.parent'), json_extract(?1,'$.parent'),"
         " json_extract(?1,'$.branch'), json_extract(?1,'$.user'),"
         " julianday(json_extract(?1,'$.date')),"
         " json_type(?1,'$.files'),"
         " (SELECT count(*) FROM temp.fsl_stage)", -1, &q, NULL);
  if( rc ){
    sqlite3_result_error(cx, sqlite3_errmsg(db), -1);
    return;
  }
  sqlite3_bind_value(q, 1, argv[0]);
  if( SQLITE_ROW!=sqlite3_step(q) ){
    sqlite3_result_error(cx, sqlite3_errmsg(db), -1);
    sqlite3_finalize(q);
    return;
  }
#define COL(N) (sqlite3_column_text(q, N) \
                ? fsl_strdup((char const *)sqlite3_column_text(q, N)) : NULL)
  zComment = COL(0);
  hasParent = !sqlite3_column_text(q, 1)
    || 0!=strcmp("null", (char const *)sqlite3_column_text(q, 1));
  zParent = COL(2);
  zBranch = COL(3);
  zUser = COL(4);
#undef COL
  if( SQLITE_NULL!=sqlite3_column_type(q, 5) ){
    mtime = sqlite3_column_double(q, 5);
  }
  parentGiven = SQLITE_NULL!=sqlite3_column_type(q, 1);
  filesGiven = SQLITE_NULL!=sqlite3_column_type(q, 6)
    || sqlite3_column_int(q, 7)>0;
  sqlite3_finalize(q);
  if( !zComment || !*zComment ){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                        "fsl_commit() requires a \"comment\".");
    goto end;
  }
  if( fsl_cx_db_ckout(f) ){
    fsl_id_t rid = 0;
    char const * const zU = zUser ? zUser : fsl_cx_user_get(f);
    if( parentGiven || filesGiven ){
      rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "A checkout is opened, so "
                          "fsl_commit() saves its files: write them "
                          "there, use fsl_add(), fsl_rm(), and fsl_mv(), "
                          "and leave out \"parent\", \"files\", and "
                          "fsl_stage rows.");
    }else if( !zU ){
      rc = fsl_cx_err_set(f, FSL_RC_MISUSE, "No user name is known. Pass "
                          "one to fsl_open() or as \"user\".");
    }else{
      rc = fslext_commit_ckout(f, fslext_wc_of(ext, f), zComment, zBranch,
                               zU, mtime, &rid);
      if( 0==rc ) fslext_result_hash(cx, f, rid);
    }
    goto end;
  }
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if( rc ) goto end;
  if( hasParent ){
    fsl_id_t parentRid = 0;
    rc = fsl_deck_load_sym(f, &d, zParent ? zParent : "trunk",
                           FSL_SATYPE_CHECKIN);
    parentRid = d.rid;
    if( 0==rc ) rc = fsl_deck_derive(&d);
    if( 0==rc && zBranch ) rc = fslext_branch(&d, parentRid, zBranch);
  }else{
    fsl_deck_init(f, &d, FSL_SATYPE_CHECKIN);
    rc = fsl_deck_branch_set(&d, zBranch ? zBranch : "trunk");
  }
  if( 0==rc ){
    rc = fsl_deck_D_set(&d, mtime>0 ? mtime
                        : fsl_db_julian_now(fsl_cx_db_repo(f)));
  }
  if( 0==rc ) rc = fsl_deck_C_set(&d, zComment, -1);
  if( 0==rc ){
    char const * const zU = zUser ? zUser : fsl_cx_user_get(f);
    rc = zU
      ? fsl_deck_U_set(&d, zU)
      : fsl_cx_err_set(f, FSL_RC_MISUSE, "No user name is known. Pass "
                       "one to fsl_open() or as \"user\".");
  }
  if( 0==rc ){
    rc = fslext_commit_files(&d, db,
           "SELECT json_extract(value,'$.name'),"
           " json_extract(value,'$.content'),"
           " json_extract(value,'$.perm'),"
           " coalesce(json_extract(value,'$.removed'),0)"
           " FROM json_each(?1,'$.files')", argv[0]);
  }
  if( 0==rc ){
    rc = fslext_commit_files(&d, db,
           "SELECT name, content, perm, 0 FROM temp.fsl_stage", NULL);
  }
  if( 0==rc ) rc = fsl_deck_save(&d, false);
  if( 0==rc ){
    rc = fsl_cx_exec(f, "DELETE FROM temp.fsl_stage");
  }
  if( 0==rc ){
    rc = fsl_cx_txn_end(f, false);
    if( 0==rc ) fslext_result_hash(cx, f, d.rid);
  }else{
    fsl_cx_txn_end(f, true);
  }
  end:
  if( rc ) fslext_error(cx, f, rc);
  fsl_deck_finalize(&d);
  fsl_free(zParent);
  fsl_free(zComment);
  fsl_free(zBranch);
  fsl_free(zUser);
}

/*
  fsl_branch(NAME, FROM [, OPTIONS])

  Starts branch NAME at check-in FROM (anything fsl_resolve() accepts
  for a check-in) and returns the hash of the branch's first check-in,
  which has FROM's files, as fossil(1)'s branch new does. OPTIONS is a
  JSON object with any of "comment", "user", "color" ("#RRGGBB") and
  "private" (true makes the branch private). It is an error if NAME
  already has an open leaf.
*/
static void fslext_branch_new(sqlite3_context *cx, int argc,
                              sqlite3_value **argv){
  FslExt * const ext = sqlite3_user_data(cx);
  fsl_cx * const f = fslext_cx(cx);
  fsl_branch_opt opt = fsl_branch_opt_empty;
  char const * const zFrom = (char const *)sqlite3_value_text(argv[1]);
  char * zComment = NULL, * zUser = NULL, * zColor = NULL;
  sqlite3_stmt * q = NULL;
  fsl_id_t rid = 0;
  int rc;
  if( !f ) return;
  opt.name = (char const *)sqlite3_value_text(argv[0]);
  if( !opt.name || !*opt.name || !zFrom || !*zFrom ){
    sqlite3_result_error(cx, "fsl_branch() requires a name and a "
                         "starting check-in.", -1);
    return;
  }
  if( argc>2 && SQLITE_NULL!=sqlite3_value_type(argv[2]) ){
    rc = sqlite3_prepare_v2(ext->db,
           "SELECT json_extract(?1,'$.comment'), json_extract(?1,'$.user'),"
           " json_extract(?1,'$.color'),"
           " coalesce(json_extract(?1,'$.private'),0)", -1, &q, NULL);
    if( 0==rc ){
      sqlite3_bind_value(q, 1, argv[2]);
      rc = sqlite3_step(q);
      rc = SQLITE_ROW==rc ? 0 : rc;
    }
    if( rc ){
      sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
      sqlite3_finalize(q);
      return;
    }
#define COL(N) (sqlite3_column_text(q, N) \
                ? fsl_strdup((char const *)sqlite3_column_text(q, N)) : NULL)
    zComment = COL(0);
    zUser = COL(1);
    zColor = COL(2);
#undef COL
    opt.isPrivate = 0!=sqlite3_column_int(q, 3);
    sqlite3_finalize(q);
    opt.comment = zComment;
    opt.user = zUser;
    opt.bgColor = zColor;
  }
  rc = fsl_sym_to_rid(f, zFrom, FSL_SATYPE_CHECKIN, &opt.basisRid);
  if( 0==rc ) rc = fsl_branch_create(f, &opt, &rid);
  if( rc ) fslext_error(cx, f, rc);
  else fslext_result_hash(cx, f, rid);
  fsl_free(zComment);
  fsl_free(zUser);
  fsl_free(zColor);
}

/*
  fsl_setting(NAME)
  fsl_setting(NAME, VALUE [, SCOPE])

  With one argument, returns setting NAME's value as fossil(1) would
  use it: from the checkout's versioned .fossil-settings/NAME file if
  there is one (its content as is, newline included), else from the
  repository, else from the global
  configuration if it is opened (SCOPE "global" opens it), or NULL if
  none has it.

  With VALUE, sets NAME to VALUE in the repository, or, if SCOPE is
  "global", in the user's global configuration, which it opens if
  needed (that must happen outside of a transaction). A NULL VALUE
  removes the setting there. Returns VALUE.
*/
static void fslext_setting(sqlite3_context *cx, int argc,
                           sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zName = (char const *)sqlite3_value_text(argv[0]);
  char const * const zScope = argc>2
    ? (char const *)sqlite3_value_text(argv[2]) : NULL;
  fsl_confdb_e mode = FSL_CONFDB_REPO;
  int rc = 0;
  if( !f ) return;
  if( !zName || !*zName ){
    sqlite3_result_error(cx, "fsl_setting() requires a name.", -1);
    return;
  }
  if( zScope && *zScope ){
    if( 0!=fsl_strcmp(zScope, "global") && 0!=fsl_strcmp(zScope, "repo") ){
      sqlite3_result_error(cx, "fsl_setting(): SCOPE must be \"repo\" "
                           "or \"global\".", -1);
      return;
    }
    if( 'g'==*zScope ){
      mode = FSL_CONFDB_GLOBAL;
      if( !fsl_cx_db_config(f) ){
        FslExt * const ext = sqlite3_user_data(cx);
        if( !sqlite3_get_autocommit(ext->db) ){
          sqlite3_result_error(cx, "fsl_setting() cannot open the global "
                               "configuration inside a transaction.", -1);
          return;
        }
        rc = fsl_config_open(f, NULL);
      }
    }
  }
  if( 1==argc ){
    char * const z = fsl_configs_get_text(f, "vrg", zName, NULL);
    if( z ) sqlite3_result_text(cx, z, -1, SQLITE_TRANSIENT);
    else sqlite3_result_null(cx);
    fsl_free(z);
    return;
  }
  if( 0==rc ){
    char const * const zValue = (char const *)sqlite3_value_text(argv[1]);
    rc = zValue
      ? fsl_config_set_text(f, mode, zName, zValue)
      : fsl_config_unset(f, mode, zName);
  }
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_value(cx, argv[1]);
}

/*
  fsl_tag(TARGET, NAME [, VALUE [, KIND [, USER]]])

  Tags the artifact TARGET (any symbolic name) and returns the hash of
  the new control artifact. KIND is "+" (default, tags just TARGET),
  "*" (propagates to descendants) or "-" (cancels the tag).
*/
static void fslext_tag(sqlite3_context *cx, int argc, sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zTarget = (char const *)sqlite3_value_text(argv[0]);
  char const * const zName = (char const *)sqlite3_value_text(argv[1]);
  char const * const zValue = argc>2
    ? (char const *)sqlite3_value_text(argv[2]) : NULL;
  char const * const zKind = argc>3
    ? (char const *)sqlite3_value_text(argv[3]) : NULL;
  char const * zUser = argc>4
    ? (char const *)sqlite3_value_text(argv[4]) : NULL;
  fsl_tagtype_e type = FSL_TAGTYPE_ADD;
  fsl_id_t newId = 0;
  int rc;
  if( !f ) return;
  if( !zTarget || !zName || !*zName ){
    sqlite3_result_error(cx, "fsl_tag() requires a target "
                         "and a tag name.", -1);
    return;
  }
  if( zKind && '*'==*zKind ) type = FSL_TAGTYPE_PROPAGATING;
  else if( zKind && '-'==*zKind ) type = FSL_TAGTYPE_CANCEL;
  else if( zKind && *zKind && '+'!=*zKind ){
    sqlite3_result_error(cx, "fsl_tag() KIND must be "
                         "\"+\", \"*\", or \"-\".", -1);
    return;
  }
  if( !zUser ) zUser = fsl_cx_user_get(f);
  if( !zUser ){
    sqlite3_result_error(cx, "No user name is known. Pass one to "
                         "fsl_open() or fsl_tag().", -1);
    return;
  }
  /* Take the write lock first, so that a concurrent writer is waited
     for, not reported as SQLITE_BUSY. */
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_REPO);
  if( 0==rc ){
    rc = fsl_tag_sym(f, type, zTarget, zName, zValue, zUser,
                     fsl_db_julian_now(fsl_cx_db_repo(f)), &newId);
    if( 0==rc ) rc = fsl_cx_txn_end(f, false);
    else fsl_cx_txn_end(f, true);
  }
  if( rc ) fslext_error(cx, f, rc);
  else fslext_result_hash(cx, f, newId);
}

/** fsl_pw_f() which supplies the password given in an OPTIONS object. */
static int fslext_pw_f(fsl_cx * f, char const * zUrl, fsl_b * bOut,
                       void * state){
  (void)f; (void)zUrl;
  return fsl_b_append(bOut, (char const *)state, -1);
}

/**
   Applies fsl_sync()'s and fsl_clone()'s OPTIONS object, pOpt, to xc:
   "password", "save" and "private". If pzMode is not NULL, sets it to
   a copy of "mode". *pzPw gets a copy of the password, which xc's
   password callback points to and the caller must fsl_free() after
   the sync. Returns false, with an error on cx, on failure.
*/
static bool fslext_xfer_opts(sqlite3_context * const cx,
                             sqlite3_value * const pOpt,
                             fsl_xfer_config * const xc,
                             char ** pzMode, char ** pzPw){
  FslExt * const ext = sqlite3_user_data(cx);
  sqlite3_stmt * q = NULL;
  int rc = sqlite3_prepare_v2(ext->db,
             "SELECT json_extract(?1,'$.mode'),"
             " json_extract(?1,'$.password'),"
             " coalesce(json_extract(?1,'$.save'),0),"
             " coalesce(json_extract(?1,'$.private'),0)", -1, &q, NULL);
  if( 0==rc ){
    sqlite3_bind_value(q, 1, pOpt);
    rc = sqlite3_step(q);
    rc = SQLITE_ROW==rc ? 0 : rc;
  }
  if( rc ){
    sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
    sqlite3_finalize(q);
    return false;
  }
  if( pzMode && sqlite3_column_text(q, 0) ){
    *pzMode = fsl_strdup((char const *)sqlite3_column_text(q, 0));
  }
  if( sqlite3_column_text(q, 1) ){
    *pzPw = fsl_strdup((char const *)sqlite3_column_text(q, 1));
    xc->password.callback = fslext_pw_f;
    xc->password.state = *pzPw;
    /* A password given here trumps a saved one. */
    xc->password.ignoreSaved = true;
  }
  xc->password.save = 0!=sqlite3_column_int(q, 2);
  xc->op.privateContent = 0!=sqlite3_column_int(q, 3);
  sqlite3_finalize(q);
  return true;
}

/*
  fsl_sync(URL [, MODE])
  fsl_sync(URL, OPTIONS)

  Syncs the opened repository with URL. MODE is "pull", "push", or
  "sync" (default). OPTIONS is a JSON object with any of:

  - "mode": as MODE.
  - "password": the password for the URL's user, which then trumps a
    saved one. Pass it as a bound parameter, e.g.
    fsl_sync(:url, json_object('password', :pw)), to keep it out of
    the SQL text.
  - "save": true saves the (hashed) password for later syncs with
    that URL. Default false.
  - "private": true also syncs private content.

  Returns a JSON object with the counts of artifacts
  received and sent. Each protocol round commits on its own, so in
  autocommit mode other connections can write between rounds. Inside a
  host transaction, nothing reaches the disk until the host commits.
*/
static void fslext_sync_metrics(fsl_xfer_metrics const * m, void * state,
                                int theRc){
  (void)theRc;
  *(fsl_xfer_metrics*)state = *m;
}

static void fslext_sync(sqlite3_context *cx, int argc, sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * const zUrl = (char const *)sqlite3_value_text(argv[0]);
  char const * zMode = argc>1
    ? (char const *)sqlite3_value_text(argv[1]) : "sync";
  char * zOptMode = NULL, * zPw = NULL;
  fsl_xfer_config xc = fsl_xfer_config_empty;
  fsl_xfer_metrics m = fsl_xfer_metrics_empty;
  int rc;
  if( !f ) return;
  if( !zUrl || !*zUrl ){
    sqlite3_result_error(cx, "fsl_sync() requires a URL.", -1);
    return;
  }
  if( zMode && '{'==*zMode ){
    if( !fslext_xfer_opts(cx, argv[1], &xc, &zOptMode, &zPw) ) return;
    zMode = zOptMode;
  }
  if( !zMode || 0==strcmp(zMode, "sync") ){
    xc.op.pull = xc.op.push = true;
  }else if( 0==strcmp(zMode, "pull") ){
    xc.op.pull = true;
  }else if( 0==strcmp(zMode, "push") ){
    xc.op.push = true;
  }else{
    sqlite3_result_error(cx, "fsl_sync() MODE must be \"pull\", "
                         "\"push\", or \"sync\".", -1);
    fsl_free(zOptMode);
    fsl_free(zPw);
    return;
  }
  fsl_b_external(&xc.url, zUrl, -1);
  xc.compressTraffic = true;
  xc.metrics.callback = fslext_sync_metrics;
  xc.metrics.state = &m;
  rc = fsl_sync_client(f, &xc, NULL);
  fsl_xfer_config_cleanup(&xc);
  fsl_free(zOptMode);
  fsl_free(zPw);
  if( rc ){
    fslext_error(cx, f, rc);
    return;
  }
  {
    char * const z = sqlite3_mprintf(
      "{\"rounds\":%lld,\"received\":%lld,\"sent\":%lld}",
      (long long)m.trips,
      /* Only the per-card counts are maintained by xfer.c. */
      (long long)(m.cardsRx[fsl_xfcard_e_file]
                  + m.cardsRx[fsl_xfcard_e_cfile]),
      (long long)(m.cardsTx[fsl_xfcard_e_file]
                  + m.cardsTx[fsl_xfcard_e_cfile]));
    if( z ) sqlite3_result_text(cx, z, -1, sqlite3_free);
    else sqlite3_result_error_nomem(cx);
  }
}

/*
  fsl_clone(URL, FILE [, OPTIONS])
  fsl_clone(URL, 'repo:NAME' [, OPTIONS])

  Clones URL into the new repository FILE, using its own connection,
  and returns FILE. It needs no fsl_open(). OPTIONS is a JSON object
  with fsl_sync()'s "password", "save" and "private".

  'repo:NAME' clones into a temporary file beside this connection's
  main db (see the top of this file), so that nothing holds the host's
  write lock during the network exchange, and fsl_import()s that, in
  one short transaction, opened as fsl_open('repo:NAME') does. It
  deletes the file and returns 'repo:NAME'. Any failure leaves no
  trace of repo:NAME, though a process which dies during the clone
  leaves the file, named after the host db with a suffix of
  "-fslclone-" and a random number. It needs room for the whole
  repository there, a main db which is a file and, as fsl_open(), no
  transaction. It checks that repo:NAME is free before the download,
  and the import checks again, for one which appeared meanwhile.
*/
static void fslext_clone(sqlite3_context *cx, int argc, sqlite3_value **argv){
  char const * const zUrl = (char const *)sqlite3_value_text(argv[0]);
  char const * const zFile = (char const *)sqlite3_value_text(argv[1]);
  FslExt * const ext = sqlite3_user_data(cx);
  fsl_clone_config cc = fsl_clone_config_empty;
  fsl_error err = fsl_error_empty;
  char zRepo[FSLEXT_WC_NAME_MAX+1];
  int const repoKind = fslext_repo_name(zFile, zRepo);
  char * zPw = NULL;
  char * zTmp = NULL;
  char * zPre = NULL;
  fsl_cx * f = NULL;
  int rc;
  if( !zUrl || !*zUrl || !zFile || !*zFile ){
    sqlite3_result_error(cx, "fsl_clone() requires a URL and a "
                         "file name.", -1);
    return;
  }else if( repoKind<0 ){
    sqlite3_result_error(cx, FSLEXT_REPO_NAME_ERR, -1);
    return;
  }else if( repoKind>0 && !fslext_open_ok(cx, ext, "fsl_clone") ){
    return;
  }else if( repoKind>0 && fslext_find(ext, zFile) ){
    fslext_already_open(cx, zRepo);
    return;
  }
  if( argc>2 && SQLITE_NULL!=sqlite3_value_type(argv[2])
      && !fslext_xfer_opts(cx, argv[2], &cc.xfer, NULL, &zPw) ){
    return;
  }
  if( repoKind>0 ){
    char const * const zHost = sqlite3_db_filename(ext->db, "main");
    sqlite3_uint64 nRand;
    if( !zHost || !*zHost ){
      sqlite3_result_error(cx, "fsl_clone() into a repo:NAME repository "
                           "needs a main db which is a file.", -1);
      fsl_free(zPw);
      return;
    }
    sqlite3_randomness((int)sizeof(nRand), &nRand);
    zTmp = fsl_mprintf("%s-fslclone-%016llx", zHost,
                       (unsigned long long)nRand);
    zPre = fsl_mprintf(FSLEXT_REPO_PREFIX "%s_", zRepo);
    rc = (zTmp && zPre) ? fsl_cx_init(&f, NULL) : FSL_RC_OOM;
    if( 0==rc ) rc = fsl_cx_host_db(f, ext->db);
    if( 0==rc ){
      /* Before the download, which may be long. */
      fsl_db h = fsl_db_empty;
      fsl__db_borrow(&h, ext->db);
      rc = fsl__cx_repo_prefix_check(f, &h, zPre);
      if( 0==rc ) rc = fsl__repo_host_free_check(f, &h, zPre);
      fsl_db_close(&h)/*does not close the host's handle*/;
    }
    if( rc ){
      if( f ) fslext_open_finish(cx, ext, f, rc, argv[1]);
      else sqlite3_result_error_nomem(cx);
      fsl_free(zPw);
      fsl_free(zTmp);
      fsl_free(zPre);
      return;
    }
  }
  cc.repo.filename = zTmp ? zTmp : zFile;
  cc.repo.allowOverwrite = false;
  cc.repo.commitMessage = NULL;
  fsl_b_external(&cc.xfer.url, zUrl, -1);
  cc.xfer.op.clone = 3;
  cc.xfer.compressTraffic = true;
  rc = fsl_clone(&cc, &err);
  if( rc ){
    char * const z = sqlite3_mprintf("%s", err.msg.used
                                     ? fsl_b_cstr(&err.msg)
                                     : fsl_rc_cstr(rc));
    sqlite3_result_error(cx, z ? z : "fsl_clone() failed", -1);
    sqlite3_free(z);
    fsl_cx_finalize(f);
  }else if( zTmp ){
    fslext_open_finish(cx, ext, f, fsl_repo_import(f, zTmp, zPre), argv[1]);
    /* Only here: if fsl_clone() failed, it removed what it made, and
       the file may not be its own. */
    fsl_file_unlink(zTmp);
  }else{
    sqlite3_result_value(cx, argv[1]);
  }
  fsl_error_clear(&err);
  fsl_free(zPw);
  fsl_free(zTmp);
  fsl_free(zPre);
}

/**
   Returns the bound context if it has an opened checkout, else sets
   an error on cx and returns NULL.
*/
static fsl_cx * fslext_ckout_cx(sqlite3_context * const cx){
  fsl_cx * const f = fslext_cx(cx);
  if( f && !fsl_cx_db_ckout(f) ){
    sqlite3_result_error(cx, "No checkout is opened. Use fsl_open(DIR) "
                         "or fsl_checkout(DIR) first.", -1);
    return NULL;
  }
  return f;
}

/**
   Returns true if the host connection is in autocommit mode, else
   sets an error on cx and returns false. Functions which write files
   need this because a ROLLBACK cannot undo a file write.
*/
static bool fslext_autocommit(sqlite3_context * const cx,
                              char const * zFunc){
  FslExt * const ext = sqlite3_user_data(cx);
  char * z;
  if( sqlite3_get_autocommit(ext->db) ) return true;
  z = sqlite3_mprintf("%s() cannot run inside a transaction: it "
                      "writes files, which a ROLLBACK cannot undo.",
                      zFunc);
  sqlite3_result_error(cx, z ? z : "Cannot run inside a transaction.",
                       -1);
  sqlite3_free(z);
  return false;
}

/**
   Appends z to s as a JSON string.
*/
static void fslext_json_str(sqlite3_str * const s, char const * z){
  sqlite3_str_appendchar(s, 1, '"');
  for( ; z && *z; ++z ){
    unsigned char const c = (unsigned char)*z;
    if( '"'==c || '\\'==c ) sqlite3_str_appendf(s, "\\%c", c);
    else if( c<0x20 ) sqlite3_str_appendf(s, "\\u%04x", c);
    else sqlite3_str_appendchar(s, 1, (char)c);
  }
  sqlite3_str_appendchar(s, 1, '"');
}

/**
   Sets cx's result to the text built in s, or to an out-of-memory
   error. Frees s.
*/
static void fslext_result_str(sqlite3_context * const cx,
                              sqlite3_str * const s){
  int const n = sqlite3_str_length(s);
  char * const z = sqlite3_str_finish(s);
  if( z ) sqlite3_result_text(cx, z, n, sqlite3_free);
  else sqlite3_result_error_nomem(cx);
}

/**
   Sets cx's result to the hash of f's checkout version, or NULL if the
   checkout has no version (its repository had no check-ins).
*/
static void fslext_result_ckout(sqlite3_context * const cx,
                                fsl_cx * const f){
  fsl_id_t rid = 0;
  fsl_ckout_version_info(f, &rid, NULL);
  if( rid>0 ) fslext_result_hash(cx, f, rid);
  else sqlite3_result_null(cx);
}

/**
   Resolves zSym to a check-in rid. Without zSym it picks what
   fossil(1)'s open does: the tip of the main branch, else the newest
   check-in. *pRid is 0 if the repository has no check-ins.
*/
static int fslext_ckout_version(fsl_cx * const f, char const * zSym,
                                fsl_id_t * const pRid){
  char * zMain = NULL;
  int rc;
  *pRid = 0;
  if( zSym ) return fsl_sym_to_rid(f, zSym, FSL_SATYPE_CHECKIN, pRid);
  zMain = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", NULL);
  rc = fsl_sym_to_rid(f, zMain ? zMain : "trunk", FSL_SATYPE_CHECKIN,
                      pRid);
  fsl_free(zMain);
  if( FSL_RC_NOT_FOUND==rc ){
    fsl_cx_err_reset(f);
    rc = fsl_sym_to_rid(f, "tip", FSL_SATYPE_CHECKIN, pRid);
  }
  if( FSL_RC_NOT_FOUND==rc ){
    fsl_cx_err_reset(f);
    *pRid = 0;
    rc = 0;
  }
  return rc;
}

/**
   Fails if directory zDir, or the nearest existing directory above
   it, is in a checkout, as fossil(1)'s open does without --nested.
   fsl_repo_open_ckout()'s own check looks from the cwd, not from its
   target directory.
*/
static int fslext_ckout_nested_check(fsl_cx * const f,
                                     char const * zDir){
  fsl_b dir = fsl_b_empty, found = fsl_b_empty;
  int rc = fsl_file_canonical_name(zDir, &dir, false);
  while( 0==rc && dir.used>1 && fsl_dir_check(fsl_b_cstr(&dir))<=0 ){
    while( dir.used>1 && '/'!=dir.mem[dir.used-1] ) --dir.used;
    if( dir.used>1 ) --dir.used;
    dir.mem[dir.used] = 0;
  }
  if( 0==rc ){
    int const rc2 = fsl_ckout_db_search(fsl_b_cstr(&dir), true, &found);
    if( 0==rc2 ){
      rc = fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS, "%s is inside the "
                          "checkout at %b.", zDir, &found);
    }else if( FSL_RC_OOM==rc2 ){
      rc = rc2;
    }
  }
  if( FSL_RC_OOM==rc ) rc = fsl_cx_err_set(f, rc, NULL);
  fsl_b_clear(&dir);
  fsl_b_clear(&found);
  return rc;
}

/**
   fsl_ckup_f() for fsl_checkout(): records each written file's name
   so that a failed checkout can remove what it wrote.
*/
static int fslext_checkout_f(fsl_ckup_state const * st){
  fsl_list * const written = st->callbackState;
  char * z;
  if( FSL_CKUP_FCHANGE_UPDATED!=st->fileChangeType ) return 0;
  z = fsl_strdup(st->extractState->fCard->name);
  if( !z ) return FSL_RC_OOM;
  if( fsl_list_append(written, z) ){
    fsl_free(z);
    return FSL_RC_OOM;
  }
  return 0;
}

/**
   Removes the files named in written, relative to zDir, and the
   directories under zDir left empty by that. Errors are ignored:
   this cleans up after an error, and has no recovery of its own.
*/
static void fslext_checkout_undo(char const * zDir, fsl_list * written){
  fsl_b path = fsl_b_empty;
  fsl_size_t const nDir = fsl_strlen(zDir);
  for( fsl_size_t i = 0; i < written->used; ++i ){
    char * const zName = written->list[i];
    fsl_b_reuse(&path);
    if( 0==fsl_b_appendf(&path, "%s/%s", zDir, zName) ){
      fsl_file_unlink(fsl_b_cstr(&path));
      /* Then each directory above the file, up to zDir. fsl_rmdir()
         fails on one which is not empty, which ends the walk. */
      while( path.used > nDir+1 ){
        while( path.used > nDir+1 && '/'!=path.mem[path.used-1] ){
          --path.used;
        }
        if( path.used <= nDir+1 ) break;
        path.mem[--path.used] = 0;
        if( fsl_rmdir(fsl_b_cstr(&path)) ) break;
      }
    }
    fsl_free(zName);
    written->list[i] = NULL;
  }
  fsl_list_reserve(written, 0);
  fsl_b_clear(&path);
}

/**
   After a failed fsl_checkout() which opened a checkout on f: leaves
   f's repository opened as before (zRepo, as fsl__cx_repo_ref() names
   it), with its user zUser, and
   nothing behind which later calls would take for a checkout, or, if
   that fails, closes f altogether. fsl_close_scm_dbs() forgets the
   user. A db: working copy's storage is removed, but not its tables.
*/
static void fslext_ckout_abandon(FslExt * const ext, fsl_cx * const f,
                                 char const * zRepo, char const * zUser){
  char zSfx[16];
  bool closed;
  fslext_suffix(ext, f, zSfx);
  closed = 0==fsl_close_scm_dbs(f) && 0==fsl_cx_ckout_fs(f, NULL, NULL);
  if( closed ) fslext_wc_free(ext, f);
  if( !closed || fslext_repo_open_ref(f, zRepo)
      || (zUser && fsl_cx_user_set(f, zUser)) ){
    fslext_forget(ext, f);
    fsl_close_dbs(f);
    fslext_wc_free(ext, f);
    fsl_cx_finalize(f);
    fslext_views_drop(ext, zSfx);
  }else{
    /* Reopened, f has joined the connection's registry anew, with a
       new id for its TEMP tables and without being the SQL functions'
       default. Its views keep their suffix. */
    if( fslext_views_create(ext, f) ) fsl_cx_err_reset(f);
    fslext_use(ext, ext->f);
  }
}

/**
   fsl_checkout('db:NAME' [, VERSION]) on f, whose repository is
   opened and which has no checkout. zName is NAME in lower case.
*/
static void fslext_checkout_wc(sqlite3_context * const cx,
                               fsl_cx * const f, char const * zName,
                               char const * zVersion){
  FslExt * const ext = sqlite3_user_data(cx);
  fsl_repo_open_ckout_opt oOpt = fsl_repo_open_ckout_opt_empty;
  char * zRepo = NULL, * zUser = NULL;
  bool hasFiles = false, hasVvar = false;
  bool made = false /* the files table, by this call */;
  bool opened = false /* libfossil's tables, by this call */;
  FslextWc * w = NULL;
  fsl_id_t rid = 0;
  int rc = 0;
  if( !sqlite3_get_autocommit(ext->db) ){
    /* libfossil sets the repository's PRAGMA synchronous when it opens
       a checkout, which SQLite refuses inside a transaction. */
    sqlite3_result_error(cx, "fsl_checkout() cannot run inside a "
                         "transaction.", -1);
    return;
  }else if( !fslext_wc_alone(cx, ext, "fsl_checkout") ){
    return;
  }
  rc = fslext_ckout_version(f, zVersion, &rid);
  if( 0==rc && fslext_wc_tables(ext->db, zName, &hasFiles, &hasVvar) ){
    rc = fsl_cx_err_set(f, FSL_RC_DB, "%s", sqlite3_errmsg(ext->db));
  }
  if( 0==rc && hasFiles && hasVvar ){
    rc = fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS, "Working copy db:%s "
                        "already exists. Use fsl_open('db:%s').",
                        zName, zName);
  }else if( 0==rc && (hasFiles || hasVvar) ){
    rc = fslext_wc_incomplete(f, zName, hasFiles);
  }
  if( 0==rc ){
    char const * const zU = fsl_cx_user_get(f);
    zRepo = fsl__cx_repo_ref(f);
    zUser = zU ? fsl_strdup(zU) : NULL;
    if( !zRepo || (zU && !zUser) ) rc = fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  }
  if( 0==rc ){
    /* The files table first, which only one connection can create:
       from here on this call owns the name. */
    bool const nocase = !fsl_cx_is_case_sensitive(f, false);
    rc = fslext_wc_create(ext->db, f, zName, nocase);
    made = 0==rc;
    if( made ) rc = fslext_wc_install(ext, f, zName, nocase);
  }
  if( 0==rc ){
    w = fslext_wc_of(ext, f);
    oOpt.targetDir = w->zRoot;
    oOpt.fileOverwritePolicy = FSL_OVERWRITE_NEVER;
    oOpt.checkForOpenedCkout = false;
    oOpt.hostTablePrefix = w->zPre;
    rc = fsl_repo_open_ckout(f, &oOpt);
    /* Its namespace had no vvar table above, so libfossil created the
       tables (it refuses a namespace which is not empty). */
    opened = 0==rc;
  }
  if( 0==rc && rid>0 ){
    fsl_ckup_opt cOpt = fsl_ckup_opt_empty;
    cOpt.checkinRid = rid;
    cOpt.setMtime = false;
    cOpt.scanForChanges = true;
    rc = fsl_cx_txn_begin(f);
    if( 0==rc ){
      rc = fsl_repo_ckout(f, &cOpt);
      if( 0==rc ) rc = fsl_cx_txn_end(f, false);
      else fsl_cx_txn_end(f, true);
    }
  }
  if( 0==rc ){
    fslext_result_ckout(cx, f);
  }else{
    char const * zMsg = NULL;
    char * zErr, * zDrop = NULL;
    bool stuck = false /* the storage stays installed */;
    fsl_cx_err_get(f, &zMsg, NULL);
    zErr = sqlite3_mprintf("%s", (zMsg && *zMsg) ? zMsg
                           : fsl_rc_cstr(rc));
    fsl_cx_err_reset(f);
    if( opened ){
      fslext_ckout_abandon(ext, f, zRepo, zUser);
    }else if( fslext_wc_of(ext, f) ){
      /* Freed only once it is no longer installed. */
      if( 0==fsl_cx_ckout_fs(f, NULL, NULL) ) fslext_wc_free(ext, f);
      else stuck = true;
    }
    if( made ) zDrop = fslext_wc_drop(ext->db, zName, opened);
    if( zDrop ){
      char * const z = sqlite3_mprintf("%s Removing the half-made working "
                                       "copy db:%s failed too (%s): DROP "
                                       "the tables of main named "
                                       "fslfiles_%s, fslclock_%s and "
                                       "fslwc_%s_*.", zErr, zName, zDrop,
                                       zName, zName, zName);
      sqlite3_free(zErr);
      zErr = z;
    }
    if( zErr && stuck ){
      char * const z = sqlite3_mprintf("%s The repository's context "
                                       "still has the working copy's "
                                       "storage: fsl_close() it before "
                                       "another fsl_checkout().", zErr);
      sqlite3_free(zErr);
      zErr = z;
    }
    if( zErr ) sqlite3_result_error(cx, zErr, -1);
    else sqlite3_result_error_nomem(cx);
    sqlite3_free(zErr);
    sqlite3_free(zDrop);
  }
  fsl_free(zRepo);
  fsl_free(zUser);
}

/*
  fsl_checkout(DIR [, VERSION])

  Creates a checkout of the opened repository in directory DIR, which
  must be empty or not exist yet, and writes VERSION's files into it,
  as fossil(1)'s open does. VERSION defaults to the tip of the main
  branch. The checkout is
  ATTACHed as "ckout", or "ckout_2" and so on if that is taken (see
  fsl_repos), and stays open until fsl_close(). Returns the
  checked-out version's hash, or NULL if the repository has no
  check-ins. If writing the files fails, e.g. because the repository
  lacks some content, the files written so far and the checkout db
  are removed again, and the repository stays opened. It must run
  outside of a transaction.

  DIR 'db:NAME' makes the working copy in tables of the connection's
  main db instead (see the top of this file), and writes nothing to
  disk. Each file's row is a reference to its blob, with NULL
  content: read the bytes as coalesce(content, fsl_content(uuid)).
  NAME may not already exist. If checking out fails, its tables are
  dropped again.
*/
static void fslext_checkout(sqlite3_context *cx, int argc,
                            sqlite3_value **argv){
  fsl_cx * const f = fslext_cx(cx);
  char const * zDir = (char const *)sqlite3_value_text(argv[0]);
  char const * const zVersion = argc>1
    ? (char const *)sqlite3_value_text(argv[1]) : NULL;
  fsl_b absDir = fsl_b_empty;
  fsl_b ckDb = fsl_b_empty;
  fsl_repo_open_ckout_opt oOpt = fsl_repo_open_ckout_opt_empty;
  fsl_list written = fsl_list_empty;
  char * zRepo = NULL, * zDb = NULL, * zUser = NULL;
  fsl_id_t rid = 0;
  fsl_size_t nExisting = 0 /* length of the deepest existing ancestor
                              of zDir, if zDir is created here */;
  char zWc[FSLEXT_WC_NAME_MAX+1];
  int const wcKind = fslext_wc_name(zDir, zWc);
  int rc;
  if( !f || (!wcKind && !fslext_autocommit(cx, "fsl_checkout")) ) return;
  if( fsl_cx_db_ckout(f) ){
    sqlite3_result_error(cx, "A checkout is already opened. Use "
                         "fsl_close() first.", -1);
    return;
  }else if( wcKind<0 ){
    sqlite3_result_error(cx, FSLEXT_WC_NAME_ERR, -1);
    return;
  }else if( wcKind>0 ){
    fslext_checkout_wc(cx, f, zWc, zVersion);
    return;
  }else if( !zDir || !*zDir ){
    sqlite3_result_error(cx, "fsl_checkout() requires a directory.", -1);
    return;
  }
  rc = fsl_file_canonical_name(zDir, &absDir, false);
  if( rc ){
    fslext_error(cx, f, fsl_cx_err_set(f, rc, "Cannot resolve %s.", zDir));
    fsl_b_clear(&absDir);
    return;
  }
  zDir = fsl_b_cstr(&absDir) /* the directory walks below need it */;
  rc = fslext_ckout_version(f, zVersion, &rid);
  if( 0==rc ) rc = fslext_ckout_nested_check(f, zDir);
  if( 0==rc && fsl_dir_check(zDir)>0 && 0!=fsl_dir_is_empty(zDir) ){
    rc = fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS, "Directory %s is "
                        "not empty.", zDir);
  }else if( 0==rc && fsl_dir_check(zDir)<=0 ){
    char * const zUp = fsl_strdup(zDir);
    if( !zUp ){
      rc = FSL_RC_OOM;
    }else{
      fsl_size_t n = fsl_strlen(zUp);
      while( n>1 && fsl_dir_check(zUp)<=0 ){
        while( n>1 && '/'!=zUp[n-1] ) --n;
        if( n>1 ) --n;
        zUp[n] = 0;
      }
      nExisting = n>1 ? n : 0;
      fsl_free(zUp);
      rc = fsl_mkdir_for_file(zDir, false);
      if( 0==rc && fsl_dir_check(zDir)<=0 ) rc = fsl_mkdir(zDir, false);
      if( rc ){
        rc = fsl_cx_err_set(f, rc, "Cannot create directory %s.", zDir);
      }
    }
  }
  if( 0==rc ){
    char const * const zU = fsl_cx_user_get(f);
    zRepo = fsl__cx_repo_ref(f);
    zUser = zU ? fsl_strdup(zU) : NULL;
    if( !zRepo || (zU && !zUser) ) rc = FSL_RC_OOM;
  }
  if( 0==rc ){
    oOpt.targetDir = zDir;
    /* DIR was checked above, as f-open does. FSL_OVERWRITE_ERROR
       would reject an empty directory. */
    oOpt.fileOverwritePolicy = FSL_OVERWRITE_NEVER;
    oOpt.dbOverwritePolicy = false;
    oOpt.checkForOpenedCkout = false /* checked above */;
    /* Name the checkout db by its full path, as fsl_repo_open_ckout()
       would also derive it from DIR. A VFS which does not follow the
       process's cwd (e.g. SQLite's OPFS pool, or a wasm build's
       filesystem) must never see a relative name: every checkout would
       then share one "/.fslckout". */
    rc = fsl_b_appendf(&ckDb, "%s/%s", zDir, fsl_preferred_ckout_db_name());
    if( 0==rc ) oOpt.ckoutDbFile = fsl_b_cstr(&ckDb);
    if( 0==rc ) rc = fsl_repo_open_ckout(f, &oOpt);
    if( fsl_cx_db_ckout(f) ){
      zDb = fsl_strdup(fsl_cx_db_file_ckout(f, NULL));
    }
  }
  if( 0==rc && rid>0 ){
    fsl_ckup_opt cOpt = fsl_ckup_opt_empty;
    cOpt.checkinRid = rid;
    cOpt.setMtime = false;
    cOpt.scanForChanges = true;
    cOpt.callback = fslext_checkout_f;
    cOpt.callbackState = &written;
    rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
    if( 0==rc ){
      rc = fsl_repo_ckout(f, &cOpt);
      if( 0==rc ) rc = fsl_cx_txn_end(f, false);
      else fsl_cx_txn_end(f, true);
    }
  }
  if( 0==rc ){
    fslext_result_ckout(cx, f);
  }else{
    fslext_error(cx, f, rc);
    if( zDb ){
      fslext_ckout_abandon(sqlite3_user_data(cx), f, zRepo, zUser);
      fsl_file_unlink(zDb);
    }
    fslext_checkout_undo(zDir, &written);
    if( nExisting ){
      /* Remove the directories created above, up to the ancestor
         which already existed. */
      char * const zUp = fsl_strdup(zDir);
      fsl_size_t n = zUp ? fsl_strlen(zUp) : 0;
      while( zUp && n>nExisting && 0==fsl_rmdir(zUp) ){
        while( n>nExisting && '/'!=zUp[n-1] ) --n;
        if( n>nExisting ) --n;
        zUp[n] = 0;
      }
      fsl_free(zUp);
    }
  }
  for( fsl_size_t i = 0; i < written.used; ++i ) fsl_free(written.list[i]);
  fsl_list_reserve(&written, 0);
  fsl_free(zRepo);
  fsl_free(zDb);
  fsl_free(zUser);
  fsl_b_clear(&absDir);
  fsl_b_clear(&ckDb);
}

/**
   A JSON array of changed files, built by the checkout functions'
   callbacks.
*/
typedef struct {
  sqlite3_str * s;
  int n;
} FslExtFiles;

/**
   Appends {"name":zName,"change":zChange} to p, with "from":zFrom if
   zFrom is not NULL.
*/
static void fslext_files_add(FslExtFiles * const p, char const * zName,
                             char const * zChange, char const * zFrom){
  sqlite3_str_appendall(p->s, p->n++ ? ",{\"name\":" : "{\"name\":");
  fslext_json_str(p->s, zName);
  sqlite3_str_appendf(p->s, ",\"change\":\"%s\"", zChange);
  if( zFrom ){
    sqlite3_str_appendall(p->s, ",\"from\":");
    fslext_json_str(p->s, zFrom);
  }
  sqlite3_str_appendchar(p->s, 1, '}');
}

/**
   Sets cx's result to {"checkout":HASH,"KEY":[p's files]}. Frees p's
   text.
*/
static void fslext_result_files(sqlite3_context * const cx,
                                fsl_cx * const f, char const * zKey,
                                FslExtFiles * const p){
  sqlite3_str * const s = sqlite3_str_new(NULL);
  fsl_uuid_cstr zHash = NULL;
  int const nFiles = sqlite3_str_length(p->s);
  char * const zFiles = sqlite3_str_finish(p->s);
  p->s = NULL;
  fsl_ckout_version_info(f, NULL, &zHash);
  sqlite3_str_appendall(s, "{\"checkout\":");
  if( zHash ) fslext_json_str(s, zHash);
  else sqlite3_str_appendall(s, "null");
  sqlite3_str_appendf(s, ",\"%s\":[", zKey);
  if( nFiles ) sqlite3_str_append(s, zFiles, nFiles);
  sqlite3_str_appendall(s, "]}");
  sqlite3_free(zFiles);
  fslext_result_str(cx, s);
}

/**
   fsl_ckup_f() for fsl_update().
*/
static int fslext_update_f(fsl_ckup_state const * st){
  fsl_card_F const * const fc = st->extractState->fCard;
  char const * zChange;
  switch( st->fileChangeType ){
    case FSL_CKUP_FCHANGE_ADDED:
    case FSL_CKUP_FCHANGE_ADD_PROPAGATED: zChange = "added"; break;
    case FSL_CKUP_FCHANGE_UPDATED: zChange = "updated"; break;
    case FSL_CKUP_FCHANGE_MERGED: zChange = "merged"; break;
    case FSL_CKUP_FCHANGE_CONFLICT_MERGED: zChange = "conflict"; break;
    case FSL_CKUP_FCHANGE_RENAMED: zChange = "renamed"; break;
    case FSL_CKUP_FCHANGE_UPDATED_BINARY:
    case FSL_CKUP_FCHANGE_CONFLICT_SYMLINK:
    case FSL_CKUP_FCHANGE_CONFLICT_ADDED_UNMANAGED:
      zChange = "overwritten"; break;
    case FSL_CKUP_FCHANGE_CONFLICT_ADDED:
    case FSL_CKUP_FCHANGE_CONFLICT_RM: zChange = "kept"; break;
    case FSL_CKUP_FCHANGE_CONFLICT_BINARY: zChange = "skipped"; break;
    case FSL_CKUP_FCHANGE_RM:
    case FSL_CKUP_FCHANGE_RM_PROPAGATED:
      zChange = FSL_CKUP_RM_KEPT==st->fileRmInfo ? "kept" : "removed";
      break;
    default: return 0;
  }
  fslext_files_add(st->callbackState, fc->name, zChange,
                   fc->priorName);
  return 0;
}

/**
   Sets *pDryRun from OPTIONS object pOpt's "dryRun" member. Returns
   false, with an error on cx, if pOpt cannot be read.
*/
static bool fslext_dry_run_opt(sqlite3_context * const cx,
                               sqlite3_value * const pOpt,
                               bool * const pDryRun){
  FslExt * const ext = sqlite3_user_data(cx);
  sqlite3_stmt * q = NULL;
  int rc = sqlite3_prepare_v2(ext->db,
             "SELECT coalesce(json_extract(?1,'$.dryRun'),0)",
             -1, &q, NULL);
  if( 0==rc ){
    sqlite3_bind_value(q, 1, pOpt);
    rc = sqlite3_step(q);
    rc = SQLITE_ROW==rc ? 0 : rc;
  }
  if( rc ) sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
  else *pDryRun = 0!=sqlite3_column_int(q, 0);
  sqlite3_finalize(q);
  return 0==rc;
}

/*
  fsl_update([VERSION [, OPTIONS]])

  Moves the opened checkout to VERSION, merging local edits into the
  files which changed, as fossil(1)'s update does. VERSION defaults to
  the newest leaf of the checkout's branch. Returns a JSON object with
  the new version's "checkout" hash and the "files" it changed, each
  with its "name" and "change":

  - "added", "updated", "removed", "renamed" (with "from", the old
    name): taken from VERSION. "removed" also covers a file already
    removed locally with fsl_rm().
  - "merged": local edits merged with VERSION's changes.
  - "conflict": merged, with conflict markers to resolve.
  - "overwritten": VERSION's copy replaced a local file: an unmanaged
    one, or an edited one which could not be merged (binary or
    symlink).
  - "kept": the local copy stays: it was added locally and also in
    VERSION, or it has local edits and VERSION removed it.
  - "skipped": binary, not merged; the local copy stays.

  OPTIONS is a JSON object. With {"dryRun": true} it reports the same
  files but writes none and leaves the checkout's version and state as
  they were; "checkout" is then the current version.

  It must run outside of a transaction.
*/
static void fslext_update(sqlite3_context *cx, int argc,
                          sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  char const * const zVersion = argc>0
    ? (char const *)sqlite3_value_text(argv[0]) : NULL;
  fsl_ckup_opt uOpt = fsl_ckup_opt_empty;
  FslExtFiles files = {NULL, 0};
  fsl_id_t rid = 0;
  bool dryRun = false;
  int rc;
  if( !f || !fslext_autocommit(cx, "fsl_update") ) return;
  if( argc>1 && !fslext_dry_run_opt(cx, argv[1], &dryRun) ) return;
  files.s = sqlite3_str_new(NULL);
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if( 0==rc ){
    rc = zVersion
      ? fsl_sym_to_rid(f, zVersion, FSL_SATYPE_CHECKIN, &rid)
      : fsl_ckout_calc_update_version(f, &rid);
    if( 0==rc && !rid ){
      /* No newer version on the branch: "update" to the current one,
         which reports local edits, as f-update does. */
      fsl_ckout_version_info(f, &rid, NULL);
    }
    if( 0==rc ){
      uOpt.checkinRid = rid;
      uOpt.setMtime = false;
      uOpt.scanForChanges = true;
      uOpt.callback = fslext_update_f;
      uOpt.callbackState = &files;
      uOpt.dryRun = dryRun;
      rc = fsl_ckout_update(f, &uOpt);
    }
    if( 0==rc && !dryRun ) rc = fsl_cx_txn_end(f, false);
    else fsl_cx_txn_end(f, true);
    if( dryRun && 0==rc ){
      /* The rollback undid the version change in the db, but not in
         f's cached copy of it. */
      rc = fsl__ckout_version_fetch(f);
    }
  }
  if( 0==rc && SQLITE_OK!=sqlite3_str_errcode(files.s) ){
    rc = FSL_RC_OOM;
  }
  if( 0==rc ){
    fslext_result_files(cx, f, "files", &files);
  }else{
    fslext_error(cx, f, rc);
    sqlite3_free(sqlite3_str_finish(files.s));
  }
}

/**
   fsl_merge_f() for fsl_merge().
*/
static int fslext_merge_f(fsl_merge_state const * const st){
  char const * zChange;
  switch( st->fileChangeType ){
    case FSL_MERGE_FCHANGE_ADDED: zChange = "added"; break;
    case FSL_MERGE_FCHANGE_COPIED: zChange = "updated"; break;
    case FSL_MERGE_FCHANGE_MERGED: zChange = "merged"; break;
    case FSL_MERGE_FCHANGE_RENAMED: zChange = "renamed"; break;
    case FSL_MERGE_FCHANGE_CONFLICT_MERGED: zChange = "conflict"; break;
    case FSL_MERGE_FCHANGE_CONFLICT_ADDED_UNMANAGED:
      zChange = "overwritten"; break;
    case FSL_MERGE_FCHANGE_CONFLICT_SYMLINK:
    case FSL_MERGE_FCHANGE_CONFLICT_BINARY: zChange = "skipped"; break;
    case FSL_MERGE_FCHANGE_RM:
      zChange = FSL_CKUP_RM_KEPT==st->fileRmInfo ? "kept" : "removed";
      break;
    default: return 0;
  }
  fslext_files_add(st->opt->callbackState, st->filename, zChange,
                   st->priorName);
  return 0;
}

/*
  fsl_merge(VERSION [, KIND [, OPTIONS]])

  Merges VERSION into the opened checkout's files, as fossil(1)'s
  merge does, for the next fsl_commit() to save. KIND is "merge"
  (default), "integrate" (the commit also closes VERSION's branch),
  "cherrypick" (only VERSION's own changes), or "backout" (undoes
  VERSION's own changes). Returns a JSON object like fsl_update()'s.
  "skipped" files are binaries or symlinks which could not be merged.
  OPTIONS takes {"dryRun": true} as for fsl_update(). It must run
  outside of a transaction.
*/
static void fslext_merge(sqlite3_context *cx, int argc,
                         sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  char const * const zVersion = (char const *)sqlite3_value_text(argv[0]);
  char const * const zKind = argc>1
    ? (char const *)sqlite3_value_text(argv[1]) : NULL;
  fsl_merge_opt mOpt = fsl_merge_opt_empty;
  FslExtFiles files = {NULL, 0};
  bool dryRun = false;
  int rc;
  if( !f || !fslext_autocommit(cx, "fsl_merge") ) return;
  if( argc>2 && !fslext_dry_run_opt(cx, argv[2], &dryRun) ) return;
  if( !zVersion || !*zVersion ){
    sqlite3_result_error(cx, "fsl_merge() requires a version.", -1);
    return;
  }
  if( !zKind || 0==strcmp(zKind, "merge") ){
    mOpt.mergeType = FSL_MERGE_TYPE_NORMAL;
  }else if( 0==strcmp(zKind, "integrate") ){
    mOpt.mergeType = FSL_MERGE_TYPE_INTEGRATE;
  }else if( 0==strcmp(zKind, "cherrypick") ){
    mOpt.mergeType = FSL_MERGE_TYPE_CHERRYPICK;
  }else if( 0==strcmp(zKind, "backout") ){
    mOpt.mergeType = FSL_MERGE_TYPE_BACKOUT;
  }else{
    sqlite3_result_error(cx, "fsl_merge() KIND must be \"merge\", "
                         "\"integrate\", \"cherrypick\", or "
                         "\"backout\".", -1);
    return;
  }
  files.s = sqlite3_str_new(NULL);
  rc = fsl_cx_txn_begin_write(f, FSL_DBROLE_CKOUT);
  if( 0==rc ){
    rc = fsl_sym_to_rid(f, zVersion, FSL_SATYPE_CHECKIN, &mOpt.mergeRid);
    if( 0==rc ){
      mOpt.scanForChanges = true;
      mOpt.callback = fslext_merge_f;
      mOpt.callbackState = &files;
      mOpt.dryRun = dryRun;
      rc = fsl_ckout_merge(f, &mOpt);
    }
    if( 0==rc && !dryRun ) rc = fsl_cx_txn_end(f, false);
    else fsl_cx_txn_end(f, true);
    if( dryRun && 0==rc ){
      /* The rollback undid the version change in the db, but not in
         f's cached copy of it. */
      rc = fsl__ckout_version_fetch(f);
    }
  }
  if( 0==rc && SQLITE_OK!=sqlite3_str_errcode(files.s) ){
    rc = FSL_RC_OOM;
  }
  if( 0==rc ){
    fslext_result_files(cx, f, "files", &files);
  }else{
    fslext_error(cx, f, rc);
    sqlite3_free(sqlite3_str_finish(files.s));
  }
}

/**
   fsl_ckout_changes_f() for fsl_status().
*/
static int fslext_status_f(void * state, fsl_ckout_change_e change,
                           char const * zName, char const * zOrig){
  char const * zChange;
  switch( change ){
    case FSL_CKOUT_CHANGE_ADDED: zChange = "added"; break;
    case FSL_CKOUT_CHANGE_REMOVED: zChange = "deleted"; break;
    case FSL_CKOUT_CHANGE_MISSING: zChange = "missing"; break;
    case FSL_CKOUT_CHANGE_NOT_A_FILE: zChange = "not_a_file"; break;
    case FSL_CKOUT_CHANGE_MOD: zChange = "edited"; break;
    case FSL_CKOUT_CHANGE_RENAMED: zChange = "renamed"; break;
    case FSL_CKOUT_CHANGE_IS_EXEC: zChange = "executable"; break;
    case FSL_CKOUT_CHANGE_NOT_EXEC: zChange = "unexec"; break;
    case FSL_CKOUT_CHANGE_BECAME_SYMLINK: zChange = "symlink"; break;
    case FSL_CKOUT_CHANGE_NOT_SYMLINK: zChange = "unlink"; break;
    case FSL_CKOUT_CHANGE_MERGE_ADD: zChange = "added_by_merge"; break;
    case FSL_CKOUT_CHANGE_MERGE_MOD: zChange = "updated_by_merge"; break;
    case FSL_CKOUT_CHANGE_INTEGRATE_ADD:
      zChange = "added_by_integrate"; break;
    case FSL_CKOUT_CHANGE_INTEGRATE_MOD:
      zChange = "updated_by_integrate"; break;
    default: return 0;
  }
  fslext_files_add(state, zName, zChange,
                   zOrig && 0!=fsl_strcmp(zOrig, zName) ? zOrig : NULL);
  return 0;
}

/*
  fsl_status()

  Compares the opened checkout's files with its version and returns a
  JSON object with the version's "checkout" hash and the "changes",
  each with its "name" and "change", named as fossil(1)'s status
  names them: "added", "deleted", "missing", "not_a_file", "edited",
  "renamed",
  "executable", "unexec", "symlink", "unlink", "added_by_merge",
  "updated_by_merge", "added_by_integrate", or "updated_by_integrate".
  A renamed file also has "from", its old name. Files not in the
  checkout are not listed.
*/
static void fslext_status(sqlite3_context *cx, int argc,
                          sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  FslExtFiles files = {NULL, 0};
  int rc;
  (void)argc; (void)argv;
  if( !f ) return;
  files.s = sqlite3_str_new(NULL);
  rc = fsl_ckout_changes_visit(f, -1, true, fslext_status_f, &files);
  if( 0==rc && SQLITE_OK!=sqlite3_str_errcode(files.s) ){
    rc = FSL_RC_OOM;
  }
  if( 0==rc ){
    fslext_result_files(cx, f, "changes", &files);
  }else{
    fslext_error(cx, f, rc);
    sqlite3_free(sqlite3_str_finish(files.s));
  }
}

/**
   Returns argv[0] as a checkout-relative name, or sets an error on cx
   naming zFunc and returns NULL.
*/
static char const * fslext_name_arg(sqlite3_context * const cx,
                                    sqlite3_value * const v,
                                    char const * zFunc){
  char const * const z = (char const *)sqlite3_value_text(v);
  if( !z || !*z ){
    char * const zMsg = sqlite3_mprintf("%s() requires a file or "
                                        "directory name.", zFunc);
    sqlite3_result_error(cx, zMsg ? zMsg : "A name is required.", -1);
    sqlite3_free(zMsg);
    return NULL;
  }
  return z;
}

/*
  fsl_add(NAME)

  Adds the file NAME, or every file under the directory NAME, to the
  opened checkout, to be saved by the next fsl_commit(). Names must
  be relative to the checkout's top directory; "." adds every file.
  Files matching the ignore-glob setting are skipped. Returns the
  number of files added.
*/
static void fslext_add(sqlite3_context *cx, int argc,
                       sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  fsl_ckout_manage_opt opt = fsl_ckout_manage_opt_empty;
  char const * const zName = fslext_name_arg(cx, argv[0], "fsl_add");
  char * zAbs;
  int rc;
  (void)argc;
  if( !f || !zName ) return;
  if( fsl_is_absolute_path(zName) ){
    sqlite3_result_error(cx, "fsl_add() takes a name relative to the "
                         "checkout's top directory.", -1);
    return;
  }
  /* fsl_ckout_manage() resolves the name from the cwd regardless of
     relativeToCwd, so give it an absolute one. The checkout dir name
     ends with a slash. */
  zAbs = fsl_mprintf("%s%s", fsl_cx_ckout_dir_name(f, NULL), zName);
  if( !zAbs ){
    sqlite3_result_error_nomem(cx);
    return;
  }
  opt.filename = zAbs;
  opt.relativeToCwd = false;
  opt.checkIgnoreGlobs = true;
  rc = fsl_ckout_manage(f, &opt);
  fsl_free(zAbs);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_int64(cx, (sqlite3_int64)opt.counts.added);
}

static int fslext_rm_f(fsl_ckout_unmanage_state const * st){
  ++*(sqlite3_int64*)st->opt->callbackState;
  return 0;
}

/*
  fsl_rm(NAME)

  Removes the file NAME, or every file under the directory NAME, from
  the opened checkout, so that the next fsl_commit() records them as
  deleted. The files stay on disk, as with fossil(1)'s rm. Returns the
  number of files removed.
*/
static void fslext_rm(sqlite3_context *cx, int argc,
                      sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  fsl_ckout_unmanage_opt opt = fsl_ckout_unmanage_opt_empty;
  sqlite3_int64 n = 0;
  int rc;
  (void)argc;
  if( !f ) return;
  opt.filename = fslext_name_arg(cx, argv[0], "fsl_rm");
  if( !opt.filename ) return;
  opt.relativeToCwd = false;
  opt.scanForChanges = true;
  opt.callback = fslext_rm_f;
  opt.callbackState = &n;
  rc = fsl_ckout_unmanage(f, &opt);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_int64(cx, n);
}

static int fslext_mv_f(fsl_cx * f, fsl_ckout_rename_opt const * opt,
                       char const * zSrc, char const * zDest){
  (void)f; (void)zSrc; (void)zDest;
  ++*(sqlite3_int64*)opt->callbackState;
  return 0;
}

/*
  fsl_mv(FROM, TO)

  Renames the file or directory FROM to TO in the opened checkout, to
  be saved by the next fsl_commit(). Only the checkout's records
  change, not the files on disk, as with fossil(1)'s mv. Returns the
  number of files renamed.
*/
static void fslext_mv(sqlite3_context *cx, int argc,
                      sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  fsl_ckout_rename_opt opt = fsl_ckout_rename_opt_empty;
  fsl_list src = fsl_list_empty;
  char const * zFrom;
  sqlite3_int64 n = 0;
  int rc;
  (void)argc;
  if( !f ) return;
  zFrom = fslext_name_arg(cx, argv[0], "fsl_mv");
  if( !zFrom ) return;
  opt.dest = fslext_name_arg(cx, argv[1], "fsl_mv");
  if( !opt.dest ) return;
  rc = fsl_list_append(&src, (void*)zFrom);
  if( 0==rc ){
    opt.src = &src;
    opt.relativeToCwd = false;
    opt.doFsMv = false;
    opt.callback = fslext_mv_f;
    opt.callbackState = &n;
    rc = fsl_ckout_rename(f, &opt);
  }
  fsl_list_reserve(&src, 0);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_int64(cx, n);
}

static int fslext_revert_f(char const * zName, fsl_ckout_revert_e type,
                           void * state){
  (void)zName; (void)type;
  ++*(sqlite3_int64*)state;
  return 0;
}

/*
  fsl_revert([NAME])

  Undoes local changes to the file NAME, or to every file under the
  directory NAME, or to the whole opened checkout without NAME or
  with NULL:
  rewrites edited files from the checkout's version and cancels
  pending adds, removes, and renames, as fossil(1)'s revert does.
  Returns the number of files reverted. It must run outside of a
  transaction.
*/
static void fslext_revert(sqlite3_context *cx, int argc,
                          sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  fsl_ckout_revert_opt opt = fsl_ckout_revert_opt_empty;
  sqlite3_int64 n = 0;
  int rc;
  if( !f || !fslext_autocommit(cx, "fsl_revert") ) return;
  if( argc>0 && SQLITE_NULL!=sqlite3_value_type(argv[0]) ){
    opt.filename = fslext_name_arg(cx, argv[0], "fsl_revert");
    if( !opt.filename ) return;
  }
  opt.relativeToCwd = false;
  opt.scanForChanges = true;
  opt.callback = fslext_revert_f;
  opt.callbackState = &n;
  rc = fsl_ckout_revert(f, &opt);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_int64(cx, n);
}

/*
  fsl_undo_state()

  Returns what the opened checkout can undo or redo, as a JSON object:
  {"undo": OPERATION}, {"redo": OPERATION}, or {} for nothing, where
  OPERATION names it, e.g. "update", "merge" or "revert".
*/
static void fslext_undo_state(sqlite3_context *cx, int argc,
                              sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  fsl_undo_e state = FSL_UNDO_NONE;
  char * zLabel = NULL;
  sqlite3_str * s;
  int rc;
  (void)argc; (void)argv;
  if( !f ) return;
  rc = fsl_undo_state(f, &state, &zLabel);
  if( rc ){
    fslext_error(cx, f, rc);
    return;
  }
  s = sqlite3_str_new(NULL);
  sqlite3_str_appendchar(s, 1, '{');
  if( FSL_UNDO_NONE!=state ){
    sqlite3_str_appendall(s, FSL_UNDO_UNDO==state
                          ? "\"undo\":" : "\"redo\":");
    fslext_json_str(s, zLabel);
  }
  sqlite3_str_appendchar(s, 1, '}');
  fsl_free(zLabel);
  fslext_result_str(cx, s);
}

/*
  fsl_undo([FORCE])
  fsl_redo([FORCE])

  Undoes the opened checkout's most recent fsl_update(), fsl_merge() or
  fsl_revert(), restoring its files, version and merge state as they
  were, or redoes the most recent undo. Returns the name of the
  operation undone or redone. It is an error if there is nothing to
  undo or redo, if the checkout has since moved to another version
  (e.g. by a commit), or, unless FORCE is true, if its files changed
  after the operation. Like the operations themselves, these must run
  outside of a transaction.
*/
static void fslext_undo_impl(sqlite3_context *cx, int argc,
                             sqlite3_value **argv, bool redo){
  char const * const zFunc = redo ? "fsl_redo" : "fsl_undo";
  fsl_cx * const f = fslext_ckout_cx(cx);
  bool const force = argc>0 && sqlite3_value_int(argv[0]);
  fsl_undo_e state = FSL_UNDO_NONE;
  char * zLabel = NULL;
  int rc;
  if( !f || !fslext_autocommit(cx, zFunc) ) return;
  rc = fsl_undo_state(f, &state, &zLabel);
  if( 0==rc && (redo ? FSL_UNDO_REDO : FSL_UNDO_UNDO)!=state ){
    char * const z = sqlite3_mprintf("%s(): there is nothing to %s.",
                                     zFunc, redo ? "redo" : "undo");
    sqlite3_result_error(cx, z ? z : "Nothing to do.", -1);
    sqlite3_free(z);
    fsl_free(zLabel);
    return;
  }
  if( 0==rc ) rc = fsl_undo(f, redo, force);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_text(cx, zLabel, -1, SQLITE_TRANSIENT);
  fsl_free(zLabel);
}

static void fslext_undo(sqlite3_context *cx, int argc,
                        sqlite3_value **argv){
  fslext_undo_impl(cx, argc, argv, false);
}

static void fslext_redo(sqlite3_context *cx, int argc,
                        sqlite3_value **argv){
  fslext_undo_impl(cx, argc, argv, true);
}

/*
  fsl_stash_save([COMMENT [, KEEP]])

  Saves the opened checkout's uncommitted changes as a new stash with
  the given comment, then reverts them unless KEEP is true (fossil(1)'s
  stash snapshot). Returns the new stash's id. It is an error if there
  is nothing to stash. Like the other functions which write files, it
  must run outside of a transaction.
*/
static void fslext_stash_save(sqlite3_context *cx, int argc,
                              sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  fsl_stash_save_opt opt = fsl_stash_save_opt_empty;
  fsl_id_t id = 0;
  int rc;
  if( !f || !fslext_autocommit(cx, "fsl_stash_save") ) return;
  opt.comment = argc>0 ? (char const *)sqlite3_value_text(argv[0]) : NULL;
  opt.keepChanges = argc>1 && sqlite3_value_int(argv[1]);
  opt.relativeToCwd = false;
  rc = fsl_stash_save(f, &opt, &id);
  if( FSL_RC_NOOP==rc ){
    fsl_cx_err_reset(f);
    sqlite3_result_error(cx, "fsl_stash_save(): there are no changes "
                         "to stash.", -1);
  }else if( rc ){
    fslext_error(cx, f, rc);
  }else{
    sqlite3_result_int64(cx, id);
  }
}

/*
  fsl_stash_apply([ID])
  fsl_stash_pop([ID])

  Applies stash ID, or the most recent one, to the opened checkout's
  files, merging with any local changes, as fossil(1)'s stash apply
  and stash pop do; pop then drops the stash. Returns a JSON object:
  {"stash": ID, "conflicts": N}, where N counts the files left with
  conflict markers or which could not be merged. Must run outside of
  a transaction.
*/
static void fslext_stash_apply_impl(sqlite3_context *cx, int argc,
                                    sqlite3_value **argv, bool pop){
  char const * const zFunc = pop ? "fsl_stash_pop" : "fsl_stash_apply";
  fsl_cx * const f = fslext_ckout_cx(cx);
  fsl_stash_apply_opt opt = fsl_stash_apply_opt_empty;
  unsigned nConflicts = 0;
  int rc = 0;
  if( !f || !fslext_autocommit(cx, zFunc) ) return;
  opt.pop = pop;
  if( argc>0 && SQLITE_NULL!=sqlite3_value_type(argv[0]) ){
    opt.stashId = (fsl_id_t)sqlite3_value_int64(argv[0]);
  }else{
    rc = fsl_stash_latest(f, &opt.stashId);
  }
  if( 0==rc ) rc = fsl_stash_apply(f, &opt, &nConflicts);
  if( rc ){
    fslext_error(cx, f, rc);
  }else{
    char * const z = sqlite3_mprintf("{\"stash\":%lld,\"conflicts\":%u}",
                                     (long long)opt.stashId, nConflicts);
    if( z ) sqlite3_result_text(cx, z, -1, sqlite3_free);
    else sqlite3_result_error_nomem(cx);
  }
}

static void fslext_stash_apply(sqlite3_context *cx, int argc,
                               sqlite3_value **argv){
  fslext_stash_apply_impl(cx, argc, argv, false);
}

static void fslext_stash_pop(sqlite3_context *cx, int argc,
                             sqlite3_value **argv){
  fslext_stash_apply_impl(cx, argc, argv, true);
}

/*
  fsl_stash_drop(ID)

  Deletes stash ID, or every stash if ID is negative. Returns 1. It
  changes no files.
*/
static void fslext_stash_drop(sqlite3_context *cx, int argc,
                              sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  int rc;
  (void)argc;
  if( !f ) return;
  if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
    sqlite3_result_error(cx, "fsl_stash_drop() requires a stash id.", -1);
    return;
  }
  rc = fsl_stash_drop(f, (fsl_id_t)sqlite3_value_int64(argv[0]));
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_int(cx, 1);
}

/*
  fsl_stash_list()

  Returns the opened checkout's stashes as a JSON array, newest first:
  [{"id": ID, "comment": TEXT, "time": "YYYY-MM-DD HH:MM:SS",
    "checkin": HASH, "files": N}, ...], where checkin is the version
  the changes were made against.
*/
static void fslext_stash_list(sqlite3_context *cx, int argc,
                              sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  fsl_stmt q = fsl_stmt_empty;
  fsl_id_t dummy = 0;
  sqlite3_str * s;
  bool first = true;
  int rc;
  (void)argc; (void)argv;
  if( !f ) return;
  /* fsl_stash_latest() creates the stash tables if needed. */
  rc = fsl_stash_latest(f, &dummy);
  if( 0==rc ){
    rc = fsl_cx_prepare(f, &q,
           "SELECT stashid, comment, datetime(ctime), hash,"
           " (SELECT count(*) FROM {{dbname.ckout}}.stashfile sf"
           "   WHERE sf.stashid=s.stashid)"
           " FROM {{dbname.ckout}}.stash s ORDER BY stashid DESC");
  }
  if( rc ){
    fslext_error(cx, f, rc);
    return;
  }
  s = sqlite3_str_new(NULL);
  sqlite3_str_appendchar(s, 1, '[');
  while( FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
    if( !first ) sqlite3_str_appendchar(s, 1, ',');
    first = false;
    sqlite3_str_appendf(s, "{\"id\":%lld,\"comment\":",
                        (long long)fsl_stmt_g_int64(&q, 0));
    fslext_json_str(s, fsl_stmt_g_text(&q, 1, NULL));
    sqlite3_str_appendall(s, ",\"time\":");
    fslext_json_str(s, fsl_stmt_g_text(&q, 2, NULL));
    sqlite3_str_appendall(s, ",\"checkin\":");
    fslext_json_str(s, fsl_stmt_g_text(&q, 3, NULL));
    sqlite3_str_appendf(s, ",\"files\":%lld}",
                        (long long)fsl_stmt_g_int64(&q, 4));
  }
  fsl_stmt_finalize(&q);
  sqlite3_str_appendchar(s, 1, ']');
  fslext_result_str(cx, s);
}

/** Appends ,"KEY":HASH, or null for rid 0, to s. */
static void fslext_json_hash(sqlite3_str * const s, fsl_cx * const f,
                             char const * zKey, fsl_id_t rid){
  char * const z = rid>0 ? fsl_rid_to_uuid(f, rid) : NULL;
  sqlite3_str_appendf(s, ",\"%s\":", zKey);
  if( z ) fslext_json_str(s, z);
  else sqlite3_str_appendall(s, "null");
  fsl_free(z);
}

/*
  fsl_bisect(ACTION [, VERSION])

  Runs fossil(1)'s bisect on the opened checkout. ACTION is:

  - "good", "bad" or "skip": marks VERSION, or the checkout's version,
    and then, when the session has both a good and a bad check-in and
    the auto-next bisect option is on (the default), updates the
    checkout to the next check-in to test, as fossil(1) does.
  - "next": updates the checkout to the next check-in to test.
  - "undo": takes back the most recent good, bad or skip.
  - "reset": ends the session.
  - "state": only reports.

  Returns a JSON object: {"good": HASH, "bad": HASH, "current": HASH,
  "complete": BOOL}, plus, after a step, "span" and "stepsLeft", with
  null for a check-in not yet known. Actions which move the checkout
  must run outside of a transaction.
*/
static void fslext_bisect(sqlite3_context *cx, int argc,
                          sqlite3_value **argv){
  fsl_cx * const f = fslext_ckout_cx(cx);
  char const * zAct = (char const *)sqlite3_value_text(argv[0]);
  char const * const zVersion = argc>1
    ? (char const *)sqlite3_value_text(argv[1]) : NULL;
  fsl_bisect_state_t st = fsl_bisect_state_t_empty;
  fsl_bisect_e verdict = 0;
  bool step = false, moved = false;
  fsl_id_t rid = 0, cur = 0;
  sqlite3_str * s;
  int rc = 0;
  if( !f ) return;
  if( !zAct ) zAct = "";
  if( 0==strcmp(zAct, "good") ) verdict = FSL_BISECT_GOOD;
  else if( 0==strcmp(zAct, "bad") ) verdict = FSL_BISECT_BAD;
  else if( 0==strcmp(zAct, "skip") ) verdict = FSL_BISECT_SKIP;
  else if( 0==strcmp(zAct, "next") ) step = true;
  else if( strcmp(zAct, "undo") && strcmp(zAct, "reset")
           && strcmp(zAct, "state") ){
    sqlite3_result_error(cx, "fsl_bisect() ACTION must be \"good\", "
                         "\"bad\", \"skip\", \"next\", \"undo\", "
                         "\"reset\" or \"state\".", -1);
    return;
  }
  if( (verdict || step) && !fslext_autocommit(cx, "fsl_bisect") ) return;
  if( verdict ){
    if( zVersion ) rc = fsl_sym_to_rid(f, zVersion, FSL_SATYPE_CHECKIN, &rid);
    if( 0==rc ) rc = fsl_bisect_mark(f, verdict, rid);
    if( 0==rc ) rc = fsl_bisect_state(f, &st);
    step = 0==rc && fsl_bisect_option_is_on(f, "auto-next")
      && ((FSL_BISECT_BAD==verdict && st.good>0)
          || (FSL_BISECT_GOOD==verdict && st.bad>0)
          || (FSL_BISECT_SKIP==verdict && st.good>0 && st.bad>0));
  }else if( 0==strcmp(zAct, "undo") ){
    rc = fsl_bisect_undo(f);
  }else if( 0==strcmp(zAct, "reset") ){
    rc = fsl_bisect_reset(f);
  }
  if( 0==rc && step ){
    fsl_ckup_opt uOpt = fsl_ckup_opt_empty;
    uOpt.setMtime = false;
    uOpt.scanForChanges = true;
    rc = fsl_bisect_next(f, &uOpt, &st);
    moved = 0==rc;
  }
  if( 0==rc && !moved ) rc = fsl_bisect_state(f, &st);
  if( rc ){
    fslext_error(cx, f, rc);
    return;
  }
  fsl_ckout_version_info(f, &cur, NULL);
  s = sqlite3_str_new(NULL);
  sqlite3_str_appendall(s, "{\"complete\":");
  sqlite3_str_appendall(s, st.complete ? "true" : "false");
  fslext_json_hash(s, f, "good", st.good);
  fslext_json_hash(s, f, "bad", st.bad);
  fslext_json_hash(s, f, "current", cur);
  if( moved ){
    sqlite3_str_appendf(s, ",\"span\":%d,\"stepsLeft\":%d",
                        st.span, st.stepsLeft);
  }
  sqlite3_str_appendchar(s, 1, '}');
  fslext_result_str(cx, s);
}

/**
   Resolves ticket id or unique id prefix zId to the full id, which the
   caller must fsl_free(). Returns non-0, with f's error state set, if
   no ticket, or more than one, has that id.
*/
static int fslext_ticket_id(fsl_cx * const f, char const * zId,
                            char ** pzId){
  fsl_stmt q = fsl_stmt_empty;
  int rc, n = 0;
  *pzId = NULL;
  rc = fsl_cx_prepare(f, &q, "SELECT substr(tagname,5)"
                      " FROM {{dbname.repo}}.tag"
                      " WHERE tagname GLOB 'tkt-%q*'", zId);
  while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
    if( ++n>1 ) break;
    *pzId = fsl_strdup(fsl_stmt_g_text(&q, 0, NULL));
    if( !*pzId ) rc = FSL_RC_OOM;
  }
  fsl_stmt_finalize(&q);
  if( 0==rc && 1!=n ){
    fsl_free(*pzId);
    *pzId = NULL;
    rc = n>1
      ? fsl_cx_err_set(f, FSL_RC_AMBIGUOUS, "Ambiguous ticket id: %s", zId)
      : fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "No such ticket: %s", zId);
  }
  return rc;
}

/**
   Saves a ticket change, setting FIELDS (a JSON object of field names
   and values) on ticket zId, or on a new ticket if zId is NULL, and
   sets cx's result to the ticket's id.
*/
static void fslext_ticket_save(sqlite3_context *cx, char const * zFunc,
                               char const * zId, sqlite3_value * pFields){
  FslExt * const ext = sqlite3_user_data(cx);
  fsl_cx * const f = fslext_cx(cx);
  fsl_deck d = fsl_deck_empty;
  sqlite3_stmt * q = NULL;
  char * zFull = NULL, * zUser = NULL;
  int rc = 0, nField = 0;
  if( !f ) return;
  if( zId ) rc = fslext_ticket_id(f, zId, &zFull);
  if( 0==rc ){
    fsl_deck_init(f, &d, FSL_SATYPE_TICKET);
    rc = fsl_deck_D_set(&d, fsl_db_julian_now(fsl_cx_db_repo(f)));
  }
  if( 0==rc ) rc = fsl_deck_K_set(&d, zFull);
  if( 0==rc ){
    rc = sqlite3_prepare_v2(ext->db,
           "SELECT key, CASE WHEN type IN ('object','array') THEN json(value)"
           " ELSE value END FROM json_each(?1) ORDER BY key", -1, &q, NULL);
    if( rc ){
      sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
      goto end;
    }
    sqlite3_bind_value(q, 1, pFields);
    while( 0==rc && SQLITE_ROW==sqlite3_step(q) ){
      ++nField;
      rc = fsl_deck_J_add(&d, false, (char const *)sqlite3_column_text(q, 0),
                          (char const *)sqlite3_column_text(q, 1));
    }
    if( 0==rc && SQLITE_OK!=sqlite3_errcode(ext->db)
        && SQLITE_DONE!=sqlite3_errcode(ext->db) ){
      sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
      goto end;
    }
    sqlite3_finalize(q);
    q = NULL;
    if( 0==rc && !nField ){
      char * const z = sqlite3_mprintf("%s() requires a JSON object of "
                                       "at least one field.", zFunc);
      sqlite3_result_error(cx, z ? z : "No fields.", -1);
      sqlite3_free(z);
      goto end;
    }
  }
  if( 0==rc ){
    char const * zU = fsl_cx_user_get(f);
    if( !zU ){
      zUser = fsl_user_name_guess();
      zU = zUser;
    }
    rc = zU ? fsl_deck_U_set(&d, zU) : FSL_RC_OOM;
  }
  if( 0==rc ) rc = fsl_deck_save(&d, false);
  if( rc ) fslext_error(cx, f, rc);
  else sqlite3_result_text(cx, d.K, -1, SQLITE_TRANSIENT);
  end:
  sqlite3_finalize(q);
  fsl_deck_finalize(&d);
  fsl_free(zFull);
  fsl_free(zUser);
}

/*
  fsl_ticket_new(FIELDS)
  fsl_ticket_change(ID, FIELDS)

  Make a new ticket, or change ticket ID (its 40-digit id or a unique
  prefix), as fossil(1)'s ticket add and ticket set do. FIELDS is a
  JSON object of ticket field names and their new values, e.g.
  {"title": "Crash on open", "status": "Open", "type": "Code_Defect"}.
  Fields the ticket table has no column for are recorded but not
  shown, as with fossil(1). Returns the ticket's id. The user is
  fsl_open()'s USER.
*/
static void fslext_ticket_new(sqlite3_context *cx, int argc,
                              sqlite3_value **argv){
  (void)argc;
  fslext_ticket_save(cx, "fsl_ticket_new", NULL, argv[0]);
}

static void fslext_ticket_change(sqlite3_context *cx, int argc,
                                 sqlite3_value **argv){
  char const * const zId = (char const *)sqlite3_value_text(argv[0]);
  (void)argc;
  if( !zId || !*zId ){
    sqlite3_result_error(cx, "fsl_ticket_change() requires a ticket id.",
                         -1);
    return;
  }
  fslext_ticket_save(cx, "fsl_ticket_change", zId, argv[1]);
}

/*
  fsl_ticket(ID)

  Returns ticket ID's current fields, as fossil(1)'s ticket table holds
  them, as a JSON object, or NULL if there is no such ticket. ID is
  its 40-digit id or a unique prefix.
*/
static void fslext_ticket(sqlite3_context *cx, int argc,
                          sqlite3_value **argv){
  FslExt * const ext = sqlite3_user_data(cx);
  fsl_cx * const f = fslext_cx(cx);
  char const * const zId = (char const *)sqlite3_value_text(argv[0]);
  char * zFull = NULL;
  sqlite3_stmt * q = NULL;
  int rc;
  (void)argc;
  if( !f ) return;
  if( !zId || !*zId ){
    sqlite3_result_error(cx, "fsl_ticket() requires a ticket id.", -1);
    return;
  }
  rc = fslext_ticket_id(f, zId, &zFull);
  if( FSL_RC_NOT_FOUND==rc ){
    fsl_cx_err_reset(f);
    sqlite3_result_null(cx);
    return;
  }else if( rc ){
    fslext_error(cx, f, rc);
    return;
  }
  {
    char const * const zPre = fsl__db_repo_prefix(f->dbMain);
    char * const zSql = zPre
      ? sqlite3_mprintf("SELECT * FROM main.\"%wticket\""
                        " WHERE tkt_uuid=?1", zPre)
      : sqlite3_mprintf("SELECT * FROM \"%w\".ticket"
                        " WHERE tkt_uuid=?1",
                        fsl__db_schema(f->dbMain, FSL_DBROLE_REPO));
    rc = zSql ? sqlite3_prepare_v2(ext->db, zSql, -1, &q, NULL)
      : SQLITE_NOMEM;
    sqlite3_free(zSql);
  }
  if( 0==rc ){
    sqlite3_bind_text(q, 1, zFull, -1, SQLITE_STATIC);
    rc = sqlite3_step(q);
  }
  if( SQLITE_ROW==rc ){
    sqlite3_str * const s = sqlite3_str_new(NULL);
    int const n = sqlite3_column_count(q);
    sqlite3_str_appendchar(s, 1, '{');
    for( int i = 0; i < n; ++i ){
      if( i ) sqlite3_str_appendchar(s, 1, ',');
      fslext_json_str(s, sqlite3_column_name(q, i));
      sqlite3_str_appendchar(s, 1, ':');
      switch( sqlite3_column_type(q, i) ){
        case SQLITE_NULL: sqlite3_str_appendall(s, "null"); break;
        case SQLITE_INTEGER:
          sqlite3_str_appendf(s, "%lld", sqlite3_column_int64(q, i));
          break;
        case SQLITE_FLOAT:
          sqlite3_str_appendf(s, "%!.17g", sqlite3_column_double(q, i));
          break;
        default:
          fslext_json_str(s, (char const *)sqlite3_column_text(q, i));
      }
    }
    sqlite3_str_appendchar(s, 1, '}');
    fslext_result_str(cx, s);
  }else if( SQLITE_DONE==rc ){
    sqlite3_result_null(cx);
  }else{
    sqlite3_result_error(cx, sqlite3_errmsg(ext->db), -1);
  }
  sqlite3_finalize(q);
  fsl_free(zFull);
}

/*
  fsl_repos

  An eponymous table: one row per repository fsl_open() has opened on
  this connection, in the order it did.

  - name: the schema a repository file is attached as ("repo",
    "repo_2", ...), or the NAME of a repo:NAME repository, as
    fsl_use(), fsl_close() and fsl_export() take it.
  - path: the repository file, NULL for a repo:NAME repository.
  - ckout: the checkout directory, if one is opened, else NULL.
  - ckout_schema: the schema the checkout is attached as ("ckout",
    "ckout_2", ...), else NULL.
  - current: 1 for the repository the other functions act on, else 0.
  - files_table: for a db:NAME working copy, the name of the host's
    main table which holds its files ("fslfiles_NAME"), else NULL.
  - location: the repository file, or "host" for a repo:NAME
    repository, whose tables are in this connection's main db.

  The rows are those of when the query starts, so that e.g.
  SELECT fsl_close(name) FROM fsl_repos closes each of them.

  SELECT name, path FROM fsl_repos WHERE current;
*/
typedef struct {
  sqlite3_vtab base;
  FslExt * ext;
} FslextReposTab;

/** One fsl_repos row, copied when the query starts. */
typedef struct {
  char * aCol[6] /* name, path, ckout, ckout_schema, files_table,
                    location */;
  int current;
} FslextReposRow;

typedef struct {
  sqlite3_vtab_cursor base;
  FslextReposRow * aRow;
  unsigned nRow;
  unsigned i;
} FslextReposCursor;

static void fslext_repos_rows_free(FslextReposCursor * const c){
  for( unsigned i = 0; i < c->nRow; ++i ){
    for( unsigned k = 0; k < 6; ++k ) sqlite3_free(c->aRow[i].aCol[k]);
  }
  sqlite3_free(c->aRow);
  c->aRow = NULL;
  c->nRow = c->i = 0;
}

static int fslextReposConnect(sqlite3 *db, void *pAux, int argc,
                              const char *const*argv,
                              sqlite3_vtab **ppVtab, char **pzErr){
  FslextReposTab * p;
  int rc;
  (void)argc; (void)argv; (void)pzErr;
  rc = sqlite3_declare_vtab(db, "CREATE TABLE x(name TEXT, path TEXT,"
                            " ckout TEXT, ckout_schema TEXT,"
                            " current INTEGER, files_table TEXT,"
                            " location TEXT)");
  if( rc ) return rc;
  p = sqlite3_malloc(sizeof(*p));
  if( !p ) return SQLITE_NOMEM;
  memset(p, 0, sizeof(*p));
  p->ext = pAux;
  *ppVtab = &p->base;
  return SQLITE_OK;
}

static int fslextReposDisconnect(sqlite3_vtab *pVtab){
  sqlite3_free(pVtab);
  return SQLITE_OK;
}

static int fslextReposBestIndex(sqlite3_vtab *tab,
                                sqlite3_index_info *pIdx){
  (void)tab;
  pIdx->estimatedCost = 10;
  return SQLITE_OK;
}

static int fslextReposOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCur){
  FslextReposCursor * const c = sqlite3_malloc(sizeof(*c));
  (void)p;
  if( !c ) return SQLITE_NOMEM;
  memset(c, 0, sizeof(*c));
  *ppCur = &c->base;
  return SQLITE_OK;
}

static int fslextReposClose(sqlite3_vtab_cursor *c){
  fslext_repos_rows_free((FslextReposCursor*)c);
  sqlite3_free(c);
  return SQLITE_OK;
}

static int fslextReposFilter(sqlite3_vtab_cursor *cur, int idxNum,
                             const char *idxStr, int argc,
                             sqlite3_value **argv){
  FslextReposCursor * const c = (FslextReposCursor*)cur;
  FslExt const * const ext = ((FslextReposTab*)cur->pVtab)->ext;
  (void)idxNum; (void)idxStr; (void)argc; (void)argv;
  fslext_repos_rows_free(c);
  if( !ext->n ) return SQLITE_OK;
  c->aRow = sqlite3_malloc64(ext->n * sizeof(FslextReposRow));
  if( !c->aRow ) return SQLITE_NOMEM;
  memset(c->aRow, 0, ext->n * sizeof(FslextReposRow));
  c->nRow = ext->n;
  for( unsigned i = 0; i < ext->n; ++i ){
    fsl_cx * const f = ext->a[i];
    bool const ck = NULL!=fsl_cx_db_ckout(f);
    bool const host = NULL!=fsl__db_repo_prefix(f->dbMain);
    FslextWc const * const w = ck ? fslext_wc_of(ext, f) : NULL;
    fsl_size_t nName = 0;
    char const * const zName = fslext_name(f, &nName);
    char const * const az[6] = {
      NULL, host ? NULL : fsl_cx_db_file_repo(f, NULL),
      ck ? fsl_cx_ckout_dir_name(f, NULL) : NULL,
      ck ? fsl__db_schema(f->dbMain, FSL_DBROLE_CKOUT) : NULL,
      w ? w->zFiles : NULL,
      host ? "host" : fsl_cx_db_file_repo(f, NULL)
    };
    if( !(c->aRow[i].aCol[0] = sqlite3_mprintf("%.*s", (int)nName,
                                               zName)) ){
      return SQLITE_NOMEM;
    }
    for( unsigned k = 1; k < 6; ++k ){
      if( az[k] && !(c->aRow[i].aCol[k] = sqlite3_mprintf("%s", az[k])) ){
        return SQLITE_NOMEM;
      }
    }
    c->aRow[i].current = f==ext->f;
  }
  return SQLITE_OK;
}

static int fslextReposNext(sqlite3_vtab_cursor *c){
  ++((FslextReposCursor*)c)->i;
  return SQLITE_OK;
}

static int fslextReposEof(sqlite3_vtab_cursor *cur){
  FslextReposCursor const * const c = (FslextReposCursor const*)cur;
  return c->i >= c->nRow;
}

static int fslextReposColumn(sqlite3_vtab_cursor *cur, sqlite3_context *cx,
                             int iCol){
  FslextReposRow const * const row =
    &((FslextReposCursor*)cur)->aRow[((FslextReposCursor*)cur)->i];
  if( 4==iCol ){
    sqlite3_result_int(cx, row->current);
  }else{
    int const k = iCol<4 ? iCol : iCol-1 /* past current */;
    if( row->aCol[k] ){
      sqlite3_result_text(cx, row->aCol[k], -1, SQLITE_TRANSIENT);
    }
  }
  return SQLITE_OK;
}

static int fslextReposRowid(sqlite3_vtab_cursor *c, sqlite3_int64 *pRowid){
  *pRowid = (sqlite3_int64)((FslextReposCursor*)c)->i + 1;
  return SQLITE_OK;
}

static sqlite3_module fslextReposModule = {
  0,                       /* iVersion */
  0,                       /* xCreate: eponymous-only */
  fslextReposConnect,      /* xConnect */
  fslextReposBestIndex,    /* xBestIndex */
  fslextReposDisconnect,   /* xDisconnect */
  0,                       /* xDestroy */
  fslextReposOpen,         /* xOpen */
  fslextReposClose,        /* xClose */
  fslextReposFilter,       /* xFilter */
  fslextReposNext,         /* xNext */
  fslextReposEof,          /* xEof */
  fslextReposColumn,       /* xColumn */
  fslextReposRowid,        /* xRowid */
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

int fsl_sqlext_init(sqlite3 * db, char ** pzErrMsg,
                    sqlite3_api_routines const * pApi){
  static struct {
    char const * zName;
    int nArg;
    void (*xFunc)(sqlite3_context*, int, sqlite3_value**);
  } const aFunc[] = {
    {"fsl_open", 1, fslext_open},   {"fsl_open", 2, fslext_open},
    {"fsl_open", 3, fslext_open},
    {"fsl_import", 2, fslext_import},
    {"fsl_export", 2, fslext_export},  {"fsl_export", 3, fslext_export},
    {"fsl_drop", 1, fslext_drop},
    {"fsl_close", 0, fslext_close},   {"fsl_close", 1, fslext_close},
    {"fsl_use", 1, fslext_use_name},
    {"fsl_resolve", 1, fslext_resolve},
    {"fsl_file", 2, fslext_file},
    {"fsl_extract", 2, fslext_extract}, {"fsl_extract", 3, fslext_extract},
    {"fsl_zip", 2, fslext_zip},         {"fsl_zip", 3, fslext_zip},
    {"fsl_rebuild", 0, fslext_rebuild}, {"fsl_rebuild", 1, fslext_rebuild},
    {"fsl_wiki", 1, fslext_wiki},
    {"fsl_wiki_save", 2, fslext_wiki_save},
    {"fsl_wiki_save", 3, fslext_wiki_save},
    {"fsl_technote", 1, fslext_technote},
    {"fsl_technote_save", 1, fslext_technote_save},
    {"fsl_technote_save", 2, fslext_technote_save},
    {"fsl_forum", 1, fslext_forum},
    {"fsl_forum_post", 2, fslext_forum_post},
    {"fsl_diff", 2, fslext_diff},      {"fsl_diff", 3, fslext_diff},
    {"fsl_commit", 1, fslext_commit},
    {"fsl_tag", 2, fslext_tag},     {"fsl_tag", 3, fslext_tag},
    {"fsl_tag", 4, fslext_tag},     {"fsl_tag", 5, fslext_tag},
    {"fsl_branch", 2, fslext_branch_new},
    {"fsl_branch", 3, fslext_branch_new},
    {"fsl_setting", 1, fslext_setting},
    {"fsl_setting", 2, fslext_setting},
    {"fsl_setting", 3, fslext_setting},
    {"fsl_sync", 1, fslext_sync},   {"fsl_sync", 2, fslext_sync},
    {"fsl_clone", 2, fslext_clone},   {"fsl_clone", 3, fslext_clone},
    {"fsl_checkout", 1, fslext_checkout},
    {"fsl_checkout", 2, fslext_checkout},
    {"fsl_update", 0, fslext_update},  {"fsl_update", 1, fslext_update},
    {"fsl_update", 2, fslext_update},
    {"fsl_merge", 1, fslext_merge},    {"fsl_merge", 2, fslext_merge},
    {"fsl_merge", 3, fslext_merge},
    {"fsl_status", 0, fslext_status},
    {"fsl_add", 1, fslext_add},        {"fsl_rm", 1, fslext_rm},
    {"fsl_mv", 2, fslext_mv},
    {"fsl_revert", 0, fslext_revert},  {"fsl_revert", 1, fslext_revert},
    {"fsl_undo", 0, fslext_undo},      {"fsl_undo", 1, fslext_undo},
    {"fsl_redo", 0, fslext_redo},      {"fsl_redo", 1, fslext_redo},
    {"fsl_undo_state", 0, fslext_undo_state},
    {"fsl_stash_save", 0, fslext_stash_save},
    {"fsl_stash_save", 1, fslext_stash_save},
    {"fsl_stash_save", 2, fslext_stash_save},
    {"fsl_stash_apply", 0, fslext_stash_apply},
    {"fsl_stash_apply", 1, fslext_stash_apply},
    {"fsl_stash_pop", 0, fslext_stash_pop},
    {"fsl_stash_pop", 1, fslext_stash_pop},
    {"fsl_stash_drop", 1, fslext_stash_drop},
    {"fsl_stash_list", 0, fslext_stash_list},
    {"fsl_bisect", 1, fslext_bisect},  {"fsl_bisect", 2, fslext_bisect},
    {"fsl_ticket", 1, fslext_ticket},
    {"fsl_ticket_new", 1, fslext_ticket_new},
    {"fsl_ticket_change", 2, fslext_ticket_change}
  };
  FslExt * ext;
  int rc;
  (void)pApi;
  fsl__lib_hosted();
  ext = sqlite3_malloc(sizeof(*ext));
  if( !ext ) return SQLITE_NOMEM;
  memset(ext, 0, sizeof(*ext));
  ext->db = db;
  rc = sqlite3_set_clientdata(db, "fsl_sqlext", ext, fslext_free);
  if( rc ) return rc /* SQLite has already freed ext */;
  for( unsigned i = 0; 0==rc && i < sizeof(aFunc)/sizeof(aFunc[0]); ++i ){
    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
                                 SQLITE_UTF8 | SQLITE_DIRECTONLY, ext,
                                 aFunc[i].xFunc, 0, 0);
  }
  if( 0==rc ){
    rc = sqlite3_create_module(db, "fsl_sqlext_life",
                               &fslextLifeModule, ext);
  }
  if( 0==rc ){
    rc = sqlite3_create_module(db, "fsl_annotate", &fslextAnnModule, ext);
  }
  if( 0==rc ){
    rc = sqlite3_create_module(db, "fsl_repos", &fslextReposModule, ext);
  }
  if( rc && pzErrMsg ){
    *pzErrMsg = sqlite3_mprintf("fossil extension init failed: %s",
                                sqlite3_errmsg(db));
  }
  return rc;
}

#if defined(FSL_SQLEXT_LOADABLE)
#  if defined(_WIN32)
__declspec(dllexport)
#  endif
int sqlite3_fossilext_init(sqlite3 * db, char ** pzErrMsg,
                           sqlite3_api_routines const * pApi){
  SQLITE_EXTENSION_INIT2(pApi);
  if( sqlite3_libversion_number()<3044000 ){
    /* sqlite3_set_clientdata() is new in 3.44.0: on an older SQLite
       its entry in pApi does not exist. */
    if( pzErrMsg ){
      *pzErrMsg = sqlite3_mprintf("fossilext needs SQLite 3.44.0 or later, "
                                  "and this is %s.", sqlite3_libversion());
    }
    return SQLITE_ERROR;
  }
  return fsl_sqlext_init(db, pzErrMsg, pApi);
}
#endif
/* end of file src/sqlext.c */
/* start of file src/difftk_cstr.c */
/** @page page_difftk_cstr difftk.tcl

Binary form of file difftk.tcl.

*/
/* auto-generated code - edit at your own risk! (Good luck with that!) */
static char const fsl_difftk_cstr_a[] = {
35, 32, 84, 104, 105, 115, 32, 115, 99, 114, 105, 112, 116, 32, 119, 97, 115, 32, 116, 97, 
107, 101, 110, 32, 118, 101, 114, 98, 97, 116, 105, 109, 32, 102, 114, 111, 109, 32, 116, 104, 
101, 32, 70, 111, 115, 115, 105, 108, 32, 83, 67, 77, 32, 112, 114, 111, 106, 101, 99, 116, 
46, 32, 32, 73, 116, 32, 105, 115, 10, 35, 32, 110, 111, 116, 32, 115, 116, 97, 110, 100, 
97, 108, 111, 110, 101, 58, 32, 105, 116, 32, 105, 115, 32, 105, 110, 116, 101, 110, 100, 101, 
100, 32, 116, 111, 32, 98, 101, 32, 101, 109, 98, 101, 100, 100, 101, 100, 32, 105, 110, 32, 
111, 117, 116, 112, 117, 116, 32, 103, 101, 110, 101, 114, 97, 116, 101, 100, 32, 98, 121, 10, 
35, 32, 102, 45, 118, 100, 105, 102, 102, 32, 40, 111, 114, 32, 115, 105, 109, 105, 108, 97, 
114, 41, 46, 10, 115, 101, 116, 32, 112, 114, 111, 103, 32, 123, 10, 112, 97, 99, 107, 97, 
103, 101, 32, 114, 101, 113, 117, 105, 114, 101, 32, 84, 107, 10, 10, 97, 114, 114, 97, 121, 
32, 115, 101, 116, 32, 67, 70, 71, 32, 123, 10, 32, 32, 84, 73, 84, 76, 69, 32, 32, 
32, 32, 32, 32, 123, 70, 111, 115, 115, 105, 108, 32, 68, 105, 102, 102, 125, 10, 32, 32, 
76, 78, 95, 67, 79, 76, 95, 66, 71, 32, 32, 35, 100, 100, 100, 100, 100, 100, 10, 32, 
32, 76, 78, 95, 67, 79, 76, 95, 70, 71, 32, 32, 35, 52, 52, 52, 52, 52, 52, 10, 
32, 32, 84, 88, 84, 95, 67, 79, 76, 95, 66, 71, 32, 35, 102, 102, 102, 102, 102, 102, 
10, 32, 32, 84, 88, 84, 95, 67, 79, 76, 95, 70, 71, 32, 35, 48, 48, 48, 48, 48, 
48, 10, 32, 32, 77, 75, 82, 95, 67, 79, 76, 95, 66, 71, 32, 35, 52, 52, 52, 52, 
52, 52, 10, 32, 32, 77, 75, 82, 95, 67, 79, 76, 95, 70, 71, 32, 35, 100, 100, 100, 
100, 100, 100, 10, 32, 32, 67, 72, 78, 71, 95, 66, 71, 32, 32, 32, 32, 35, 100, 48, 
100, 48, 102, 102, 10, 32, 32, 65, 68, 68, 95, 66, 71, 32, 32, 32, 32, 32, 35, 99, 
48, 102, 102, 99, 48, 10, 32, 32, 82, 77, 95, 66, 71, 32, 32, 32, 32, 32, 32, 35, 
102, 102, 99, 48, 99, 48, 10, 32, 32, 72, 82, 95, 70, 71, 32, 32, 32, 32, 32, 32, 
35, 52, 52, 52, 52, 52, 52, 10, 32, 32, 72, 82, 95, 80, 65, 68, 95, 84, 79, 80, 
32, 52, 10, 32, 32, 72, 82, 95, 80, 65, 68, 95, 66, 84, 77, 32, 56, 10, 32, 32, 
70, 78, 95, 66, 71, 32, 32, 32, 32, 32, 32, 35, 52, 52, 52, 52, 52, 52, 10, 32, 
32, 70, 78, 95, 70, 71, 32, 32, 32, 32, 32, 32, 35, 102, 102, 102, 102, 102, 102, 10, 
32, 32, 70, 78, 95, 80, 65, 68, 32, 32, 32, 32, 32, 53, 10, 32, 32, 69, 82, 82, 
95, 70, 71, 32, 32, 32, 32, 32, 35, 101, 101, 48, 48, 48, 48, 10, 32, 32, 80, 65, 
68, 88, 32, 32, 32, 32, 32, 32, 32, 53, 10, 32, 32, 87, 73, 68, 84, 72, 32, 32, 
32, 32, 32, 32, 56, 48, 10, 32, 32, 72, 69, 73, 71, 72, 84, 32, 32, 32, 32, 32, 
52, 53, 10, 32, 32, 76, 66, 95, 72, 69, 73, 71, 72, 84, 32, 32, 50, 53, 10, 125, 
10, 10, 105, 102, 32, 123, 33, 91, 110, 97, 109, 101, 115, 112, 97, 99, 101, 32, 101, 120, 
105, 115, 116, 115, 32, 116, 116, 107, 93, 125, 32, 123, 10, 32, 32, 105, 110, 116, 101, 114, 
112, 32, 97, 108, 105, 97, 115, 32, 123, 125, 32, 58, 58, 116, 116, 107, 58, 58, 115, 99, 
114, 111, 108, 108, 98, 97, 114, 32, 123, 125, 32, 58, 58, 115, 99, 114, 111, 108, 108, 98, 
97, 114, 10, 32, 32, 105, 110, 116, 101, 114, 112, 32, 97, 108, 105, 97, 115, 32, 123, 125, 
32, 58, 58, 116, 116, 107, 58, 58, 109, 101, 110, 117, 98, 117, 116, 116, 111, 110, 32, 123, 
125, 32, 58, 58, 109, 101, 110, 117, 98, 117, 116, 116, 111, 110, 10, 125, 10, 10, 112, 114, 
111, 99, 32, 100, 101, 104, 116, 109, 108, 32, 123, 120, 125, 32, 123, 10, 32, 32, 115, 101, 
116, 32, 120, 32, 91, 114, 101, 103, 115, 117, 98, 32, 45, 97, 108, 108, 32, 123, 60, 91, 
94, 62, 93, 42, 62, 125, 32, 36, 120, 32, 123, 125, 93, 10, 32, 32, 114, 101, 116, 117, 
114, 110, 32, 91, 115, 116, 114, 105, 110, 103, 32, 109, 97, 112, 32, 123, 38, 97, 109, 112, 
59, 32, 38, 32, 38, 108, 116, 59, 32, 60, 32, 38, 103, 116, 59, 32, 62, 32, 38, 35, 
51, 57, 59, 32, 39, 32, 38, 113, 117, 111, 116, 59, 32, 92, 34, 125, 32, 36, 120, 93, 
10, 125, 10, 10, 112, 114, 111, 99, 32, 99, 111, 108, 115, 32, 123, 125, 32, 123, 10, 32, 
32, 114, 101, 116, 117, 114, 110, 32, 91, 108, 105, 115, 116, 32, 46, 108, 110, 65, 32, 46, 
116, 120, 116, 65, 32, 46, 109, 107, 114, 32, 46, 108, 110, 66, 32, 46, 116, 120, 116, 66, 
93, 10, 125, 10, 10, 112, 114, 111, 99, 32, 99, 111, 108, 84, 121, 112, 101, 32, 123, 99, 
125, 32, 123, 10, 32, 32, 114, 101, 103, 101, 120, 112, 32, 123, 91, 97, 45, 122, 93, 43, 
125, 32, 36, 99, 32, 116, 121, 112, 101, 10, 32, 32, 114, 101, 116, 117, 114, 110, 32, 36, 
116, 121, 112, 101, 10, 125, 10, 10, 112, 114, 111, 99, 32, 103, 101, 116, 76, 105, 110, 101, 
32, 123, 100, 105, 102, 102, 116, 120, 116, 32, 78, 32, 105, 105, 118, 97, 114, 125, 32, 123, 
10, 32, 32, 117, 112, 118, 97, 114, 32, 36, 105, 105, 118, 97, 114, 32, 105, 105, 10, 32, 
32, 105, 102, 32, 123, 36, 105, 105, 62, 61, 36, 78, 125, 32, 123, 114, 101, 116, 117, 114, 
110, 32, 45, 49, 125, 10, 32, 32, 115, 101, 116, 32, 120, 32, 91, 108, 105, 110, 100, 101, 
120, 32, 36, 100, 105, 102, 102, 116, 120, 116, 32, 36, 105, 105, 93, 10, 32, 32, 105, 110, 
99, 114, 32, 105, 105, 10, 32, 32, 114, 101, 116, 117, 114, 110, 32, 36, 120, 10, 125, 10, 
10, 112, 114, 111, 99, 32, 114, 101, 97, 100, 68, 105, 102, 102, 115, 32, 123, 102, 111, 115, 
115, 105, 108, 99, 109, 100, 125, 32, 123, 10, 32, 32, 103, 108, 111, 98, 97, 108, 32, 100, 
105, 102, 102, 116, 120, 116, 10, 32, 32, 105, 102, 32, 123, 33, 91, 105, 110, 102, 111, 32, 
101, 120, 105, 115, 116, 115, 32, 100, 105, 102, 102, 116, 120, 116, 93, 125, 32, 123, 10, 32, 
32, 32, 32, 115, 101, 116, 32, 105, 110, 32, 91, 111, 112, 101, 110, 32, 36, 102, 111, 115, 
115, 105, 108, 99, 109, 100, 32, 114, 93, 10, 32, 32, 32, 32, 102, 99, 111, 110, 102, 105, 
103, 117, 114, 101, 32, 36, 105, 110, 32, 45, 101, 110, 99, 111, 100, 105, 110, 103, 32, 117, 
116, 102, 45, 56, 10, 32, 32, 32, 32, 115, 101, 116, 32, 100, 105, 102, 102, 116, 120, 116, 
32, 91, 115, 112, 108, 105, 116, 32, 91, 114, 101, 97, 100, 32, 36, 105, 110, 93, 32, 92, 
110, 93, 10, 32, 32, 32, 32, 99, 108, 111, 115, 101, 32, 36, 105, 110, 10, 32, 32, 125, 
10, 32, 32, 115, 101, 116, 32, 78, 32, 91, 108, 108, 101, 110, 103, 116, 104, 32, 36, 100, 
105, 102, 102, 116, 120, 116, 93, 10, 32, 32, 115, 101, 116, 32, 105, 105, 32, 48, 10, 32, 
32, 115, 101, 116, 32, 110, 68, 105, 102, 102, 115, 32, 48, 10, 32, 32, 115, 101, 116, 32, 
110, 49, 32, 48, 10, 32, 32, 115, 101, 116, 32, 110, 50, 32, 48, 32, 32, 10, 32, 32, 
97, 114, 114, 97, 121, 32, 115, 101, 116, 32, 119, 105, 100, 116, 104, 115, 32, 123, 116, 120, 
116, 32, 51, 32, 108, 110, 32, 54, 32, 109, 107, 114, 32, 49, 125, 10, 32, 32, 119, 104, 
105, 108, 101, 32, 123, 91, 115, 101, 116, 32, 108, 105, 110, 101, 32, 91, 103, 101, 116, 76, 
105, 110, 101, 32, 36, 100, 105, 102, 102, 116, 120, 116, 32, 36, 78, 32, 105, 105, 93, 93, 
32, 33, 61, 32, 45, 49, 125, 32, 123, 10, 32, 32, 32, 32, 115, 119, 105, 116, 99, 104, 
32, 45, 45, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 48, 93, 
32, 123, 10, 32, 32, 32, 32, 32, 32, 70, 73, 76, 69, 32, 123, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 105, 110, 99, 114, 32, 110, 68, 105, 102, 102, 115, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 102, 111, 114, 101, 97, 99, 104, 32, 119, 120, 32, 91, 108, 105, 115, 116, 
32, 91, 115, 116, 114, 105, 110, 103, 32, 108, 101, 110, 103, 116, 104, 32, 36, 110, 49, 93, 
32, 91, 115, 116, 114, 105, 110, 103, 32, 108, 101, 110, 103, 116, 104, 32, 36, 110, 50, 93, 
93, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 105, 102, 32, 123, 36, 119, 
120, 62, 36, 119, 105, 100, 116, 104, 115, 40, 108, 110, 41, 125, 32, 123, 115, 101, 116, 32, 
119, 105, 100, 116, 104, 115, 40, 108, 110, 41, 32, 36, 119, 120, 125, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 
110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 102, 110, 32, 92, 110, 32, 45, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 
116, 32, 101, 110, 100, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 
49, 93, 92, 110, 32, 102, 110, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 
32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 
102, 110, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 66, 
32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 102, 110, 32, 92, 110, 
32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 
101, 114, 116, 32, 101, 110, 100, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 
101, 32, 50, 93, 92, 110, 32, 102, 110, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 
32, 32, 32, 46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 105, 110, 115, 101, 114, 116, 
32, 101, 110, 100, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 50, 
93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 110, 49, 32, 48, 10, 32, 
32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 110, 50, 32, 48, 10, 32, 32, 32, 32, 
32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 83, 75, 73, 80, 32, 123, 10, 32, 32, 32, 
32, 32, 32, 32, 32, 115, 101, 116, 32, 110, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 
108, 105, 110, 101, 32, 49, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 
32, 110, 49, 32, 36, 110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 
110, 50, 32, 36, 110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 
110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 46, 46, 46, 92, 110, 32, 104, 114, 108, 110, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 
116, 32, 101, 110, 100, 32, 91, 115, 116, 114, 105, 110, 103, 32, 114, 101, 112, 101, 97, 116, 
32, 46, 32, 51, 48, 93, 92, 110, 32, 104, 114, 116, 120, 116, 10, 32, 32, 32, 32, 32, 
32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 
110, 32, 104, 114, 108, 110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 66, 32, 
105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 46, 46, 46, 92, 110, 32, 104, 114, 108, 
110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 101, 
114, 116, 32, 101, 110, 100, 32, 91, 115, 116, 114, 105, 110, 103, 32, 114, 101, 112, 101, 97, 
116, 32, 46, 32, 51, 48, 93, 92, 110, 32, 104, 114, 116, 120, 116, 10, 32, 32, 32, 32, 
32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 67, 79, 77, 32, 123, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 115, 101, 116, 32, 120, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 
105, 110, 101, 32, 49, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 
110, 49, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 110, 50, 10, 32, 
32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 
110, 100, 32, 36, 110, 49, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 
116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 92, 110, 
32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 
114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 
46, 108, 110, 66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 110, 50, 92, 
110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 
115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 92, 110, 32, 45, 10, 32, 32, 32, 32, 
32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 73, 78, 83, 32, 123, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 115, 101, 116, 32, 120, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 
105, 110, 101, 32, 49, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 
110, 50, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 110, 115, 101, 
114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 
46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 
45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, 
116, 32, 101, 110, 100, 32, 62, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 
46, 108, 110, 66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 110, 50, 92, 
110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 
115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 32, 97, 100, 100, 32, 92, 110, 32, 45, 
10, 32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 68, 69, 76, 32, 123, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 120, 32, 91, 108, 105, 110, 100, 
101, 120, 32, 36, 108, 105, 110, 101, 32, 49, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 
105, 110, 99, 114, 32, 110, 49, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 
32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 110, 49, 92, 110, 32, 45, 10, 
32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 
32, 101, 110, 100, 32, 36, 120, 32, 114, 109, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 
60, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 66, 32, 105, 
110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 
32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 
92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 69, 
68, 73, 84, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 110, 
49, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 110, 50, 10, 32, 32, 
32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 
100, 32, 36, 110, 49, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 
110, 66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 110, 50, 92, 110, 32, 
45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, 
116, 32, 101, 110, 100, 32, 124, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 
115, 101, 116, 32, 110, 110, 32, 91, 108, 108, 101, 110, 103, 116, 104, 32, 36, 108, 105, 110, 
101, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 102, 111, 114, 32, 123, 115, 101, 116, 32, 
105, 32, 49, 125, 32, 123, 36, 105, 60, 36, 110, 110, 125, 32, 123, 105, 110, 99, 114, 32, 
105, 32, 51, 125, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 
32, 120, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 36, 105, 93, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 105, 102, 32, 123, 36, 120, 32, 110, 101, 
32, 34, 34, 125, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 
116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 32, 45, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 
110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 32, 45, 10, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 105, 102, 32, 
123, 36, 105, 43, 50, 60, 36, 110, 110, 125, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 115, 101, 116, 32, 120, 49, 32, 91, 108, 105, 110, 100, 101, 120, 32, 
36, 108, 105, 110, 101, 32, 91, 101, 120, 112, 114, 32, 123, 36, 105, 43, 49, 125, 93, 93, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 120, 50, 32, 
91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 91, 101, 120, 112, 114, 32, 
123, 36, 105, 43, 50, 125, 93, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 105, 102, 32, 123, 34, 36, 120, 49, 34, 32, 101, 113, 32, 34, 34, 125, 32, 123, 10, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 
105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 50, 32, 97, 100, 100, 10, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 105, 102, 32, 
123, 34, 36, 120, 50, 34, 32, 101, 113, 32, 34, 34, 125, 32, 123, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 
114, 116, 32, 101, 110, 100, 32, 36, 120, 49, 32, 114, 109, 10, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 
116, 32, 101, 110, 100, 32, 36, 120, 49, 32, 99, 104, 110, 103, 10, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 101, 114, 
116, 32, 101, 110, 100, 32, 36, 120, 50, 32, 99, 104, 110, 103, 10, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 125, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 
116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 101, 114, 
116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 125, 10, 32, 
32, 32, 32, 32, 32, 34, 34, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 102, 111, 
114, 101, 97, 99, 104, 32, 119, 120, 32, 91, 108, 105, 115, 116, 32, 91, 115, 116, 114, 105, 
110, 103, 32, 108, 101, 110, 103, 116, 104, 32, 36, 110, 49, 93, 32, 91, 115, 116, 114, 105, 
110, 103, 32, 108, 101, 110, 103, 116, 104, 32, 36, 110, 50, 93, 93, 32, 123, 10, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 105, 102, 32, 123, 36, 119, 120, 62, 36, 119, 105, 100, 
116, 104, 115, 40, 108, 110, 41, 125, 32, 123, 115, 101, 116, 32, 119, 105, 100, 116, 104, 115, 
40, 108, 110, 41, 32, 36, 119, 120, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 125, 10, 
32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 100, 101, 102, 97, 117, 108, 
116, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 110, 115, 
101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 
32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 108, 
105, 110, 101, 92, 110, 32, 101, 114, 114, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 109, 
107, 114, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 45, 10, 32, 
32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 
110, 100, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 
66, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 108, 105, 110, 101, 92, 110, 
32, 101, 114, 114, 10, 32, 32, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 125, 10, 32, 
32, 125, 10, 10, 32, 32, 102, 111, 114, 101, 97, 99, 104, 32, 99, 32, 91, 99, 111, 108, 
115, 93, 32, 123, 10, 32, 32, 32, 32, 115, 101, 116, 32, 116, 121, 112, 101, 32, 91, 99, 
111, 108, 84, 121, 112, 101, 32, 36, 99, 93, 10, 32, 32, 32, 32, 105, 102, 32, 123, 36, 
116, 121, 112, 101, 32, 110, 101, 32, 34, 116, 120, 116, 34, 125, 32, 123, 10, 32, 32, 32, 
32, 32, 32, 36, 99, 32, 99, 111, 110, 102, 105, 103, 32, 45, 119, 105, 100, 116, 104, 32, 
36, 119, 105, 100, 116, 104, 115, 40, 36, 116, 121, 112, 101, 41, 10, 32, 32, 32, 32, 125, 
10, 32, 32, 32, 32, 36, 99, 32, 99, 111, 110, 102, 105, 103, 32, 45, 115, 116, 97, 116, 
101, 32, 100, 105, 115, 97, 98, 108, 101, 100, 10, 32, 32, 125, 10, 32, 32, 105, 102, 32, 
123, 36, 110, 68, 105, 102, 102, 115, 32, 60, 61, 32, 91, 46, 119, 102, 105, 108, 101, 115, 
46, 108, 98, 32, 99, 103, 101, 116, 32, 45, 104, 101, 105, 103, 104, 116, 93, 125, 32, 123, 
10, 32, 32, 32, 32, 46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 99, 111, 110, 102, 
105, 103, 32, 45, 104, 101, 105, 103, 104, 116, 32, 36, 110, 68, 105, 102, 102, 115, 10, 32, 
32, 32, 32, 103, 114, 105, 100, 32, 114, 101, 109, 111, 118, 101, 32, 46, 119, 102, 105, 108, 
101, 115, 46, 115, 98, 10, 32, 32, 125, 10, 10, 32, 32, 114, 101, 116, 117, 114, 110, 32, 
36, 110, 68, 105, 102, 102, 115, 10, 125, 10, 10, 112, 114, 111, 99, 32, 118, 105, 101, 119, 
68, 105, 102, 102, 32, 123, 105, 100, 120, 125, 32, 123, 10, 32, 32, 46, 116, 120, 116, 65, 
32, 121, 118, 105, 101, 119, 32, 36, 105, 100, 120, 10, 32, 32, 46, 116, 120, 116, 65, 32, 
120, 118, 105, 101, 119, 32, 109, 111, 118, 101, 116, 111, 32, 48, 10, 125, 10, 10, 112, 114, 
111, 99, 32, 99, 121, 99, 108, 101, 68, 105, 102, 102, 115, 32, 123, 123, 114, 101, 118, 101, 
114, 115, 101, 32, 48, 125, 125, 32, 123, 10, 32, 32, 105, 102, 32, 123, 36, 114, 101, 118, 
101, 114, 115, 101, 125, 32, 123, 10, 32, 32, 32, 32, 115, 101, 116, 32, 114, 97, 110, 103, 
101, 32, 91, 46, 116, 120, 116, 65, 32, 116, 97, 103, 32, 112, 114, 101, 118, 114, 97, 110, 
103, 101, 32, 102, 110, 32, 64, 48, 44, 48, 32, 49, 46, 48, 93, 10, 32, 32, 32, 32, 
105, 102, 32, 123, 36, 114, 97, 110, 103, 101, 32, 101, 113, 32, 34, 34, 125, 32, 123, 10, 
32, 32, 32, 32, 32, 32, 118, 105, 101, 119, 68, 105, 102, 102, 32, 123, 102, 110, 46, 108, 
97, 115, 116, 32, 45, 49, 99, 125, 10, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 32, 
123, 10, 32, 32, 32, 32, 32, 32, 118, 105, 101, 119, 68, 105, 102, 102, 32, 91, 108, 105, 
110, 100, 101, 120, 32, 36, 114, 97, 110, 103, 101, 32, 48, 93, 10, 32, 32, 32, 32, 125, 
10, 32, 32, 125, 32, 101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 115, 101, 116, 32, 
114, 97, 110, 103, 101, 32, 91, 46, 116, 120, 116, 65, 32, 116, 97, 103, 32, 110, 101, 120, 
116, 114, 97, 110, 103, 101, 32, 102, 110, 32, 123, 64, 48, 44, 48, 32, 43, 49, 99, 125, 
32, 101, 110, 100, 93, 10, 32, 32, 32, 32, 105, 102, 32, 123, 36, 114, 97, 110, 103, 101, 
32, 101, 113, 32, 34, 34, 32, 124, 124, 32, 91, 108, 105, 110, 100, 101, 120, 32, 91, 46, 
116, 120, 116, 65, 32, 121, 118, 105, 101, 119, 93, 32, 49, 93, 32, 61, 61, 32, 49, 125, 
32, 123, 10, 32, 32, 32, 32, 32, 32, 118, 105, 101, 119, 68, 105, 102, 102, 32, 102, 110, 
46, 102, 105, 114, 115, 116, 10, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 32, 123, 10, 
32, 32, 32, 32, 32, 32, 118, 105, 101, 119, 68, 105, 102, 102, 32, 91, 108, 105, 110, 100, 
101, 120, 32, 36, 114, 97, 110, 103, 101, 32, 48, 93, 10, 32, 32, 32, 32, 125, 10, 32, 
32, 125, 10, 125, 10, 10, 112, 114, 111, 99, 32, 120, 118, 105, 115, 32, 123, 99, 111, 108, 
125, 32, 123, 10, 32, 32, 115, 101, 116, 32, 118, 105, 101, 119, 32, 91, 36, 99, 111, 108, 
32, 120, 118, 105, 101, 119, 93, 10, 32, 32, 114, 101, 116, 117, 114, 110, 32, 91, 101, 120, 
112, 114, 32, 123, 91, 108, 105, 110, 100, 101, 120, 32, 36, 118, 105, 101, 119, 32, 49, 93, 
45, 91, 108, 105, 110, 100, 101, 120, 32, 36, 118, 105, 101, 119, 32, 48, 93, 125, 93, 10, 
125, 10, 10, 112, 114, 111, 99, 32, 115, 99, 114, 111, 108, 108, 45, 120, 32, 123, 97, 114, 
103, 115, 125, 32, 123, 10, 32, 32, 115, 101, 116, 32, 99, 32, 46, 116, 120, 116, 91, 101, 
120, 112, 114, 32, 123, 91, 120, 118, 105, 115, 32, 46, 116, 120, 116, 65, 93, 32, 60, 32, 
91, 120, 118, 105, 115, 32, 46, 116, 120, 116, 66, 93, 32, 63, 32, 34, 65, 34, 32, 58, 
32, 34, 66, 34, 125, 93, 10, 32, 32, 101, 118, 97, 108, 32, 36, 99, 32, 120, 118, 105, 
101, 119, 32, 36, 97, 114, 103, 115, 10, 125, 10, 10, 105, 110, 116, 101, 114, 112, 32, 97, 
108, 105, 97, 115, 32, 123, 125, 32, 115, 99, 114, 111, 108, 108, 45, 121, 32, 123, 125, 32, 
46, 116, 120, 116, 65, 32, 121, 118, 105, 101, 119, 10, 10, 112, 114, 111, 99, 32, 110, 111, 
111, 112, 32, 123, 97, 114, 103, 115, 125, 32, 123, 125, 10, 10, 112, 114, 111, 99, 32, 101, 
110, 97, 98, 108, 101, 83, 121, 110, 99, 32, 123, 97, 120, 105, 115, 125, 32, 123, 10, 32, 
32, 117, 112, 100, 97, 116, 101, 32, 105, 100, 108, 101, 116, 97, 115, 107, 115, 10, 32, 32, 
105, 110, 116, 101, 114, 112, 32, 97, 108, 105, 97, 115, 32, 123, 125, 32, 115, 121, 110, 99, 
45, 36, 97, 120, 105, 115, 32, 123, 125, 10, 32, 32, 114, 101, 110, 97, 109, 101, 32, 95, 
115, 121, 110, 99, 45, 36, 97, 120, 105, 115, 32, 115, 121, 110, 99, 45, 36, 97, 120, 105, 
115, 10, 125, 10, 10, 112, 114, 111, 99, 32, 100, 105, 115, 97, 98, 108, 101, 83, 121, 110, 
99, 32, 123, 97, 120, 105, 115, 125, 32, 123, 10, 32, 32, 114, 101, 110, 97, 109, 101, 32, 
115, 121, 110, 99, 45, 36, 97, 120, 105, 115, 32, 95, 115, 121, 110, 99, 45, 36, 97, 120, 
105, 115, 10, 32, 32, 105, 110, 116, 101, 114, 112, 32, 97, 108, 105, 97, 115, 32, 123, 125, 
32, 115, 121, 110, 99, 45, 36, 97, 120, 105, 115, 32, 123, 125, 32, 110, 111, 111, 112, 10, 
125, 10, 10, 112, 114, 111, 99, 32, 115, 121, 110, 99, 45, 120, 32, 123, 99, 111, 108, 32, 
102, 105, 114, 115, 116, 32, 108, 97, 115, 116, 125, 32, 123, 10, 32, 32, 100, 105, 115, 97, 
98, 108, 101, 83, 121, 110, 99, 32, 120, 10, 32, 32, 36, 99, 111, 108, 32, 120, 118, 105, 
101, 119, 32, 109, 111, 118, 101, 116, 111, 32, 91, 101, 120, 112, 114, 32, 123, 36, 102, 105, 
114, 115, 116, 42, 91, 120, 118, 105, 115, 32, 36, 99, 111, 108, 93, 47, 40, 36, 108, 97, 
115, 116, 45, 36, 102, 105, 114, 115, 116, 41, 125, 93, 10, 32, 32, 102, 111, 114, 101, 97, 
99, 104, 32, 115, 105, 100, 101, 32, 123, 65, 32, 66, 125, 32, 123, 10, 32, 32, 32, 32, 
115, 101, 116, 32, 115, 98, 32, 46, 115, 98, 120, 36, 115, 105, 100, 101, 10, 32, 32, 32, 
32, 115, 101, 116, 32, 120, 118, 105, 101, 119, 32, 91, 46, 116, 120, 116, 36, 115, 105, 100, 
101, 32, 120, 118, 105, 101, 119, 93, 10, 32, 32, 32, 32, 105, 102, 32, 123, 91, 108, 105, 
110, 100, 101, 120, 32, 36, 120, 118, 105, 101, 119, 32, 48, 93, 32, 62, 32, 48, 32, 124, 
124, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 120, 118, 105, 101, 119, 32, 49, 93, 32, 
60, 32, 49, 125, 32, 123, 10, 32, 32, 32, 32, 32, 32, 103, 114, 105, 100, 32, 36, 115, 
98, 10, 32, 32, 32, 32, 32, 32, 101, 118, 97, 108, 32, 36, 115, 98, 32, 115, 101, 116, 
32, 36, 120, 118, 105, 101, 119, 10, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 32, 123, 
10, 32, 32, 32, 32, 32, 32, 103, 114, 105, 100, 32, 114, 101, 109, 111, 118, 101, 32, 36, 
115, 98, 10, 32, 32, 32, 32, 125, 10, 32, 32, 125, 10, 32, 32, 101, 110, 97, 98, 108, 
101, 83, 121, 110, 99, 32, 120, 10, 125, 10, 10, 112, 114, 111, 99, 32, 115, 121, 110, 99, 
45, 121, 32, 123, 102, 105, 114, 115, 116, 32, 108, 97, 115, 116, 125, 32, 123, 10, 32, 32, 
100, 105, 115, 97, 98, 108, 101, 83, 121, 110, 99, 32, 121, 10, 32, 32, 102, 111, 114, 101, 
97, 99, 104, 32, 99, 32, 91, 99, 111, 108, 115, 93, 32, 123, 10, 32, 32, 32, 32, 36, 
99, 32, 121, 118, 105, 101, 119, 32, 109, 111, 118, 101, 116, 111, 32, 36, 102, 105, 114, 115, 
116, 10, 32, 32, 125, 10, 32, 32, 105, 102, 32, 123, 36, 102, 105, 114, 115, 116, 32, 62, 
32, 48, 32, 124, 124, 32, 36, 108, 97, 115, 116, 32, 60, 32, 49, 125, 32, 123, 10, 32, 
32, 32, 32, 103, 114, 105, 100, 32, 46, 115, 98, 121, 10, 32, 32, 32, 32, 46, 115, 98, 
121, 32, 115, 101, 116, 32, 36, 102, 105, 114, 115, 116, 32, 36, 108, 97, 115, 116, 10, 32, 
32, 125, 32, 101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 103, 114, 105, 100, 32, 114, 
101, 109, 111, 118, 101, 32, 46, 115, 98, 121, 10, 32, 32, 125, 10, 32, 32, 101, 110, 97, 
98, 108, 101, 83, 121, 110, 99, 32, 121, 10, 125, 10, 10, 119, 109, 32, 119, 105, 116, 104, 
100, 114, 97, 119, 32, 46, 10, 119, 109, 32, 116, 105, 116, 108, 101, 32, 46, 32, 36, 67, 
70, 71, 40, 84, 73, 84, 76, 69, 41, 10, 119, 109, 32, 105, 99, 111, 110, 110, 97, 109, 
101, 32, 46, 32, 36, 67, 70, 71, 40, 84, 73, 84, 76, 69, 41, 10, 35, 32, 75, 101, 
121, 115, 116, 114, 111, 107, 101, 32, 98, 105, 110, 100, 105, 110, 103, 115, 32, 102, 111, 114, 
32, 111, 110, 32, 116, 104, 101, 32, 116, 111, 112, 45, 108, 101, 118, 101, 108, 32, 119, 105, 
110, 100, 111, 119, 32, 102, 111, 114, 32, 110, 97, 118, 105, 103, 97, 116, 105, 111, 110, 32, 
97, 110, 100, 10, 35, 32, 99, 111, 110, 116, 114, 111, 108, 32, 97, 108, 115, 111, 32, 102, 
105, 114, 101, 32, 119, 104, 101, 110, 32, 116, 104, 111, 115, 101, 32, 115, 97, 109, 101, 32, 
107, 101, 121, 115, 116, 114, 111, 107, 101, 115, 32, 97, 114, 101, 32, 112, 114, 101, 115, 115, 
101, 100, 32, 105, 110, 32, 116, 104, 101, 10, 35, 32, 83, 101, 97, 114, 99, 104, 32, 101, 
110, 116, 114, 121, 32, 98, 111, 120, 46, 32, 32, 68, 105, 115, 97, 98, 108, 101, 32, 116, 
104, 101, 109, 44, 32, 116, 111, 32, 112, 114, 101, 118, 101, 110, 116, 32, 116, 104, 101, 32, 
100, 105, 102, 102, 32, 115, 99, 114, 101, 101, 110, 32, 102, 114, 111, 109, 10, 35, 32, 100, 
105, 115, 97, 112, 112, 101, 97, 114, 105, 110, 103, 32, 97, 98, 114, 117, 112, 116, 108, 121, 
32, 97, 110, 100, 32, 117, 110, 101, 120, 112, 101, 99, 116, 101, 100, 108, 121, 32, 119, 104, 
101, 110, 32, 115, 101, 97, 114, 99, 104, 105, 110, 103, 32, 102, 111, 114, 32, 34, 113, 34, 
46, 10, 35, 10, 98, 105, 110, 100, 32, 46, 32, 60, 67, 111, 110, 116, 114, 111, 108, 45, 
113, 62, 32, 101, 120, 105, 116, 10, 98, 105, 110, 100, 32, 46, 32, 60, 67, 111, 110, 116, 
114, 111, 108, 45, 112, 62, 32, 123, 99, 97, 116, 99, 104, 32, 115, 101, 97, 114, 99, 104, 
80, 114, 101, 118, 59, 32, 98, 114, 101, 97, 107, 125, 10, 98, 105, 110, 100, 32, 46, 32, 
60, 67, 111, 110, 116, 114, 111, 108, 45, 110, 62, 32, 123, 99, 97, 116, 99, 104, 32, 115, 
101, 97, 114, 99, 104, 78, 101, 120, 116, 59, 32, 98, 114, 101, 97, 107, 125, 10, 98, 105, 
110, 100, 32, 46, 32, 60, 69, 115, 99, 97, 112, 101, 62, 60, 69, 115, 99, 97, 112, 101, 
62, 32, 101, 120, 105, 116, 10, 98, 105, 110, 100, 32, 46, 32, 60, 68, 101, 115, 116, 114, 
111, 121, 62, 32, 123, 97, 102, 116, 101, 114, 32, 48, 32, 101, 120, 105, 116, 125, 10, 98, 
105, 110, 100, 32, 46, 32, 60, 84, 97, 98, 62, 32, 123, 99, 121, 99, 108, 101, 68, 105, 
102, 102, 115, 59, 32, 98, 114, 101, 97, 107, 125, 10, 98, 105, 110, 100, 32, 46, 32, 60, 
60, 80, 114, 101, 118, 87, 105, 110, 100, 111, 119, 62, 62, 32, 123, 99, 121, 99, 108, 101, 
68, 105, 102, 102, 115, 32, 49, 59, 32, 98, 114, 101, 97, 107, 125, 10, 98, 105, 110, 100, 
32, 46, 32, 60, 67, 111, 110, 116, 114, 111, 108, 45, 102, 62, 32, 123, 115, 101, 97, 114, 
99, 104, 79, 110, 79, 102, 102, 59, 32, 98, 114, 101, 97, 107, 125, 10, 98, 105, 110, 100, 
32, 46, 32, 60, 67, 111, 110, 116, 114, 111, 108, 45, 103, 62, 32, 123, 99, 97, 116, 99, 
104, 32, 115, 101, 97, 114, 99, 104, 78, 101, 120, 116, 59, 32, 98, 114, 101, 97, 107, 125, 
10, 98, 105, 110, 100, 32, 46, 32, 60, 82, 101, 116, 117, 114, 110, 62, 32, 123, 10, 32, 
32, 101, 118, 101, 110, 116, 32, 103, 101, 110, 101, 114, 97, 116, 101, 32, 46, 98, 98, 46, 
102, 105, 108, 101, 115, 32, 60, 49, 62, 10, 32, 32, 101, 118, 101, 110, 116, 32, 103, 101, 
110, 101, 114, 97, 116, 101, 32, 46, 98, 98, 46, 102, 105, 108, 101, 115, 32, 60, 66, 117, 
116, 116, 111, 110, 82, 101, 108, 101, 97, 115, 101, 45, 49, 62, 10, 32, 32, 98, 114, 101, 
97, 107, 10, 125, 10, 102, 111, 114, 101, 97, 99, 104, 32, 123, 107, 101, 121, 32, 97, 120, 
105, 115, 32, 97, 114, 103, 115, 125, 32, 123, 10, 32, 32, 85, 112, 32, 32, 32, 32, 121, 
32, 123, 115, 99, 114, 111, 108, 108, 32, 45, 53, 32, 117, 110, 105, 116, 115, 125, 10, 32, 
32, 107, 32, 32, 32, 32, 32, 121, 32, 123, 115, 99, 114, 111, 108, 108, 32, 45, 53, 32, 
117, 110, 105, 116, 115, 125, 10, 32, 32, 68, 111, 119, 110, 32, 32, 121, 32, 123, 115, 99, 
114, 111, 108, 108, 32, 53, 32, 117, 110, 105, 116, 115, 125, 10, 32, 32, 106, 32, 32, 32, 
32, 32, 121, 32, 123, 115, 99, 114, 111, 108, 108, 32, 53, 32, 117, 110, 105, 116, 115, 125, 
10, 32, 32, 76, 101, 102, 116, 32, 32, 120, 32, 123, 115, 99, 114, 111, 108, 108, 32, 45, 
53, 32, 117, 110, 105, 116, 115, 125, 10, 32, 32, 104, 32, 32, 32, 32, 32, 120, 32, 123, 
115, 99, 114, 111, 108, 108, 32, 45, 53, 32, 117, 110, 105, 116, 115, 125, 10, 32, 32, 82, 
105, 103, 104, 116, 32, 120, 32, 123, 115, 99, 114, 111, 108, 108, 32, 53, 32, 117, 110, 105, 
116, 115, 125, 10, 32, 32, 108, 32, 32, 32, 32, 32, 120, 32, 123, 115, 99, 114, 111, 108, 
108, 32, 53, 32, 117, 110, 105, 116, 115, 125, 10, 32, 32, 80, 114, 105, 111, 114, 32, 121, 
32, 123, 115, 99, 114, 111, 108, 108, 32, 45, 49, 32, 112, 97, 103, 101, 125, 10, 32, 32, 
98, 32, 32, 32, 32, 32, 121, 32, 123, 115, 99, 114, 111, 108, 108, 32, 45, 49, 32, 112, 
97, 103, 101, 125, 10, 32, 32, 78, 101, 120, 116, 32, 32, 121, 32, 123, 115, 99, 114, 111, 
108, 108, 32, 49, 32, 112, 97, 103, 101, 125, 10, 32, 32, 115, 112, 97, 99, 101, 32, 121, 
32, 123, 115, 99, 114, 111, 108, 108, 32, 49, 32, 112, 97, 103, 101, 125, 10, 32, 32, 72, 
111, 109, 101, 32, 32, 121, 32, 123, 109, 111, 118, 101, 116, 111, 32, 48, 125, 10, 32, 32, 
103, 32, 32, 32, 32, 32, 121, 32, 123, 109, 111, 118, 101, 116, 111, 32, 48, 125, 10, 32, 
32, 69, 110, 100, 32, 32, 32, 121, 32, 123, 109, 111, 118, 101, 116, 111, 32, 49, 125, 10, 
125, 32, 123, 10, 32, 32, 98, 105, 110, 100, 32, 46, 32, 60, 36, 107, 101, 121, 62, 32, 
34, 115, 99, 114, 111, 108, 108, 45, 36, 97, 120, 105, 115, 32, 36, 97, 114, 103, 115, 59, 
32, 98, 114, 101, 97, 107, 34, 10, 32, 32, 98, 105, 110, 100, 32, 46, 32, 60, 83, 104, 
105, 102, 116, 45, 36, 107, 101, 121, 62, 32, 99, 111, 110, 116, 105, 110, 117, 101, 10, 125, 
10, 10, 102, 114, 97, 109, 101, 32, 46, 98, 98, 10, 58, 58, 116, 116, 107, 58, 58, 109, 
101, 110, 117, 98, 117, 116, 116, 111, 110, 32, 46, 98, 98, 46, 102, 105, 108, 101, 115, 32, 
45, 116, 101, 120, 116, 32, 34, 70, 105, 108, 101, 115, 34, 10, 105, 102, 32, 123, 91, 116, 
107, 32, 119, 105, 110, 100, 111, 119, 105, 110, 103, 115, 121, 115, 116, 101, 109, 93, 32, 101, 
113, 32, 34, 119, 105, 110, 51, 50, 34, 125, 32, 123, 10, 32, 32, 58, 58, 116, 116, 107, 
58, 58, 115, 116, 121, 108, 101, 32, 116, 104, 101, 109, 101, 32, 117, 115, 101, 32, 119, 105, 
110, 110, 97, 116, 105, 118, 101, 10, 32, 32, 46, 98, 98, 46, 102, 105, 108, 101, 115, 32, 
99, 111, 110, 102, 105, 103, 117, 114, 101, 32, 45, 112, 97, 100, 100, 105, 110, 103, 32, 123, 
50, 48, 32, 49, 32, 49, 48, 32, 50, 125, 10, 125, 10, 116, 111, 112, 108, 101, 118, 101, 
108, 32, 46, 119, 102, 105, 108, 101, 115, 10, 119, 109, 32, 119, 105, 116, 104, 100, 114, 97, 
119, 32, 46, 119, 102, 105, 108, 101, 115, 10, 117, 112, 100, 97, 116, 101, 32, 105, 100, 108, 
101, 116, 97, 115, 107, 115, 10, 119, 109, 32, 116, 114, 97, 110, 115, 105, 101, 110, 116, 32, 
46, 119, 102, 105, 108, 101, 115, 32, 46, 10, 119, 109, 32, 111, 118, 101, 114, 114, 105, 100, 
101, 114, 101, 100, 105, 114, 101, 99, 116, 32, 46, 119, 102, 105, 108, 101, 115, 32, 49, 10, 
108, 105, 115, 116, 98, 111, 120, 32, 46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 45, 
119, 105, 100, 116, 104, 32, 48, 32, 45, 104, 101, 105, 103, 104, 116, 32, 36, 67, 70, 71, 
40, 76, 66, 95, 72, 69, 73, 71, 72, 84, 41, 32, 45, 97, 99, 116, 105, 118, 101, 115, 
116, 121, 108, 101, 32, 110, 111, 110, 101, 32, 92, 10, 32, 32, 45, 121, 115, 99, 114, 111, 
108, 108, 32, 123, 46, 119, 102, 105, 108, 101, 115, 46, 115, 98, 32, 115, 101, 116, 125, 10, 
58, 58, 116, 116, 107, 58, 58, 115, 99, 114, 111, 108, 108, 98, 97, 114, 32, 46, 119, 102, 
105, 108, 101, 115, 46, 115, 98, 32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 123, 46, 119, 
102, 105, 108, 101, 115, 46, 108, 98, 32, 121, 118, 105, 101, 119, 125, 10, 103, 114, 105, 100, 
32, 46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 46, 119, 102, 105, 108, 101, 115, 46, 
115, 98, 32, 45, 115, 116, 105, 99, 107, 121, 32, 110, 115, 10, 98, 105, 110, 100, 32, 46, 
98, 98, 46, 102, 105, 108, 101, 115, 32, 60, 49, 62, 32, 123, 10, 32, 32, 115, 101, 116, 
32, 120, 32, 91, 119, 105, 110, 102, 111, 32, 114, 111, 111, 116, 120, 32, 37, 87, 93, 10, 
32, 32, 115, 101, 116, 32, 121, 32, 91, 101, 120, 112, 114, 32, 123, 91, 119, 105, 110, 102, 
111, 32, 114, 111, 111, 116, 121, 32, 37, 87, 93, 43, 91, 119, 105, 110, 102, 111, 32, 104, 
101, 105, 103, 104, 116, 32, 37, 87, 93, 125, 93, 10, 32, 32, 119, 109, 32, 103, 101, 111, 
109, 101, 116, 114, 121, 32, 46, 119, 102, 105, 108, 101, 115, 32, 43, 36, 120, 43, 36, 121, 
10, 32, 32, 119, 109, 32, 100, 101, 105, 99, 111, 110, 105, 102, 121, 32, 46, 119, 102, 105, 
108, 101, 115, 10, 32, 32, 102, 111, 99, 117, 115, 32, 46, 119, 102, 105, 108, 101, 115, 46, 
108, 98, 10, 125, 10, 98, 105, 110, 100, 32, 46, 119, 102, 105, 108, 101, 115, 32, 60, 70, 
111, 99, 117, 115, 79, 117, 116, 62, 32, 123, 119, 109, 32, 119, 105, 116, 104, 100, 114, 97, 
119, 32, 46, 119, 102, 105, 108, 101, 115, 125, 10, 98, 105, 110, 100, 32, 46, 119, 102, 105, 
108, 101, 115, 32, 60, 69, 115, 99, 97, 112, 101, 62, 32, 123, 102, 111, 99, 117, 115, 32, 
46, 125, 10, 102, 111, 114, 101, 97, 99, 104, 32, 101, 118, 116, 32, 123, 49, 32, 82, 101, 
116, 117, 114, 110, 125, 32, 123, 10, 32, 32, 98, 105, 110, 100, 32, 46, 119, 102, 105, 108, 
101, 115, 46, 108, 98, 32, 60, 36, 101, 118, 116, 62, 32, 123, 10, 32, 32, 32, 32, 99, 
97, 116, 99, 104, 32, 123, 10, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 105, 100, 120, 
32, 91, 108, 105, 110, 100, 101, 120, 32, 91, 46, 116, 120, 116, 65, 32, 116, 97, 103, 32, 
114, 97, 110, 103, 101, 115, 32, 102, 110, 93, 32, 91, 101, 120, 112, 114, 32, 123, 91, 37, 
87, 32, 99, 117, 114, 115, 101, 108, 101, 99, 116, 105, 111, 110, 93, 42, 50, 125, 93, 93, 
10, 32, 32, 32, 32, 32, 32, 118, 105, 101, 119, 68, 105, 102, 102, 32, 36, 105, 100, 120, 
10, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 102, 111, 99, 117, 115, 32, 46, 10, 32, 
32, 32, 32, 98, 114, 101, 97, 107, 10, 32, 32, 125, 10, 125, 10, 98, 105, 110, 100, 32, 
46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 60, 77, 111, 116, 105, 111, 110, 62, 32, 
123, 10, 32, 32, 37, 87, 32, 115, 101, 108, 101, 99, 116, 105, 111, 110, 32, 99, 108, 101, 
97, 114, 32, 48, 32, 101, 110, 100, 10, 32, 32, 37, 87, 32, 115, 101, 108, 101, 99, 116, 
105, 111, 110, 32, 115, 101, 116, 32, 64, 37, 120, 44, 37, 121, 10, 125, 10, 10, 102, 111, 
114, 101, 97, 99, 104, 32, 123, 115, 105, 100, 101, 32, 115, 121, 110, 99, 67, 111, 108, 125, 
32, 123, 65, 32, 46, 116, 120, 116, 66, 32, 66, 32, 46, 116, 120, 116, 65, 125, 32, 123, 
10, 32, 32, 115, 101, 116, 32, 108, 110, 32, 46, 108, 110, 36, 115, 105, 100, 101, 10, 32, 
32, 116, 101, 120, 116, 32, 36, 108, 110, 10, 32, 32, 36, 108, 110, 32, 116, 97, 103, 32, 
99, 111, 110, 102, 105, 103, 32, 45, 32, 45, 106, 117, 115, 116, 105, 102, 121, 32, 114, 105, 
103, 104, 116, 10, 10, 32, 32, 115, 101, 116, 32, 116, 120, 116, 32, 46, 116, 120, 116, 36, 
115, 105, 100, 101, 10, 32, 32, 116, 101, 120, 116, 32, 36, 116, 120, 116, 32, 45, 119, 105, 
100, 116, 104, 32, 36, 67, 70, 71, 40, 87, 73, 68, 84, 72, 41, 32, 45, 104, 101, 105, 
103, 104, 116, 32, 36, 67, 70, 71, 40, 72, 69, 73, 71, 72, 84, 41, 32, 45, 119, 114, 
97, 112, 32, 110, 111, 110, 101, 32, 92, 10, 32, 32, 32, 32, 45, 120, 115, 99, 114, 111, 
108, 108, 32, 34, 115, 121, 110, 99, 45, 120, 32, 36, 115, 121, 110, 99, 67, 111, 108, 34, 
10, 32, 32, 99, 97, 116, 99, 104, 32, 123, 36, 116, 120, 116, 32, 99, 111, 110, 102, 105, 
103, 32, 45, 116, 97, 98, 115, 116, 121, 108, 101, 32, 119, 111, 114, 100, 112, 114, 111, 99, 
101, 115, 115, 111, 114, 125, 32, 59, 35, 32, 82, 101, 113, 117, 105, 114, 101, 100, 32, 102, 
111, 114, 32, 84, 107, 62, 61, 56, 46, 53, 10, 32, 32, 102, 111, 114, 101, 97, 99, 104, 
32, 116, 97, 103, 32, 123, 97, 100, 100, 32, 114, 109, 32, 99, 104, 110, 103, 125, 32, 123, 
10, 32, 32, 32, 32, 36, 116, 120, 116, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 
32, 36, 116, 97, 103, 32, 45, 98, 97, 99, 107, 103, 114, 111, 117, 110, 100, 32, 36, 67, 
70, 71, 40, 91, 115, 116, 114, 105, 110, 103, 32, 116, 111, 117, 112, 112, 101, 114, 32, 36, 
116, 97, 103, 93, 95, 66, 71, 41, 10, 32, 32, 32, 32, 36, 116, 120, 116, 32, 116, 97, 
103, 32, 108, 111, 119, 101, 114, 32, 36, 116, 97, 103, 10, 32, 32, 125, 10, 32, 32, 36, 
116, 120, 116, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 102, 110, 32, 45, 98, 
97, 99, 107, 103, 114, 111, 117, 110, 100, 32, 36, 67, 70, 71, 40, 70, 78, 95, 66, 71, 
41, 32, 45, 102, 111, 114, 101, 103, 114, 111, 117, 110, 100, 32, 36, 67, 70, 71, 40, 70, 
78, 95, 70, 71, 41, 32, 92, 10, 32, 32, 32, 32, 45, 106, 117, 115, 116, 105, 102, 121, 
32, 99, 101, 110, 116, 101, 114, 10, 32, 32, 36, 116, 120, 116, 32, 116, 97, 103, 32, 99, 
111, 110, 102, 105, 103, 32, 101, 114, 114, 32, 45, 102, 111, 114, 101, 103, 114, 111, 117, 110, 
100, 32, 36, 67, 70, 71, 40, 69, 82, 82, 95, 70, 71, 41, 10, 125, 10, 116, 101, 120, 
116, 32, 46, 109, 107, 114, 10, 10, 102, 111, 114, 101, 97, 99, 104, 32, 99, 32, 91, 99, 
111, 108, 115, 93, 32, 123, 10, 32, 32, 115, 101, 116, 32, 107, 101, 121, 80, 114, 101, 102, 
105, 120, 32, 91, 115, 116, 114, 105, 110, 103, 32, 116, 111, 117, 112, 112, 101, 114, 32, 91, 
99, 111, 108, 84, 121, 112, 101, 32, 36, 99, 93, 93, 95, 67, 79, 76, 95, 10, 32, 32, 
105, 102, 32, 123, 91, 116, 107, 32, 119, 105, 110, 100, 111, 119, 105, 110, 103, 115, 121, 115, 
116, 101, 109, 93, 32, 101, 113, 32, 34, 119, 105, 110, 51, 50, 34, 125, 32, 123, 36, 99, 
32, 99, 111, 110, 102, 105, 103, 32, 45, 102, 111, 110, 116, 32, 123, 99, 111, 117, 114, 105, 
101, 114, 32, 57, 125, 125, 10, 32, 32, 36, 99, 32, 99, 111, 110, 102, 105, 103, 32, 45, 
98, 103, 32, 36, 67, 70, 71, 40, 36, 123, 107, 101, 121, 80, 114, 101, 102, 105, 120, 125, 
66, 71, 41, 32, 45, 102, 103, 32, 36, 67, 70, 71, 40, 36, 123, 107, 101, 121, 80, 114, 
101, 102, 105, 120, 125, 70, 71, 41, 32, 45, 98, 111, 114, 100, 101, 114, 119, 105, 100, 116, 
104, 32, 48, 32, 92, 10, 32, 32, 32, 32, 45, 112, 97, 100, 120, 32, 36, 67, 70, 71, 
40, 80, 65, 68, 88, 41, 32, 45, 121, 115, 99, 114, 111, 108, 108, 32, 115, 121, 110, 99, 
45, 121, 10, 32, 32, 36, 99, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 104, 
114, 108, 110, 32, 45, 115, 112, 97, 99, 105, 110, 103, 49, 32, 36, 67, 70, 71, 40, 72, 
82, 95, 80, 65, 68, 95, 84, 79, 80, 41, 32, 45, 115, 112, 97, 99, 105, 110, 103, 51, 
32, 36, 67, 70, 71, 40, 72, 82, 95, 80, 65, 68, 95, 66, 84, 77, 41, 32, 92, 10, 
32, 32, 32, 32, 32, 45, 102, 111, 114, 101, 103, 114, 111, 117, 110, 100, 32, 36, 67, 70, 
71, 40, 72, 82, 95, 70, 71, 41, 32, 45, 106, 117, 115, 116, 105, 102, 121, 32, 114, 105, 
103, 104, 116, 10, 32, 32, 36, 99, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 
104, 114, 116, 120, 116, 32, 32, 45, 115, 112, 97, 99, 105, 110, 103, 49, 32, 36, 67, 70, 
71, 40, 72, 82, 95, 80, 65, 68, 95, 84, 79, 80, 41, 32, 45, 115, 112, 97, 99, 105, 
110, 103, 51, 32, 36, 67, 70, 71, 40, 72, 82, 95, 80, 65, 68, 95, 66, 84, 77, 41, 
32, 92, 10, 32, 32, 32, 32, 32, 45, 102, 111, 114, 101, 103, 114, 111, 117, 110, 100, 32, 
36, 67, 70, 71, 40, 72, 82, 95, 70, 71, 41, 32, 45, 106, 117, 115, 116, 105, 102, 121, 
32, 99, 101, 110, 116, 101, 114, 10, 32, 32, 36, 99, 32, 116, 97, 103, 32, 99, 111, 110, 
102, 105, 103, 32, 102, 110, 32, 45, 115, 112, 97, 99, 105, 110, 103, 49, 32, 36, 67, 70, 
71, 40, 70, 78, 95, 80, 65, 68, 41, 32, 45, 115, 112, 97, 99, 105, 110, 103, 51, 32, 
36, 67, 70, 71, 40, 70, 78, 95, 80, 65, 68, 41, 10, 32, 32, 98, 105, 110, 100, 116, 
97, 103, 115, 32, 36, 99, 32, 34, 46, 32, 36, 99, 32, 84, 101, 120, 116, 32, 97, 108, 
108, 34, 10, 32, 32, 98, 105, 110, 100, 32, 36, 99, 32, 60, 49, 62, 32, 123, 102, 111, 
99, 117, 115, 32, 37, 87, 125, 10, 125, 10, 10, 58, 58, 116, 116, 107, 58, 58, 115, 99, 
114, 111, 108, 108, 98, 97, 114, 32, 46, 115, 98, 121, 32, 45, 99, 111, 109, 109, 97, 110, 
100, 32, 123, 46, 116, 120, 116, 65, 32, 121, 118, 105, 101, 119, 125, 32, 45, 111, 114, 105, 
101, 110, 116, 32, 118, 101, 114, 116, 105, 99, 97, 108, 10, 58, 58, 116, 116, 107, 58, 58, 
115, 99, 114, 111, 108, 108, 98, 97, 114, 32, 46, 115, 98, 120, 65, 32, 45, 99, 111, 109, 
109, 97, 110, 100, 32, 123, 46, 116, 120, 116, 65, 32, 120, 118, 105, 101, 119, 125, 32, 45, 
111, 114, 105, 101, 110, 116, 32, 104, 111, 114, 105, 122, 111, 110, 116, 97, 108, 10, 58, 58, 
116, 116, 107, 58, 58, 115, 99, 114, 111, 108, 108, 98, 97, 114, 32, 46, 115, 98, 120, 66, 
32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 123, 46, 116, 120, 116, 66, 32, 120, 118, 105, 
101, 119, 125, 32, 45, 111, 114, 105, 101, 110, 116, 32, 104, 111, 114, 105, 122, 111, 110, 116, 
97, 108, 10, 102, 114, 97, 109, 101, 32, 46, 115, 112, 97, 99, 101, 114, 10, 10, 105, 102, 
32, 123, 91, 114, 101, 97, 100, 68, 105, 102, 102, 115, 32, 36, 102, 111, 115, 115, 105, 108, 
99, 109, 100, 93, 32, 61, 61, 32, 48, 125, 32, 123, 10, 32, 32, 116, 107, 95, 109, 101, 
115, 115, 97, 103, 101, 66, 111, 120, 32, 45, 116, 121, 112, 101, 32, 111, 107, 32, 45, 116, 
105, 116, 108, 101, 32, 36, 67, 70, 71, 40, 84, 73, 84, 76, 69, 41, 32, 45, 109, 101, 
115, 115, 97, 103, 101, 32, 34, 78, 111, 32, 99, 104, 97, 110, 103, 101, 115, 34, 10, 32, 
32, 101, 120, 105, 116, 10, 125, 10, 117, 112, 100, 97, 116, 101, 32, 105, 100, 108, 101, 116, 
97, 115, 107, 115, 10, 10, 112, 114, 111, 99, 32, 115, 97, 118, 101, 68, 105, 102, 102, 32, 
123, 125, 32, 123, 10, 32, 32, 115, 101, 116, 32, 102, 110, 32, 91, 116, 107, 95, 103, 101, 
116, 83, 97, 118, 101, 70, 105, 108, 101, 93, 10, 32, 32, 105, 102, 32, 123, 36, 102, 110, 
61, 61, 34, 34, 125, 32, 114, 101, 116, 117, 114, 110, 10, 32, 32, 115, 101, 116, 32, 111, 
117, 116, 32, 91, 111, 112, 101, 110, 32, 36, 102, 110, 32, 119, 98, 93, 10, 32, 32, 112, 
117, 116, 115, 32, 36, 111, 117, 116, 32, 34, 35, 33, 47, 117, 115, 114, 47, 98, 105, 110, 
47, 116, 99, 108, 115, 104, 92, 110, 35, 92, 110, 35, 32, 82, 117, 110, 32, 116, 104, 105, 
115, 32, 115, 99, 114, 105, 112, 116, 32, 117, 115, 105, 110, 103, 32, 39, 116, 99, 108, 115, 
104, 39, 32, 111, 114, 32, 39, 119, 105, 115, 104, 39, 34, 10, 32, 32, 112, 117, 116, 115, 
32, 36, 111, 117, 116, 32, 34, 35, 32, 116, 111, 32, 115, 101, 101, 32, 116, 104, 101, 32, 
103, 114, 97, 112, 104, 105, 99, 97, 108, 32, 100, 105, 102, 102, 46, 92, 110, 35, 34, 10, 
32, 32, 112, 117, 116, 115, 32, 36, 111, 117, 116, 32, 34, 115, 101, 116, 32, 102, 111, 115, 
115, 105, 108, 99, 109, 100, 32, 123, 125, 34, 10, 32, 32, 112, 117, 116, 115, 32, 36, 111, 
117, 116, 32, 34, 115, 101, 116, 32, 112, 114, 111, 103, 32, 91, 108, 105, 115, 116, 32, 36, 
58, 58, 112, 114, 111, 103, 93, 34, 10, 32, 32, 112, 117, 116, 115, 32, 36, 111, 117, 116, 
32, 34, 115, 101, 116, 32, 100, 105, 102, 102, 116, 120, 116, 32, 92, 49, 55, 51, 34, 10, 
32, 32, 102, 111, 114, 101, 97, 99, 104, 32, 101, 32, 36, 58, 58, 100, 105, 102, 102, 116, 
120, 116, 32, 123, 112, 117, 116, 115, 32, 36, 111, 117, 116, 32, 91, 108, 105, 115, 116, 32, 
36, 101, 93, 125, 10, 32, 32, 112, 117, 116, 115, 32, 36, 111, 117, 116, 32, 34, 92, 49, 
55, 53, 34, 10, 32, 32, 112, 117, 116, 115, 32, 36, 111, 117, 116, 32, 34, 101, 118, 97, 
108, 32, 92, 36, 112, 114, 111, 103, 34, 10, 32, 32, 99, 108, 111, 115, 101, 32, 36, 111, 
117, 116, 10, 125, 10, 112, 114, 111, 99, 32, 105, 110, 118, 101, 114, 116, 68, 105, 102, 102, 
32, 123, 125, 32, 123, 10, 32, 32, 103, 108, 111, 98, 97, 108, 32, 67, 70, 71, 10, 32, 
32, 97, 114, 114, 97, 121, 32, 115, 101, 116, 32, 120, 32, 91, 103, 114, 105, 100, 32, 105, 
110, 102, 111, 32, 46, 116, 120, 116, 65, 93, 10, 32, 32, 105, 102, 32, 123, 36, 120, 40, 
45, 99, 111, 108, 117, 109, 110, 41, 61, 61, 49, 125, 32, 123, 10, 32, 32, 32, 32, 103, 
114, 105, 100, 32, 99, 111, 110, 102, 105, 103, 32, 46, 108, 110, 66, 32, 45, 99, 111, 108, 
117, 109, 110, 32, 48, 10, 32, 32, 32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, 105, 
103, 32, 46, 116, 120, 116, 66, 32, 45, 99, 111, 108, 117, 109, 110, 32, 49, 10, 32, 32, 
32, 32, 46, 116, 120, 116, 66, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 97, 
100, 100, 32, 45, 98, 97, 99, 107, 103, 114, 111, 117, 110, 100, 32, 36, 67, 70, 71, 40, 
82, 77, 95, 66, 71, 41, 10, 32, 32, 32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, 
105, 103, 32, 46, 108, 110, 65, 32, 45, 99, 111, 108, 117, 109, 110, 32, 51, 10, 32, 32, 
32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, 105, 103, 32, 46, 116, 120, 116, 65, 32, 
45, 99, 111, 108, 117, 109, 110, 32, 52, 10, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 
116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 114, 109, 32, 45, 98, 97, 99, 107, 103, 
114, 111, 117, 110, 100, 32, 36, 67, 70, 71, 40, 65, 68, 68, 95, 66, 71, 41, 10, 32, 
32, 32, 32, 46, 98, 98, 46, 105, 110, 118, 101, 114, 116, 32, 99, 111, 110, 102, 105, 103, 
32, 45, 116, 101, 120, 116, 32, 85, 110, 105, 110, 118, 101, 114, 116, 10, 32, 32, 125, 32, 
101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, 
105, 103, 32, 46, 108, 110, 65, 32, 45, 99, 111, 108, 117, 109, 110, 32, 48, 10, 32, 32, 
32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, 105, 103, 32, 46, 116, 120, 116, 65, 32, 
45, 99, 111, 108, 117, 109, 110, 32, 49, 10, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 
116, 97, 103, 32, 99, 111, 110, 102, 105, 103, 32, 114, 109, 32, 45, 98, 97, 99, 107, 103, 
114, 111, 117, 110, 100, 32, 36, 67, 70, 71, 40, 82, 77, 95, 66, 71, 41, 10, 32, 32, 
32, 32, 103, 114, 105, 100, 32, 99, 111, 110, 102, 105, 103, 32, 46, 108, 110, 66, 32, 45, 
99, 111, 108, 117, 109, 110, 32, 51, 10, 32, 32, 32, 32, 103, 114, 105, 100, 32, 99, 111, 
110, 102, 105, 103, 32, 46, 116, 120, 116, 66, 32, 45, 99, 111, 108, 117, 109, 110, 32, 52, 
10, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 116, 97, 103, 32, 99, 111, 110, 102, 105, 
103, 32, 97, 100, 100, 32, 45, 98, 97, 99, 107, 103, 114, 111, 117, 110, 100, 32, 36, 67, 
70, 71, 40, 65, 68, 68, 95, 66, 71, 41, 10, 32, 32, 32, 32, 46, 98, 98, 46, 105, 
110, 118, 101, 114, 116, 32, 99, 111, 110, 102, 105, 103, 32, 45, 116, 101, 120, 116, 32, 73, 
110, 118, 101, 114, 116, 10, 32, 32, 125, 10, 32, 32, 46, 109, 107, 114, 32, 99, 111, 110, 
102, 105, 103, 32, 45, 115, 116, 97, 116, 101, 32, 110, 111, 114, 109, 97, 108, 10, 32, 32, 
115, 101, 116, 32, 99, 108, 116, 32, 91, 46, 109, 107, 114, 32, 115, 101, 97, 114, 99, 104, 
32, 45, 97, 108, 108, 32, 60, 32, 49, 46, 48, 32, 101, 110, 100, 93, 10, 32, 32, 115, 
101, 116, 32, 99, 103, 116, 32, 91, 46, 109, 107, 114, 32, 115, 101, 97, 114, 99, 104, 32, 
45, 97, 108, 108, 32, 62, 32, 49, 46, 48, 32, 101, 110, 100, 93, 10, 32, 32, 102, 111, 
114, 101, 97, 99, 104, 32, 99, 32, 36, 99, 108, 116, 32, 123, 46, 109, 107, 114, 32, 114, 
101, 112, 108, 97, 99, 101, 32, 36, 99, 32, 34, 36, 99, 32, 43, 49, 32, 99, 104, 97, 
114, 115, 34, 32, 62, 125, 10, 32, 32, 102, 111, 114, 101, 97, 99, 104, 32, 99, 32, 36, 
99, 103, 116, 32, 123, 46, 109, 107, 114, 32, 114, 101, 112, 108, 97, 99, 101, 32, 36, 99, 
32, 34, 36, 99, 32, 43, 49, 32, 99, 104, 97, 114, 115, 34, 32, 60, 125, 10, 32, 32, 
46, 109, 107, 114, 32, 99, 111, 110, 102, 105, 103, 32, 45, 115, 116, 97, 116, 101, 32, 100, 
105, 115, 97, 98, 108, 101, 100, 10, 125, 10, 112, 114, 111, 99, 32, 115, 101, 97, 114, 99, 
104, 79, 110, 79, 102, 102, 32, 123, 125, 32, 123, 10, 32, 32, 105, 102, 32, 123, 91, 105, 
110, 102, 111, 32, 101, 120, 105, 115, 116, 115, 32, 58, 58, 115, 101, 97, 114, 99, 104, 93, 
125, 32, 123, 10, 32, 32, 32, 32, 117, 110, 115, 101, 116, 32, 58, 58, 115, 101, 97, 114, 
99, 104, 10, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 116, 97, 103, 32, 114, 101, 109, 
111, 118, 101, 32, 115, 101, 97, 114, 99, 104, 32, 49, 46, 48, 32, 101, 110, 100, 10, 32, 
32, 32, 32, 46, 116, 120, 116, 66, 32, 116, 97, 103, 32, 114, 101, 109, 111, 118, 101, 32, 
115, 101, 97, 114, 99, 104, 32, 49, 46, 48, 32, 101, 110, 100, 10, 32, 32, 32, 32, 112, 
97, 99, 107, 32, 102, 111, 114, 103, 101, 116, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 
101, 10, 32, 32, 32, 32, 102, 111, 99, 117, 115, 32, 46, 10, 32, 32, 125, 32, 101, 108, 
115, 101, 32, 123, 10, 32, 32, 32, 32, 115, 101, 116, 32, 58, 58, 115, 101, 97, 114, 99, 
104, 32, 46, 116, 120, 116, 65, 10, 32, 32, 32, 32, 105, 102, 32, 123, 33, 91, 119, 105, 
110, 102, 111, 32, 101, 120, 105, 115, 116, 115, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 
101, 93, 125, 32, 123, 10, 32, 32, 32, 32, 32, 32, 102, 114, 97, 109, 101, 32, 46, 98, 
98, 46, 115, 102, 114, 97, 109, 101, 10, 32, 32, 32, 32, 32, 32, 58, 58, 116, 116, 107, 
58, 58, 101, 110, 116, 114, 121, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 101, 
32, 45, 119, 105, 100, 116, 104, 32, 49, 48, 10, 32, 32, 32, 32, 32, 32, 112, 97, 99, 
107, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 101, 32, 45, 115, 105, 100, 101, 
32, 108, 101, 102, 116, 32, 45, 102, 105, 108, 108, 32, 121, 32, 45, 101, 120, 112, 97, 110, 
100, 32, 49, 10, 32, 32, 32, 32, 32, 32, 98, 105, 110, 100, 32, 46, 98, 98, 46, 115, 
102, 114, 97, 109, 101, 46, 101, 32, 60, 82, 101, 116, 117, 114, 110, 62, 32, 123, 115, 101, 
97, 114, 99, 104, 78, 101, 120, 116, 59, 32, 98, 114, 101, 97, 107, 125, 10, 32, 32, 32, 
32, 32, 32, 58, 58, 116, 116, 107, 58, 58, 98, 117, 116, 116, 111, 110, 32, 46, 98, 98, 
46, 115, 102, 114, 97, 109, 101, 46, 110, 120, 32, 45, 116, 101, 120, 116, 32, 92, 117, 50, 
49, 57, 51, 32, 45, 119, 105, 100, 116, 104, 32, 49, 32, 45, 99, 111, 109, 109, 97, 110, 
100, 32, 115, 101, 97, 114, 99, 104, 78, 101, 120, 116, 10, 32, 32, 32, 32, 32, 32, 58, 
58, 116, 116, 107, 58, 58, 98, 117, 116, 116, 111, 110, 32, 46, 98, 98, 46, 115, 102, 114, 
97, 109, 101, 46, 112, 118, 32, 45, 116, 101, 120, 116, 32, 92, 117, 50, 49, 57, 49, 32, 
45, 119, 105, 100, 116, 104, 32, 49, 32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 115, 101, 
97, 114, 99, 104, 80, 114, 101, 118, 10, 32, 32, 32, 32, 32, 32, 116, 107, 95, 111, 112, 
116, 105, 111, 110, 77, 101, 110, 117, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 
116, 121, 112, 32, 58, 58, 115, 101, 97, 114, 99, 104, 95, 116, 121, 112, 101, 32, 92, 10, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 69, 120, 97, 99, 116, 32, 123, 78, 111, 
32, 67, 97, 115, 101, 125, 32, 123, 82, 101, 103, 69, 120, 112, 125, 32, 123, 87, 104, 111, 
108, 101, 32, 87, 111, 114, 100, 125, 10, 32, 32, 32, 32, 32, 32, 46, 98, 98, 46, 115, 
102, 114, 97, 109, 101, 46, 116, 121, 112, 32, 99, 111, 110, 102, 105, 103, 32, 45, 119, 105, 
100, 116, 104, 32, 49, 48, 10, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 58, 58, 115, 
101, 97, 114, 99, 104, 95, 116, 121, 112, 101, 32, 69, 120, 97, 99, 116, 10, 32, 32, 32, 
32, 32, 32, 112, 97, 99, 107, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 110, 
120, 32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 112, 118, 32, 46, 98, 98, 46, 
115, 102, 114, 97, 109, 101, 46, 116, 121, 112, 32, 45, 115, 105, 100, 101, 32, 108, 101, 102, 
116, 10, 32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 112, 97, 99, 107, 32, 46, 98, 98, 
46, 115, 102, 114, 97, 109, 101, 32, 45, 115, 105, 100, 101, 32, 108, 101, 102, 116, 10, 32, 
32, 32, 32, 97, 102, 116, 101, 114, 32, 105, 100, 108, 101, 32, 123, 102, 111, 99, 117, 115, 
32, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 101, 125, 10, 32, 32, 125, 10, 125, 
10, 112, 114, 111, 99, 32, 115, 101, 97, 114, 99, 104, 78, 101, 120, 116, 32, 123, 125, 32, 
123, 115, 101, 97, 114, 99, 104, 83, 116, 101, 112, 32, 45, 102, 111, 114, 119, 97, 114, 100, 
115, 32, 43, 49, 32, 49, 46, 48, 32, 101, 110, 100, 125, 10, 112, 114, 111, 99, 32, 115, 
101, 97, 114, 99, 104, 80, 114, 101, 118, 32, 123, 125, 32, 123, 115, 101, 97, 114, 99, 104, 
83, 116, 101, 112, 32, 45, 98, 97, 99, 107, 119, 97, 114, 100, 115, 32, 45, 49, 32, 101, 
110, 100, 32, 49, 46, 48, 125, 10, 112, 114, 111, 99, 32, 115, 101, 97, 114, 99, 104, 83, 
116, 101, 112, 32, 123, 100, 105, 114, 101, 99, 116, 105, 111, 110, 32, 105, 110, 99, 114, 32, 
115, 116, 97, 114, 116, 32, 115, 116, 111, 112, 125, 32, 123, 10, 32, 32, 115, 101, 116, 32, 
112, 97, 116, 116, 101, 114, 110, 32, 91, 46, 98, 98, 46, 115, 102, 114, 97, 109, 101, 46, 
101, 32, 103, 101, 116, 93, 10, 32, 32, 105, 102, 32, 123, 36, 112, 97, 116, 116, 101, 114, 
110, 61, 61, 34, 34, 125, 32, 114, 101, 116, 117, 114, 110, 10, 32, 32, 115, 101, 116, 32, 
99, 111, 117, 110, 116, 32, 48, 10, 32, 32, 115, 101, 116, 32, 119, 32, 36, 58, 58, 115, 
101, 97, 114, 99, 104, 10, 32, 32, 105, 102, 32, 123, 34, 36, 119, 34, 61, 61, 34, 46, 
116, 120, 116, 65, 34, 125, 32, 123, 115, 101, 116, 32, 111, 116, 104, 101, 114, 32, 46, 116, 
120, 116, 66, 125, 32, 123, 115, 101, 116, 32, 111, 116, 104, 101, 114, 32, 46, 116, 120, 116, 
65, 125, 10, 32, 32, 105, 102, 32, 123, 91, 108, 115, 101, 97, 114, 99, 104, 32, 91, 36, 
119, 32, 109, 97, 114, 107, 32, 110, 97, 109, 101, 115, 93, 32, 115, 101, 97, 114, 99, 104, 
93, 60, 48, 125, 32, 123, 10, 32, 32, 32, 32, 36, 119, 32, 109, 97, 114, 107, 32, 115, 
101, 116, 32, 115, 101, 97, 114, 99, 104, 32, 36, 115, 116, 97, 114, 116, 10, 32, 32, 125, 
10, 32, 32, 115, 119, 105, 116, 99, 104, 32, 36, 58, 58, 115, 101, 97, 114, 99, 104, 95, 
116, 121, 112, 101, 32, 123, 10, 32, 32, 32, 32, 69, 120, 97, 99, 116, 32, 32, 32, 32, 
32, 32, 32, 32, 123, 115, 101, 116, 32, 115, 116, 32, 45, 101, 120, 97, 99, 116, 125, 10, 
32, 32, 32, 32, 123, 78, 111, 32, 67, 97, 115, 101, 125, 32, 32, 32, 32, 123, 115, 101, 
116, 32, 115, 116, 32, 45, 110, 111, 99, 97, 115, 101, 125, 10, 32, 32, 32, 32, 123, 82, 
101, 103, 69, 120, 112, 125, 32, 32, 32, 32, 32, 123, 115, 101, 116, 32, 115, 116, 32, 45, 
114, 101, 103, 101, 120, 112, 125, 10, 32, 32, 32, 32, 123, 87, 104, 111, 108, 101, 32, 87, 
111, 114, 100, 125, 32, 123, 115, 101, 116, 32, 115, 116, 32, 45, 114, 101, 103, 101, 120, 112, 
59, 32, 115, 101, 116, 32, 112, 97, 116, 116, 101, 114, 110, 32, 92, 92, 121, 36, 112, 97, 
116, 116, 101, 114, 110, 92, 92, 121, 125, 10, 32, 32, 125, 10, 32, 32, 115, 101, 116, 32, 
105, 100, 120, 32, 91, 36, 119, 32, 115, 101, 97, 114, 99, 104, 32, 45, 99, 111, 117, 110, 
116, 32, 99, 111, 117, 110, 116, 32, 36, 100, 105, 114, 101, 99, 116, 105, 111, 110, 32, 36, 
115, 116, 32, 45, 45, 32, 92, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 36, 112, 97, 116, 116, 101, 114, 110, 32, 34, 115, 101, 97, 114, 99, 104, 32, 36, 
105, 110, 99, 114, 32, 99, 104, 97, 114, 115, 34, 32, 36, 115, 116, 111, 112, 93, 10, 32, 
32, 105, 102, 32, 123, 34, 36, 105, 100, 120, 34, 61, 61, 34, 34, 125, 32, 123, 10, 32, 
32, 32, 32, 115, 101, 116, 32, 105, 100, 120, 32, 91, 36, 111, 116, 104, 101, 114, 32, 115, 
101, 97, 114, 99, 104, 32, 45, 99, 111, 117, 110, 116, 32, 99, 111, 117, 110, 116, 32, 36, 
100, 105, 114, 101, 99, 116, 105, 111, 110, 32, 36, 115, 116, 32, 45, 45, 32, 36, 112, 97, 
116, 116, 101, 114, 110, 32, 36, 115, 116, 97, 114, 116, 32, 36, 115, 116, 111, 112, 93, 10, 
32, 32, 32, 32, 105, 102, 32, 123, 34, 36, 105, 100, 120, 34, 33, 61, 34, 34, 125, 32, 
123, 10, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 116, 104, 105, 115, 32, 36, 119, 10, 
32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 119, 32, 36, 111, 116, 104, 101, 114, 10, 32, 
32, 32, 32, 32, 32, 115, 101, 116, 32, 111, 116, 104, 101, 114, 32, 36, 116, 104, 105, 115, 
10, 32, 32, 32, 32, 125, 32, 101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 32, 32, 
115, 101, 116, 32, 105, 100, 120, 32, 91, 36, 119, 32, 115, 101, 97, 114, 99, 104, 32, 45, 
99, 111, 117, 110, 116, 32, 99, 111, 117, 110, 116, 32, 36, 100, 105, 114, 101, 99, 116, 105, 
111, 110, 32, 36, 115, 116, 32, 45, 45, 32, 36, 112, 97, 116, 116, 101, 114, 110, 32, 36, 
115, 116, 97, 114, 116, 32, 36, 115, 116, 111, 112, 93, 10, 32, 32, 32, 32, 125, 10, 32, 
32, 125, 10, 32, 32, 36, 119, 32, 116, 97, 103, 32, 114, 101, 109, 111, 118, 101, 32, 115, 
101, 97, 114, 99, 104, 32, 49, 46, 48, 32, 101, 110, 100, 10, 32, 32, 36, 119, 32, 109, 
97, 114, 107, 32, 117, 110, 115, 101, 116, 32, 115, 101, 97, 114, 99, 104, 10, 32, 32, 36, 
111, 116, 104, 101, 114, 32, 116, 97, 103, 32, 114, 101, 109, 111, 118, 101, 32, 115, 101, 97, 
114, 99, 104, 32, 49, 46, 48, 32, 101, 110, 100, 10, 32, 32, 36, 111, 116, 104, 101, 114, 
32, 109, 97, 114, 107, 32, 117, 110, 115, 101, 116, 32, 115, 101, 97, 114, 99, 104, 10, 32, 
32, 105, 102, 32, 123, 34, 36, 105, 100, 120, 34, 33, 61, 34, 34, 125, 32, 123, 10, 32, 
32, 32, 32, 36, 119, 32, 109, 97, 114, 107, 32, 115, 101, 116, 32, 115, 101, 97, 114, 99, 
104, 32, 36, 105, 100, 120, 10, 32, 32, 32, 32, 36, 119, 32, 121, 118, 105, 101, 119, 32, 
45, 112, 105, 99, 107, 112, 108, 97, 99, 101, 32, 36, 105, 100, 120, 10, 32, 32, 32, 32, 
36, 119, 32, 116, 97, 103, 32, 97, 100, 100, 32, 115, 101, 97, 114, 99, 104, 32, 115, 101, 
97, 114, 99, 104, 32, 34, 36, 105, 100, 120, 32, 43, 36, 99, 111, 117, 110, 116, 32, 99, 
104, 97, 114, 115, 34, 10, 32, 32, 32, 32, 36, 119, 32, 116, 97, 103, 32, 99, 111, 110, 
102, 105, 103, 32, 115, 101, 97, 114, 99, 104, 32, 45, 98, 97, 99, 107, 103, 114, 111, 117, 
110, 100, 32, 123, 35, 102, 99, 99, 48, 48, 48, 125, 10, 32, 32, 125, 10, 32, 32, 115, 
101, 116, 32, 58, 58, 115, 101, 97, 114, 99, 104, 32, 36, 119, 10, 125, 10, 58, 58, 116, 
116, 107, 58, 58, 98, 117, 116, 116, 111, 110, 32, 46, 98, 98, 46, 113, 117, 105, 116, 32, 
45, 116, 101, 120, 116, 32, 123, 81, 117, 105, 116, 125, 32, 45, 99, 111, 109, 109, 97, 110, 
100, 32, 101, 120, 105, 116, 10, 58, 58, 116, 116, 107, 58, 58, 98, 117, 116, 116, 111, 110, 
32, 46, 98, 98, 46, 105, 110, 118, 101, 114, 116, 32, 45, 116, 101, 120, 116, 32, 123, 73, 
110, 118, 101, 114, 116, 125, 32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 105, 110, 118, 101, 
114, 116, 68, 105, 102, 102, 10, 58, 58, 116, 116, 107, 58, 58, 98, 117, 116, 116, 111, 110, 
32, 46, 98, 98, 46, 115, 97, 118, 101, 32, 45, 116, 101, 120, 116, 32, 123, 83, 97, 118, 
101, 32, 65, 115, 46, 46, 46, 125, 32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 115, 97, 
118, 101, 68, 105, 102, 102, 10, 58, 58, 116, 116, 107, 58, 58, 98, 117, 116, 116, 111, 110, 
32, 46, 98, 98, 46, 115, 101, 97, 114, 99, 104, 32, 45, 116, 101, 120, 116, 32, 123, 83, 
101, 97, 114, 99, 104, 125, 32, 45, 99, 111, 109, 109, 97, 110, 100, 32, 115, 101, 97, 114, 
99, 104, 79, 110, 79, 102, 102, 10, 112, 97, 99, 107, 32, 46, 98, 98, 46, 113, 117, 105, 
116, 32, 46, 98, 98, 46, 105, 110, 118, 101, 114, 116, 32, 45, 115, 105, 100, 101, 32, 108, 
101, 102, 116, 10, 105, 102, 32, 123, 36, 102, 111, 115, 115, 105, 108, 99, 109, 100, 33, 61, 
34, 34, 125, 32, 123, 112, 97, 99, 107, 32, 46, 98, 98, 46, 115, 97, 118, 101, 32, 45, 
115, 105, 100, 101, 32, 108, 101, 102, 116, 125, 10, 112, 97, 99, 107, 32, 46, 98, 98, 46, 
102, 105, 108, 101, 115, 32, 46, 98, 98, 46, 115, 101, 97, 114, 99, 104, 32, 45, 115, 105, 
100, 101, 32, 108, 101, 102, 116, 10, 103, 114, 105, 100, 32, 114, 111, 119, 99, 111, 110, 102, 
105, 103, 117, 114, 101, 32, 46, 32, 49, 32, 45, 119, 101, 105, 103, 104, 116, 32, 49, 10, 
103, 114, 105, 100, 32, 99, 111, 108, 117, 109, 110, 99, 111, 110, 102, 105, 103, 117, 114, 101, 
32, 46, 32, 49, 32, 45, 119, 101, 105, 103, 104, 116, 32, 49, 10, 103, 114, 105, 100, 32, 
99, 111, 108, 117, 109, 110, 99, 111, 110, 102, 105, 103, 117, 114, 101, 32, 46, 32, 52, 32, 
45, 119, 101, 105, 103, 104, 116, 32, 49, 10, 103, 114, 105, 100, 32, 46, 98, 98, 32, 45, 
114, 111, 119, 32, 48, 32, 45, 99, 111, 108, 117, 109, 110, 115, 112, 97, 110, 32, 54, 10, 
101, 118, 97, 108, 32, 103, 114, 105, 100, 32, 91, 99, 111, 108, 115, 93, 32, 45, 114, 111, 
119, 32, 49, 32, 45, 115, 116, 105, 99, 107, 121, 32, 110, 115, 101, 119, 10, 103, 114, 105, 
100, 32, 46, 115, 98, 121, 32, 45, 114, 111, 119, 32, 49, 32, 45, 99, 111, 108, 117, 109, 
110, 32, 53, 32, 45, 115, 116, 105, 99, 107, 121, 32, 110, 115, 10, 103, 114, 105, 100, 32, 
46, 115, 98, 120, 65, 32, 45, 114, 111, 119, 32, 50, 32, 45, 99, 111, 108, 117, 109, 110, 
115, 112, 97, 110, 32, 50, 32, 45, 115, 116, 105, 99, 107, 121, 32, 101, 119, 10, 103, 114, 
105, 100, 32, 46, 115, 112, 97, 99, 101, 114, 32, 45, 114, 111, 119, 32, 50, 32, 45, 99, 
111, 108, 117, 109, 110, 32, 50, 10, 103, 114, 105, 100, 32, 46, 115, 98, 120, 66, 32, 45, 
114, 111, 119, 32, 50, 32, 45, 99, 111, 108, 117, 109, 110, 32, 51, 32, 45, 99, 111, 108, 
117, 109, 110, 115, 112, 97, 110, 32, 50, 32, 45, 115, 116, 105, 99, 107, 121, 32, 101, 119, 
10, 10, 46, 115, 112, 97, 99, 101, 114, 32, 99, 111, 110, 102, 105, 103, 32, 45, 104, 101, 
105, 103, 104, 116, 32, 91, 119, 105, 110, 102, 111, 32, 104, 101, 105, 103, 104, 116, 32, 46, 
115, 98, 120, 65, 93, 10, 119, 109, 32, 100, 101, 105, 99, 111, 110, 105, 102, 121, 32, 46, 
10, 125, 10, 101, 118, 97, 108, 32, 36, 112, 114, 111, 103, 10, 
0};
char const * fsl_difftk_cstr = fsl_difftk_cstr_a;
/* end of difftk.tcl */
/* end of file src/difftk_cstr.c */
/* start of file src/schema_config_cstr.c */
/** @page page_schema_config_cstr config.sql

Binary form of file config.sql.

*/
/* auto-generated code - edit at your own risk! (Good luck with that!) */
static char const fsl_schema_config_cstr_a[] = {
45, 45, 32, 84, 104, 105, 115, 32, 102, 105, 108, 101, 32, 99, 111, 110, 116, 97, 105, 110, 
115, 32, 116, 104, 101, 32, 115, 99, 104, 101, 109, 97, 32, 102, 111, 114, 32, 116, 104, 101, 
32, 100, 97, 116, 97, 98, 97, 115, 101, 32, 116, 104, 97, 116, 32, 105, 115, 32, 107, 101, 
112, 116, 32, 105, 110, 32, 116, 104, 101, 10, 45, 45, 32, 126, 47, 46, 102, 111, 115, 115, 
105, 108, 32, 102, 105, 108, 101, 32, 97, 110, 100, 32, 116, 104, 97, 116, 32, 115, 116, 111, 
114, 101, 115, 32, 105, 110, 102, 111, 114, 109, 97, 116, 105, 111, 110, 32, 97, 98, 111, 117, 
116, 32, 116, 104, 101, 32, 117, 115, 101, 114, 115, 32, 115, 101, 116, 117, 112, 46, 10, 45, 
45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 99, 102, 103, 46, 103, 
108, 111, 98, 97, 108, 95, 99, 111, 110, 102, 105, 103, 40, 10, 32, 32, 110, 97, 109, 101, 
32, 84, 69, 88, 84, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 44, 10, 32, 
32, 118, 97, 108, 117, 101, 32, 84, 69, 88, 84, 10, 41, 32, 87, 73, 84, 72, 79, 85, 
84, 32, 82, 79, 87, 73, 68, 59, 10, 10, 45, 45, 32, 73, 100, 101, 110, 116, 105, 102, 
105, 101, 114, 32, 102, 111, 114, 32, 116, 104, 105, 115, 32, 102, 105, 108, 101, 32, 116, 121, 
112, 101, 46, 10, 45, 45, 32, 84, 104, 101, 32, 105, 110, 116, 101, 103, 101, 114, 32, 105, 
115, 32, 116, 104, 101, 32, 115, 97, 109, 101, 32, 97, 115, 32, 39, 70, 83, 76, 71, 39, 
46, 10, 80, 82, 65, 71, 77, 65, 32, 99, 102, 103, 46, 97, 112, 112, 108, 105, 99, 97, 
116, 105, 111, 110, 95, 105, 100, 61, 50, 53, 50, 48, 48, 54, 54, 55, 53, 59, 10, 
0};
char const * fsl_schema_config_cstr = fsl_schema_config_cstr_a;
/* end of config.sql */
/* end of file src/schema_config_cstr.c */
/* start of file src/schema_repo1_cstr.c */
/** @page page_schema_repo1_cstr repo-static.sql

Binary form of file repo-static.sql.

*/
/* auto-generated code - edit at your own risk! (Good luck with that!) */
static char const fsl_schema_repo1_cstr_a[] = {
45, 45, 32, 84, 104, 105, 115, 32, 102, 105, 108, 101, 32, 99, 111, 110, 116, 97, 105, 110, 
115, 32, 112, 97, 114, 116, 115, 32, 111, 102, 32, 116, 104, 101, 32, 115, 99, 104, 101, 109, 
97, 32, 116, 104, 97, 116, 32, 97, 114, 101, 32, 102, 105, 120, 101, 100, 32, 97, 110, 100, 
10, 45, 45, 32, 117, 110, 99, 104, 97, 110, 103, 105, 110, 103, 32, 97, 99, 114, 111, 115, 
115, 32, 70, 111, 115, 115, 105, 108, 32, 118, 101, 114, 115, 105, 111, 110, 115, 46, 10, 10, 
10, 45, 45, 32, 84, 104, 101, 32, 66, 76, 79, 66, 32, 97, 110, 100, 32, 68, 69, 76, 
84, 65, 32, 116, 97, 98, 108, 101, 115, 32, 99, 111, 110, 116, 97, 105, 110, 32, 97, 108, 
108, 32, 114, 101, 99, 111, 114, 100, 115, 32, 104, 101, 108, 100, 32, 105, 110, 32, 116, 104, 
101, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 46, 10, 45, 45, 10, 45, 45, 32, 
84, 104, 101, 32, 66, 76, 79, 66, 46, 67, 79, 78, 84, 69, 78, 84, 32, 99, 111, 108, 
117, 109, 110, 32, 105, 115, 32, 97, 108, 119, 97, 121, 115, 32, 99, 111, 109, 112, 114, 101, 
115, 115, 101, 100, 32, 117, 115, 105, 110, 103, 32, 122, 108, 105, 98, 46, 32, 32, 84, 104, 
105, 115, 10, 45, 45, 32, 99, 111, 108, 117, 109, 110, 32, 109, 105, 103, 104, 116, 32, 104, 
111, 108, 100, 32, 116, 104, 101, 32, 102, 117, 108, 108, 32, 116, 101, 120, 116, 32, 111, 102, 
32, 116, 104, 101, 32, 114, 101, 99, 111, 114, 100, 32, 111, 114, 32, 105, 116, 32, 109, 105, 
103, 104, 116, 32, 104, 111, 108, 100, 10, 45, 45, 32, 97, 32, 100, 101, 108, 116, 97, 32, 
116, 104, 97, 116, 32, 105, 115, 32, 97, 98, 108, 101, 32, 116, 111, 32, 114, 101, 99, 111, 
110, 115, 116, 114, 117, 99, 116, 32, 116, 104, 101, 32, 114, 101, 99, 111, 114, 100, 32, 102, 
114, 111, 109, 32, 115, 111, 109, 101, 32, 111, 116, 104, 101, 114, 10, 45, 45, 32, 114, 101, 
99, 111, 114, 100, 46, 32, 32, 73, 102, 32, 66, 76, 79, 66, 46, 67, 79, 78, 84, 69, 
78, 84, 32, 104, 111, 108, 100, 115, 32, 97, 32, 100, 101, 108, 116, 97, 44, 32, 116, 104, 
101, 110, 32, 97, 32, 68, 69, 76, 84, 65, 32, 116, 97, 98, 108, 101, 32, 101, 110, 116, 
114, 121, 10, 45, 45, 32, 119, 105, 108, 108, 32, 101, 120, 105, 115, 116, 32, 102, 111, 114, 
32, 116, 104, 101, 32, 114, 101, 99, 111, 114, 100, 32, 97, 110, 100, 32, 116, 104, 97, 116, 
32, 101, 110, 116, 114, 121, 32, 119, 105, 108, 108, 32, 112, 111, 105, 110, 116, 32, 116, 111, 
32, 97, 110, 111, 116, 104, 101, 114, 10, 45, 45, 32, 101, 110, 116, 114, 121, 32, 116, 104, 
97, 116, 32, 104, 111, 108, 100, 115, 32, 116, 104, 101, 32, 115, 111, 117, 114, 99, 101, 32, 
111, 102, 32, 116, 104, 101, 32, 100, 101, 108, 116, 97, 46, 32, 32, 68, 101, 108, 116, 97, 
115, 32, 99, 97, 110, 32, 98, 101, 32, 99, 104, 97, 105, 110, 101, 100, 46, 10, 45, 45, 
10, 45, 45, 32, 84, 104, 101, 32, 98, 108, 111, 98, 32, 97, 110, 100, 32, 100, 101, 108, 
116, 97, 32, 116, 97, 98, 108, 101, 115, 32, 99, 111, 108, 108, 101, 99, 116, 105, 118, 101, 
108, 121, 32, 104, 111, 108, 100, 32, 116, 104, 101, 32, 111, 118, 101, 114, 119, 104, 101, 108, 
109, 105, 110, 103, 108, 121, 32, 118, 97, 115, 116, 10, 45, 45, 32, 109, 97, 106, 111, 114, 
105, 116, 121, 32, 111, 102, 32, 112, 101, 114, 115, 105, 115, 116, 101, 110, 116, 32, 115, 116, 
97, 116, 101, 32, 111, 102, 32, 97, 32, 70, 111, 115, 115, 105, 108, 32, 114, 101, 112, 111, 
115, 105, 116, 111, 114, 121, 44, 32, 97, 110, 100, 32, 99, 111, 110, 116, 97, 105, 110, 10, 
45, 45, 32, 97, 108, 108, 32, 111, 102, 32, 116, 104, 101, 32, 83, 67, 77, 45, 116, 114, 
97, 99, 107, 101, 100, 32, 115, 116, 97, 116, 101, 46, 10, 45, 45, 10, 67, 82, 69, 65, 
84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 
112, 111, 125, 125, 46, 98, 108, 111, 98, 40, 10, 32, 32, 114, 105, 100, 32, 73, 78, 84, 
69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 44, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 82, 101, 99, 111, 114, 100, 32, 73, 68, 10, 32, 32, 
114, 99, 118, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 44, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 79, 114, 105, 103, 105, 
110, 32, 111, 102, 32, 116, 104, 105, 115, 32, 114, 101, 99, 111, 114, 100, 10, 32, 32, 115, 
105, 122, 101, 32, 73, 78, 84, 69, 71, 69, 82, 44, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 83, 105, 122, 101, 32, 111, 
102, 32, 99, 111, 110, 116, 101, 110, 116, 46, 32, 45, 49, 32, 102, 111, 114, 32, 97, 32, 
112, 104, 97, 110, 116, 111, 109, 46, 10, 32, 32, 117, 117, 105, 100, 32, 84, 69, 88, 84, 
32, 85, 78, 73, 81, 85, 69, 32, 78, 79, 84, 32, 78, 85, 76, 76, 44, 32, 32, 32, 
32, 32, 32, 45, 45, 32, 83, 72, 65, 49, 32, 104, 97, 115, 104, 32, 111, 102, 32, 116, 
104, 101, 32, 99, 111, 110, 116, 101, 110, 116, 10, 32, 32, 99, 111, 110, 116, 101, 110, 116, 
32, 66, 76, 79, 66, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 67, 111, 109, 112, 114, 101, 115, 115, 101, 100, 32, 99, 
111, 110, 116, 101, 110, 116, 32, 111, 102, 32, 116, 104, 105, 115, 32, 114, 101, 99, 111, 114, 
100, 10, 32, 32, 67, 72, 69, 67, 75, 40, 32, 108, 101, 110, 103, 116, 104, 40, 117, 117, 
105, 100, 41, 62, 61, 52, 48, 32, 65, 78, 68, 32, 114, 105, 100, 62, 48, 32, 41, 10, 
41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 
110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 100, 101, 108, 116, 97, 40, 10, 32, 
32, 114, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 
32, 75, 69, 89, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 45, 45, 32, 82, 101, 99, 111, 114, 100, 32, 73, 68, 32, 104, 111, 108, 100, 105, 
110, 103, 32, 97, 32, 100, 101, 108, 116, 97, 10, 32, 32, 115, 114, 99, 105, 100, 32, 73, 
78, 84, 69, 71, 69, 82, 32, 78, 79, 84, 32, 78, 85, 76, 76, 32, 82, 69, 70, 69, 
82, 69, 78, 67, 69, 83, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 98, 
108, 111, 98, 125, 125, 32, 32, 32, 45, 45, 32, 82, 101, 99, 111, 114, 100, 32, 104, 111, 
108, 100, 105, 110, 103, 32, 115, 111, 117, 114, 99, 101, 32, 100, 111, 99, 117, 109, 101, 110, 
116, 10, 41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 73, 78, 68, 69, 88, 32, 123, 123, 
100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 100, 101, 108, 116, 97, 95, 
105, 49, 32, 79, 78, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 100, 101, 
108, 116, 97, 125, 125, 40, 115, 114, 99, 105, 100, 41, 59, 10, 10, 45, 45, 45, 45, 45, 
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 
45, 45, 45, 45, 45, 45, 45, 45, 10, 45, 45, 32, 84, 104, 101, 32, 66, 76, 79, 66, 
32, 97, 110, 100, 32, 68, 69, 76, 84, 65, 32, 116, 97, 98, 108, 101, 115, 32, 97, 98, 
111, 118, 101, 32, 104, 111, 108, 100, 32, 116, 104, 101, 32, 34, 103, 108, 111, 98, 97, 108, 
32, 115, 116, 97, 116, 101, 34, 32, 111, 102, 32, 97, 32, 70, 111, 115, 115, 105, 108, 10, 
45, 45, 32, 112, 114, 111, 106, 101, 99, 116, 59, 32, 116, 104, 101, 32, 115, 116, 117, 102, 
102, 32, 116, 104, 97, 116, 32, 105, 115, 32, 110, 111, 114, 109, 97, 108, 108, 121, 32, 101, 
120, 99, 104, 97, 110, 103, 101, 100, 32, 100, 117, 114, 105, 110, 103, 32, 34, 115, 121, 110, 
99, 34, 46, 32, 32, 84, 104, 101, 10, 45, 45, 32, 34, 108, 111, 99, 97, 108, 32, 115, 
116, 97, 116, 101, 34, 32, 111, 102, 32, 97, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 
121, 32, 105, 115, 32, 99, 111, 110, 116, 97, 105, 110, 101, 100, 32, 105, 110, 32, 116, 104, 
101, 32, 114, 101, 109, 97, 105, 110, 105, 110, 103, 32, 116, 97, 98, 108, 101, 115, 32, 111, 
102, 10, 45, 45, 32, 116, 104, 101, 32, 122, 82, 101, 112, 111, 115, 105, 116, 111, 114, 121, 
83, 99, 104, 101, 109, 97, 49, 32, 115, 116, 114, 105, 110, 103, 46, 10, 45, 45, 45, 45, 
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 
45, 45, 45, 45, 45, 45, 45, 45, 45, 10, 10, 45, 45, 32, 87, 104, 101, 110, 101, 118, 
101, 114, 32, 110, 101, 119, 32, 98, 108, 111, 98, 115, 32, 97, 114, 101, 32, 114, 101, 99, 
101, 105, 118, 101, 100, 32, 105, 110, 116, 111, 32, 116, 104, 101, 32, 114, 101, 112, 111, 115, 
105, 116, 111, 114, 121, 44, 32, 97, 110, 32, 101, 110, 116, 114, 121, 10, 45, 45, 32, 105, 
110, 32, 116, 104, 105, 115, 32, 116, 97, 98, 108, 101, 32, 114, 101, 99, 111, 114, 100, 115, 
32, 116, 104, 101, 32, 115, 111, 117, 114, 99, 101, 32, 111, 102, 32, 116, 104, 101, 32, 98, 
108, 111, 98, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 
32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 114, 99, 118, 
102, 114, 111, 109, 40, 10, 32, 32, 114, 99, 118, 105, 100, 32, 73, 78, 84, 69, 71, 69, 
82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 44, 32, 32, 32, 32, 32, 32, 
45, 45, 32, 82, 101, 99, 101, 105, 118, 101, 100, 45, 70, 114, 111, 109, 32, 73, 68, 10, 
32, 32, 117, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 82, 69, 70, 69, 82, 69, 
78, 67, 69, 83, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 117, 115, 101, 
114, 125, 125, 44, 32, 32, 32, 32, 45, 45, 32, 85, 115, 101, 114, 32, 108, 111, 103, 105, 
110, 10, 32, 32, 109, 116, 105, 109, 101, 32, 68, 65, 84, 69, 84, 73, 77, 69, 44, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 84, 
105, 109, 101, 32, 111, 102, 32, 114, 101, 99, 101, 105, 112, 116, 46, 32, 32, 74, 117, 108, 
105, 97, 110, 32, 100, 97, 121, 46, 10, 32, 32, 110, 111, 110, 99, 101, 32, 84, 69, 88, 
84, 32, 85, 78, 73, 81, 85, 69, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 45, 45, 32, 78, 111, 110, 99, 101, 32, 117, 115, 101, 100, 32, 102, 111, 114, 
32, 108, 111, 103, 105, 110, 10, 32, 32, 105, 112, 97, 100, 100, 114, 32, 84, 69, 88, 84, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 45, 45, 32, 82, 101, 109, 111, 116, 101, 32, 73, 80, 32, 97, 100, 100, 114, 101, 115, 
115, 46, 32, 32, 78, 85, 76, 76, 32, 102, 111, 114, 32, 100, 105, 114, 101, 99, 116, 46, 
10, 41, 59, 10, 73, 78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 32, 123, 123, 100, 98, 
110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 114, 99, 118, 102, 114, 111, 109, 40, 
114, 99, 118, 105, 100, 44, 117, 105, 100, 44, 109, 116, 105, 109, 101, 44, 110, 111, 110, 99, 
101, 44, 105, 112, 97, 100, 100, 114, 41, 10, 86, 65, 76, 85, 69, 83, 32, 40, 49, 44, 
32, 49, 44, 32, 106, 117, 108, 105, 97, 110, 100, 97, 121, 40, 39, 110, 111, 119, 39, 41, 
44, 32, 78, 85, 76, 76, 44, 32, 78, 85, 76, 76, 41, 59, 10, 10, 45, 45, 32, 73, 
110, 102, 111, 114, 109, 97, 116, 105, 111, 110, 32, 97, 98, 111, 117, 116, 32, 117, 115, 101, 
114, 115, 10, 45, 45, 10, 45, 45, 32, 84, 104, 101, 32, 117, 115, 101, 114, 46, 112, 119, 
32, 102, 105, 101, 108, 100, 32, 99, 97, 110, 32, 98, 101, 32, 101, 105, 116, 104, 101, 114, 
32, 99, 108, 101, 97, 114, 116, 101, 120, 116, 32, 111, 102, 32, 116, 104, 101, 32, 112, 97, 
115, 115, 119, 111, 114, 100, 44, 32, 111, 114, 10, 45, 45, 32, 97, 32, 83, 72, 65, 49, 
32, 104, 97, 115, 104, 32, 111, 102, 32, 116, 104, 101, 32, 112, 97, 115, 115, 119, 111, 114, 
100, 46, 32, 32, 73, 102, 32, 116, 104, 101, 32, 117, 115, 101, 114, 46, 112, 119, 32, 102, 
105, 101, 108, 100, 32, 105, 115, 32, 101, 120, 97, 99, 116, 108, 121, 32, 52, 48, 10, 45, 
45, 32, 99, 104, 97, 114, 97, 99, 116, 101, 114, 115, 32, 108, 111, 110, 103, 32, 119, 101, 
32, 97, 115, 115, 117, 109, 101, 32, 105, 116, 32, 105, 115, 32, 97, 32, 83, 72, 65, 49, 
32, 104, 97, 115, 104, 46, 32, 32, 79, 116, 104, 101, 114, 119, 105, 115, 101, 44, 32, 105, 
116, 32, 105, 115, 10, 45, 45, 32, 99, 108, 101, 97, 114, 116, 101, 120, 116, 46, 32, 32, 
84, 104, 101, 32, 115, 104, 97, 49, 95, 115, 104, 97, 114, 101, 100, 95, 115, 101, 99, 114, 
101, 116, 40, 41, 32, 114, 111, 117, 116, 105, 110, 101, 32, 99, 111, 109, 112, 117, 116, 101, 
115, 32, 116, 104, 101, 32, 112, 97, 115, 115, 119, 111, 114, 100, 10, 45, 45, 32, 104, 97, 
115, 104, 32, 98, 97, 115, 101, 100, 32, 111, 110, 32, 116, 104, 101, 32, 112, 114, 111, 106, 
101, 99, 116, 45, 99, 111, 100, 101, 44, 32, 116, 104, 101, 32, 117, 115, 101, 114, 32, 108, 
111, 103, 105, 110, 44, 32, 97, 110, 100, 32, 116, 104, 101, 32, 99, 108, 101, 97, 114, 116, 
101, 120, 116, 10, 45, 45, 32, 112, 97, 115, 115, 119, 111, 114, 100, 46, 10, 45, 45, 10, 
67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 
101, 46, 114, 101, 112, 111, 125, 125, 46, 117, 115, 101, 114, 40, 10, 32, 32, 117, 105, 100, 
32, 73, 78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 
44, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 85, 115, 101, 114, 32, 73, 68, 10, 
32, 32, 108, 111, 103, 105, 110, 32, 84, 69, 88, 84, 32, 85, 78, 73, 81, 85, 69, 44, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 108, 111, 103, 
105, 110, 32, 110, 97, 109, 101, 32, 111, 102, 32, 116, 104, 101, 32, 117, 115, 101, 114, 10, 
32, 32, 112, 119, 32, 84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 112, 97, 115, 
115, 119, 111, 114, 100, 10, 32, 32, 99, 97, 112, 32, 84, 69, 88, 84, 44, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
45, 45, 32, 67, 97, 112, 97, 98, 105, 108, 105, 116, 105, 101, 115, 32, 111, 102, 32, 116, 
104, 105, 115, 32, 117, 115, 101, 114, 10, 32, 32, 99, 111, 111, 107, 105, 101, 32, 84, 69, 
88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 45, 45, 32, 87, 87, 87, 32, 108, 111, 103, 105, 110, 32, 99, 111, 111, 107, 
105, 101, 10, 32, 32, 105, 112, 97, 100, 100, 114, 32, 84, 69, 88, 84, 44, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 
73, 80, 32, 97, 100, 100, 114, 101, 115, 115, 32, 102, 111, 114, 32, 119, 104, 105, 99, 104, 
32, 99, 111, 111, 107, 105, 101, 32, 105, 115, 32, 118, 97, 108, 105, 100, 10, 32, 32, 99, 
101, 120, 112, 105, 114, 101, 32, 68, 65, 84, 69, 84, 73, 77, 69, 44, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 84, 105, 109, 101, 32, 119, 
104, 101, 110, 32, 99, 111, 111, 107, 105, 101, 32, 101, 120, 112, 105, 114, 101, 115, 10, 32, 
32, 105, 110, 102, 111, 32, 84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 99, 111, 110, 116, 
97, 99, 116, 32, 105, 110, 102, 111, 114, 109, 97, 116, 105, 111, 110, 10, 32, 32, 109, 116, 
105, 109, 101, 32, 68, 65, 84, 69, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 108, 97, 115, 116, 32, 99, 104, 
97, 110, 103, 101, 46, 32, 32, 115, 101, 99, 111, 110, 100, 115, 32, 115, 105, 110, 99, 101, 
32, 49, 57, 55, 48, 10, 32, 32, 112, 104, 111, 116, 111, 32, 66, 76, 79, 66, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
45, 45, 32, 74, 80, 69, 71, 32, 105, 109, 97, 103, 101, 32, 111, 102, 32, 116, 104, 105, 
115, 32, 117, 115, 101, 114, 10, 41, 59, 10, 10, 45, 45, 32, 84, 104, 101, 32, 86, 65, 
82, 32, 116, 97, 98, 108, 101, 32, 104, 111, 108, 100, 115, 32, 109, 105, 115, 99, 101, 108, 
108, 97, 110, 111, 117, 115, 32, 105, 110, 102, 111, 114, 109, 97, 116, 105, 111, 110, 32, 97, 
98, 111, 117, 116, 32, 116, 104, 101, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 46, 
10, 45, 45, 32, 105, 110, 32, 116, 104, 101, 32, 102, 111, 114, 109, 32, 111, 102, 32, 110, 
97, 109, 101, 45, 118, 97, 108, 117, 101, 32, 112, 97, 105, 114, 115, 46, 10, 45, 45, 10, 
67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 
101, 46, 114, 101, 112, 111, 125, 125, 46, 99, 111, 110, 102, 105, 103, 40, 10, 32, 32, 110, 
97, 109, 101, 32, 84, 69, 88, 84, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 
32, 78, 79, 84, 32, 78, 85, 76, 76, 44, 32, 32, 45, 45, 32, 80, 114, 105, 109, 97, 
114, 121, 32, 110, 97, 109, 101, 32, 111, 102, 32, 116, 104, 101, 32, 101, 110, 116, 114, 121, 
10, 32, 32, 118, 97, 108, 117, 101, 32, 67, 76, 79, 66, 44, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 67, 
111, 110, 116, 101, 110, 116, 32, 111, 102, 32, 116, 104, 101, 32, 110, 97, 109, 101, 100, 32, 
112, 97, 114, 97, 109, 101, 116, 101, 114, 10, 32, 32, 109, 116, 105, 109, 101, 32, 68, 65, 
84, 69, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 108, 97, 115, 116, 32, 109, 111, 100, 105, 102, 105, 101, 
100, 46, 32, 32, 115, 101, 99, 111, 110, 100, 115, 32, 115, 105, 110, 99, 101, 32, 49, 57, 
55, 48, 10, 32, 32, 67, 72, 69, 67, 75, 40, 32, 116, 121, 112, 101, 111, 102, 40, 110, 
97, 109, 101, 41, 61, 39, 116, 101, 120, 116, 39, 32, 65, 78, 68, 32, 108, 101, 110, 103, 
116, 104, 40, 110, 97, 109, 101, 41, 62, 61, 49, 32, 41, 10, 41, 32, 87, 73, 84, 72, 
79, 85, 84, 32, 82, 79, 87, 73, 68, 59, 10, 10, 45, 45, 32, 65, 114, 116, 105, 102, 
97, 99, 116, 115, 32, 116, 104, 97, 116, 32, 115, 104, 111, 117, 108, 100, 32, 110, 111, 116, 
32, 98, 101, 32, 112, 114, 111, 99, 101, 115, 115, 101, 100, 32, 97, 114, 101, 32, 105, 100, 
101, 110, 116, 105, 102, 105, 101, 100, 32, 105, 110, 32, 116, 104, 101, 10, 45, 45, 32, 34, 
115, 104, 117, 110, 34, 32, 116, 97, 98, 108, 101, 46, 32, 32, 65, 114, 116, 105, 102, 97, 
99, 116, 115, 32, 116, 104, 97, 116, 32, 97, 114, 101, 32, 99, 111, 110, 116, 114, 111, 108, 
45, 102, 105, 108, 101, 32, 102, 111, 114, 103, 101, 114, 105, 101, 115, 32, 111, 114, 10, 45, 
45, 32, 115, 112, 97, 109, 32, 111, 114, 32, 97, 114, 116, 105, 102, 97, 99, 116, 115, 32, 
119, 104, 111, 115, 101, 32, 99, 111, 110, 116, 101, 110, 116, 115, 32, 118, 105, 111, 108, 97, 
116, 101, 32, 97, 100, 109, 105, 110, 105, 115, 116, 114, 97, 116, 105, 118, 101, 32, 112, 111, 
108, 105, 99, 121, 10, 45, 45, 32, 99, 97, 110, 32, 98, 101, 32, 115, 104, 117, 110, 110, 
101, 100, 32, 105, 110, 32, 111, 114, 100, 101, 114, 32, 116, 111, 32, 112, 114, 101, 118, 101, 
110, 116, 32, 116, 104, 101, 109, 32, 102, 114, 111, 109, 32, 99, 111, 110, 116, 97, 109, 105, 
110, 97, 116, 105, 110, 103, 10, 45, 45, 32, 116, 104, 101, 32, 114, 101, 112, 111, 115, 105, 
116, 111, 114, 121, 46, 10, 45, 45, 10, 45, 45, 32, 83, 104, 117, 110, 110, 101, 100, 32, 
97, 114, 116, 105, 102, 97, 99, 116, 115, 32, 100, 111, 32, 110, 111, 116, 32, 101, 120, 105, 
115, 116, 32, 105, 110, 32, 116, 104, 101, 32, 98, 108, 111, 98, 32, 116, 97, 98, 108, 101, 
46, 32, 32, 72, 101, 110, 99, 101, 32, 116, 104, 101, 121, 10, 45, 45, 32, 104, 97, 118, 
101, 32, 110, 111, 116, 32, 97, 114, 116, 105, 102, 97, 99, 116, 32, 73, 68, 32, 40, 114, 
105, 100, 41, 32, 97, 110, 100, 32, 119, 101, 32, 116, 104, 117, 115, 32, 109, 117, 115, 116, 
32, 115, 116, 111, 114, 101, 32, 116, 104, 101, 105, 114, 32, 102, 117, 108, 108, 10, 45, 45, 
32, 85, 85, 73, 68, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 
76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 115, 
104, 117, 110, 40, 10, 32, 32, 117, 117, 105, 100, 32, 84, 69, 88, 84, 32, 80, 82, 73, 
77, 65, 82, 89, 32, 75, 69, 89, 44, 32, 45, 45, 32, 85, 85, 73, 68, 32, 111, 102, 
32, 97, 114, 116, 105, 102, 97, 99, 116, 32, 116, 111, 32, 98, 101, 32, 115, 104, 117, 110, 
110, 101, 100, 46, 32, 67, 97, 110, 111, 110, 105, 99, 97, 108, 32, 102, 111, 114, 109, 10, 
32, 32, 109, 116, 105, 109, 101, 32, 68, 65, 84, 69, 44, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 87, 104, 101, 110, 32, 97, 100, 100, 101, 100, 46, 32, 
32, 115, 101, 99, 111, 110, 100, 115, 32, 115, 105, 110, 99, 101, 32, 49, 57, 55, 48, 10, 
32, 32, 115, 99, 111, 109, 32, 84, 69, 88, 84, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 79, 112, 116, 105, 111, 110, 97, 108, 32, 116, 101, 120, 
116, 32, 101, 120, 112, 108, 97, 105, 110, 105, 110, 103, 32, 119, 104, 121, 32, 116, 104, 101, 
32, 115, 104, 117, 110, 32, 111, 99, 99, 117, 114, 114, 101, 100, 10, 41, 32, 87, 73, 84, 
72, 79, 85, 84, 32, 82, 79, 87, 73, 68, 59, 10, 10, 45, 45, 32, 65, 114, 116, 105, 
102, 97, 99, 116, 115, 32, 116, 104, 97, 116, 32, 115, 104, 111, 117, 108, 100, 32, 110, 111, 
116, 32, 98, 101, 32, 112, 117, 115, 104, 101, 100, 32, 97, 114, 101, 32, 115, 116, 111, 114, 
101, 100, 32, 105, 110, 32, 116, 104, 101, 32, 34, 112, 114, 105, 118, 97, 116, 101, 34, 10, 
45, 45, 32, 116, 97, 98, 108, 101, 46, 32, 32, 80, 114, 105, 118, 97, 116, 101, 32, 97, 
114, 116, 105, 102, 97, 99, 116, 115, 32, 97, 114, 101, 32, 111, 109, 105, 116, 116, 101, 100, 
32, 102, 114, 111, 109, 32, 116, 104, 101, 32, 34, 117, 110, 99, 108, 117, 115, 116, 101, 114, 
101, 100, 34, 32, 97, 110, 100, 10, 45, 45, 32, 34, 117, 110, 115, 101, 110, 116, 34, 32, 
116, 97, 98, 108, 101, 115, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 
66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 
112, 114, 105, 118, 97, 116, 101, 40, 114, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 
80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 41, 59, 10, 10, 45, 45, 32, 65, 110, 
32, 101, 110, 116, 114, 121, 32, 105, 110, 32, 116, 104, 105, 115, 32, 116, 97, 98, 108, 101, 
32, 100, 101, 115, 99, 114, 105, 98, 101, 115, 32, 97, 32, 100, 97, 116, 97, 98, 97, 115, 
101, 32, 113, 117, 101, 114, 121, 32, 116, 104, 97, 116, 32, 103, 101, 110, 101, 114, 97, 116, 
101, 115, 32, 97, 10, 45, 45, 32, 116, 97, 98, 108, 101, 32, 111, 102, 32, 116, 105, 99, 
107, 101, 116, 115, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 
69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 114, 101, 
112, 111, 114, 116, 102, 109, 116, 40, 10, 32, 32, 32, 114, 110, 32, 73, 78, 84, 69, 71, 
69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 44, 32, 32, 45, 45, 32, 
82, 101, 112, 111, 114, 116, 32, 110, 117, 109, 98, 101, 114, 10, 32, 32, 32, 111, 119, 110, 
101, 114, 32, 84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 45, 45, 32, 79, 119, 110, 101, 114, 32, 111, 102, 32, 116, 104, 105, 115, 32, 114, 
101, 112, 111, 114, 116, 32, 102, 111, 114, 109, 97, 116, 32, 40, 110, 111, 116, 32, 117, 115, 
101, 100, 41, 10, 32, 32, 32, 116, 105, 116, 108, 101, 32, 84, 69, 88, 84, 32, 85, 78, 
73, 81, 85, 69, 44, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 84, 105, 116, 108, 101, 
32, 111, 102, 32, 116, 104, 105, 115, 32, 114, 101, 112, 111, 114, 116, 10, 32, 32, 32, 109, 
116, 105, 109, 101, 32, 68, 65, 84, 69, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 45, 45, 32, 76, 97, 115, 116, 32, 109, 111, 100, 105, 102, 105, 101, 100, 
46, 32, 32, 115, 101, 99, 111, 110, 100, 115, 32, 115, 105, 110, 99, 101, 32, 49, 57, 55, 
48, 10, 32, 32, 32, 99, 111, 108, 115, 32, 84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 65, 32, 99, 111, 108, 111, 114, 
45, 107, 101, 121, 32, 115, 112, 101, 99, 105, 102, 105, 99, 97, 116, 105, 111, 110, 10, 32, 
32, 32, 115, 113, 108, 99, 111, 100, 101, 32, 84, 69, 88, 84, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 65, 110, 32, 83, 81, 76, 32, 83, 69, 76, 
69, 67, 84, 32, 115, 116, 97, 116, 101, 109, 101, 110, 116, 32, 102, 111, 114, 32, 116, 104, 
105, 115, 32, 114, 101, 112, 111, 114, 116, 10, 41, 59, 10, 10, 45, 45, 32, 83, 111, 109, 
101, 32, 116, 105, 99, 107, 101, 116, 32, 99, 111, 110, 116, 101, 110, 116, 32, 40, 115, 117, 
99, 104, 32, 97, 115, 32, 116, 104, 101, 32, 111, 114, 105, 103, 105, 110, 97, 116, 111, 114, 
115, 32, 101, 109, 97, 105, 108, 32, 97, 100, 100, 114, 101, 115, 115, 32, 111, 114, 32, 99, 
111, 110, 116, 97, 99, 116, 10, 45, 45, 32, 105, 110, 102, 111, 114, 109, 97, 116, 105, 111, 
110, 41, 32, 110, 101, 101, 100, 115, 32, 116, 111, 32, 98, 101, 32, 111, 98, 115, 99, 117, 
114, 101, 100, 32, 116, 111, 32, 112, 114, 111, 116, 101, 99, 116, 32, 112, 114, 105, 118, 97, 
99, 121, 46, 32, 32, 84, 104, 105, 115, 32, 105, 115, 32, 97, 99, 104, 105, 101, 118, 101, 
100, 10, 45, 45, 32, 98, 121, 32, 115, 116, 111, 114, 105, 110, 103, 32, 97, 110, 32, 83, 
72, 65, 49, 32, 104, 97, 115, 104, 32, 111, 102, 32, 116, 104, 101, 32, 99, 111, 110, 116, 
101, 110, 116, 46, 32, 32, 70, 111, 114, 32, 100, 105, 115, 112, 108, 97, 121, 44, 32, 116, 
104, 101, 32, 104, 97, 115, 104, 32, 105, 115, 10, 45, 45, 32, 109, 97, 112, 112, 101, 100, 
32, 98, 97, 99, 107, 32, 105, 110, 116, 111, 32, 116, 104, 101, 32, 111, 114, 105, 103, 105, 
110, 97, 108, 32, 116, 101, 120, 116, 32, 117, 115, 105, 110, 103, 32, 116, 104, 105, 115, 32, 
116, 97, 98, 108, 101, 46, 10, 45, 45, 10, 45, 45, 32, 84, 104, 105, 115, 32, 116, 97, 
98, 108, 101, 32, 99, 111, 110, 116, 97, 105, 110, 115, 32, 115, 101, 110, 115, 105, 116, 105, 
118, 101, 32, 105, 110, 102, 111, 114, 109, 97, 116, 105, 111, 110, 32, 97, 110, 100, 32, 115, 
104, 111, 117, 108, 100, 32, 110, 111, 116, 32, 98, 101, 32, 115, 104, 97, 114, 101, 100, 10, 
45, 45, 32, 119, 105, 116, 104, 32, 117, 110, 97, 117, 116, 104, 111, 114, 105, 122, 101, 100, 
32, 117, 115, 101, 114, 115, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 
66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 
99, 111, 110, 99, 101, 97, 108, 101, 100, 40, 10, 32, 32, 104, 97, 115, 104, 32, 84, 69, 
88, 84, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 44, 32, 32, 32, 32, 45, 
45, 32, 84, 104, 101, 32, 83, 72, 65, 49, 32, 104, 97, 115, 104, 32, 111, 102, 32, 99, 
111, 110, 116, 101, 110, 116, 10, 32, 32, 109, 116, 105, 109, 101, 32, 68, 65, 84, 69, 44, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 84, 105, 
109, 101, 32, 99, 114, 101, 97, 116, 101, 100, 46, 32, 32, 83, 101, 99, 111, 110, 100, 115, 
32, 115, 105, 110, 99, 101, 32, 49, 57, 55, 48, 10, 32, 32, 99, 111, 110, 116, 101, 110, 
116, 32, 84, 69, 88, 84, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
45, 45, 32, 67, 111, 110, 116, 101, 110, 116, 32, 105, 110, 116, 101, 110, 100, 101, 100, 32, 
116, 111, 32, 98, 101, 32, 99, 111, 110, 99, 101, 97, 108, 101, 100, 10, 41, 32, 87, 73, 
84, 72, 79, 85, 84, 32, 82, 79, 87, 73, 68, 59, 10, 
0};
char const * fsl_schema_repo1_cstr = fsl_schema_repo1_cstr_a;
/* end of repo-static.sql */
/* end of file src/schema_repo1_cstr.c */
/* start of file src/schema_repo2_cstr.c */
/** @page page_schema_repo2_cstr repo-transient.sql

Binary form of file repo-transient.sql.

*/
/* auto-generated code - edit at your own risk! (Good luck with that!) */
static char const fsl_schema_repo2_cstr_a[] = {
45, 45, 32, 84, 104, 105, 115, 32, 102, 105, 108, 101, 32, 99, 111, 110, 116, 97, 105, 110, 
115, 32, 112, 97, 114, 116, 115, 32, 111, 102, 32, 116, 104, 101, 32, 115, 99, 104, 101, 109, 
97, 32, 116, 104, 97, 116, 32, 99, 97, 110, 32, 99, 104, 97, 110, 103, 101, 32, 102, 114, 
111, 109, 32, 111, 110, 101, 10, 45, 45, 32, 118, 101, 114, 115, 105, 111, 110, 32, 116, 111, 
32, 116, 104, 101, 32, 110, 101, 120, 116, 46, 32, 84, 104, 101, 32, 100, 97, 116, 97, 32, 
115, 116, 111, 114, 101, 100, 32, 105, 110, 32, 116, 104, 101, 115, 101, 32, 116, 97, 98, 108, 
101, 115, 32, 105, 115, 10, 45, 45, 32, 114, 101, 99, 111, 110, 115, 116, 114, 117, 99, 116, 
101, 100, 32, 102, 114, 111, 109, 32, 116, 104, 101, 32, 105, 110, 102, 111, 114, 109, 97, 116, 
105, 111, 110, 32, 105, 110, 32, 116, 104, 101, 32, 109, 97, 105, 110, 32, 114, 101, 112, 111, 
32, 115, 99, 104, 101, 109, 97, 32, 98, 121, 32, 116, 104, 101, 10, 45, 45, 32, 34, 114, 
101, 98, 117, 105, 108, 100, 34, 32, 111, 112, 101, 114, 97, 116, 105, 111, 110, 46, 10, 10, 
45, 45, 32, 70, 105, 108, 101, 110, 97, 109, 101, 115, 10, 45, 45, 10, 67, 82, 69, 65, 
84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 
112, 111, 125, 125, 46, 102, 105, 108, 101, 110, 97, 109, 101, 40, 10, 32, 32, 102, 110, 105, 
100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 
89, 44, 32, 32, 32, 32, 45, 45, 32, 70, 105, 108, 101, 110, 97, 109, 101, 32, 73, 68, 
10, 32, 32, 110, 97, 109, 101, 32, 84, 69, 88, 84, 32, 85, 78, 73, 81, 85, 69, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 78, 97, 109, 101, 32, 
111, 102, 32, 102, 105, 108, 101, 32, 112, 97, 103, 101, 10, 41, 59, 10, 10, 45, 45, 32, 
76, 105, 110, 107, 97, 103, 101, 115, 32, 98, 101, 116, 119, 101, 101, 110, 32, 99, 104, 101, 
99, 107, 45, 105, 110, 115, 44, 32, 102, 105, 108, 101, 115, 32, 99, 114, 101, 97, 116, 101, 
100, 32, 98, 121, 32, 101, 97, 99, 104, 32, 99, 104, 101, 99, 107, 45, 105, 110, 44, 32, 
97, 110, 100, 10, 45, 45, 32, 116, 104, 101, 32, 110, 97, 109, 101, 115, 32, 111, 102, 32, 
116, 104, 111, 115, 101, 32, 102, 105, 108, 101, 115, 46, 10, 45, 45, 10, 45, 45, 32, 69, 
97, 99, 104, 32, 101, 110, 116, 114, 121, 32, 114, 101, 112, 114, 101, 115, 101, 110, 116, 115, 
32, 97, 32, 102, 105, 108, 101, 32, 116, 104, 97, 116, 32, 99, 104, 97, 110, 103, 101, 100, 
32, 99, 111, 110, 116, 101, 110, 116, 32, 102, 114, 111, 109, 32, 112, 105, 100, 32, 116, 111, 
32, 102, 105, 100, 10, 45, 45, 32, 100, 117, 101, 32, 116, 111, 32, 116, 104, 101, 32, 99, 
104, 101, 99, 107, 45, 105, 110, 32, 116, 104, 97, 116, 32, 103, 111, 101, 115, 32, 102, 114, 
111, 109, 32, 112, 109, 105, 100, 32, 116, 111, 32, 109, 105, 100, 46, 32, 32, 102, 110, 105, 
100, 32, 105, 115, 32, 116, 104, 101, 32, 110, 97, 109, 101, 10, 45, 45, 32, 111, 102, 32, 
116, 104, 101, 32, 102, 105, 108, 101, 32, 105, 110, 32, 116, 104, 101, 32, 109, 105, 100, 32, 
99, 104, 101, 99, 107, 45, 105, 110, 46, 32, 32, 73, 102, 32, 116, 104, 101, 32, 102, 105, 
108, 101, 32, 119, 97, 115, 32, 114, 101, 110, 97, 109, 101, 100, 32, 97, 115, 32, 112, 97, 
114, 116, 10, 45, 45, 32, 111, 102, 32, 116, 104, 101, 32, 109, 105, 100, 32, 99, 104, 101, 
99, 107, 45, 105, 110, 44, 32, 116, 104, 101, 110, 32, 112, 102, 110, 105, 100, 32, 105, 115, 
32, 116, 104, 101, 32, 112, 114, 101, 118, 105, 111, 117, 115, 32, 102, 105, 108, 101, 110, 97, 
109, 101, 46, 10, 45, 45, 10, 45, 45, 32, 84, 104, 101, 114, 101, 32, 99, 97, 110, 32, 
98, 101, 32, 109, 117, 108, 116, 105, 112, 108, 101, 32, 101, 110, 116, 114, 105, 101, 115, 32, 
102, 111, 114, 32, 40, 109, 105, 100, 44, 102, 105, 100, 41, 32, 105, 102, 32, 116, 104, 101, 
32, 109, 105, 100, 32, 99, 104, 101, 99, 107, 45, 105, 110, 32, 119, 97, 115, 10, 45, 45, 
32, 97, 32, 109, 101, 114, 103, 101, 46, 32, 32, 69, 110, 116, 114, 105, 101, 115, 32, 119, 
105, 116, 104, 32, 105, 115, 97, 117, 120, 61, 61, 48, 32, 97, 114, 101, 32, 102, 114, 111, 
109, 32, 116, 104, 101, 32, 112, 114, 105, 109, 97, 114, 121, 32, 112, 97, 114, 101, 110, 116, 
46, 32, 32, 77, 101, 114, 103, 101, 10, 45, 45, 32, 112, 97, 114, 101, 110, 116, 115, 32, 
104, 97, 118, 101, 32, 105, 115, 97, 117, 120, 32, 115, 101, 116, 32, 116, 111, 32, 116, 114, 
117, 101, 46, 10, 45, 45, 10, 45, 45, 32, 70, 105, 101, 108, 100, 32, 110, 97, 109, 101, 
32, 109, 110, 101, 109, 111, 110, 105, 99, 115, 58, 10, 45, 45, 32, 32, 32, 32, 109, 105, 
100, 32, 61, 32, 77, 97, 110, 105, 102, 101, 115, 116, 32, 73, 68, 46, 32, 32, 40, 69, 
97, 99, 104, 32, 99, 104, 101, 99, 107, 45, 105, 110, 32, 105, 115, 32, 115, 116, 111, 114, 
101, 100, 32, 97, 115, 32, 97, 32, 34, 77, 97, 110, 105, 102, 101, 115, 116, 34, 41, 10, 
45, 45, 32, 32, 32, 32, 102, 105, 100, 32, 61, 32, 70, 105, 108, 101, 32, 73, 68, 46, 
10, 45, 45, 32, 32, 32, 32, 112, 109, 105, 100, 32, 61, 32, 80, 97, 114, 101, 110, 116, 
32, 77, 97, 110, 105, 102, 101, 115, 116, 32, 73, 68, 46, 10, 45, 45, 32, 32, 32, 32, 
112, 105, 100, 32, 61, 32, 80, 97, 114, 101, 110, 116, 32, 102, 105, 108, 101, 32, 73, 68, 
46, 10, 45, 45, 32, 32, 32, 32, 102, 110, 105, 100, 32, 61, 32, 70, 105, 108, 101, 32, 
78, 97, 109, 101, 32, 73, 68, 46, 10, 45, 45, 32, 32, 32, 32, 112, 102, 110, 105, 100, 
32, 61, 32, 80, 97, 114, 101, 110, 116, 32, 70, 105, 108, 101, 32, 78, 97, 109, 101, 32, 
73, 68, 46, 10, 45, 45, 32, 32, 32, 32, 105, 115, 97, 117, 120, 32, 61, 32, 112, 109, 
105, 100, 32, 73, 83, 32, 65, 85, 88, 105, 108, 105, 97, 114, 121, 32, 112, 97, 114, 101, 
110, 116, 44, 32, 110, 111, 116, 32, 112, 114, 105, 109, 97, 114, 121, 32, 112, 97, 114, 101, 
110, 116, 10, 45, 45, 10, 45, 45, 32, 112, 105, 100, 61, 61, 48, 32, 32, 32, 32, 105, 
102, 32, 116, 104, 101, 32, 102, 105, 108, 101, 32, 105, 115, 32, 97, 100, 100, 101, 100, 32, 
98, 121, 32, 99, 104, 101, 99, 107, 45, 105, 110, 32, 109, 105, 100, 46, 10, 45, 45, 32, 
112, 105, 100, 61, 61, 40, 45, 49, 41, 32, 105, 102, 32, 116, 104, 101, 32, 102, 105, 108, 
101, 32, 101, 120, 105, 115, 116, 115, 32, 105, 110, 32, 97, 32, 109, 101, 114, 103, 101, 32, 
112, 97, 114, 101, 110, 116, 115, 32, 98, 117, 116, 32, 110, 111, 116, 32, 105, 110, 32, 116, 
104, 101, 32, 112, 114, 105, 109, 97, 114, 121, 10, 45, 45, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 112, 97, 114, 101, 110, 116, 46, 32, 32, 73, 110, 32, 111, 116, 104, 101, 
114, 32, 119, 111, 114, 100, 115, 44, 32, 105, 102, 32, 116, 104, 101, 32, 102, 105, 108, 101, 
32, 102, 105, 108, 101, 32, 119, 97, 115, 32, 97, 100, 100, 101, 100, 32, 98, 121, 32, 109, 
101, 114, 103, 101, 46, 10, 45, 45, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 40, 
84, 79, 68, 79, 58, 32, 99, 111, 110, 102, 105, 114, 109, 32, 105, 102, 47, 119, 104, 101, 
114, 101, 32, 116, 104, 105, 115, 32, 105, 115, 32, 117, 115, 101, 100, 32, 105, 110, 32, 102, 
111, 115, 115, 105, 108, 32, 97, 110, 100, 32, 116, 104, 101, 110, 32, 109, 97, 107, 101, 32, 
115, 117, 114, 101, 10, 45, 45, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 108, 105, 
98, 102, 111, 115, 115, 105, 108, 32, 100, 111, 101, 115, 32, 115, 111, 44, 32, 116, 111, 111, 
46, 41, 10, 45, 45, 32, 102, 105, 100, 61, 61, 48, 32, 32, 32, 32, 105, 102, 32, 116, 
104, 101, 32, 102, 105, 108, 101, 32, 105, 115, 32, 114, 101, 109, 111, 118, 101, 100, 32, 98, 
121, 32, 99, 104, 101, 99, 107, 45, 105, 110, 32, 109, 105, 100, 46, 10, 45, 45, 10, 67, 
82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 
46, 114, 101, 112, 111, 125, 125, 46, 109, 108, 105, 110, 107, 40, 10, 32, 32, 109, 105, 100, 
32, 73, 78, 84, 69, 71, 69, 82, 44, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 
67, 104, 101, 99, 107, 45, 105, 110, 32, 116, 104, 97, 116, 32, 99, 111, 110, 116, 97, 105, 
110, 115, 32, 102, 105, 100, 10, 32, 32, 102, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 
44, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 78, 101, 119, 32, 102, 105, 108, 101, 
32, 99, 111, 110, 116, 101, 110, 116, 32, 82, 73, 68, 46, 32, 48, 32, 105, 102, 32, 100, 
101, 108, 101, 116, 101, 100, 10, 32, 32, 112, 109, 105, 100, 32, 73, 78, 84, 69, 71, 69, 
82, 44, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 67, 104, 101, 99, 107, 45, 105, 110, 
32, 82, 73, 68, 32, 116, 104, 97, 116, 32, 99, 111, 110, 116, 97, 105, 110, 115, 32, 112, 
105, 100, 10, 32, 32, 112, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 44, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 80, 114, 101, 118, 32, 102, 105, 108, 101, 32, 99, 111, 
110, 116, 101, 110, 116, 32, 82, 73, 68, 46, 32, 48, 32, 105, 102, 32, 110, 101, 119, 46, 
32, 45, 49, 32, 105, 102, 32, 102, 114, 111, 109, 32, 97, 32, 109, 101, 114, 103, 101, 10, 
32, 32, 102, 110, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 82, 69, 70, 69, 82, 
69, 78, 67, 69, 83, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 102, 105, 
108, 101, 110, 97, 109, 101, 125, 125, 44, 32, 32, 32, 45, 45, 32, 78, 97, 109, 101, 32, 
111, 102, 32, 116, 104, 101, 32, 102, 105, 108, 101, 10, 32, 32, 112, 102, 110, 105, 100, 32, 
73, 78, 84, 69, 71, 69, 82, 44, 32, 32, 32, 32, 32, 32, 45, 45, 32, 80, 114, 101, 
118, 105, 111, 117, 115, 32, 110, 97, 109, 101, 46, 32, 48, 32, 105, 102, 32, 117, 110, 99, 
104, 97, 110, 103, 101, 100, 10, 32, 32, 109, 112, 101, 114, 109, 32, 73, 78, 84, 69, 71, 
69, 82, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 70, 105, 108, 101, 32, 112, 101, 114, 109, 105, 115, 115, 
105, 111, 110, 115, 46, 32, 32, 49, 61, 61, 101, 120, 101, 99, 10, 32, 32, 105, 115, 97, 
117, 120, 32, 66, 79, 79, 76, 69, 65, 78, 32, 68, 69, 70, 65, 85, 76, 84, 32, 48, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 84, 82, 85, 69, 
32, 105, 102, 32, 112, 109, 105, 100, 32, 105, 115, 32, 116, 104, 101, 32, 112, 114, 105, 109, 
97, 114, 121, 10, 41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 73, 78, 68, 69, 88, 32, 
123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 109, 108, 105, 110, 
107, 95, 105, 49, 32, 79, 78, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 
109, 108, 105, 110, 107, 125, 125, 40, 109, 105, 100, 41, 59, 10, 67, 82, 69, 65, 84, 69, 
32, 73, 78, 68, 69, 88, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 
125, 125, 46, 109, 108, 105, 110, 107, 95, 105, 50, 32, 79, 78, 32, 123, 123, 98, 97, 114, 
101, 46, 114, 101, 112, 111, 46, 109, 108, 105, 110, 107, 125, 125, 40, 102, 110, 105, 100, 41, 
59, 10, 67, 82, 69, 65, 84, 69, 32, 73, 78, 68, 69, 88, 32, 123, 123, 100, 98, 110, 
97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 109, 108, 105, 110, 107, 95, 105, 51, 32, 
79, 78, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 109, 108, 105, 110, 107, 
125, 125, 40, 102, 105, 100, 41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 73, 78, 68, 69, 
88, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 109, 108, 
105, 110, 107, 95, 105, 52, 32, 79, 78, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 
111, 46, 109, 108, 105, 110, 107, 125, 125, 40, 112, 105, 100, 41, 59, 10, 10, 45, 45, 32, 
80, 97, 114, 101, 110, 116, 47, 99, 104, 105, 108, 100, 32, 108, 105, 110, 107, 97, 103, 101, 
115, 32, 98, 101, 116, 119, 101, 101, 110, 32, 99, 104, 101, 99, 107, 105, 110, 115, 10, 45, 
45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 
97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 112, 108, 105, 110, 107, 40, 10, 32, 32, 
112, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 82, 69, 70, 69, 82, 69, 78, 67, 
69, 83, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 98, 108, 111, 98, 125, 
125, 44, 32, 32, 32, 32, 45, 45, 32, 80, 97, 114, 101, 110, 116, 32, 109, 97, 110, 105, 
102, 101, 115, 116, 10, 32, 32, 99, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 82, 
69, 70, 69, 82, 69, 78, 67, 69, 83, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 
111, 46, 98, 108, 111, 98, 125, 125, 44, 32, 32, 32, 32, 45, 45, 32, 67, 104, 105, 108, 
100, 32, 109, 97, 110, 105, 102, 101, 115, 116, 10, 32, 32, 105, 115, 112, 114, 105, 109, 32, 
66, 79, 79, 76, 69, 65, 78, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 112, 105, 100, 32, 105, 115, 32, 116, 104, 101, 32, 112, 
114, 105, 109, 97, 114, 121, 32, 112, 97, 114, 101, 110, 116, 32, 111, 102, 32, 99, 105, 100, 
10, 32, 32, 109, 116, 105, 109, 101, 32, 68, 65, 84, 69, 84, 73, 77, 69, 44, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 116, 104, 
101, 32, 100, 97, 116, 101, 47, 116, 105, 109, 101, 32, 115, 116, 97, 109, 112, 32, 111, 110, 
32, 99, 105, 100, 46, 32, 32, 74, 117, 108, 105, 97, 110, 32, 100, 97, 121, 46, 10, 32, 
32, 98, 97, 115, 101, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 82, 69, 70, 69, 
82, 69, 78, 67, 69, 83, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 98, 
108, 111, 98, 125, 125, 44, 32, 45, 45, 32, 66, 97, 115, 101, 108, 105, 110, 101, 32, 105, 
102, 32, 99, 105, 100, 32, 105, 115, 32, 97, 32, 100, 101, 108, 116, 97, 32, 109, 97, 110, 
105, 102, 101, 115, 116, 46, 10, 32, 32, 85, 78, 73, 81, 85, 69, 40, 112, 105, 100, 44, 
32, 99, 105, 100, 41, 10, 41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 73, 78, 68, 69, 
88, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 112, 108, 
105, 110, 107, 95, 105, 50, 32, 79, 78, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 
111, 46, 112, 108, 105, 110, 107, 125, 125, 40, 99, 105, 100, 44, 112, 105, 100, 41, 59, 10, 
10, 45, 45, 32, 65, 32, 34, 108, 101, 97, 102, 34, 32, 99, 104, 101, 99, 107, 105, 110, 
32, 105, 115, 32, 97, 32, 99, 104, 101, 99, 107, 105, 110, 32, 116, 104, 97, 116, 32, 104, 
97, 115, 32, 110, 111, 32, 99, 104, 105, 108, 100, 114, 101, 110, 32, 105, 110, 32, 116, 104, 
101, 32, 115, 97, 109, 101, 10, 45, 45, 32, 98, 114, 97, 110, 99, 104, 46, 32, 32, 84, 
104, 101, 32, 115, 101, 116, 32, 111, 102, 32, 97, 108, 108, 32, 108, 101, 97, 118, 101, 115, 
32, 105, 115, 32, 101, 97, 115, 105, 108, 121, 32, 99, 111, 109, 112, 117, 116, 101, 100, 32, 
119, 105, 116, 104, 32, 97, 32, 106, 111, 105, 110, 44, 10, 45, 45, 32, 98, 101, 116, 119, 
101, 101, 110, 32, 116, 104, 101, 32, 112, 108, 105, 110, 107, 32, 97, 110, 100, 32, 116, 97, 
103, 120, 114, 101, 102, 32, 116, 97, 98, 108, 101, 115, 44, 32, 98, 117, 116, 32, 105, 116, 
32, 105, 115, 32, 97, 32, 115, 108, 111, 119, 101, 114, 32, 106, 111, 105, 110, 32, 102, 111, 
114, 10, 45, 45, 32, 118, 101, 114, 121, 32, 108, 97, 114, 103, 101, 32, 114, 101, 112, 111, 
115, 105, 116, 111, 114, 105, 101, 115, 32, 40, 114, 101, 112, 111, 115, 105, 116, 111, 114, 105, 
101, 115, 32, 119, 105, 116, 104, 32, 49, 48, 48, 44, 48, 48, 48, 32, 111, 114, 32, 109, 
111, 114, 101, 32, 99, 104, 101, 99, 107, 105, 110, 115, 41, 10, 45, 45, 32, 97, 110, 100, 
32, 115, 111, 32, 105, 116, 32, 109, 97, 107, 101, 115, 32, 115, 101, 110, 115, 101, 32, 116, 
111, 32, 112, 114, 101, 99, 111, 109, 112, 117, 116, 101, 32, 116, 104, 101, 32, 115, 101, 116, 
32, 111, 102, 32, 108, 101, 97, 118, 101, 115, 46, 32, 32, 84, 104, 101, 114, 101, 32, 105, 
115, 10, 45, 45, 32, 111, 110, 101, 32, 101, 110, 116, 114, 121, 32, 105, 110, 32, 116, 104, 
101, 32, 102, 111, 108, 108, 111, 119, 105, 110, 103, 32, 116, 97, 98, 108, 101, 32, 102, 111, 
114, 32, 101, 97, 99, 104, 32, 108, 101, 97, 102, 46, 10, 45, 45, 10, 67, 82, 69, 65, 
84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 
112, 111, 125, 125, 46, 108, 101, 97, 102, 40, 114, 105, 100, 32, 73, 78, 84, 69, 71, 69, 
82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 41, 59, 10, 10, 45, 45, 32, 
69, 118, 101, 110, 116, 115, 32, 117, 115, 101, 100, 32, 116, 111, 32, 103, 101, 110, 101, 114, 
97, 116, 101, 32, 97, 32, 116, 105, 109, 101, 108, 105, 110, 101, 10, 45, 45, 10, 67, 82, 
69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 
114, 101, 112, 111, 125, 125, 46, 101, 118, 101, 110, 116, 40, 10, 32, 32, 116, 121, 112, 101, 
32, 84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 84, 121, 112, 101, 32, 111, 102, 32, 101, 
118, 101, 110, 116, 58, 32, 39, 99, 105, 39, 44, 32, 39, 119, 39, 44, 32, 39, 101, 39, 
44, 32, 39, 116, 39, 44, 32, 39, 103, 39, 10, 32, 32, 109, 116, 105, 109, 101, 32, 68, 
65, 84, 69, 84, 73, 77, 69, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 84, 105, 109, 101, 32, 111, 102, 32, 111, 99, 99, 117, 
114, 114, 101, 110, 99, 101, 46, 32, 74, 117, 108, 105, 97, 110, 32, 100, 97, 121, 46, 10, 
32, 32, 111, 98, 106, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 
65, 82, 89, 32, 75, 69, 89, 44, 32, 32, 32, 32, 32, 32, 45, 45, 32, 65, 115, 115, 
111, 99, 105, 97, 116, 101, 100, 32, 114, 101, 99, 111, 114, 100, 32, 73, 68, 10, 32, 32, 
116, 97, 103, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 44, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 65, 115, 115, 111, 99, 
105, 97, 116, 101, 100, 32, 116, 105, 99, 107, 101, 116, 32, 111, 114, 32, 119, 105, 107, 105, 
32, 110, 97, 109, 101, 32, 116, 97, 103, 10, 32, 32, 117, 105, 100, 32, 73, 78, 84, 69, 
71, 69, 82, 32, 82, 69, 70, 69, 82, 69, 78, 67, 69, 83, 32, 123, 123, 98, 97, 114, 
101, 46, 114, 101, 112, 111, 46, 117, 115, 101, 114, 125, 125, 44, 32, 32, 32, 32, 45, 45, 
32, 85, 115, 101, 114, 32, 119, 104, 111, 32, 99, 97, 117, 115, 101, 100, 32, 116, 104, 101, 
32, 101, 118, 101, 110, 116, 10, 32, 32, 98, 103, 99, 111, 108, 111, 114, 32, 84, 69, 88, 
84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 45, 45, 32, 67, 111, 108, 111, 114, 32, 115, 101, 116, 32, 98, 121, 32, 39, 98, 103, 
99, 111, 108, 111, 114, 39, 32, 112, 114, 111, 112, 101, 114, 116, 121, 10, 32, 32, 101, 117, 
115, 101, 114, 32, 84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 85, 115, 101, 114, 32, 115, 101, 
116, 32, 98, 121, 32, 39, 117, 115, 101, 114, 39, 32, 112, 114, 111, 112, 101, 114, 116, 121, 
10, 32, 32, 117, 115, 101, 114, 32, 84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 78, 97, 
109, 101, 32, 111, 102, 32, 116, 104, 101, 32, 117, 115, 101, 114, 10, 32, 32, 101, 99, 111, 
109, 109, 101, 110, 116, 32, 84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 67, 111, 109, 109, 101, 110, 116, 32, 
115, 101, 116, 32, 98, 121, 32, 39, 99, 111, 109, 109, 101, 110, 116, 39, 32, 112, 114, 111, 
112, 101, 114, 116, 121, 10, 32, 32, 99, 111, 109, 109, 101, 110, 116, 32, 84, 69, 88, 84, 
44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
45, 45, 32, 67, 111, 109, 109, 101, 110, 116, 32, 100, 101, 115, 99, 114, 105, 98, 105, 110, 
103, 32, 116, 104, 101, 32, 101, 118, 101, 110, 116, 10, 32, 32, 98, 114, 105, 101, 102, 32, 
84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 45, 45, 32, 83, 104, 111, 114, 116, 32, 99, 111, 109, 109, 101, 
110, 116, 32, 119, 104, 101, 110, 32, 116, 97, 103, 105, 100, 32, 97, 108, 114, 101, 97, 100, 
121, 32, 115, 101, 101, 110, 10, 32, 32, 111, 109, 116, 105, 109, 101, 32, 68, 65, 84, 69, 
84, 73, 77, 69, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 45, 45, 32, 79, 114, 105, 103, 105, 110, 97, 108, 32, 117, 110, 99, 104, 97, 110, 103, 
101, 100, 32, 100, 97, 116, 101, 43, 116, 105, 109, 101, 44, 32, 111, 114, 32, 78, 85, 76, 
76, 10, 41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 73, 78, 68, 69, 88, 32, 123, 123, 
100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 101, 118, 101, 110, 116, 95, 
105, 49, 32, 79, 78, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 101, 118, 
101, 110, 116, 125, 125, 40, 109, 116, 105, 109, 101, 41, 59, 10, 10, 45, 45, 32, 65, 32, 
114, 101, 99, 111, 114, 100, 32, 111, 102, 32, 112, 104, 97, 110, 116, 111, 109, 115, 46, 32, 
32, 65, 32, 112, 104, 97, 110, 116, 111, 109, 32, 105, 115, 32, 97, 32, 114, 101, 99, 111, 
114, 100, 32, 102, 111, 114, 32, 119, 104, 105, 99, 104, 32, 119, 101, 32, 107, 110, 111, 119, 
32, 116, 104, 101, 10, 45, 45, 32, 85, 85, 73, 68, 32, 98, 117, 116, 32, 119, 101, 32, 
100, 111, 32, 110, 111, 116, 32, 40, 121, 101, 116, 41, 32, 107, 110, 111, 119, 32, 116, 104, 
101, 32, 102, 105, 108, 101, 32, 99, 111, 110, 116, 101, 110, 116, 46, 10, 45, 45, 10, 67, 
82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 
46, 114, 101, 112, 111, 125, 125, 46, 112, 104, 97, 110, 116, 111, 109, 40, 10, 32, 32, 114, 
105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 
69, 89, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 82, 101, 99, 111, 114, 100, 
32, 73, 68, 32, 111, 102, 32, 116, 104, 101, 32, 112, 104, 97, 110, 116, 111, 109, 10, 41, 
59, 10, 10, 45, 45, 32, 65, 32, 114, 101, 99, 111, 114, 100, 32, 111, 102, 32, 111, 114, 
112, 104, 97, 110, 101, 100, 32, 100, 101, 108, 116, 97, 45, 109, 97, 110, 105, 102, 101, 115, 
116, 115, 46, 32, 32, 65, 110, 32, 111, 114, 112, 104, 97, 110, 32, 105, 115, 32, 97, 32, 
100, 101, 108, 116, 97, 45, 109, 97, 110, 105, 102, 101, 115, 116, 10, 45, 45, 32, 102, 111, 
114, 32, 119, 104, 105, 99, 104, 32, 119, 101, 32, 104, 97, 118, 101, 32, 99, 111, 110, 116, 
101, 110, 116, 44, 32, 98, 117, 116, 32, 105, 116, 115, 32, 98, 97, 115, 101, 108, 105, 110, 
101, 45, 109, 97, 110, 105, 102, 101, 115, 116, 32, 105, 115, 32, 97, 32, 112, 104, 97, 110, 
116, 111, 109, 46, 10, 45, 45, 32, 87, 101, 32, 104, 97, 118, 101, 32, 116, 111, 32, 116, 
114, 97, 99, 107, 32, 97, 108, 108, 32, 111, 114, 112, 104, 97, 110, 32, 109, 97, 110, 105, 
102, 101, 115, 116, 115, 32, 115, 111, 32, 116, 104, 97, 116, 32, 119, 104, 101, 110, 32, 116, 
104, 101, 32, 98, 97, 115, 101, 108, 105, 110, 101, 32, 97, 114, 114, 105, 118, 101, 115, 44, 
10, 45, 45, 32, 119, 101, 32, 107, 110, 111, 119, 32, 116, 111, 32, 112, 114, 111, 99, 101, 
115, 115, 32, 116, 104, 101, 32, 111, 114, 112, 104, 97, 110, 101, 100, 32, 100, 101, 108, 116, 
97, 115, 46, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 
98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 111, 114, 112, 104, 97, 110, 40, 
10, 32, 32, 114, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 
82, 89, 32, 75, 69, 89, 44, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 68, 101, 
108, 116, 97, 32, 109, 97, 110, 105, 102, 101, 115, 116, 32, 119, 105, 116, 104, 32, 97, 32, 
112, 104, 97, 110, 116, 111, 109, 32, 98, 97, 115, 101, 108, 105, 110, 101, 10, 32, 32, 98, 
97, 115, 101, 108, 105, 110, 101, 32, 73, 78, 84, 69, 71, 69, 82, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 80, 104, 97, 110, 116, 111, 
109, 32, 98, 97, 115, 101, 108, 105, 110, 101, 32, 111, 102, 32, 116, 104, 105, 115, 32, 111, 
114, 112, 104, 97, 110, 10, 41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 73, 78, 68, 69, 
88, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 111, 114, 
112, 104, 97, 110, 95, 98, 97, 115, 101, 108, 105, 110, 101, 32, 79, 78, 32, 123, 123, 98, 
97, 114, 101, 46, 114, 101, 112, 111, 46, 111, 114, 112, 104, 97, 110, 125, 125, 40, 98, 97, 
115, 101, 108, 105, 110, 101, 41, 59, 10, 10, 45, 45, 32, 85, 110, 99, 108, 117, 115, 116, 
101, 114, 101, 100, 32, 114, 101, 99, 111, 114, 100, 115, 46, 32, 32, 65, 110, 32, 117, 110, 
99, 108, 117, 115, 116, 101, 114, 101, 100, 32, 114, 101, 99, 111, 114, 100, 32, 105, 115, 32, 
97, 32, 114, 101, 99, 111, 114, 100, 32, 40, 105, 110, 99, 108, 117, 100, 105, 110, 103, 10, 
45, 45, 32, 97, 32, 99, 108, 117, 115, 116, 101, 114, 32, 114, 101, 99, 111, 114, 100, 115, 
32, 116, 104, 101, 109, 115, 101, 108, 118, 101, 115, 41, 32, 116, 104, 97, 116, 32, 105, 115, 
32, 110, 111, 116, 32, 109, 101, 110, 116, 105, 111, 110, 101, 100, 32, 98, 121, 32, 115, 111, 
109, 101, 32, 111, 116, 104, 101, 114, 10, 45, 45, 32, 99, 108, 117, 115, 116, 101, 114, 46, 
10, 45, 45, 10, 45, 45, 32, 80, 104, 97, 110, 116, 111, 109, 115, 32, 97, 114, 101, 32, 
117, 115, 117, 97, 108, 108, 121, 32, 105, 110, 99, 108, 117, 100, 101, 100, 32, 105, 110, 32, 
116, 104, 101, 32, 117, 110, 99, 108, 117, 115, 116, 101, 114, 101, 100, 32, 116, 97, 98, 108, 
101, 46, 32, 32, 65, 32, 110, 101, 119, 32, 99, 108, 117, 115, 116, 101, 114, 10, 45, 45, 
32, 119, 105, 108, 108, 32, 110, 101, 118, 101, 114, 32, 98, 101, 32, 99, 114, 101, 97, 116, 
101, 100, 32, 116, 104, 97, 116, 32, 99, 111, 110, 116, 97, 105, 110, 115, 32, 97, 32, 112, 
104, 97, 110, 116, 111, 109, 46, 32, 32, 66, 117, 116, 32, 97, 110, 111, 116, 104, 101, 114, 
32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 10, 45, 45, 32, 109, 105, 103, 104, 116, 
32, 115, 101, 110, 100, 32, 117, 115, 32, 97, 32, 99, 108, 117, 115, 116, 101, 114, 32, 116, 
104, 97, 116, 32, 99, 111, 110, 116, 97, 105, 110, 115, 32, 101, 110, 116, 114, 105, 101, 115, 
32, 116, 104, 97, 116, 32, 97, 114, 101, 32, 112, 104, 97, 110, 116, 111, 109, 115, 32, 116, 
111, 10, 45, 45, 32, 117, 115, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 
65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 
46, 117, 110, 99, 108, 117, 115, 116, 101, 114, 101, 100, 40, 10, 32, 32, 114, 105, 100, 32, 
73, 78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 82, 101, 99, 111, 114, 100, 32, 73, 68, 
32, 111, 102, 32, 116, 104, 101, 32, 117, 110, 99, 108, 117, 115, 116, 101, 114, 101, 100, 32, 
102, 105, 108, 101, 10, 41, 59, 10, 10, 45, 45, 32, 82, 101, 99, 111, 114, 100, 115, 32, 
119, 104, 105, 99, 104, 32, 104, 97, 118, 101, 32, 110, 101, 118, 101, 114, 32, 98, 101, 101, 
110, 32, 112, 117, 115, 104, 101, 100, 32, 116, 111, 32, 97, 110, 111, 116, 104, 101, 114, 32, 
115, 101, 114, 118, 101, 114, 46, 32, 32, 84, 104, 105, 115, 32, 105, 115, 10, 45, 45, 32, 
117, 115, 101, 100, 32, 116, 111, 32, 114, 101, 100, 117, 99, 101, 32, 112, 117, 115, 104, 32, 
111, 112, 101, 114, 97, 116, 105, 111, 110, 115, 32, 116, 111, 32, 97, 32, 115, 105, 110, 103, 
108, 101, 32, 72, 84, 84, 80, 32, 114, 101, 113, 117, 101, 115, 116, 32, 105, 110, 32, 116, 
104, 101, 10, 45, 45, 32, 99, 111, 109, 109, 111, 110, 32, 99, 97, 115, 101, 32, 119, 104, 
101, 110, 32, 111, 110, 101, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 32, 111, 110, 
108, 121, 32, 116, 97, 108, 107, 115, 32, 116, 111, 32, 97, 32, 115, 105, 110, 103, 108, 101, 
32, 115, 101, 114, 118, 101, 114, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 
65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 
46, 117, 110, 115, 101, 110, 116, 40, 10, 32, 32, 114, 105, 100, 32, 73, 78, 84, 69, 71, 
69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 45, 45, 32, 82, 101, 99, 111, 114, 100, 32, 73, 68, 32, 111, 102, 32, 116, 
104, 101, 32, 112, 104, 97, 110, 116, 111, 109, 10, 41, 59, 10, 10, 45, 45, 32, 69, 97, 
99, 104, 32, 98, 97, 115, 101, 108, 105, 110, 101, 32, 111, 114, 32, 109, 97, 110, 105, 102, 
101, 115, 116, 32, 99, 97, 110, 32, 104, 97, 118, 101, 32, 111, 110, 101, 32, 111, 114, 32, 
109, 111, 114, 101, 32, 116, 97, 103, 115, 46, 32, 32, 65, 32, 116, 97, 103, 10, 45, 45, 
32, 105, 115, 32, 100, 101, 102, 105, 110, 101, 100, 32, 98, 121, 32, 97, 32, 114, 111, 119, 
32, 105, 110, 32, 116, 104, 101, 32, 110, 101, 120, 116, 32, 116, 97, 98, 108, 101, 46, 10, 
45, 45, 10, 45, 45, 32, 87, 105, 107, 105, 32, 112, 97, 103, 101, 115, 32, 97, 114, 101, 
32, 116, 97, 103, 103, 101, 100, 32, 119, 105, 116, 104, 32, 34, 119, 105, 107, 105, 45, 78, 
65, 77, 69, 34, 32, 119, 104, 101, 114, 101, 32, 78, 65, 77, 69, 32, 105, 115, 32, 116, 
104, 101, 32, 110, 97, 109, 101, 32, 111, 102, 10, 45, 45, 32, 116, 104, 101, 32, 119, 105, 
107, 105, 32, 112, 97, 103, 101, 46, 32, 32, 84, 105, 99, 107, 101, 116, 115, 32, 99, 104, 
97, 110, 103, 101, 115, 32, 97, 114, 101, 32, 116, 97, 103, 103, 101, 100, 32, 119, 105, 116, 
104, 32, 34, 116, 105, 99, 107, 101, 116, 45, 85, 85, 73, 68, 34, 32, 119, 104, 101, 114, 
101, 10, 45, 45, 32, 85, 85, 73, 68, 32, 105, 115, 32, 116, 104, 101, 32, 105, 110, 100, 
101, 110, 116, 105, 102, 105, 101, 114, 32, 111, 102, 32, 116, 104, 101, 32, 116, 105, 99, 107, 
101, 116, 46, 32, 32, 84, 97, 103, 115, 32, 117, 115, 101, 100, 32, 116, 111, 32, 97, 115, 
115, 105, 103, 110, 32, 115, 121, 109, 98, 111, 108, 105, 99, 10, 45, 45, 32, 110, 97, 109, 
101, 115, 32, 116, 111, 32, 98, 97, 115, 101, 108, 105, 110, 101, 115, 32, 97, 114, 101, 32, 
98, 114, 97, 110, 99, 104, 101, 115, 32, 97, 114, 101, 32, 111, 102, 32, 116, 104, 101, 32, 
102, 111, 114, 109, 32, 34, 115, 121, 109, 45, 78, 65, 77, 69, 34, 32, 119, 104, 101, 114, 
101, 10, 45, 45, 32, 78, 65, 77, 69, 32, 105, 115, 32, 116, 104, 101, 32, 115, 121, 109, 
98, 111, 108, 105, 99, 32, 110, 97, 109, 101, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 
69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 
111, 125, 125, 46, 116, 97, 103, 40, 10, 32, 32, 116, 97, 103, 105, 100, 32, 73, 78, 84, 
69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 44, 32, 32, 32, 
32, 32, 32, 32, 45, 45, 32, 78, 117, 109, 101, 114, 105, 99, 32, 116, 97, 103, 32, 73, 
68, 10, 32, 32, 116, 97, 103, 110, 97, 109, 101, 32, 84, 69, 88, 84, 32, 85, 78, 73, 
81, 85, 69, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 
84, 97, 103, 32, 110, 97, 109, 101, 46, 10, 41, 59, 10, 73, 78, 83, 69, 82, 84, 32, 
73, 78, 84, 79, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 
46, 116, 97, 103, 32, 86, 65, 76, 85, 69, 83, 40, 49, 44, 32, 39, 98, 103, 99, 111, 
108, 111, 114, 39, 41, 59, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 70, 83, 
76, 95, 84, 65, 71, 73, 68, 95, 66, 71, 67, 79, 76, 79, 82, 10, 73, 78, 83, 69, 
82, 84, 32, 73, 78, 84, 79, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 
111, 125, 125, 46, 116, 97, 103, 32, 86, 65, 76, 85, 69, 83, 40, 50, 44, 32, 39, 99, 
111, 109, 109, 101, 110, 116, 39, 41, 59, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 
32, 70, 83, 76, 95, 84, 65, 71, 73, 68, 95, 67, 79, 77, 77, 69, 78, 84, 10, 73, 
78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 
114, 101, 112, 111, 125, 125, 46, 116, 97, 103, 32, 86, 65, 76, 85, 69, 83, 40, 51, 44, 
32, 39, 117, 115, 101, 114, 39, 41, 59, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 45, 45, 32, 70, 83, 76, 95, 84, 65, 71, 73, 68, 95, 85, 83, 69, 82, 10, 73, 
78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 
114, 101, 112, 111, 125, 125, 46, 116, 97, 103, 32, 86, 65, 76, 85, 69, 83, 40, 52, 44, 
32, 39, 100, 97, 116, 101, 39, 41, 59, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 45, 45, 32, 70, 83, 76, 95, 84, 65, 71, 73, 68, 95, 68, 65, 84, 69, 10, 73, 
78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 
114, 101, 112, 111, 125, 125, 46, 116, 97, 103, 32, 86, 65, 76, 85, 69, 83, 40, 53, 44, 
32, 39, 104, 105, 100, 100, 101, 110, 39, 41, 59, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 45, 45, 32, 70, 83, 76, 95, 84, 65, 71, 73, 68, 95, 72, 73, 68, 68, 69, 78, 
10, 73, 78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 32, 123, 123, 100, 98, 110, 97, 109, 
101, 46, 114, 101, 112, 111, 125, 125, 46, 116, 97, 103, 32, 86, 65, 76, 85, 69, 83, 40, 
54, 44, 32, 39, 112, 114, 105, 118, 97, 116, 101, 39, 41, 59, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 45, 45, 32, 70, 83, 76, 95, 84, 65, 71, 73, 68, 95, 80, 82, 73, 86, 
65, 84, 69, 10, 73, 78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 32, 123, 123, 100, 98, 
110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 116, 97, 103, 32, 86, 65, 76, 85, 
69, 83, 40, 55, 44, 32, 39, 99, 108, 117, 115, 116, 101, 114, 39, 41, 59, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 45, 45, 32, 70, 83, 76, 95, 84, 65, 71, 73, 68, 95, 67, 
76, 85, 83, 84, 69, 82, 10, 73, 78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 32, 123, 
123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 116, 97, 103, 32, 86, 
65, 76, 85, 69, 83, 40, 56, 44, 32, 39, 98, 114, 97, 110, 99, 104, 39, 41, 59, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 70, 83, 76, 95, 84, 65, 71, 73, 
68, 95, 66, 82, 65, 78, 67, 72, 10, 73, 78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 
32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 116, 97, 103, 
32, 86, 65, 76, 85, 69, 83, 40, 57, 44, 32, 39, 99, 108, 111, 115, 101, 100, 39, 41, 
59, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 70, 83, 76, 95, 84, 65, 
71, 73, 68, 95, 67, 76, 79, 83, 69, 68, 10, 73, 78, 83, 69, 82, 84, 32, 73, 78, 
84, 79, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 116, 
97, 103, 32, 86, 65, 76, 85, 69, 83, 40, 49, 48, 44, 39, 112, 97, 114, 101, 110, 116, 
39, 41, 59, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 70, 83, 76, 95, 
84, 65, 71, 73, 68, 95, 80, 65, 82, 69, 78, 84, 10, 73, 78, 83, 69, 82, 84, 32, 
73, 78, 84, 79, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 
46, 116, 97, 103, 32, 86, 65, 76, 85, 69, 83, 40, 49, 49, 44, 39, 110, 111, 116, 101, 
39, 41, 59, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 70, 83, 
76, 95, 84, 65, 71, 95, 78, 79, 84, 69, 10, 45, 45, 32, 97, 114, 103, 117, 97, 98, 
108, 101, 44, 32, 116, 111, 32, 102, 111, 114, 99, 101, 32, 97, 117, 116, 111, 45, 105, 110, 
99, 114, 101, 109, 101, 110, 116, 32, 116, 111, 32, 115, 116, 97, 114, 116, 32, 97, 116, 32, 
49, 48, 48, 58, 10, 45, 45, 32, 73, 78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 32, 
116, 97, 103, 32, 86, 65, 76, 85, 69, 83, 40, 57, 57, 44, 39, 70, 83, 76, 95, 84, 
65, 71, 73, 68, 95, 77, 65, 88, 95, 73, 78, 84, 69, 82, 78, 65, 76, 39, 41, 59, 
10, 10, 45, 45, 32, 65, 115, 115, 105, 103, 110, 109, 101, 110, 116, 115, 32, 111, 102, 32, 
116, 97, 103, 115, 32, 116, 111, 32, 98, 97, 115, 101, 108, 105, 110, 101, 115, 46, 32, 32, 
78, 111, 116, 101, 32, 116, 104, 97, 116, 32, 119, 101, 32, 97, 108, 108, 111, 119, 32, 116, 
97, 103, 115, 32, 116, 111, 10, 45, 45, 32, 104, 97, 118, 101, 32, 118, 97, 108, 117, 101, 
115, 32, 97, 115, 115, 105, 103, 110, 101, 100, 32, 116, 111, 32, 116, 104, 101, 109, 46, 32, 
32, 83, 111, 32, 119, 101, 32, 97, 114, 101, 32, 110, 111, 116, 32, 114, 101, 97, 108, 108, 
121, 32, 100, 101, 97, 108, 105, 110, 103, 32, 119, 105, 116, 104, 10, 45, 45, 32, 116, 97, 
103, 115, 32, 104, 101, 114, 101, 46, 32, 32, 84, 104, 101, 115, 101, 32, 97, 114, 101, 32, 
114, 101, 97, 108, 108, 121, 32, 112, 114, 111, 112, 101, 114, 116, 105, 101, 115, 46, 32, 32, 
66, 117, 116, 32, 119, 101, 32, 97, 114, 101, 32, 103, 111, 105, 110, 103, 32, 116, 111, 10, 
45, 45, 32, 107, 101, 101, 112, 32, 99, 97, 108, 108, 105, 110, 103, 32, 116, 104, 101, 109, 
32, 116, 97, 103, 115, 32, 98, 101, 99, 97, 117, 115, 101, 32, 105, 110, 32, 109, 97, 110, 
121, 32, 99, 97, 115, 101, 115, 32, 116, 104, 101, 32, 118, 97, 108, 117, 101, 32, 105, 115, 
32, 105, 103, 110, 111, 114, 101, 100, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 
84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 
125, 46, 116, 97, 103, 120, 114, 101, 102, 40, 10, 32, 32, 116, 97, 103, 105, 100, 32, 73, 
78, 84, 69, 71, 69, 82, 32, 82, 69, 70, 69, 82, 69, 78, 67, 69, 83, 32, 123, 123, 
98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 116, 97, 103, 125, 125, 44, 32, 32, 32, 45, 
45, 32, 84, 104, 101, 32, 116, 97, 103, 32, 116, 104, 97, 116, 32, 119, 97, 115, 32, 97, 
100, 100, 101, 100, 32, 111, 114, 32, 114, 101, 109, 111, 118, 101, 100, 10, 32, 32, 116, 97, 
103, 116, 121, 112, 101, 32, 73, 78, 84, 69, 71, 69, 82, 44, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 48, 58, 45, 44, 99, 97, 110, 
99, 101, 108, 32, 32, 49, 58, 43, 44, 115, 105, 110, 103, 108, 101, 32, 32, 50, 58, 42, 
44, 112, 114, 111, 112, 97, 103, 97, 116, 101, 10, 32, 32, 115, 114, 99, 105, 100, 32, 73, 
78, 84, 69, 71, 69, 82, 32, 82, 69, 70, 69, 82, 69, 78, 67, 69, 83, 32, 123, 123, 
98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 98, 108, 111, 98, 125, 125, 44, 32, 32, 45, 
45, 32, 65, 114, 116, 105, 102, 97, 99, 116, 32, 111, 102, 32, 116, 97, 103, 46, 32, 48, 
32, 102, 111, 114, 32, 112, 114, 111, 112, 97, 103, 97, 116, 101, 100, 32, 116, 97, 103, 115, 
10, 32, 32, 111, 114, 105, 103, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 82, 69, 
70, 69, 82, 69, 78, 67, 69, 83, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 
46, 98, 108, 111, 98, 125, 125, 44, 32, 45, 45, 32, 99, 104, 101, 99, 107, 45, 105, 110, 
32, 104, 111, 108, 100, 105, 110, 103, 32, 112, 114, 111, 112, 97, 103, 97, 116, 101, 100, 32, 
116, 97, 103, 10, 32, 32, 118, 97, 108, 117, 101, 32, 84, 69, 88, 84, 44, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 
32, 86, 97, 108, 117, 101, 32, 111, 102, 32, 116, 104, 101, 32, 116, 97, 103, 46, 32, 32, 
77, 105, 103, 104, 116, 32, 98, 101, 32, 78, 85, 76, 76, 46, 10, 32, 32, 109, 116, 105, 
109, 101, 32, 84, 73, 77, 69, 83, 84, 65, 77, 80, 44, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 84, 105, 109, 101, 32, 111, 102, 32, 
97, 100, 100, 105, 116, 105, 111, 110, 32, 111, 114, 32, 114, 101, 109, 111, 118, 97, 108, 46, 
32, 74, 117, 108, 105, 97, 110, 32, 100, 97, 121, 10, 32, 32, 114, 105, 100, 32, 73, 78, 
84, 69, 71, 69, 82, 32, 82, 69, 70, 69, 82, 69, 78, 67, 69, 32, 98, 108, 111, 98, 
44, 32, 32, 32, 32, 32, 45, 45, 32, 65, 114, 116, 105, 102, 97, 99, 116, 32, 116, 97, 
103, 32, 105, 115, 32, 97, 112, 112, 108, 105, 101, 100, 32, 116, 111, 10, 32, 32, 85, 78, 
73, 81, 85, 69, 40, 114, 105, 100, 44, 32, 116, 97, 103, 105, 100, 41, 10, 41, 59, 10, 
67, 82, 69, 65, 84, 69, 32, 73, 78, 68, 69, 88, 32, 123, 123, 100, 98, 110, 97, 109, 
101, 46, 114, 101, 112, 111, 125, 125, 46, 116, 97, 103, 120, 114, 101, 102, 95, 105, 49, 32, 
79, 78, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 116, 97, 103, 120, 114, 
101, 102, 125, 125, 40, 116, 97, 103, 105, 100, 44, 32, 109, 116, 105, 109, 101, 41, 59, 10, 
10, 45, 45, 32, 87, 104, 101, 110, 32, 97, 32, 104, 121, 112, 101, 114, 108, 105, 110, 107, 
32, 111, 99, 99, 117, 114, 115, 32, 102, 114, 111, 109, 32, 111, 110, 101, 32, 97, 114, 116, 
105, 102, 97, 99, 116, 32, 116, 111, 32, 97, 110, 111, 116, 104, 101, 114, 32, 40, 102, 111, 
114, 32, 101, 120, 97, 109, 112, 108, 101, 10, 45, 45, 32, 119, 104, 101, 110, 32, 97, 32, 
99, 104, 101, 99, 107, 45, 105, 110, 32, 99, 111, 109, 109, 101, 110, 116, 32, 114, 101, 102, 
101, 114, 115, 32, 116, 111, 32, 97, 32, 116, 105, 99, 107, 101, 116, 41, 32, 97, 110, 32, 
101, 110, 116, 114, 121, 32, 105, 115, 32, 109, 97, 100, 101, 32, 105, 110, 10, 45, 45, 32, 
116, 104, 101, 32, 102, 111, 108, 108, 111, 119, 105, 110, 103, 32, 116, 97, 98, 108, 101, 32, 
102, 111, 114, 32, 116, 104, 97, 116, 32, 104, 121, 112, 101, 114, 108, 105, 110, 107, 46, 32, 
32, 84, 104, 105, 115, 32, 116, 97, 98, 108, 101, 32, 105, 115, 32, 117, 115, 101, 100, 32, 
116, 111, 10, 45, 45, 32, 102, 97, 99, 105, 108, 105, 116, 97, 116, 101, 32, 116, 104, 101, 
32, 100, 105, 115, 112, 108, 97, 121, 32, 111, 102, 32, 34, 98, 97, 99, 107, 32, 108, 105, 
110, 107, 115, 34, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 
69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 98, 97, 
99, 107, 108, 105, 110, 107, 40, 10, 32, 32, 116, 97, 114, 103, 101, 116, 32, 84, 69, 88, 
84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 87, 104, 101, 114, 
101, 32, 116, 104, 101, 32, 104, 121, 112, 101, 114, 108, 105, 110, 107, 32, 112, 111, 105, 110, 
116, 115, 32, 116, 111, 10, 32, 32, 115, 114, 99, 116, 121, 112, 101, 32, 73, 78, 84, 44, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 48, 58, 32, 99, 104, 101, 
99, 107, 45, 105, 110, 32, 32, 49, 58, 32, 116, 105, 99, 107, 101, 116, 32, 32, 50, 58, 
32, 119, 105, 107, 105, 10, 32, 32, 115, 114, 99, 105, 100, 32, 73, 78, 84, 44, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 114, 105, 100, 32, 102, 111, 
114, 32, 99, 104, 101, 99, 107, 105, 110, 32, 111, 114, 32, 119, 105, 107, 105, 46, 32, 32, 
116, 107, 116, 95, 105, 100, 32, 102, 111, 114, 32, 116, 105, 99, 107, 101, 116, 46, 10, 32, 
32, 109, 116, 105, 109, 101, 32, 84, 73, 77, 69, 83, 84, 65, 77, 80, 44, 32, 32, 32, 
32, 32, 32, 32, 45, 45, 32, 116, 105, 109, 101, 32, 116, 104, 97, 116, 32, 116, 104, 101, 
32, 104, 121, 112, 101, 114, 108, 105, 110, 107, 32, 119, 97, 115, 32, 97, 100, 100, 101, 100, 
46, 32, 74, 117, 108, 105, 97, 110, 32, 100, 97, 121, 46, 10, 32, 32, 85, 78, 73, 81, 
85, 69, 40, 116, 97, 114, 103, 101, 116, 44, 32, 115, 114, 99, 116, 121, 112, 101, 44, 32, 
115, 114, 99, 105, 100, 41, 10, 41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 73, 78, 68, 
69, 88, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 98, 
97, 99, 107, 108, 105, 110, 107, 95, 115, 114, 99, 32, 79, 78, 32, 123, 123, 98, 97, 114, 
101, 46, 114, 101, 112, 111, 46, 98, 97, 99, 107, 108, 105, 110, 107, 125, 125, 40, 115, 114, 
99, 105, 100, 44, 32, 115, 114, 99, 116, 121, 112, 101, 41, 59, 10, 10, 45, 45, 32, 69, 
97, 99, 104, 32, 97, 116, 116, 97, 99, 104, 109, 101, 110, 116, 32, 105, 115, 32, 97, 110, 
32, 101, 110, 116, 114, 121, 32, 105, 110, 32, 116, 104, 101, 32, 102, 111, 108, 108, 111, 119, 
105, 110, 103, 32, 116, 97, 98, 108, 101, 46, 32, 32, 79, 110, 108, 121, 10, 45, 45, 32, 
116, 104, 101, 32, 109, 111, 115, 116, 32, 114, 101, 99, 101, 110, 116, 32, 97, 116, 116, 97, 
99, 104, 109, 101, 110, 116, 32, 40, 105, 100, 101, 110, 116, 105, 102, 105, 101, 100, 32, 98, 
121, 32, 116, 104, 101, 32, 68, 32, 99, 97, 114, 100, 41, 32, 105, 115, 32, 115, 97, 118, 
101, 100, 46, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 
123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 97, 116, 116, 97, 
99, 104, 109, 101, 110, 116, 40, 10, 32, 32, 97, 116, 116, 97, 99, 104, 105, 100, 32, 73, 
78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 44, 32, 
32, 32, 45, 45, 32, 76, 111, 99, 97, 108, 32, 105, 100, 32, 102, 111, 114, 32, 116, 104, 
105, 115, 32, 97, 116, 116, 97, 99, 104, 109, 101, 110, 116, 10, 32, 32, 105, 115, 76, 97, 
116, 101, 115, 116, 32, 66, 79, 79, 76, 69, 65, 78, 32, 68, 69, 70, 65, 85, 76, 84, 
32, 48, 44, 32, 32, 32, 32, 32, 45, 45, 32, 84, 114, 117, 101, 32, 105, 102, 32, 116, 
104, 105, 115, 32, 105, 115, 32, 116, 104, 101, 32, 111, 110, 101, 32, 116, 111, 32, 117, 115, 
101, 10, 32, 32, 109, 116, 105, 109, 101, 32, 84, 73, 77, 69, 83, 84, 65, 77, 80, 44, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 76, 
97, 115, 116, 32, 99, 104, 97, 110, 103, 101, 100, 46, 32, 32, 74, 117, 108, 105, 97, 110, 
32, 100, 97, 121, 46, 10, 32, 32, 115, 114, 99, 32, 84, 69, 88, 84, 44, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
45, 45, 32, 85, 85, 73, 68, 32, 111, 102, 32, 116, 104, 101, 32, 97, 116, 116, 97, 99, 
104, 109, 101, 110, 116, 46, 32, 32, 78, 85, 76, 76, 32, 116, 111, 32, 100, 101, 108, 101, 
116, 101, 10, 32, 32, 116, 97, 114, 103, 101, 116, 32, 84, 69, 88, 84, 44, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 
79, 98, 106, 101, 99, 116, 32, 97, 116, 116, 97, 99, 104, 101, 100, 32, 116, 111, 46, 32, 
87, 105, 107, 105, 110, 97, 109, 101, 32, 111, 114, 32, 84, 107, 116, 32, 85, 85, 73, 68, 
10, 32, 32, 102, 105, 108, 101, 110, 97, 109, 101, 32, 84, 69, 88, 84, 44, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 70, 105, 
108, 101, 110, 97, 109, 101, 32, 102, 111, 114, 32, 116, 104, 101, 32, 97, 116, 116, 97, 99, 
104, 109, 101, 110, 116, 10, 32, 32, 99, 111, 109, 109, 101, 110, 116, 32, 84, 69, 88, 84, 
44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
45, 45, 32, 67, 111, 109, 109, 101, 110, 116, 32, 97, 115, 115, 111, 99, 105, 97, 116, 101, 
100, 32, 119, 105, 116, 104, 32, 116, 104, 105, 115, 32, 97, 116, 116, 97, 99, 104, 109, 101, 
110, 116, 10, 32, 32, 117, 115, 101, 114, 32, 84, 69, 88, 84, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 
78, 97, 109, 101, 32, 111, 102, 32, 117, 115, 101, 114, 32, 97, 100, 100, 105, 110, 103, 32, 
97, 116, 116, 97, 99, 104, 109, 101, 110, 116, 10, 41, 59, 10, 67, 82, 69, 65, 84, 69, 
32, 73, 78, 68, 69, 88, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 
125, 125, 46, 97, 116, 116, 97, 99, 104, 109, 101, 110, 116, 95, 105, 100, 120, 49, 32, 79, 
78, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 97, 116, 116, 97, 99, 104, 
109, 101, 110, 116, 125, 125, 40, 116, 97, 114, 103, 101, 116, 44, 32, 102, 105, 108, 101, 110, 
97, 109, 101, 44, 32, 109, 116, 105, 109, 101, 41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 
73, 78, 68, 69, 88, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 
125, 46, 97, 116, 116, 97, 99, 104, 109, 101, 110, 116, 95, 105, 100, 120, 50, 32, 79, 78, 
32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 97, 116, 116, 97, 99, 104, 109, 
101, 110, 116, 125, 125, 40, 115, 114, 99, 41, 59, 10, 10, 45, 45, 32, 70, 111, 114, 32, 
116, 114, 97, 99, 107, 105, 110, 103, 32, 99, 104, 101, 114, 114, 121, 112, 105, 99, 107, 32, 
109, 101, 114, 103, 101, 115, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 
123, 123, 100, 98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 99, 104, 101, 114, 
114, 121, 112, 105, 99, 107, 40, 10, 32, 32, 112, 97, 114, 101, 110, 116, 105, 100, 32, 73, 
78, 84, 44, 10, 32, 32, 99, 104, 105, 108, 100, 105, 100, 32, 73, 78, 84, 44, 10, 32, 
32, 105, 115, 69, 120, 99, 108, 117, 100, 101, 32, 66, 79, 79, 76, 69, 65, 78, 32, 68, 
69, 70, 65, 85, 76, 84, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 80, 82, 73, 77, 
65, 82, 89, 32, 75, 69, 89, 40, 112, 97, 114, 101, 110, 116, 105, 100, 44, 32, 99, 104, 
105, 108, 100, 105, 100, 41, 10, 41, 32, 87, 73, 84, 72, 79, 85, 84, 32, 82, 79, 87, 
73, 68, 59, 10, 67, 82, 69, 65, 84, 69, 32, 73, 78, 68, 69, 88, 32, 123, 123, 100, 
98, 110, 97, 109, 101, 46, 114, 101, 112, 111, 125, 125, 46, 99, 104, 101, 114, 114, 121, 112, 
105, 99, 107, 95, 99, 105, 100, 32, 79, 78, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 
112, 111, 46, 99, 104, 101, 114, 114, 121, 112, 105, 99, 107, 125, 125, 40, 99, 104, 105, 108, 
100, 105, 100, 41, 59, 10, 
0};
char const * fsl_schema_repo2_cstr = fsl_schema_repo2_cstr_a;
/* end of repo-transient.sql */
/* end of file src/schema_repo2_cstr.c */
/* start of file src/schema_ckout_cstr.c */
/** @page page_schema_ckout_cstr checkout.sql

Binary form of file checkout.sql.

*/
/* auto-generated code - edit at your own risk! (Good luck with that!) */
static char const fsl_schema_ckout_cstr_a[] = {
45, 45, 32, 84, 104, 101, 32, 86, 86, 65, 82, 32, 116, 97, 98, 108, 101, 32, 104, 111, 
108, 100, 115, 32, 109, 105, 115, 99, 101, 108, 108, 97, 110, 111, 117, 115, 32, 105, 110, 102, 
111, 114, 109, 97, 116, 105, 111, 110, 32, 97, 98, 111, 117, 116, 32, 116, 104, 101, 32, 108, 
111, 99, 97, 108, 32, 100, 97, 116, 97, 98, 97, 115, 101, 10, 45, 45, 32, 105, 110, 32, 
116, 104, 101, 32, 102, 111, 114, 109, 32, 111, 102, 32, 110, 97, 109, 101, 45, 118, 97, 108, 
117, 101, 32, 112, 97, 105, 114, 115, 46, 32, 32, 84, 104, 105, 115, 32, 105, 115, 32, 115, 
105, 109, 105, 108, 97, 114, 32, 116, 111, 32, 116, 104, 101, 32, 86, 65, 82, 32, 116, 97, 
98, 108, 101, 10, 45, 45, 32, 116, 97, 98, 108, 101, 32, 105, 110, 32, 116, 104, 101, 32, 
114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 32, 101, 120, 99, 101, 112, 116, 32, 116, 104, 
97, 116, 32, 116, 104, 105, 115, 32, 116, 97, 98, 108, 101, 32, 104, 111, 108, 100, 115, 32, 
105, 110, 102, 111, 114, 109, 97, 116, 105, 111, 110, 32, 116, 104, 97, 116, 10, 45, 45, 32, 
105, 115, 32, 115, 112, 101, 99, 105, 102, 105, 99, 32, 116, 111, 32, 116, 104, 101, 32, 108, 
111, 99, 97, 108, 32, 99, 104, 101, 99, 107, 111, 117, 116, 46, 10, 45, 45, 10, 45, 45, 
32, 73, 109, 112, 111, 114, 116, 97, 110, 116, 32, 86, 97, 114, 105, 97, 98, 108, 101, 115, 
58, 10, 45, 45, 10, 45, 45, 32, 32, 32, 32, 32, 114, 101, 112, 111, 115, 105, 116, 111, 
114, 121, 32, 32, 32, 32, 32, 32, 32, 32, 70, 117, 108, 108, 32, 112, 97, 116, 104, 110, 
97, 109, 101, 32, 111, 102, 32, 116, 104, 101, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 
121, 32, 100, 97, 116, 97, 98, 97, 115, 101, 10, 45, 45, 32, 32, 32, 32, 32, 117, 115, 
101, 114, 45, 105, 100, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 85, 115, 101, 114, 
105, 100, 32, 116, 111, 32, 117, 115, 101, 10, 45, 45, 10, 67, 82, 69, 65, 84, 69, 32, 
84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 99, 107, 111, 117, 116, 
125, 125, 46, 118, 118, 97, 114, 40, 10, 32, 32, 110, 97, 109, 101, 32, 84, 69, 88, 84, 
32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 32, 78, 79, 84, 32, 78, 85, 76, 
76, 44, 32, 32, 45, 45, 32, 80, 114, 105, 109, 97, 114, 121, 32, 110, 97, 109, 101, 32, 
111, 102, 32, 116, 104, 101, 32, 101, 110, 116, 114, 121, 10, 32, 32, 118, 97, 108, 117, 101, 
32, 67, 76, 79, 66, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 67, 111, 110, 116, 101, 110, 116, 32, 111, 
102, 32, 116, 104, 101, 32, 110, 97, 109, 101, 100, 32, 112, 97, 114, 97, 109, 101, 116, 101, 
114, 10, 32, 32, 67, 72, 69, 67, 75, 40, 32, 116, 121, 112, 101, 111, 102, 40, 110, 97, 
109, 101, 41, 61, 39, 116, 101, 120, 116, 39, 32, 65, 78, 68, 32, 108, 101, 110, 103, 116, 
104, 40, 110, 97, 109, 101, 41, 62, 61, 49, 32, 41, 10, 41, 32, 87, 73, 84, 72, 79, 
85, 84, 32, 82, 79, 87, 73, 68, 59, 10, 10, 45, 45, 32, 69, 97, 99, 104, 32, 101, 
110, 116, 114, 121, 32, 105, 110, 32, 116, 104, 101, 32, 118, 102, 105, 108, 101, 32, 116, 97, 
98, 108, 101, 32, 114, 101, 112, 114, 101, 115, 101, 110, 116, 115, 32, 97, 32, 115, 105, 110, 
103, 108, 101, 32, 102, 105, 108, 101, 32, 105, 110, 32, 116, 104, 101, 10, 45, 45, 32, 99, 
117, 114, 114, 101, 110, 116, 32, 99, 104, 101, 99, 107, 111, 117, 116, 46, 10, 45, 45, 10, 
45, 45, 32, 84, 104, 101, 32, 102, 105, 108, 101, 46, 114, 105, 100, 32, 102, 105, 101, 108, 
100, 32, 105, 115, 32, 48, 32, 102, 111, 114, 32, 102, 105, 108, 101, 115, 32, 111, 114, 32, 
102, 111, 108, 100, 101, 114, 115, 32, 116, 104, 97, 116, 32, 104, 97, 118, 101, 32, 98, 101, 
101, 110, 10, 45, 45, 32, 97, 100, 100, 101, 100, 32, 98, 117, 116, 32, 110, 111, 116, 32, 
121, 101, 116, 32, 99, 111, 109, 109, 105, 116, 116, 101, 100, 46, 10, 45, 45, 10, 45, 45, 
32, 86, 102, 105, 108, 101, 46, 99, 104, 110, 103, 101, 100, 32, 105, 115, 32, 48, 32, 102, 
111, 114, 32, 117, 110, 109, 111, 100, 105, 102, 105, 101, 100, 32, 102, 105, 108, 101, 115, 44, 
32, 49, 32, 102, 111, 114, 32, 102, 105, 108, 101, 115, 32, 116, 104, 97, 116, 32, 104, 97, 
118, 101, 10, 45, 45, 32, 98, 101, 101, 110, 32, 101, 100, 105, 116, 101, 100, 32, 111, 114, 
32, 119, 104, 105, 99, 104, 32, 104, 97, 118, 101, 32, 98, 101, 101, 110, 32, 115, 117, 98, 
106, 101, 99, 116, 101, 100, 32, 116, 111, 32, 97, 32, 51, 45, 119, 97, 121, 32, 109, 101, 
114, 103, 101, 46, 10, 45, 45, 32, 86, 102, 105, 108, 101, 46, 99, 104, 110, 103, 101, 100, 
32, 105, 115, 32, 50, 32, 105, 102, 32, 116, 104, 101, 32, 102, 105, 108, 101, 32, 104, 97, 
115, 32, 98, 101, 101, 110, 32, 114, 101, 112, 108, 97, 99, 101, 100, 32, 102, 114, 111, 109, 
32, 97, 32, 100, 105, 102, 102, 101, 114, 101, 110, 116, 10, 45, 45, 32, 118, 101, 114, 115, 
105, 111, 110, 32, 98, 121, 32, 116, 104, 101, 32, 109, 101, 114, 103, 101, 32, 97, 110, 100, 
32, 51, 32, 105, 102, 32, 116, 104, 101, 32, 102, 105, 108, 101, 32, 104, 97, 115, 32, 98, 
101, 101, 110, 32, 97, 100, 100, 101, 100, 32, 98, 121, 32, 97, 32, 109, 101, 114, 103, 101, 
46, 10, 45, 45, 32, 86, 102, 105, 108, 101, 46, 99, 104, 110, 103, 101, 100, 32, 105, 115, 
32, 52, 124, 53, 32, 105, 115, 32, 116, 104, 101, 32, 115, 97, 109, 101, 32, 97, 115, 32, 
50, 124, 51, 44, 32, 98, 117, 116, 32, 116, 104, 101, 32, 111, 112, 101, 114, 97, 116, 105, 
111, 110, 32, 104, 97, 115, 32, 98, 101, 101, 110, 10, 45, 45, 32, 100, 111, 110, 101, 32, 
98, 121, 32, 97, 110, 32, 45, 45, 105, 110, 116, 101, 103, 114, 97, 116, 101, 32, 109, 101, 
114, 103, 101, 46, 32, 32, 84, 104, 101, 32, 100, 105, 102, 102, 101, 114, 101, 110, 99, 101, 
32, 98, 101, 116, 119, 101, 101, 110, 32, 118, 102, 105, 108, 101, 46, 99, 104, 110, 103, 101, 
100, 61, 61, 50, 124, 52, 10, 45, 45, 32, 97, 110, 100, 32, 97, 32, 114, 101, 103, 117, 
108, 97, 114, 32, 97, 100, 100, 32, 105, 115, 32, 116, 104, 97, 116, 32, 119, 105, 116, 104, 
32, 118, 102, 105, 108, 101, 46, 99, 104, 110, 103, 101, 100, 61, 61, 50, 124, 52, 32, 119, 
101, 32, 107, 110, 111, 119, 32, 116, 104, 97, 116, 32, 116, 104, 101, 10, 45, 45, 32, 99, 
117, 114, 114, 101, 110, 116, 32, 118, 101, 114, 115, 105, 111, 110, 32, 111, 102, 32, 116, 104, 
101, 32, 102, 105, 108, 101, 32, 105, 115, 32, 97, 108, 114, 101, 97, 100, 121, 32, 105, 110, 
32, 116, 104, 101, 32, 114, 101, 112, 111, 115, 105, 116, 111, 114, 121, 46, 10, 45, 45, 10, 
67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 
101, 46, 99, 107, 111, 117, 116, 125, 125, 46, 118, 102, 105, 108, 101, 40, 10, 32, 32, 105, 
100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 
89, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 73, 68, 32, 111, 
102, 32, 116, 104, 101, 32, 99, 104, 101, 99, 107, 101, 100, 32, 111, 117, 116, 32, 102, 105, 
108, 101, 10, 32, 32, 118, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 82, 69, 70, 
69, 82, 69, 78, 67, 69, 83, 32, 98, 108, 111, 98, 44, 32, 32, 32, 32, 32, 32, 45, 
45, 32, 84, 104, 101, 32, 98, 97, 115, 101, 108, 105, 110, 101, 32, 116, 104, 105, 115, 32, 
102, 105, 108, 101, 32, 105, 115, 32, 112, 97, 114, 116, 32, 111, 102, 46, 10, 32, 32, 99, 
104, 110, 103, 101, 100, 32, 73, 78, 84, 32, 68, 69, 70, 65, 85, 76, 84, 32, 48, 44, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 69, 110, 99, 111, 
100, 101, 100, 32, 105, 110, 32, 102, 115, 108, 95, 118, 102, 105, 108, 101, 95, 99, 104, 97, 
110, 103, 101, 95, 101, 32, 101, 110, 117, 109, 46, 10, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 48, 58, 117, 110, 99, 104, 110, 103, 101, 
100, 32, 49, 58, 101, 100, 105, 116, 101, 100, 32, 50, 58, 109, 45, 99, 104, 110, 103, 32, 
51, 58, 109, 45, 97, 100, 100, 32, 52, 58, 105, 45, 99, 104, 110, 103, 32, 53, 58, 105, 
45, 97, 100, 100, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 45, 45, 32, 54, 58, 43, 120, 32, 98, 117, 116, 32, 117, 110, 109, 111, 100, 105, 102, 
105, 101, 100, 44, 32, 55, 58, 99, 104, 97, 110, 103, 101, 100, 32, 116, 111, 32, 115, 121, 
109, 108, 105, 110, 107, 32, 98, 117, 116, 32, 117, 110, 109, 111, 100, 105, 102, 105, 101, 100, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 
56, 58, 45, 120, 32, 98, 117, 116, 32, 117, 110, 109, 111, 100, 105, 102, 105, 101, 100, 44, 
32, 57, 58, 99, 104, 97, 110, 103, 101, 100, 32, 116, 111, 32, 110, 111, 116, 32, 115, 121, 
109, 108, 105, 110, 107, 32, 98, 117, 116, 32, 117, 110, 109, 111, 100, 105, 102, 105, 101, 100, 
10, 32, 32, 100, 101, 108, 101, 116, 101, 100, 32, 66, 79, 79, 76, 69, 65, 78, 32, 68, 
69, 70, 65, 85, 76, 84, 32, 48, 44, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 
84, 114, 117, 101, 32, 105, 102, 32, 100, 101, 108, 101, 116, 101, 100, 10, 32, 32, 105, 115, 
101, 120, 101, 32, 66, 79, 79, 76, 69, 65, 78, 44, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 84, 114, 117, 101, 32, 
105, 102, 32, 102, 105, 108, 101, 32, 115, 104, 111, 117, 108, 100, 32, 98, 101, 32, 101, 120, 
101, 99, 117, 116, 97, 98, 108, 101, 10, 32, 32, 105, 115, 108, 105, 110, 107, 32, 66, 79, 
79, 76, 69, 65, 78, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 84, 114, 117, 101, 32, 105, 102, 32, 102, 105, 108, 101, 
32, 115, 104, 111, 117, 108, 100, 32, 98, 101, 32, 115, 121, 109, 108, 105, 110, 107, 10, 32, 
32, 114, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 44, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 79, 114, 
105, 103, 105, 110, 97, 108, 108, 121, 32, 102, 114, 111, 109, 32, 116, 104, 105, 115, 32, 114, 
101, 112, 111, 115, 105, 116, 111, 114, 121, 32, 114, 101, 99, 111, 114, 100, 10, 32, 32, 109, 
114, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 44, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 66, 97, 115, 101, 
100, 32, 111, 110, 32, 116, 104, 105, 115, 32, 114, 101, 99, 111, 114, 100, 32, 100, 117, 101, 
32, 116, 111, 32, 97, 32, 109, 101, 114, 103, 101, 10, 32, 32, 109, 116, 105, 109, 101, 32, 
73, 78, 84, 69, 71, 69, 82, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 77, 116, 105, 109, 101, 32, 111, 102, 32, 
102, 105, 108, 101, 32, 111, 110, 32, 100, 105, 115, 107, 46, 32, 115, 101, 99, 32, 115, 105, 
110, 99, 101, 32, 49, 57, 55, 48, 10, 32, 32, 112, 97, 116, 104, 110, 97, 109, 101, 32, 
84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 45, 45, 32, 70, 117, 108, 108, 32, 112, 97, 116, 104, 110, 97, 109, 
101, 32, 114, 101, 108, 97, 116, 105, 118, 101, 32, 116, 111, 32, 114, 111, 111, 116, 10, 32, 
32, 111, 114, 105, 103, 110, 97, 109, 101, 32, 84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 79, 114, 
105, 103, 105, 110, 97, 108, 32, 112, 97, 116, 104, 110, 97, 109, 101, 46, 32, 78, 85, 76, 
76, 32, 105, 102, 32, 117, 110, 99, 104, 97, 110, 103, 101, 100, 10, 32, 32, 109, 104, 97, 
115, 104, 32, 84, 69, 88, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 72, 97, 115, 104, 32, 111, 
102, 32, 109, 114, 105, 100, 32, 105, 102, 102, 32, 109, 114, 105, 100, 33, 61, 114, 105, 100, 
46, 32, 65, 100, 100, 101, 100, 32, 50, 48, 49, 57, 45, 48, 49, 45, 49, 57, 46, 10, 
32, 32, 85, 78, 73, 81, 85, 69, 40, 112, 97, 116, 104, 110, 97, 109, 101, 44, 118, 105, 
100, 41, 10, 41, 59, 10, 10, 45, 45, 32, 84, 104, 105, 115, 32, 116, 97, 98, 108, 101, 
32, 104, 111, 108, 100, 115, 32, 97, 32, 114, 101, 99, 111, 114, 100, 32, 111, 102, 32, 117, 
110, 99, 111, 109, 109, 105, 116, 116, 101, 100, 32, 109, 101, 114, 103, 101, 115, 32, 105, 110, 
32, 116, 104, 101, 32, 108, 111, 99, 97, 108, 10, 45, 45, 32, 102, 105, 108, 101, 32, 116, 
114, 101, 101, 46, 32, 32, 73, 102, 32, 97, 32, 86, 70, 73, 76, 69, 32, 101, 110, 116, 
114, 121, 32, 119, 105, 116, 104, 32, 105, 100, 32, 104, 97, 115, 32, 109, 101, 114, 103, 101, 
100, 32, 119, 105, 116, 104, 32, 97, 110, 111, 116, 104, 101, 114, 10, 45, 45, 32, 114, 101, 
99, 111, 114, 100, 44, 32, 116, 104, 101, 114, 101, 32, 105, 115, 32, 97, 110, 32, 101, 110, 
116, 114, 121, 32, 105, 110, 32, 116, 104, 105, 115, 32, 116, 97, 98, 108, 101, 32, 119, 105, 
116, 104, 32, 40, 105, 100, 44, 109, 101, 114, 103, 101, 41, 32, 119, 104, 101, 114, 101, 10, 
45, 45, 32, 109, 101, 114, 103, 101, 32, 105, 115, 32, 116, 104, 101, 32, 82, 69, 67, 79, 
82, 68, 32, 116, 97, 98, 108, 101, 32, 101, 110, 116, 114, 121, 32, 116, 104, 97, 116, 32, 
116, 104, 101, 32, 102, 105, 108, 101, 32, 109, 101, 114, 103, 101, 100, 32, 97, 103, 97, 105, 
110, 115, 116, 46, 10, 45, 45, 32, 65, 110, 32, 105, 100, 32, 111, 102, 32, 48, 32, 111, 
114, 32, 60, 45, 51, 32, 104, 101, 114, 101, 32, 109, 101, 97, 110, 115, 32, 116, 104, 101, 
32, 118, 101, 114, 115, 105, 111, 110, 32, 114, 101, 99, 111, 114, 100, 32, 105, 116, 115, 101, 
108, 102, 46, 32, 32, 87, 104, 101, 110, 10, 45, 45, 32, 105, 100, 61, 61, 40, 45, 49, 
41, 32, 116, 104, 97, 116, 32, 105, 115, 32, 97, 32, 99, 104, 101, 114, 114, 121, 112, 105, 
99, 107, 32, 109, 101, 114, 103, 101, 44, 32, 105, 100, 61, 61, 40, 45, 50, 41, 32, 116, 
104, 97, 116, 32, 105, 115, 32, 97, 10, 45, 45, 32, 98, 97, 99, 107, 111, 117, 116, 32, 
109, 101, 114, 103, 101, 32, 97, 110, 100, 32, 105, 100, 61, 61, 40, 45, 52, 41, 32, 105, 
115, 32, 97, 32, 105, 110, 116, 101, 103, 114, 97, 116, 101, 32, 109, 101, 114, 103, 101, 46, 
10, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 
97, 109, 101, 46, 99, 107, 111, 117, 116, 125, 125, 46, 118, 109, 101, 114, 103, 101, 40, 10, 
32, 32, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 82, 69, 70, 69, 82, 69, 78, 
67, 69, 83, 32, 123, 123, 98, 97, 114, 101, 46, 99, 107, 111, 117, 116, 46, 118, 102, 105, 
108, 101, 125, 125, 44, 32, 32, 32, 32, 32, 32, 45, 45, 32, 86, 70, 73, 76, 69, 32, 
101, 110, 116, 114, 121, 32, 116, 104, 97, 116, 32, 104, 97, 115, 32, 98, 101, 101, 110, 32, 
109, 101, 114, 103, 101, 100, 10, 32, 32, 109, 101, 114, 103, 101, 32, 73, 78, 84, 69, 71, 
69, 82, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 45, 45, 32, 77, 101, 114, 103, 101, 100, 32, 119, 105, 116, 104, 32, 116, 104, 
105, 115, 32, 114, 101, 99, 111, 114, 100, 10, 32, 32, 109, 104, 97, 115, 104, 32, 84, 69, 
88, 84, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 45, 45, 32, 83, 72, 65, 49, 47, 83, 72, 65, 51, 32, 104, 
97, 115, 104, 32, 102, 111, 114, 32, 109, 101, 114, 103, 101, 32, 111, 98, 106, 101, 99, 116, 
10, 41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 85, 78, 73, 81, 85, 69, 32, 73, 78, 
68, 69, 88, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 99, 107, 111, 117, 116, 125, 125, 
46, 118, 109, 101, 114, 103, 101, 120, 49, 32, 79, 78, 32, 123, 123, 98, 97, 114, 101, 46, 
99, 107, 111, 117, 116, 46, 118, 109, 101, 114, 103, 101, 125, 125, 40, 105, 100, 44, 109, 104, 
97, 115, 104, 41, 59, 10, 10, 45, 45, 32, 84, 104, 101, 32, 102, 111, 108, 108, 111, 119, 
105, 110, 103, 32, 116, 114, 105, 103, 103, 101, 114, 32, 119, 105, 108, 108, 32, 112, 114, 101, 
118, 101, 110, 116, 32, 111, 108, 100, 101, 114, 32, 118, 101, 114, 115, 105, 111, 110, 115, 32, 
111, 102, 32, 70, 111, 115, 115, 105, 108, 32, 116, 104, 97, 116, 10, 45, 45, 32, 100, 111, 
32, 110, 111, 116, 32, 107, 110, 111, 119, 32, 97, 98, 111, 117, 116, 32, 116, 104, 101, 32, 
110, 101, 119, 32, 118, 109, 101, 114, 103, 101, 46, 109, 104, 97, 115, 104, 32, 99, 111, 108, 
117, 109, 110, 32, 102, 114, 111, 109, 32, 117, 112, 100, 97, 116, 105, 110, 103, 32, 116, 104, 
101, 10, 45, 45, 32, 118, 109, 101, 114, 103, 101, 32, 116, 97, 98, 108, 101, 46, 32, 32, 
84, 104, 105, 115, 32, 109, 117, 115, 116, 32, 98, 101, 32, 100, 111, 110, 101, 32, 119, 105, 
116, 104, 32, 97, 32, 116, 114, 105, 103, 103, 101, 114, 44, 32, 115, 105, 110, 99, 101, 32, 
108, 101, 103, 97, 99, 121, 32, 70, 111, 115, 115, 105, 108, 10, 45, 45, 32, 117, 115, 101, 
115, 32, 73, 78, 83, 69, 82, 84, 32, 79, 82, 32, 73, 71, 78, 79, 82, 69, 32, 116, 
111, 32, 117, 112, 100, 97, 116, 101, 32, 118, 109, 101, 114, 103, 101, 44, 32, 97, 110, 100, 
32, 116, 104, 101, 32, 79, 82, 32, 73, 71, 78, 79, 82, 69, 32, 119, 105, 108, 108, 32, 
99, 97, 117, 115, 101, 10, 45, 45, 32, 97, 32, 78, 79, 84, 32, 78, 85, 76, 76, 32, 
99, 111, 110, 115, 116, 114, 97, 105, 110, 116, 32, 116, 111, 32, 98, 101, 32, 115, 105, 108, 
101, 110, 116, 108, 121, 32, 105, 103, 110, 111, 114, 101, 100, 46, 10, 67, 82, 69, 65, 84, 
69, 32, 84, 82, 73, 71, 71, 69, 82, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 99, 
107, 111, 117, 116, 125, 125, 46, 118, 109, 101, 114, 103, 101, 95, 99, 107, 49, 32, 65, 70, 
84, 69, 82, 32, 73, 78, 83, 69, 82, 84, 32, 79, 78, 32, 123, 123, 98, 97, 114, 101, 
46, 99, 107, 111, 117, 116, 46, 118, 109, 101, 114, 103, 101, 125, 125, 10, 87, 72, 69, 78, 
32, 110, 101, 119, 46, 109, 104, 97, 115, 104, 32, 73, 83, 32, 78, 85, 76, 76, 32, 66, 
69, 71, 73, 78, 10, 32, 32, 83, 69, 76, 69, 67, 84, 32, 114, 97, 105, 115, 101, 40, 
70, 65, 73, 76, 44, 10, 32, 32, 39, 116, 114, 121, 105, 110, 103, 32, 116, 111, 32, 117, 
112, 100, 97, 116, 101, 32, 97, 32, 110, 101, 119, 101, 114, 32, 99, 104, 101, 99, 107, 111, 
117, 116, 32, 119, 105, 116, 104, 32, 97, 110, 32, 111, 108, 100, 101, 114, 32, 118, 101, 114, 
115, 105, 111, 110, 32, 111, 102, 32, 70, 111, 115, 115, 105, 108, 39, 41, 59, 10, 69, 78, 
68, 59, 10, 
0};
char const * fsl_schema_ckout_cstr = fsl_schema_ckout_cstr_a;
/* end of checkout.sql */
/* end of file src/schema_ckout_cstr.c */
/* start of file src/schema_ticket_cstr.c */
/** @page page_schema_ticket_cstr ticket.sql

Binary form of file ticket.sql.

*/
/* auto-generated code - edit at your own risk! (Good luck with that!) */
static char const fsl_schema_ticket_cstr_a[] = {
45, 45, 32, 84, 101, 109, 112, 108, 97, 116, 101, 32, 102, 111, 114, 32, 116, 104, 101, 32, 
84, 73, 67, 75, 69, 84, 32, 116, 97, 98, 108, 101, 10, 67, 82, 69, 65, 84, 69, 32, 
84, 65, 66, 76, 69, 32, 114, 101, 112, 111, 46, 116, 105, 99, 107, 101, 116, 40, 10, 32, 
32, 45, 45, 32, 68, 111, 32, 110, 111, 116, 32, 99, 104, 97, 110, 103, 101, 32, 97, 110, 
121, 32, 99, 111, 108, 117, 109, 110, 32, 116, 104, 97, 116, 32, 98, 101, 103, 105, 110, 115, 
32, 119, 105, 116, 104, 32, 116, 107, 116, 95, 10, 32, 32, 116, 107, 116, 95, 105, 100, 32, 
73, 78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 82, 89, 32, 75, 69, 89, 44, 
10, 32, 32, 116, 107, 116, 95, 117, 117, 105, 100, 32, 84, 69, 88, 84, 32, 85, 78, 73, 
81, 85, 69, 44, 10, 32, 32, 116, 107, 116, 95, 109, 116, 105, 109, 101, 32, 68, 65, 84, 
69, 44, 10, 32, 32, 116, 107, 116, 95, 99, 116, 105, 109, 101, 32, 68, 65, 84, 69, 44, 
10, 32, 32, 45, 45, 32, 65, 100, 100, 32, 97, 115, 32, 109, 97, 110, 121, 32, 102, 105, 
101, 108, 100, 32, 97, 115, 32, 114, 101, 113, 117, 105, 114, 101, 100, 32, 98, 101, 108, 111, 
119, 32, 116, 104, 105, 115, 32, 108, 105, 110, 101, 10, 32, 32, 116, 121, 112, 101, 32, 84, 
69, 88, 84, 44, 10, 32, 32, 115, 116, 97, 116, 117, 115, 32, 84, 69, 88, 84, 44, 10, 
32, 32, 115, 117, 98, 115, 121, 115, 116, 101, 109, 32, 84, 69, 88, 84, 44, 10, 32, 32, 
112, 114, 105, 111, 114, 105, 116, 121, 32, 84, 69, 88, 84, 44, 10, 32, 32, 115, 101, 118, 
101, 114, 105, 116, 121, 32, 84, 69, 88, 84, 44, 10, 32, 32, 102, 111, 117, 110, 100, 105, 
110, 32, 84, 69, 88, 84, 44, 10, 32, 32, 112, 114, 105, 118, 97, 116, 101, 95, 99, 111, 
110, 116, 97, 99, 116, 32, 84, 69, 88, 84, 44, 10, 32, 32, 114, 101, 115, 111, 108, 117, 
116, 105, 111, 110, 32, 84, 69, 88, 84, 44, 10, 32, 32, 116, 105, 116, 108, 101, 32, 84, 
69, 88, 84, 44, 10, 32, 32, 99, 111, 109, 109, 101, 110, 116, 32, 84, 69, 88, 84, 10, 
41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 114, 101, 112, 111, 
46, 116, 105, 99, 107, 101, 116, 99, 104, 110, 103, 40, 10, 32, 32, 45, 45, 32, 68, 111, 
32, 110, 111, 116, 32, 99, 104, 97, 110, 103, 101, 32, 97, 110, 121, 32, 99, 111, 108, 117, 
109, 110, 32, 116, 104, 97, 116, 32, 98, 101, 103, 105, 110, 115, 32, 119, 105, 116, 104, 32, 
116, 107, 116, 95, 10, 32, 32, 116, 107, 116, 95, 105, 100, 32, 73, 78, 84, 69, 71, 69, 
82, 32, 82, 69, 70, 69, 82, 69, 78, 67, 69, 83, 32, 116, 105, 99, 107, 101, 116, 44, 
10, 32, 32, 116, 107, 116, 95, 114, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 82, 
69, 70, 69, 82, 69, 78, 67, 69, 83, 32, 98, 108, 111, 98, 44, 10, 32, 32, 116, 107, 
116, 95, 109, 116, 105, 109, 101, 32, 68, 65, 84, 69, 44, 10, 32, 32, 45, 45, 32, 65, 
100, 100, 32, 97, 115, 32, 109, 97, 110, 121, 32, 102, 105, 101, 108, 100, 115, 32, 97, 115, 
32, 114, 101, 113, 117, 105, 114, 101, 100, 32, 98, 101, 108, 111, 119, 32, 116, 104, 105, 115, 
32, 108, 105, 110, 101, 10, 32, 32, 108, 111, 103, 105, 110, 32, 84, 69, 88, 84, 44, 10, 
32, 32, 117, 115, 101, 114, 110, 97, 109, 101, 32, 84, 69, 88, 84, 44, 10, 32, 32, 109, 
105, 109, 101, 116, 121, 112, 101, 32, 84, 69, 88, 84, 44, 10, 32, 32, 105, 99, 111, 109, 
109, 101, 110, 116, 32, 84, 69, 88, 84, 10, 41, 59, 10, 67, 82, 69, 65, 84, 69, 32, 
73, 78, 68, 69, 88, 32, 114, 101, 112, 111, 46, 116, 105, 99, 107, 101, 116, 99, 104, 110, 
103, 95, 105, 100, 120, 49, 32, 79, 78, 32, 116, 105, 99, 107, 101, 116, 99, 104, 110, 103, 
40, 116, 107, 116, 95, 105, 100, 44, 32, 116, 107, 116, 95, 109, 116, 105, 109, 101, 41, 59, 
10, 
0};
char const * fsl_schema_ticket_cstr = fsl_schema_ticket_cstr_a;
/* end of ticket.sql */
/* end of file src/schema_ticket_cstr.c */
/* start of file src/schema_ticket_reports_cstr.c */
/** @page page_schema_ticket_reports_cstr ticket-reports.sql

Binary form of file ticket-reports.sql.

*/
/* auto-generated code - edit at your own risk! (Good luck with that!) */
static char const fsl_schema_ticket_reports_cstr_a[] = {
73, 78, 83, 69, 82, 84, 32, 73, 78, 84, 79, 32, 123, 123, 100, 98, 110, 97, 109, 101, 
46, 114, 101, 112, 111, 125, 125, 46, 114, 101, 112, 111, 114, 116, 102, 109, 116, 40, 116, 105, 
116, 108, 101, 44, 109, 116, 105, 109, 101, 44, 99, 111, 108, 115, 44, 115, 113, 108, 99, 111, 
100, 101, 41, 32, 10, 86, 65, 76, 85, 69, 83, 40, 39, 65, 108, 108, 32, 84, 105, 99, 
107, 101, 116, 115, 39, 44, 106, 117, 108, 105, 97, 110, 100, 97, 121, 40, 39, 49, 57, 55, 
48, 45, 48, 49, 45, 48, 49, 39, 41, 44, 39, 35, 102, 102, 102, 102, 102, 102, 32, 75, 
101, 121, 58, 10, 35, 102, 50, 100, 99, 100, 99, 32, 65, 99, 116, 105, 118, 101, 10, 35, 
101, 56, 101, 56, 101, 56, 32, 82, 101, 118, 105, 101, 119, 10, 35, 99, 102, 101, 56, 98, 
100, 32, 70, 105, 120, 101, 100, 10, 35, 98, 100, 101, 53, 100, 54, 32, 84, 101, 115, 116, 
101, 100, 10, 35, 99, 97, 99, 97, 101, 53, 32, 68, 101, 102, 101, 114, 114, 101, 100, 10, 
35, 99, 56, 99, 56, 99, 56, 32, 67, 108, 111, 115, 101, 100, 39, 44, 39, 83, 69, 76, 
69, 67, 84, 10, 32, 32, 67, 65, 83, 69, 32, 87, 72, 69, 78, 32, 115, 116, 97, 116, 
117, 115, 32, 73, 78, 32, 40, 39, 39, 79, 112, 101, 110, 39, 39, 44, 39, 39, 86, 101, 
114, 105, 102, 105, 101, 100, 39, 39, 41, 32, 84, 72, 69, 78, 32, 39, 39, 35, 102, 50, 
100, 99, 100, 99, 39, 39, 10, 32, 32, 32, 32, 32, 32, 32, 87, 72, 69, 78, 32, 115, 
116, 97, 116, 117, 115, 61, 39, 39, 82, 101, 118, 105, 101, 119, 39, 39, 32, 84, 72, 69, 
78, 32, 39, 39, 35, 101, 56, 101, 56, 101, 56, 39, 39, 10, 32, 32, 32, 32, 32, 32, 
32, 87, 72, 69, 78, 32, 115, 116, 97, 116, 117, 115, 61, 39, 39, 70, 105, 120, 101, 100, 
39, 39, 32, 84, 72, 69, 78, 32, 39, 39, 35, 99, 102, 101, 56, 98, 100, 39, 39, 10, 
32, 32, 32, 32, 32, 32, 32, 87, 72, 69, 78, 32, 115, 116, 97, 116, 117, 115, 61, 39, 
39, 84, 101, 115, 116, 101, 100, 39, 39, 32, 84, 72, 69, 78, 32, 39, 39, 35, 98, 100, 
101, 53, 100, 54, 39, 39, 10, 32, 32, 32, 32, 32, 32, 32, 87, 72, 69, 78, 32, 115, 
116, 97, 116, 117, 115, 61, 39, 39, 68, 101, 102, 101, 114, 114, 101, 100, 39, 39, 32, 84, 
72, 69, 78, 32, 39, 39, 35, 99, 97, 99, 97, 101, 53, 39, 39, 10, 32, 32, 32, 32, 
32, 32, 32, 69, 76, 83, 69, 32, 39, 39, 35, 99, 56, 99, 56, 99, 56, 39, 39, 32, 
69, 78, 68, 32, 65, 83, 32, 39, 39, 98, 103, 99, 111, 108, 111, 114, 39, 39, 44, 10, 
32, 32, 115, 117, 98, 115, 116, 114, 40, 116, 107, 116, 95, 117, 117, 105, 100, 44, 49, 44, 
49, 48, 41, 32, 65, 83, 32, 39, 39, 35, 39, 39, 44, 10, 32, 32, 100, 97, 116, 101, 
116, 105, 109, 101, 40, 116, 107, 116, 95, 109, 116, 105, 109, 101, 41, 32, 65, 83, 32, 39, 
39, 109, 116, 105, 109, 101, 39, 39, 44, 10, 32, 32, 116, 121, 112, 101, 44, 10, 32, 32, 
115, 116, 97, 116, 117, 115, 44, 10, 32, 32, 115, 117, 98, 115, 121, 115, 116, 101, 109, 44, 
10, 32, 32, 116, 105, 116, 108, 101, 10, 70, 82, 79, 77, 32, 116, 105, 99, 107, 101, 116, 
39, 41, 59, 10, 
0};
char const * fsl_schema_ticket_reports_cstr = fsl_schema_ticket_reports_cstr_a;
/* end of ticket-reports.sql */
/* end of file src/schema_ticket_reports_cstr.c */
/* start of file src/schema_forum_cstr.c */
/** @page page_schema_forum_cstr forum.sql

Binary form of file forum.sql.

*/
/* auto-generated code - edit at your own risk! (Good luck with that!) */
static char const fsl_schema_forum_cstr_a[] = {
67, 82, 69, 65, 84, 69, 32, 84, 65, 66, 76, 69, 32, 123, 123, 100, 98, 110, 97, 109, 
101, 46, 114, 101, 112, 111, 125, 125, 46, 102, 111, 114, 117, 109, 112, 111, 115, 116, 40, 10, 
32, 32, 102, 112, 105, 100, 32, 73, 78, 84, 69, 71, 69, 82, 32, 80, 82, 73, 77, 65, 
82, 89, 32, 75, 69, 89, 44, 32, 32, 45, 45, 32, 66, 76, 79, 66, 46, 114, 105, 100, 
32, 102, 111, 114, 32, 116, 104, 101, 32, 97, 114, 116, 105, 102, 97, 99, 116, 10, 32, 32, 
102, 114, 111, 111, 116, 32, 73, 78, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 102, 112, 105, 100, 32, 111, 102, 32, 116, 104, 
101, 32, 116, 104, 114, 101, 97, 100, 32, 114, 111, 111, 116, 10, 32, 32, 102, 112, 114, 101, 
118, 32, 73, 78, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 45, 45, 32, 80, 114, 101, 118, 105, 111, 117, 115, 32, 118, 101, 114, 115, 105, 
111, 110, 32, 111, 102, 32, 116, 104, 105, 115, 32, 115, 97, 109, 101, 32, 112, 111, 115, 116, 
10, 32, 32, 102, 105, 114, 116, 32, 73, 78, 84, 44, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 84, 104, 105, 115, 32, 112, 111, 
115, 116, 32, 105, 115, 32, 105, 110, 45, 114, 101, 112, 108, 121, 45, 116, 111, 10, 32, 32, 
102, 109, 116, 105, 109, 101, 32, 82, 69, 65, 76, 32, 32, 32, 32, 32, 32, 32, 32, 32, 
32, 32, 32, 32, 32, 32, 32, 45, 45, 32, 87, 104, 101, 110, 32, 112, 111, 115, 116, 101, 
100, 46, 32, 32, 74, 117, 108, 105, 97, 110, 32, 100, 97, 121, 10, 41, 59, 10, 67, 82, 
69, 65, 84, 69, 32, 73, 78, 68, 69, 88, 32, 123, 123, 100, 98, 110, 97, 109, 101, 46, 
114, 101, 112, 111, 125, 125, 46, 102, 111, 114, 117, 109, 116, 104, 114, 101, 97, 100, 32, 79, 
78, 32, 123, 123, 98, 97, 114, 101, 46, 114, 101, 112, 111, 46, 102, 111, 114, 117, 109, 112, 
111, 115, 116, 125, 125, 40, 102, 114, 111, 111, 116, 44, 102, 109, 116, 105, 109, 101, 41, 59, 
10, 
0};
char const * fsl_schema_forum_cstr = fsl_schema_forum_cstr_a;
/* end of forum.sql */
/* end of file src/schema_forum_cstr.c */