/// This function detects an equal or colon followed by an escaped quote after an argument
/// then modifies the string to replace the equality with a space.  This is needed
/// to allow the split up function to work properly and is intended to be used with the find_and_modify function
/// the return value is the offset+1 which is required by the find_and_modify function.


/// Convert a flag into an integer value  typically binary flags


// Returns false if not a short option. Otherwise, sets opt name and rest and returns true


// Returns false if not a long option. Otherwise, sets opt name and other side of = and returns true


// Returns false if not a windows style option. Otherwise, sets opt name and value and returns true


// Splits a string into multiple long and short names


/// The list of parents and name joined by "."


/// Get a flag value


/// Parse a config file, throw an error (ParseError:ConfigParseError or FileError) on failure


/// Specify the start and end characters for an array


/// Specify the type string


/// Specify whether the Validator is active or not


/// Specify the application index of a validator


/// get the type of the path from a file name


/// Helper function to allow checks to ignore spaces to be passed to IsMember or Transform


/// If kb_is_1000 is true,
/// interpret 'kb', 'k' as 1000 and 'kib', 'ki' as 1024
/// (same applies to higher order units as well).
/// Otherwise, interpret all literals as factors of 1024.
/// The first option is formally correct, but
/// the second interpretation is more wide-spread
/// (see https://en.wikipedia.org/wiki/Binary_prefix).


/// Split a string into a program name and command line arguments
/// the string is assumed to contain a file name followed by other arguments
/// the return value contains is a pair with the first argument containing the program name and the second
/// everything else.


/// This prints out an option help line, either positional or optional form


/// Set the multi option policy to take last


/// Set the multi option policy to take all arguments


/// Set the multi option policy to join


/// Set the multi option policy to join with a specific delimiter


/// Set the number of expected arguments


/// Set the range of expected arguments


/// Adds a Validator with a built in type name


/// Adds a Validator. Takes a const string& and returns an error message (empty if conversion/check is okay).


/// Adds a transforming Validator with a built in type name


/// Adds a Validator-like function that can change result


/// Adds a user supplied function to run on each item passed in (communicate though lambda capture)


/// Sets required options


/// Remove needs link from an option. Returns true if the option really was in the needs list.


/// Sets excluded options


/// Take the last argument if given multiple times (or another policy)


/// Process the callback


/// Check a name. Requires "-" or "--" for short / long, supports positional name


/// Requires "--" to be removed from string


/// Puts a result at the end


/// Puts a result at the end and get a count of the number of arguments actually added


/// Get a copy of the results


/// Set a custom option size


/// Set a custom option type size range


/// Capture the default value from the original value (if it can be captured)


/// Run the results through the Validators


/** reduce the results in accordance with the MultiOptionPolicy
    @param[out] res results are assigned to res if there if they are different
    */


// Run a result through the Validators


/// Add a single result to the result set, taking into account delimiters


/// Special private constructor for subcommand


/// Set a callback for execution when all parsing and processing has completed
///
/// Due to a bug in c++11,
/// it is not possible to overload on std::function (fixed in c++14
/// and backported to c++11 on newer compilers). Use capture by reference
/// to get a pointer to App if needed.


/// Set a name for the app (empty will use parser to set the name)


/// Set an alias for the app


/// Set the subcommand to be disabled by default, so on clear(), at the start of each parse it is disabled


/// Set the subcommand to be enabled by default, so on clear(), at the start of each parse it is enabled (not
/// disabled)


/// Set the subcommand callback to be executed immediately on subcommand completion


/// ignore extras in config files


/// Ignore case. Subcommands inherit value.


/// Ignore underscore. Subcommands inherit value.


/// Add an option, will automatically understand the type for common types.
///
/// To use, create a variable with the expected type, and pass it in after the name.
/// After start is called, you can use count to see if the value was passed, and
/// the value will be initialized properly. Numbers, vectors, and strings are supported.
///
/// ->required(), ->default, and the validators are options,
/// The positional options take an optional number of arguments.
///
/// For example,
///
///     std::string filename;
///     program.add_option("filename", filename, "description of filename");
///


/// Internal function for adding a flag


/// Add option for callback that is triggered with a true flag and takes no arguments


/// Add option for callback with an integer value


/// Add option for callback (C++14 or better only)


/// Removes an option from the App. Takes an option pointer. Returns true if found and removed.


/// Add a subcommand. Inherits INHERITABLE and OptionDefaults, and help flag


/// Add a previously created app as a subcommand


/// Removes a subcommand from the App. Takes a subcommand pointer. Returns true if found and removed.


/// Get a count of all the arguments processed in options and subcommands, this excludes arguments which were
/// treated as extras.


/// The argumentless form of require subcommand requires 1 or more subcommands


/// Require a subcommand to be given (does not affect help call)
/// The number required can be given. Negative values indicate maximum
/// number allowed (0 for any number). Max number inheritable.


/// Explicitly control the number of subcommands required. Setting 0
/// for the max means unlimited number allowed. Max number inheritable.


/// The argumentless form of require option requires 1 or more options be used


/// Require an option to be given (does not affect help call)
/// The number required can be given. Negative values indicate maximum
/// number allowed (0 for any number).


/// Explicitly control the number of options required. Setting 0
/// for the max means unlimited number allowed. Max number inheritable.


///@}
/// @name Parsing
///@{
//
/// Reset the parsed data


/// Parses the command line - throws errors.
/// This must be called after the options are in but before the rest of the program.


/// Parse a single string as if it contained command line arguments.
/// This function splits the string into arguments then calls parse(std::vector<std::string> &)
/// the function takes an optional boolean argument specifying if the programName is included in the string to
/// process


/// The real work is done here. Expects a reversed vector.
/// Changes the vector to the remaining options.


/// The real work is done here. Expects a reversed vector.


/// Print a nice error message and return the exit code


/// Sets excluded options for the subcommand


/// Sets excluded subcommands for the subcommand


/// Removes an option from the excludes list of this subcommand


/// Removes a subcommand from the excludes list of this subcommand


/// Removes an option from the needs list of this subcommand


/// Removes a subcommand from the needs list of this subcommand


/// Makes a help message, using the currently configured formatter
/// Will only do one subcommand at a time


/// Check the name, case insensitive and underscore insensitive if set


/// Check the options to make sure there are no conflicts.
///
/// Currently checks to see if multiple positionals exist with unlimited args and checks if the min and max options
/// are feasible


/// configure subcommands to enable parsing through the current object
/// set the correct fallthrough and prefix for nameless subcommands and manage the automatic enable or disable
/// makes sure parent is set correctly


/// Internal function to run (App) callback, bottom up


/// Check to see if a subcommand is valid. Give up immediately if subcommand max has been reached.


/// Selects a Classifier enum based on the type of the current argument


/// Read and process a configuration file (main app only)


/// Get envname options if not yet passed. Runs on *all* subcommands.


/// Process callbacks. Runs on *all* subcommands.


/// Run help flag processing if any are found.
///
/// The flags allow recursive calls to remember if there was a help flag on a parent.


/// Verify required options and cross requirements. Subcommands too (only if selected).


/// Process callbacks and such.


/// Throw an error if anything is left over and should not be.


/// Throw an error if anything is left over and should not be.
/// Modifies the args to fill in the missing items before throwing.


/// Internal function to recursively increment the parsed counter on the current app as well unnamed subcommands


/// Internal parse function


/// Parse one config param, return false if not found in any subcommand, remove if it is
///
/// If this has more than one dot.separated.name, go into the subcommand matching it
/// Returns true if it managed to find the option, if false you'll need to remove the arg manually.


/// Fill in a single config option


/// Parse "one" argument (some may eat more than one), delegate to parent if fails, add to missing if missing
/// from master return false if the parse has failed and needs to return to parent


/// Parse a positional, go up the tree to check
/// @param haltOnSubcommand if set to true the operation will not process subcommands merely return false
/// Return true if the positional was used false otherwise


/// Locate a subcommand by name with two conditions, should disabled subcommands be ignored, and should used
/// subcommands be ignored


/// Parse a subcommand, modify args and continue
///
/// Unlike the others, this one will always allow fallthrough
/// return true if the subcommand was processed false otherwise


/// Parse a short (false) or long (true) argument, must be at the top of the list
/// return true if the argument was processed or false if nothing was done


/// Trigger the pre_parse callback if needed


/// Get the appropriate parent to fallthrough to which is the first one that has a name or the main app


/// Helper function to place extra values in the most appropriate position


/// function that could be used by subclasses of App to shift options around into subcommands


/// Add an existing option to the Option_group


/// Add an existing subcommand to be a member of an option_group


/// Helper function to enable one option group/subcommand when another is used


/// Helper function to disable one option group/subcommand when another is used


/// Helper function to mark an option as deprecated


/// Helper function to mark an option as retired


/// Printout a clean, simple message on error (the default in CLI11 1.5+)


/// Printout the full help string on error (if this fn is set, the old default for CLI11)


/// Comma separated join, adds quotes if needed


/// assuming non default segments do a check on the close and open of the segments in a configItem structure


///@brief Insert an item into the LRU.
///
///The item is either added to the queue or its entry is moved to the top of
///the queue. If the item is new and the length of the queue is greater than
///maxlen, then the least recently seen item is evicted from the queue.
///
///@param entry The item to add to the queue.


///@brief Evict the least-recently used item out of the LRU cache.


///@brief Evict items from the LRU cache until it is within its capacity.


//TODO: Use of checkval here is kinda gross. Is there a good way to get rid of
//it?


///Eliminate spaces from the beginning and end of str


///Get only the filename without its extension. That is, convert
///"path/to/file.ext" to "file"


///@brief  Construct a new LayoutfileReader object reading from a given file.
///@author Richard Barnes
///
///@param  layout_filename Layoutfile to read from.


///@brief Advance the reader to the next layoutfile entry.
///@return True if reader advanced successfully; false if not.


///@brief Constructs a new writer object
///@param layout_filename Path+Filename of layoutfile to write


///@brief Adds a new row to the layoutfile


///@brief Add a new entry to the layout file.
///@param filename File to add. Use `filename=""` to indicate a null tile.


/**
    @brief Wraps a flat array in an Array3D object.

    Wraps a flat array in an Array3D object. The Array3D does not take ownership
    of the data.

    @param[in] data0   Pointer to data to wrap
    @param[in] width   Width of the data
    @param[in] height  Height of the data
  */


/**
    @brief Whether or not a cell is NoData using x,y coordinates

    @param[in]  x   X-coordinate of cell to test
    @param[in]  y   Y-coordinate of cell to test

    @return Returns TRUE if the cell is NoData
  */


/**
    @brief Resize the raster. Note: this clears all the raster's data.

    @param[in]   width0    New width of the raster
    @param[in]   height0   New height of the raster
    @param[in]   val0      Value to set all the cells to. Defaults to the
                          raster's template type default value
  */


/**
    @brief Counts the number of cells which are not NoData.
  */


/**
    @brief Returns the number of cells which are not NoData. May count them.

    @return Returns the number of cells which are not NoData.
  */


/**
    @brief Wraps a flat array in an Array2D object.

    Wraps a flat array in an Array2D object. The Array2D does not take ownership
    of the data.

    @param[in] data0   Pointer to data to wrap
    @param[in] width   Width of the data
    @param[in] height  Height of the data
  */


/**
    @brief Loads data from disk into RAM.

    If dumpData() has been previously called, data is loaded from the cache;
    otherwise, it is loaded from a GDAL file. No data is loaded if data is
    already present in RAM.
  */


///Finds the minimum value of the raster, ignoring NoData cells


///Finds the maximum value of the raster, ignoring NoData cells


/**
    @brief Replace one cell value with another throughout the raster. Can
           operate on NoData cells.

    @param[in] oldval   Value to be replaced
    @param[in] newval   Value to replace 'oldval' with
  */


/**
    @brief Counts the number of occurrences of a particular value in the raster.
           Can operate on NoData cells.

    @param[in] val   Value to be be counted

    @return The number of times 'val' appears in the raster. Will be 0 if raster
            is not loaded in RAM.
  */


/**
    @brief Convert from index coordinates to x,y coordinates

    @param[in]  i   Index coordinate
    @param[out] x   X-coordinate of i
    @param[out] y   Y-coordinate of i
  */


/**
    @brief Given a cell identified by an i-coordinate, return the i-coordinate
           of the neighbour identified by dx,dy

    @param[in]  i   i-coordinate of cell whose neighbour needs to be identified
    @param[in] dx   x-displacement of the neighbour from i
    @param[in] dy   y-displacement of the neighbour from i

    @return i-coordinate of the neighbour. Usually referred to as 'ni'
  */


/**
    @brief Flips the raster from top to bottom
  */


/**
    @brief Flips the raster from side-to-side
  */


/**
    @brief Flips the raster about its diagonal axis, like a matrix tranpose.
  */


/**
    @brief Makes a raster larger and retains the raster's old data, similar to resize.

    Note: Using this command requires RAM equal to the sum of the old raster and
    the new raster. The old raster is placed in the upper-left of the new
    raster.

    @param[in] new_width  New width of the raster. Must be >= the old width.
    @param[in] new_height New height of the raster. Must be >= the old height.
    @param[in] val        Value to set the new cells to
  */


/**
    @brief Prints a square of cells centered at x,y. Useful for debugging.

    @param[in]    radius   Output stamp will be 2*radius x 2*radius
    @param[in]        x0   X-coordinate of block center
    @param[in]        y0   Y-coordinate of block center
    @param[in]     color   Print the (x,y) cell in colour?
    @param[in]       msg   Optional message to print above the block
    @param[in]    fwidth   Field width in which to print each array value
    @param[in] precision   Number of decimal digits to display
  */


/**
    @brief Prints the entire array

    @param[in] msg       Optional message to print above the block
    @param[in] fwidth    Field width to print to
    @param[in] precision Precision (number of decimal digits) to print
  */


/**
    @brief Prints the entire array as flow directions

    @param[in] msg       Optional message to print above the block
    @param[in] fwidth    Field width to print to
    @param[in] precision Precision (number of decimal digits) to print
  */


/**
    @brief Prints a square of cells centered at x,y indicating the index of each

    @param[in]    radius   Output stamp will be 2*radius x 2*radius
    @param[in]        x0   X-coordinate of block center
    @param[in]        y0   Y-coordinate of block center
    @param[in]     color   Print the (x,y) cell in colour?
    @param[in]       msg   Optional message to print above the block
    @param[in]    fwidth   Field width in which to print each array value
  */


/**
    @brief Prints the flat indices of the entire array

    @param[in]     msg   Optional message to print above the block
  */


/**
    @brief Multiplies the entire array by a scalar

    @param[in]     x     Value to multiply array by
  */


/**
  @brief Return memory statistics of the process

  This code is drawn from "http://stackoverflow.com/a/671389/752843"

  @param[out]   vmpeak    Peak virtual memory size (kB)
  @param[out]   vmhwm     Peak resident set size (kB)
*/


///@brief Start/reset the progress bar.
///@param total_work  The amount of work to be completed, usually specified in cells.


///@brief Update the visible progress bar, but only if enough work has been done.
///
///Define the global `RICHDEM_NO_PROGRESS` flag to prevent this from having
///an effect. Doing so may speed up the program's execution.


///Stop the progress bar. Throws an exception if it wasn't started.
///@return The number of seconds the progress bar was running.


///@brief Send a pre-serialized object using non-blocking communication.
///
///The object must be pre-serialized because the buffer containing
///the serialization must persist until the communication is complete. It makes
///more sense to manage this buffer outside of this library.


///@brief Check tag of incoming message. Blocksing.


///@brief Get my unique process identifier (i.e. rank)


///Start the timers. Throws an exception if timer was already running.


///Stop the timer. Throws an exception if timer was already stopped.
///Calling this adds to the timer's accumulated time.
///
///@return The accumulated time in seconds.


///Returns the timer's accumulated time. Throws an exception if the timer is
///running.
///
///@return The timer's accumulated time, in seconds.


///Returns the time between when the timer was started and the current
///moment. Throws an exception if the timer is not running.
///
///@return Time since the timer was started and current moment, in seconds.


///Takes the program's command line arguments and prints to stdout a header with
///a variety of useful information for identifying the particulars of what was
///run.


//When a set value X is passed to the data structure, this checks to see if
//the set exists. If not, the set is created, along with all the sets between
//the old maximum set id and X.


// Create a DisjointDenseIntSet with `N` initial sets preallocated. More sets
// can be dynamically allocated as the data structure is used.


// Follows a set's chain of parents until a set which is its own parent is
// reached. This ultimate parent's id is returned as the representative id of
// the set in question. Note that this collapses the chain of parents so that
// after this method has run every set between the one in question and the
// ultimate parent points to the ultimate parent. This means that while the
// first call to this function may take `O(N)` lookups in the worst-case (less
// due to the use of ranks, as explained below), subsequent calls to any set
// in the chain will take `O(1)` time. This technique is known as "path
// compression".


// Join two sets into a single set. Note that we "cannot" predict the `id` of
// the resulting set ahead of time.


// Using `unionSet` merges two sets in a way which does not allow us to decide
// which set is the parent; however, `unionSet` helps guarantee fast queries.
// `mergeAintoB` sacrifices speed but preserves parenthood by always making A
// a child of B, regardless of the height of `B`.


///Creates a ManagedVector with \p size members each set to \p default_val
///
///@param[in] size         Number of elements to be created in the vector
///@param[in] default_val  Initial value of the elements


///Creates a ManagedVector which wraps \p data0 of length \p size0
///
///@param[in] data         Memory to wrap
///@param[in] size         Number of elements to wrap


//TODO: Should this clear old data?
//Copy Constructor


//234
//105
//876
//d8_masked_FlowDir
/**
  @brief  Helper function to d8_flow_flats()
  @author Richard Barnes (rbarnes@umn.edu)

  This determines a cell's flow direction, taking into account flat membership.
  It is a helper function to d8_flow_flats()

  @param[in]  &flat_mask      A mask from resolve_flats_barnes()
  @param[in]  &labels         The labels output from resolve_flats_barnes()
  @param[in]  x               x coordinate of cell
  @param[in]  y               y coordinate of cell

  @returns    The flow direction of the cell
*/


/**
  @brief Build a gradient away from the high edges of the flats
  @author Richard Barnes (rbarnes@umn.edu)

  The queue of high-edge cells developed in FindFlatEdges() is copied
  into the procedure. A breadth-first expansion labels cells by their
  distance away from terrain of higher elevation. The maximal distance
  encountered is noted.

  @param[in]  &flats        2D array indicating flat membership from FindFlats()
  @param[out] &flat_mask    A 2D array for storing flat_mask
  @param[in]  &edges        The high-edge FIFO queue from FindFlatEdges()
  @param[out] &flat_height  Vector with length equal to max number of labels
  @param[in]  &labels       2D array storing labels developed in LabelFlat()

  @pre
    1. Every cell in **labels** is marked either 0, indicating that the cell is
       not part of a flat, or a number greater than zero which identifies the
       flat to which the cell belongs.
    2. Any cell without a local gradient is marked IS_A_FLAT in **flats**.
    3. Every cell in **flat_mask** is initialized to 0.
    4. **edges** contains, in no particular order, all the high edge cells of
       the DEM (those flat cells adjacent to higher terrain) which are part of
       drainable flats.

  @post
    1. **flat_height** will have an entry for each label value of **labels**
       indicating the maximal number of increments to be applied to the flat
       identified by that label.
    2. **flat_mask** will contain the number of increments to be applied
       to each cell to form a gradient away from higher terrain; cells not in a
       flat will have a value of 0.
*/


/**
  @brief Builds gradient away from the low edges of flats, combines gradients
  @author Richard Barnes (rbarnes@umn.edu)

  The queue of low-edge cells developed in FindFlatEdges() is copied
  into the procedure. A breadth-first expansion labels cells by their
  distance away from terrain of lower elevation. This is combined with
  the gradient from BuildAwayGradient() to give the final increments of
  each cell in forming the flat mask.

  @param[in]  &flats        2D array indicating flat membership from FindFlats()
  @param[in,out] &flat_mask A 2D array for storing flat_mask
  @param[in]  &edges        The low-edge FIFO queue from FindFlatEdges()
  @param[in]  &flat_height  Vector with length equal to max number of labels
  @param[in]  &labels       2D array storing labels developed in LabelFlat()

  @pre
    1. Every cell in **labels** is marked either 0, indicating that the cell
       is not part of a flat, or a number greater than zero which identifies
       the flat to which the cell belongs.
    2. Any cell without a local gradient is marked IS_A_FLAT in **flats**.
    3. Every cell in **flat_mask** has either a value of 0, indicating
       that the cell is not part of a flat, or a value greater than zero
       indicating the number of increments which must be added to it to form a
       gradient away from higher terrain.
    4. **flat_height** has an entry for each label value of **labels**
       indicating the maximal number of increments to be applied to the flat
       identified by that label in order to form the gradient away from higher
       terrain.
    5. **edges** contains, in no particular order, all the low edge cells of
       the DEM (those flat cells adjacent to lower terrain).

  @post
    1. **flat_mask** will contain the number of increments to be applied
       to each cell to form a superposition of the gradient away from higher
       terrain with the gradient towards lower terrain; cells not in a flat
       have a value of 0.
*/


//! Registers a shared pointer with the archive
/*! This function is used to track shared pointer targets to prevent
          unnecessary saves from taking place if multiple shared pointers
          point to the same data.

          @internal
          @param addr The address (see shared_ptr get()) pointed to by the shared pointer
          @return A key that uniquely identifies the pointer */


//! Registers a polymorphic type name with the archive
/*! This function is used to track polymorphic types to prevent
          unnecessary saves of identifying strings used by the polymorphic
          support functionality.

          @internal
          @param name The name to associate with a polymorphic type
          @return A key that uniquely identifies the polymorphic type name */


//! Construct the output archive
/*! @param derived A pointer to the derived ArchiveType (pass this from the derived archive) */


//! Registers a shared pointer to its unique identifier
/*! After a shared pointer has been allocated for the first time, it should
          be registered with its loaded id for future references to it.

          @param id The unique identifier for the shared pointer
          @param ptr The actual shared pointer */


//! Registers a polymorphic name string to its unique identifier
/*! After a polymorphic type has been loaded for the first time, it should
          be registered with its loaded id for future references to it.

          @param id The unique identifier for the polymorphic type
          @param name The name associated with the tyep */


//! Constructs parse error


//! Allocates a new node from the pool, and optionally assigns name and value to it.
//! If the allocation request cannot be accomodated, this function will throw std::bad_alloc.
//! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
//! will call rapidxml::parse_error_handler() function.
//! \param type Type of node to create.
//! \param name Name to assign to the node, or 0 to assign no name.
//! \param value Value to assign to the node, or 0 to assign no value.
//! \param name_size Size of name to assign, or 0 to automatically calculate size from name string.
//! \param value_size Size of value to assign, or 0 to automatically calculate size from value string.
//! \return Pointer to allocated node. This pointer will never be NULL.


//! Allocates a new attribute from the pool, and optionally assigns name and value to it.
//! If the allocation request cannot be accomodated, this function will throw std::bad_alloc.
//! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
//! will call rapidxml::parse_error_handler() function.
//! \param name Name to assign to the attribute, or 0 to assign no name.
//! \param value Value to assign to the attribute, or 0 to assign no value.
//! \param name_size Size of name to assign, or 0 to automatically calculate size from name string.
//! \param value_size Size of value to assign, or 0 to automatically calculate size from value string.
//! \return Pointer to allocated attribute. This pointer will never be NULL.


//! Allocates a char array of given size from the pool, and optionally copies a given string to it.
//! If the allocation request cannot be accomodated, this function will throw std::bad_alloc.
//! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
//! will call rapidxml::parse_error_handler() function.
//! \param source String to initialize the allocated memory with, or 0 to not initialize it.
//! \param size Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated.
//! \return Pointer to allocated char array. This pointer will never be NULL.


//! Sets name of node to a non zero-terminated string.
//! See \ref ownership_of_strings.
//!

//! Note that node does not own its name or value, it only stores a pointer to it.
//! It will not delete or otherwise free the pointer on destruction.
//! It is reponsibility of the user to properly manage lifetime of the string.
//! The easiest way to achieve it is to use memory_pool of the document to allocate the string -
//! on destruction of the document the string will be automatically freed.
//!

//! Size of name must be specified separately, because name does not have to be zero terminated.
//! Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated).
//! \param name Name of node to set. Does not have to be zero terminated.
//! \param size Size of name, in characters. This does not include zero terminator, if one is present.


//! Sets value of node to a non zero-terminated string.
//! See \ref ownership_of_strings.
//!

//! Note that node does not own its name or value, it only stores a pointer to it.
//! It will not delete or otherwise free the pointer on destruction.
//! It is reponsibility of the user to properly manage lifetime of the string.
//! The easiest way to achieve it is to use memory_pool of the document to allocate the string -
//! on destruction of the document the string will be automatically freed.
//!

//! Size of value must be specified separately, because it does not have to be zero terminated.
//! Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated).
//!

//! If an element has a child node of type node_data, it will take precedence over element value when printing.
//! If you want to manipulate data of elements using values, use parser flag rapidxml::parse_no_data_nodes to prevent creation of data nodes by the parser.
//! \param value value of node to set. Does not have to be zero terminated.
//! \param size Size of value, in characters. This does not include zero terminator, if one is present.


//! Gets previous attribute, optionally matching attribute name.
//! \param name Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
//! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
//! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
//! \return Pointer to found attribute, or 0 if not found.


//! Gets next attribute, optionally matching attribute name.
//! \param name Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
//! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
//! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
//! \return Pointer to found attribute, or 0 if not found.


//! Constructs an empty node with the specified type.
//! Consider using memory_pool of appropriate document to allocate nodes manually.
//! \param type Type of node to construct.


//! Gets first child node, optionally matching node name.
//! \param name Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
//! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
//! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
//! \return Pointer to found child, or 0 if not found.


//! Gets last child node, optionally matching node name.
//! Behaviour is undefined if node has no children.
//! Use first_node() to test if node has children.
//! \param name Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
//! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
//! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
//! \return Pointer to found child, or 0 if not found.


//! Gets previous sibling node, optionally matching node name.
//! Behaviour is undefined if node has no parent.
//! Use parent() to test if node has a parent.
//! \param name Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
//! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
//! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
//! \return Pointer to found sibling, or 0 if not found.


//! Gets next sibling node, optionally matching node name.
//! Behaviour is undefined if node has no parent.
//! Use parent() to test if node has a parent.
//! \param name Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
//! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
//! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
//! \return Pointer to found sibling, or 0 if not found.


//! Gets first attribute of node, optionally matching attribute name.
//! \param name Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
//! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
//! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
//! \return Pointer to found attribute, or 0 if not found.


//! Gets last attribute of node, optionally matching attribute name.
//! \param name Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
//! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
//! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
//! \return Pointer to found attribute, or 0 if not found.


//! Prepends a new child node.
//! The prepended child becomes the first child, and all existing children are moved one position back.
//! \param child Node to prepend.


//! Appends a new child node.
//! The appended child becomes the last child.
//! \param child Node to append.


//! Inserts a new child node at specified place inside the node.
//! All children after and including the specified node are moved one position back.
//! \param where Place where to insert the child, or 0 to insert at the back.
//! \param child Node to insert.


//! Removes first child node.
//! If node has no children, behaviour is undefined.
//! Use first_node() to test if node has children.


//! Removes last child of the node.
//! If node has no children, behaviour is undefined.
//! Use first_node() to test if node has children.


//! Removes specified child from the node
// \param where Pointer to child to be removed.


//! Prepends a new attribute to the node.
//! \param attribute Attribute to prepend.


//! Appends a new attribute to the node.
//! \param attribute Attribute to append.


//! Inserts a new attribute at specified place inside the node.
//! All attributes after and including the specified attribute are moved one position back.
//! \param where Place where to insert the attribute, or 0 to insert at the back.
//! \param attribute Attribute to insert.


//! Removes first attribute of the node.
//! If node has no attributes, behaviour is undefined.
//! Use first_attribute() to test if node has attributes.


//! Removes last attribute of the node.
//! If node has no attributes, behaviour is undefined.
//! Use first_attribute() to test if node has attributes.


//! Removes specified attribute from node.
//! \param where Pointer to attribute to be removed.


//! Loads file into the memory. Data will be automatically destroyed by the destructor.
//! \param filename Filename to load.


//! Loads file into the memory. Data will be automatically destroyed by the destructor
//! \param stream Stream to load from


//! Saves the state of some type inheriting from enable_shared_from_this
/*! @param ptr The raw pointer held by the shared_ptr */


//! Specify specific options for the XMLOutputArchive
/*! @param precision The precision used for floating point numbers
              @param indent Whether to indent each line of XML
              @param outputType Whether to output the type of each serialized object as an attribute */


//! Construct, outputting to the provided stream upon destruction
/*! @param stream  The stream to output to.  Note that XML is only guaranteed to flush
                         its output to the stream upon destruction.
          @param options The XML specific options to use.  See the Options struct
                         for the values of default parameters */


//! Saves some binary data, encoded as a base64 string, with an optional name
/*! This can be called directly by users and it will automatically create a child node for
          the current XML node, populate it with a base64 encoded string, and optionally name
          it.  The node will be finished after it has been populated.  */


//! Creates a new node that is a child of the node at the top of the stack
/*! Nodes will be given a name that has either been pre-set by a name value pair,
          or generated based upon a counter unique to the parent node.  If you want to
          give a node a specific name, use setNextName prior to calling startNode.

          The node will then be pushed onto the node stack. */


//! Appends an attribute to the current top level node


//! Construct, reading in from the provided stream
/*! Reads in an entire XML document from some stream and parses it as soon
          as serialization starts

          @param stream The stream to read from.  Can be a stringstream or a file. */


//! Loads some binary data, encoded as a base64 string, optionally specified by some name
/*! This will automatically start and finish a node to load the data, and can be called directly by
          users.

          Note that this follows the same ordering rules specified in the class description in regards
          to loading in/out of order */


//! Prepares to start reading the next node
/*! This places the next node to be parsed onto the nodes stack.

          By default our strategy is to start with the document root node and then
          recursively iterate through all children in the order they show up in the document.
          We don't need to know NVPs do to this; we'll just blindly load in the order things appear in.

          We check to see if the specified NVP matches what the next automatically loaded node is.  If they
          match, we just continue as normal, going in order.  If they don't match, we attempt to find a node
          named after the NVP that is being loaded.  If that NVP does not exist, we throw an exception. */


//! Finishes reading the current node


//! Loads a type best represented as a float from the current top node


//! Loads a type best represented as a double from the current top node


//! Loads a type best represented as a long double from the current top node


//! Advances to the next sibling node of the child
/*! If this is the last sibling child will be null after calling */


//! Searches for a child with the given name in this node
/*! @param searchName The name to search for (must be null terminated)
            @return The node if found, nullptr otherwise */


//! Writes size bytes of data to the output stream


//! Reads size bytes of data from the input stream


//! Specify specific options for the JSONOutputArchive
/*! @param precision The precision used for floating point numbers
              @param indentChar The type of character to indent with
              @param indentLength The number of indentChar to use for indentation
                             (0 corresponds to no indentation) */


//! Construct, outputting to the provided stream
/*! @param stream The stream to output to.
          @param options The JSON specific options to use.  See the Options struct
                         for the values of default parameters */


//! Saves some binary data, encoded as a base64 string, with an optional name
/*! This will create a new node, optionally named, and insert a value that consists of
          the data encoded as a base64 string */


//! Starts a new node in the JSON output
/*! The node can optionally be given a name by calling setNextName prior
          to creating the node

          Nodes only need to be started for types that are themselves objects or arrays */


//! Designates the most recently added node as finished


//! Write the name of the upcoming node and prepare object/array state
/*! Since writeName is called for every value that is output, regardless of
          whether it has a name or not, it is the place where we will do a deferred
          check of our node state and decide whether we are in an array or an object.

          The general workflow of saving to the JSON archive is:

            1. (optional) Set the name for the next node to be created, usually done by an NVP
            2. Start the node
            3. (if there is data to save) Write the name of the node (this function)
            4. (if there is data to save) Save the data (with saveValue)
            5. Finish the node
          */


//! Construct, reading from the provided stream
/*! @param stream The stream to read from */


//! Loads some binary data, encoded as a base64 string
/*! This will automatically start and finish a node to load the data, and can be called directly by
          users.

          Note that this follows the same ordering rules specified in the class description in regards
          to loading in/out of order */


//! Get the name of the current node, or nullptr if it has no name


//! Adjust our position such that we are at the node with the given name
/*! @throws Exception if no such named node exists */


//! Searches for the expectedName node if it doesn't match the actualName
/*! This needs to be called before every load or node start occurs.  This function will
          check to see if an NVP has been provided (with setNextName) and if so, see if that name matches the actual
          next name given.  If the names do not match, it will search in the current level of the JSON for that name.
          If the name is not found, an exception will be thrown.

          Resets the NVP name after called.

          @throws Exception if an expectedName is given and not found */


//! Starts a new node, going into its proper iterator
/*! This places an iterator for the next node to be parsed onto the iterator stack.  If the next
          node is an array, this will be a value iterator, otherwise it will be a member iterator.

          By default our strategy is to start with the document root node and then recursively iterate through
          all children in the order they show up in the document.
          We don't need to know NVPs to do this; we'll just blindly load in the order things appear in.

          If we were given an NVP, we will search for it if it does not match our the name of the next node
          that would normally be loaded.  This functionality is provided by search(). */


//! Finishes the most recently started node


//! Returns true if the current machine is little endian
/*! @ingroup Internal */


//! Initialize the binding


//! Writes appropriate metadata to the archive for this polymorphic type


/*! Wrap a raw polymorphic pointer in a shared_ptr to its true type

              The wrapped pointer will not be responsible for ownership of the held pointer
              so it will not attempt to destroy it; instead the refcount of the wrapped
              pointer will be tied to a fake 'ownership pointer' that will do nothing
              when it ultimately goes out of scope.

              The main reason for doing this, other than not to destroy the true object
              with our wrapper pointer, is to avoid meddling with the internal reference
              count in a polymorphic type that inherits from std::enable_shared_from_this.

              @param dptr A void pointer to the contents of the shared_ptr to serialize */


//! Does the actual work of saving a polymorphic shared_ptr
/*! This function will properly create a shared_ptr from the void * that is passed in
          before passing it to the archive for serialization.

          In addition, this will also preserve the state of any internal enable_shared_from_this mechanisms

          @param ar The archive to serialize to
          @param dptr Pointer to the actual data held by the shared_ptr */


//! Does the actual work of saving a polymorphic shared_ptr
/*! This function will properly create a shared_ptr from the void * that is passed in
          before passing it to the archive for serialization.

          This version is for types that do not inherit from std::enable_shared_from_this.

          @param ar The archive to serialize to
          @param dptr Pointer to the actual data held by the shared_ptr */


//! Demangles the type encoded in a string
/*! @internal */


// Initialize with the reference values for the permutation vector


// Generate a new permutation vector based on the value of seed


//Preparer divides up the input raster file into tiles which can be processed
//independently by the Consumers. Since the tileing may be done on-the-fly or
//rely on preparation the user has done, the Preparer routine knows how to deal
//with both. Once assemebled, the collection of jobs is passed off to Producer,
//which is agnostic as to the original form of the jobs and handles
//communication and solution assembly.


//After running this function on all the top and bottom edge cells, we can
//quickly determine the ultimate destination of any initial cell.


//However, at this point we know how much flow accumulation to add to each cell.
//Therefore, we add this additional accumulation to each cell as we pass it.


/** Generic version of armlength. Will use putp iteratively to
    find the delay corresponding to a photon trajectory backward
    from t along "arm" */


// --- OriginalLISA LISA class ---------------------------------------------------------


// OriginalLISA does not move; hence the length (but not the
// direction!) of positive and negative arms is the same


// --- ModifiedLISA LISA class ---------------------------------------------------------


// implement simple LISA rotation in xy plane with period of a year
// take input time in seconds


// full constructor; initialize positions and arm vectors
// measure everything in seconds
// if the last argument is negative, switch 2 and 3; needed for coherence with the Montana simulator


// Set the correct components of the rotation matrix for the current time
// set also the position of the guiding center


// Return the position of "craft" at time t in vector p
// does so by multiplying the initial position of the craft (with respect to the guiding center)
// by a rotation matrix computed at the current time (if it is not already cached)


// fit to armlength modulation from armlength.nb


// --- EccentricInclined LISA class -----------------------------------------------------


// positions of spacecraft according to the LISA simulator


// need this because basicLISA's putn will call basicLISA's armlength


/* Box-Muller transform to get Gaussian deviate from uniform random,
   number, adapted from GSL 1.4 randist/gauss.c

   Since pos is not actually used, this will give sensible results only
   within a buffered environment */


/* This will work as long as doubles are 8 bytes */


// pass 0 for bigendian, 1 for littleendian, -1 for native


// will pad with zeros on the negative index side
// NEW BEHAVIOR: will pad with zeros outside the sampled length, but will
// warn once


/* Note that FIR makes a copy of the coefficient array. Normally filters
   are defined so that a[0] = 1 */


/* Note that IIR makes copies of the coefficient arrays. Normally filters
   are defined so that a[0] = 1 and b[0] = 0; b[0] is not used, anyway */


// do everything much more carefully (and slowly) to avoid rounding error
// there may be a more efficient way to do this


// in these expressions the order of the delays is physically
// motivated, but the combination still does not cancel laser
// noise (from the final ref. lasers) in ModifiedLISA


// to be updated with physical-delay expressions
// and with multiple arm expressions


// fast C++ replacement for getobs and getobsc in lisautils.py


// can improve precision by calling value with two times
// (assuming the underlying implementation supports it)


// note that the call to putn is already computing the armlength that we request later
// we could make putn return the corresponding armlength


// the next three names are not standard!


// this version takes the parameters of the basic noises and lets us allocate objects as needed


// this version takes arrays of basic-noise parameters, allowing for different noises on different objects,
// and lets us allocate objects as needed


// this version takes pointers to noise objects, allowing for user-specified noises on different objects


// locking procedure: use negative numbers for starred lasers


// this is a debugging function, which appears in lisasim-swig.i


// standard noises for TDI, with utility function


// --- Standard Noise factories ---


/* TDIdoppler::TDIdoppler(LISA *mylisa, Noise *proofnoise[6],Noise *shotnoise[6],Noise *lasernoise[6],double laserfreqs[6])
    : TDInoise(mylisa,proofnoise,shotnoise,lasernoise) {
    lf[1] = laserfreqs[0];
    lfs[1] = laserfreqs[1];

    lf[2] = laserfreqs[2];
    lfs[2] = laserfreqs[3];

    lf[3] = laserfreqs[4];
    lfs[3] = laserfreqs[5];
}; */


// this code is repeated from above, and calls to these static methods
// could be used above


// full constructor for SimpleBinary; takes frequency in Hertz
// b and l are SSB ecliptic latitude and longitude


// compatible with MLDC GalacticBinary; note different convention for amplitudes (or equivalently inclination)


// originally written to compare with John's fortran code


// the error on the arms is defined in seconds


// we're doing something funny here: we're defining Noise-like objects
// which will actually provide the LISA armlength measures, based on a regular
// (but noisy) sampling of the actual armlengths


// Unfortunately it is hard to make the distinction between the
// baseline and the accurate armlength within the LISANoise class. But
// this should be good enough.


// Box-Muller transform to get Gaussian deviate from uniform random number
// adapted from GSL 1.4 randist/gauss.c


// modified from Numerical Recipes


// it would be better to throw an exception!


// constructor based on SampledNoise. Need to pass:
// - pointer to noise buffer
// - number of samples
// - sampling time
// - requested prebuffer time
// - normalization factor
// - the noise exponent ex, which determines the filtering


// should update the paper to say that the earliest accessible time
// actually depends on the interpolation scheme!


// end catch_matchers_floating.cpp
// start catch_matchers_generic.cpp


/**
 * initializes the default surface
 */


/**
 * Calculation of force and torque due to radiation pressure
 *
 * \par Assumptions and Limitations
 *  - Assumes that flux magnitude is positive.
 *  - Will only be called if flux magnitude is positive.
 *  - Assumes spherical surface.
 * \param[in] flux_mag the magnitude of the incident flux
 * \param[in] flux_struc_hat the unit vector in structural frame for the flux vector.
 * \param[in] calculate_forces boolean indicating whether to calculate forces.
 */


/**
 * Test for necessity of maintaining thermal updates, and performs them as
 * necessary
 */


/**
 * initializes the base surface
 */


/**
 * Calculation of force, torques and irradiance due to ThirdBody flux.
 * \param[in,out] third_body_ptr Third body that emits radiation
 * \param[in] calculate_forces Calculate forces on this facet if true.
 */


/**
 * To initialize the values during each update run
 */


/**
 * Defines the facet data values
 * \param[in] flat_plate pointer to the flat plate object
 */


/**
 * Initializes the Facet for use in the model
 * \param[in] center_grav center of gravity position\n Units: M
 */


/**
 * Calculation of force and torque due to radiation pressure
 *
 * \par Assumptions and Limitations
 *  - Only called when flux_mag > 0
 * \param[in] flux_mag incident flux (per unit area)\n Units: N/m
 * \param[in] flux_struct_hat the flux unit vector in structural frame
 * \param[in] calculate_forces on/off flag for whether to calculate forces.
 */


/**
 * Calculates the radiative emission force, accumulated force, and torque
 * acting on a facet.
 */


/******************************************************************************
  Purpose:
    (Initialize the radiation pressure model when using a
    RadiationDefaultSurface (i.e. spherical, uniform properties.))
******************************************************************************/


/**
 * Used to update the model when the surface is a default surface.
 */


/**
 * initializes the third body
 * \param[in] dyn_mgr_ptr pointer to the dynamics manager
 */


/**
 * Calculates the effect of shadowing by a third body.
 */


/**
 * generate_alpha( rho_adj, delta: generates an approximate alpha-value given
 * a relative disk size and fraction of maximum possible eclipse
 * \param[in] rho_adj relative disk size
 * \param[in] delta fraction of eclipse achieved.
 */


/**
 * convert from the old style framework in which the shadow geometry was
 * owned by the RadiationSource (same for all third bodies) to the new style
 * framework where the geometry is owned by each ThirdBody
 * \param[in] old_shadow_geometry integer representation of the shadow geometry enumeration.
 */


/**
 * Primary executable for handling the Third Body effects
 * @return shading fraction
 * \param[in] real_time Current time.\n Units: s
 * \param[in] veh_struc_frame Unused.
 */


/**
 * Updates the state of the Third Body.  Because the ThirdBody may be
 * associated with multiple vehicles, and because its state
 * typically changes much more slowly than the vehicle anyway, it is
 * not always necessary to update the ThirdBodyState.
 */


/**
 * Add a set of radiation parameters to those available to Radiation
 * Surface.
 * \param[in] to_add pointer to the parameter list to add.
 */


/******************************************************************************
  Purpose:
    (Constructor for RadiationPressure)
******************************************************************************/


/**
 * Initializes the source and third bodies.
 * \param[in] dyn_mgr_ptr The dynamics manager
 */


/**
 * Updates the model at each time step.
 * \param[in] veh_struc_frame The vehicle structural reference frame.
 * \param[in] center_grav position of center of mass\n Units: M
 * \param[in] scale_factor the scale between the simulator time and the dynamic time.
 * \param[in] real_time The current time, e.g. TAI or UT1.\n Units: s
 */


/**
 * Used to modify the flux for shadowing.
 * \param[in] real_time The current time, e.g. TAI or UT1.\n Units: s
 * \param[in] veh_struc_frame Structure frame of vehicle
 */


/**
 * Adds a third body to the vector storage of third bodies
 * \param[in] third_body_ptr pointer to ThirdBody
 */


/**
 * Sets a Third Body to be active when it previously was not
 * \param[in] third_body_name Name of ThirdBody
 */


/**
 * Sets a Third Body to be inactive when it previously was not
 * \param[in] third_body_name Name of ThirdBody
 */


/**
 * Finds the index of a third body based on its name
 * @return void
 * \param[in] third_body_name Name of ThirdBody
 */


/**
 * Sets the value calculate_forces
 * \param[in] value whether forces are needed
 */


/**
 * Run sanity checks on input variables
 */


/**
 * Defines the inherent facet values
 * \param[in] facet pointer to the facet
 * \param[in] facet_thermal reference to the thermal components of the facet.
 * \param[in] params pointer to the list of material parameters for the facet.
 */


/**
 * Records the data for the Flat Plate Radiation Facet.
 * @return pointer to the interaction facet that this function creates.
 * \param[in] facet pointer to the facet
 * \param[in] params pointer to the set of parameters for the facet.
 */


/**
 * Tests to ensure that the factory can function on the facet as
 * intended.
 * @return Boolean, is this the correct factory?
 * \param[in] facet pointer to the facet being manipulated by the factory
 */


/**
 * Initializes the radiation surface.
 * \param[in] center_grav position of center of mass\n Units: M
 */


/**
 * Allocates memory for an array of radiation facets
 * \param[in] size Size of array
 */


/**
 * Turns facet memory into radiaiton facet memory.
 * \param[in] facet pointer to the facet
 * \param[in] factory pointer to the facet factory
 * \param[in] params pointer to the generic facet parameter.
 * \param[in] index index value in the facet list.
 */


/**
 * systematically calls the method to calculate the interaction on each facet.
 * \param[in] flux_mag Magnitude of incident flux
 * \param[in] flux_struc_hat unit vector of incident flux
 * \param[in] calculate_forces boolean indicating whether to calculate forces.
 */


/**
 * systematically calls the method to calculate the interaction of each facet
 * with ThirdBody flux.
 * \param[in,out] third_body_ptr Third body that emits radiation.
 * \param[in] calculate_forces Calculate forces on the surface if true.
 */


/**
 * systematically calls the method to accumulate thermal sources on each facet.
 */


/**
 * systematically calls the method to integrate the temperature variation for each facet.
 */


/**
 * systematically calls the method to ensure that the same for each facet.
 */


/**
 * systematically calls the method to wrap up the radiation pressure calculation on each facet and accumulate forces and
 * torques over all facets.
 */


/**
 * To attach thermal integrators from each facet to the integration
 * group of a DynBody
 * \param[in,out] dyn_body Body to which integrators are to be added.
 */


/*****************************************************************************
  Purpose:
    (calculates the flux vector from the vehicle's position.)
*****************************************************************************/


/**
 * Initializes the source object for use in the Radiation Pressure model
 * \param[in] dyn_mgr_ptr pointer to the dynamics manager
 */


/******************************************************************************
  Purpose:
    (Initialize the radiation pressure model when using a RadiationSurface (i.e.
    with facets).)
******************************************************************************/


/**
 * Used to update the model when the surface comprises facets.
 */


/**
 * Create a FlatPlateAeroFacet from a flat plate facet and a
 * FlatePlateAeroParams object
 * @return The new FlatPlateAeroFacet. Note that this is allocated and YOU are responsible for destroying it at the end!
 * \param[in] facet The FlatPlate. This MUST be a flat plate or the algorithm will send a failure message
 * \param[in] params FlatPlateAeroParams. This MUST be of the type FlatPlateAeroParams, or the algorithm will send a
 * failture message\n Units: The
 */


/**
 * FlatPlateAeroFactory specific implementation of this function.
 * If the Facet is of type FlatPlate, returns true. False otherwise
 * @return true if facet is a FlatPlate, false otherwise
 * \param[in] facet The facet to check
 */


/**
 * The FlatPlateAeroFacet specific implementation of aerodynamic
 * drag force, based on the given parameters
 * \param[in] rel_vel_mag The magnitude of the relative velocity\n Units: M/s
 * \param[in] rel_vel_struct_hat The unit vector of the total relative velocity, in the structural frame
 * \param[in] aero_drag_param_ptr The aerodynamic drag parameters used for drag calculation
 * \param[in] center_grav The center of gravity of the vehicle, in the structural frame\n Units: M
 */


/**
 * FlatPlateThermalAeroFactory specific implementation of this function.
 * If the Facet is of type FlatPlate, returns true. False otherwise
 * @return true if facet is a FlatPlate, false otherwise
 * \param[in] facet The facet to check
 */


/**
 * Calculates the total aerodynamic drag force and torque, from
 * the information given
 * \param[in] inertial_velocity vehicle velocity in inertial RF\n Units: M/s
 * \param[in] atmos_ptr Pointer to the AtmosphereState used for density and wind information
 * \param[in] T_inertial_struct Transformation matrix from the inertial frame to the structural
 * \param[in] mass kg Mass of the vehicle
 * \param[in] center_grav position of the center of gravity, in the structural frame\n Units: M
 */


/**
 * Add a named set of facet params to the surface factory. Intended
 * to be used when an aerodynamic specific surface is created, to
 * convert a basic facet to an aerodynamic interaction facet. This
 * MUST be a parameter inheriting from AeroParam, or the function
 * will fail and send a failure message
 * \param[in] to_add The facet parameters to add
 */


/**
 * Allocates an array of AeroFacet pointers, of the
 * size indicated by the input variable
 * \param[in] size The size of the needed array\n Units: cnt:
 */


/**
 * Allocates a particular interaction facet, from an inputted general
 * facet, using the inputted parameters and interaction facet
 * factory. This facet is then placed at the index given. If the
 * correct InteractionFacetFactory and Facet Params are not given
 * for the aerodynamic interaction or for the type of facet given,
 * a fail message will be sent
 * \param[in] facet The basic facet used to create the interaction facet
 * \param[in] factory The factory used to create the interaction facet
 * \param[in] params The aero params used to create the interaction facet
 * \param[in] index Where the new interaction facet will be placed in the aero_facets array\n Units: cnt
 */


/**
 * The implementation for this aerodynamic drags force and torque
 * calculations. Can be overriden by an inheriting class to create
 * extensibility
 * \param[in] velocity_mag The magnitude of the relative velocity of the vehicle; not used here but some child classes
 * need it\n Units: M/s \param[in] rel_vel_hat The unit vector of the relative velocity of the vehicle, in the
 * structural frame \param[in] aero_drag_param_ptr The aerodynamic drag parameters used to calculate drag \param[in]
 * mass The current mass of the vehicle\n Units: kg \param[out] force The aerodynamic force, in the structural frame\n
 * Units: N \param[out] torque The aerodynamic torque, in the structural frame\n Units: N*M
 */


/**
 * Overloaded functions that create a ContactPair and pass the address
 * of it to the Contact class for addition to the list of pairs.
 * This function is called to create a pair that only contains a subject.
 * @return ContactPair that was created
 */


/**
 * Overloaded functions that create a ContactPair and pass the address
 * of it to the Contact class for addition to the list of pairs.
 * This function is called when a subject and target are known.
 * @return ContactPair that was created
 * \param[in,out] target target ContactFacet
 * \param[in] contact Contact object used to find the pair interaction
 */


/**
 * Use the relstate and radius of contact to calculate a contact point
 * on this facet.
 * \param[in] nvec direction vector between the two facets
 */


/**
 * Calculate the torque generated on the vehicle by the facet.  Assumes
 * that the force is in the vehicle structural frame, but that close_point is not.
 * \param[in] tmp_force force from one contact interaction.\n Units: N
 */


/**
 * Creates an interaction surface, in the inter_surface parameter,
 * from the given SurfaceModel. The InteractionSurfaceFactory
 * should contain all necessary InteractionFacetFactories and
 * FacetParams already
 * \param[in] surface The surface model used to create the interaction surface
 * \param[out] inter_surface Where the interaction surface will be produced
 */


/**
 * Add a named set of facet params to the surface factory. Intended
 * to be used when an contact specific surface is created, to
 * convert a basic facet to an contact interaction facet. This
 * MUST be a parameter inheriting from ContactParam, or the function
 * will fail and send a failure message
 * \param[in] to_add The facet parameters to add
 */


/**
 * Determine if contact has occurred between the facets of the pair.
 */


/**
 * Initialize the contact pair by setting the subject, target, and creating
 * the relstate if possible.
 * \param[in,out] subject_facet subject ContactFacet
 * \param[in,out] target_facet target ContactFacet
 */


/**
 * Overloaded functions that creates a ContactPair and pass the address
 * of it to the Contact class for addition to the list of pairs.
 * This function is called when a subject and target are known.
 * @return ContactPair that was created
 * \param[in,out] target target ContactFacet
 * \param[in] contact Contact object used to find the pair interaction
 */


/**
 * Find the point on the surface that coorisponds to the closest point on
 * line segments using the radius value
 * \param[in] nvec vector between line points
 */


/**
 * Allocates an array of ContactFacet pointers, of the
 * size indicated by the input variable
 * \param[in] size The size of the needed array\n Units: cnt:
 */


/**
 * Creates an interaction facet or more accurately a contact
 * facet from a basic facet and set of parameters
 * \param[in] facet The basic facet used to create the interaction facet
 * \param[in] factory The factory used to create the interaction facet
 * \param[in] params The contact params used to create the interaction facet
 * \param[in] index Where the new interaction facet will be placed in the contact_facets array\n Units: cnt
 */


/**
 * collect the forces and torques from all the facets in this contact
 * surface
 */


/**
 * Create a PointContactFacet from a CircularFlatPlate facet and a
 * ContactParams object
 * @return The new EllipsoidContactFacet. Note that this is allocated and YOU are responsible for destroying it at the
 * end! \param[in] facet The CircularFlatPlate. This MUST be a circular flat plate or the algorithm will send a failure
 * message \param[in] params ContactParams
 */


/**
 * PointContactFacetFactory specific implementation of this function.
 * If the Facet is of type CircularFlatPlate, returns true. False otherwise
 * @return true if facet is a FlatPlateCircular, false otherwise
 * \param[in] facet The facet to check
 */


/**
 * Check a pair of contact params for a match to the ones defined for
 * this pair_interaction.
 * @return bool
 * \param[in] subject_params parameters of the subject
 * \param[in] target_params parameters of the target
 */


/**
 * test whether the pair is in range for interaction
 * @return bool
 */


/**
 * Determine if contact can occur between the two facets.
 * @return bool
 */


/**
 * Determine if the pair has a target facet.
 * @return bool
 */


/**
 * Make sure the two contact facets are not on the same mass tree.
 * @return bool
 */


/**
 * force calculation for a simple spring based contact
 * dynamics model, takes in geometry information from the appropriate
 * ContactFacet::calculate_forces but doesn't know about specific type of
 * ContactFacet
 * \param[in,out] subject subject frame of the relative state
 * \param[in,out] target target frame of the relative state
 * \param[in] rel_state relative state between subject and target in subject frame
 * \param[in] penetration_vector vector that characterises the interpenetration of the subject and the target
 * \param[in] rel_velocity relative velocity of the subject and the target in the subject frame
 */


/**
 * iterate through contact pairs list then call the
 * appropriate contact resolution functions
 */


/**
 * Initialize ContactFacets and the mananger by cleaning up the pair list
 * \param[in,out] manager Dynamics Manager
 */


/**
 * Check to see if a pair of facets already exists.
 * @return bool
 * \param[in,out] facet_1 ContactFacet
 * \param[in,out] facet_2 ContactFacet
 */


/**
 * Register one ContactFacet with all inclusive interactions
 * with other registered ContactFacets.
 * \param[in,out] facet ContactFacet
 */


/**
 * Register an array of ContactFacets with all inclusive
 * interactions with other registered ContactFacets.
 * \param[in,out] facets array of ContactFacets
 * \param[in] nFacets number of ContactFacets in array
 */


/**
 * Register two facets as a pair.
 * \param[in,out] facet1 Contact Facet 1
 * \param[in,out] facet2 Contact Facet 2
 */


/**
 * Regiser to arrays of facets and create specific pairs between all of
 * them.
 * \param[in,out] facets1 array of ContactFacets
 * \param[in] nFacets1 number of ContactFacets in array
 * \param[in,out] facets2 array of ContactFacets
 * \param[in] nFacets2 number of ContactFacets in array
 */


/**
 * find a PairInteraction baced on a set of ContactParams.
 * @return pointer to a PairInteraction
 * \param[in] params_1 ContactParams from a ContactFacet
 * \param[in] params_2 ContactParams from a ContactFacet
 */


/**
 * Create a vehicle point from the base facet position and orientation
 * and store the created vehicle point in the contact facet
 */


/*******************************************************************************
 Function: initialize
 Purpose: (initialize terrain pointer and planet fixed coordinates)
 *******************************************************************************/


/*******************************************************************************
 Function: in_range
 Purpose: (test whether the pair is in range for interaction)
 *******************************************************************************/


/*******************************************************************************
 Function: is_active
 Purpose: (deturmine if the subject and ground facets are active)
 *******************************************************************************/


/*******************************************************************************
  Function: ContactGround
  Purpose: (Default Constructor)
*******************************************************************************/


/*******************************************************************************
  Function: ~ContactGround
  Purpose: (Destructor)
*******************************************************************************/


/*******************************************************************************
Function: check_contact_ground
Purpose: (iterate through ground interaction list then call the
   appropriate contact resolution functions)
*******************************************************************************/


/*******************************************************************************
 Function: get_ground_interaction
 Purpose: (Get the ground_interaction for a specific ContactFacet.)
 *******************************************************************************/


/*******************************************************************************
 Function: is_unique_ground_interaction
 Purpose: (Check if a contact facet already has an GroundInterface defined)
 *******************************************************************************/


/*******************************************************************************
 Function: initialize_ground
 Purpose: (create the ground interfaces list)
 Class: (initialization)
 *******************************************************************************/


/*******************************************************************************
 Function: register_ground_facet
 Purpose: (Register a GroundFacet with the ContactGround class.)
 Class: (initialization)
 *******************************************************************************/


/*******************************************************************************
 Function: in_contact
 Purpose: (deturmine if the subject facet is in contact with the ground facet)
 *******************************************************************************/


/*******************************************************************************
  Function: GroundFacet
  Purpose: (Default constructor)
*******************************************************************************/


/*******************************************************************************
 Function: create_interaction
 Purpose: (Overloaded function to create a GroundInteraction of the appropriate type and return
 a pointer to the Contact class.)
 Purpose: (initialization)
 *******************************************************************************/


/**
 * create a name for a relstate out of two facet names
 * @return char**
 * \param[in] name1 name of first contact facet
 * \param[in] name2 name of second contact facet
 * \param[in,out] out_str output name for the relstate
 */


/**
 * calculate the closest points between two line segments
 * @return success
 * \param[in] p1 vector to one point of the first line seg\n Units: M
 * \param[in] p2 vector to one point of the first line seg\n Units: M
 * \param[in] p3 vector to one point of the second line seg\n Units: M
 * \param[in] p4 vector to one point of the second line seg\n Units: M
 * \param[out] pa vector to close_point on line 1\n Units: M
 * \param[out] pb vector to close_point on line 2\n Units: M
 */


/**
 * Collects together all surface and internal thermal sources that affect
 * a facet.
 */


/**
 * Initialize the thermal aspects of the facet.
 * \param[in] temperature temperature of facet\n Units: K
 * \param[in] surface_area area of facet surface\n Units: M*M
 */


/**
 * Runge-Kutta 4th order integration of the temperature variation
 * @return void
 */


/**
 * ThermalIntegrableObject default constructor.
 */


/**
 * Integrate the thermal state
 * @param[in]     dyn_dt        Dynamic time step, in dynamic time seconds.
 * @param[in]     target_stage  The stage of the integration process
 *                              that the integrator should try to attain.
 * @return The status (time advance, pass/fail status) of the integration.
 */


/**
 * Initialize temperature and cache a pointer to the ThermalFacetRider
 * @param temperature -- initial temperature
 * @param associated_rider -- the associated ThermalFacetRider
 */


/**
 * Compute emitted power and the time derivative of temperature.
 */


/**
 * update the thermal aspects of all facets
 * \param[in] surface_ptr pointer the surface.
 */


/**
 * Perform GravityTorque updates.
 */


/**
 * Many of the static methods are a pass-through to a private non-static method,
 * with the static method testing that the pass-through is valid. This method
 * performs that test and handles the failure response.
 * @return True if Master is not null
 * \param[in] error_is_fatal True => call fail
 * \param[in] line __LINE__
 */


/**
 * Set the debug level.
 * \param[in] level New debug level
 */


/**
 * Set the guard_enabled flag.
 * \param[in] value New value
 */


/**
 * Query whether all allocated memory has been freed.
 *
 * \par Assumptions and Limitations
 *  - Intended for testing use only.
 *     This method does not use a thread-safe query.
 * @return Has all memory been freed?
 */


/**
 * Register a class with the memory manager.
 *
 * \par Assumptions and Limitations
 *  - This method must not be called before the singleton memory manager has
 *     been created or after it has been destroyed.
 *     A fatal error results when this is not true.
 *  - Access to this method is through the JEOD memory allocation macros.
 *     Use in any other context is caveat emptor.
 * @return Type entry for the class
 * \param[in] tdesc Type pre-descriptor
 */


/**
 * Get a type descriptor from the memory manager's type table.
 *
 * \par Assumptions and Limitations
 *  - This method must not be called before the singleton memory manager has
 *     been created or after it has been destroyed.
 *     A fatal error results when this is not true.
 * @return Type descriptor
 * \param[in] typeid_info C++ type descriptor
 */


/**
 * Get a type descriptor from the memory manager's type table.
 *
 * \par Assumptions and Limitations
 *  - This method must not be called before the singleton memory manager has
 *     been created or after it has been destroyed.
 *     A fatal error results when this is not true.
 * @return Type descriptor
 * \param[in] name_type Typeid or demangled name
 * \param[in] type_name Type name
 */


/**
 * Allocate memory and register the allocated memory with JEOD.
 *
 * \par Assumptions and Limitations
 *  - This method must not be called before the singleton memory manager has
 *     been created or after it has been destroyed.
 *     A fatal error results when this is not true.
 *  - The allocated memory is not constructed by this method.
 *     The calling routine should initialize the memory with placement new.
 *  - Access to this method is through the JEOD memory allocation macros.
 *     Use in any other context is caveat emptor.
 * @return Allocated memory
 * \param[in] is_array Memory constructed by new[] if set
 * \param[in] nelems Number of elements to be allocated
 * \param[in] fill Byte fill pattern
 * \param[in] tentry Type entry
 * \param[in] file Source file containing JEOD_ALLOC
 * \param[in] line Line number containing JEOD_ALLOC
 */


/**
 * Query whether some address was allocated by JEOD.
 *
 * \par Assumptions and Limitations
 *  - This method must not be called before the singleton memory manager has
 *     been created or after it has been destroyed.
 *     A fatal error results when this is not true.
 * @return True if allocated by JEOD
 * \param[in] addr Memory to be queried
 * \param[in] file Source file containing query
 * \param[in] line Line number containing query
 */


/**
 * Destroy memory previously registered with JEOD.
 *
 * \par Assumptions and Limitations
 *  - This method must not be called before the singleton memory manager has
 *     been created or after it has been destroyed.
 *     A fatal error results when this is not true.
 *  - The provided memory shall not be used in any way after calling this method.
 *     This method destructs and frees that memory.
 *  - Access to this method is through the JEOD memory allocation macros.
 *     Use in any other context is caveat emptor.
 * \param[in,out] addr Memory to be destroyed
 * \param[in] delete_array DELETE_ARRAY (true) vs. DELETE_OBJECT
 * \param[in] file Source file containing delete
 * \param[in] line Line number containing delete
 */


/**
 * Set the memory manager's simulation interface mode.
 *
 * \par Assumptions and Limitations
 *  - This method must not be called before the singleton memory manager has
 *     been created or after it has been destroyed.
 *     A fatal error results when this is not true.
 * \param[in] new_mode New mode
 */


/**
 * Purpose:
 *   (Prepare for a set of operations that must be done atomically.)
 * Assumptions and limitations:
 *   This method must be used in conjunction with end_atomic_block.@code
 *        try {
 *           begin_atomic_block ();
 *           operate_on_protected_members();
 *           end_atomic_block (false);
 *        }
 *        catch (...) {
 *           end_atomic_block (true);
 *           throw;
 *        }
 *     @endcode
 *    (See the class header for a detailed description.))
 */


/**
 * End an atomic set of operations.
 * \param[in] ignore_errors Ignore errors from unlock?
 */


/**
 * Add a location identifier string to the string table.
 *
 * \par Assumptions and Limitations
 *  - Operations on the map must be atomic.
 *     This method satisfies that requirement.
 * @return String table index
 * \param[in] str String to add
 */


/*
Purpose:
  (Retrieve the index for the specified type from the type table,
   adding an entry if needed.)
Assumptions and limitations:
  ((Operations on the type table must be atomic.
    This method *does not* satisfy that requirement.))
*/


/**
 * Return the type entry for the input type descriptor, adding the
 * descriptor to the type table if the type has not yet been registered.
 *
 * \par Assumptions and Limitations
 *  - The mangled name returned by the std::type_info name method is unique
 *     across all allocatable types and is invariant.
 *  - Operations on the map must be atomic.
 *     This method satisfies that requirement.
 * @return Type descriptor index
 * \param[in] tdesc Type pre-descriptor
 */


/**
 * Retrieve the descriptor for the specified type from the type table.
 *
 * \par Assumptions and Limitations
 *  - Operations on the map must be atomic.
 *     This method satisfies that requirement.
 * @return Type descriptor
 * \param[in] typeid_info Type info
 */


/**
 * Retrieve the descriptor for the specified type from the type table.
 *
 * \par Assumptions and Limitations
 *  - Operations on the map must be atomic.
 *     This method satisfies that requirement.
 * @return Type entry
 * \param[in] name_type Name type spec
 * \param[in] type_name Type name
 */


/*
Purpose:
  (Create a unique identifier for an allocation.)
Assumptions and limitations:
  ((Operations on the map must be atomic.
    This method satisfies that requirement.))
*/


/**
 * Reset the unique identifier for a restart.
 *
 * \par Assumptions and Limitations
 *  - Operations on the map must be atomic.
 *     This method satisfies that requirement.
 * \param[in] unique_id Unique id of a restored allocation
 */


/**
 * Find the allocation table entry that matches the input address,
 * and delete it if delete_entry is true.
 *
 * The matching is strict. A match occurs only if the input address is a key in
 * the allocation table. An error is reported if the input address is inside
 * the allocated space corresponding to one of the allocation table entries.
 *
 * Output values:
 *  - Entry not found:
 *    - The @a found_addr and @a found_type are set to NULL.
 *    - The @a found_item is not touched.
 *  - Entry found:
 *    - The @a found_addr is set to the key of the found entry.
 *    - The @a found_item is copied from the value of the found entry.
 *    - The @a found_type points to the type_descriptor entry for the
 *      found item's type.
 *
 * \par Assumptions and Limitations
 *  - Operations on the map must be atomic.
 *     This method satisfies that requirement.
 * \param[in] addr Address
 * \param[in] delete_entry Indicates entry is to be deleted
 * \param[in] file Source file containing JEOD_XXX
 * \param[in] line Line number containing JEOD_XXX
 * \param[out] found_addr Address found in table
 * \param[out] found_item Descriptor for above
 * \param[out] found_type Type descriptor
 */


/**
 * Add the specified addr/item pair to the table.
 *
 * \par Assumptions and Limitations
 *  - Operations on the map must be atomic.
 *     This method satisfies that requirement.
 *  - The specified address must not already be in the table.
 * \param[in] addr Newly allocated memory
 * \param[in] item Description of that memory
 * \param[in] tdesc Description of the type
 * \param[in] file Source file containing JEOD_ALLOC
 * \param[in] line Line number containing JEOD_ALLOC
 */


/**
 * Find and delete the alloc table entry with the smallest unique id,
 * setting the provided references with info about the deleted item.
 * The addr and type are set to NULL if the table is empty.
 *
 * \par Assumptions and Limitations
 *  - Operations on the map must be atomic.
 *     This method satisfies that requirement.
 *  - If the restore doesn't work the sim will be knee deep in alligators.
 * \param[out] addr Address found in table
 * \param[out] item Descriptor for above
 * \param[out] type Type descriptor
 */


/**
 * Destruct a MemoryManager object.
 *
 * \par Assumptions and Limitations
 *  - In a multi-threaded environment,
 *     - This destructor shall be called once and once only to destroy the
 *       singleton JeodMemoryManager object.
 *     - The thread that calls this destructor shall wait until all other threads
 *       that access JEOD memory have finished, either by default or by force.
 *     .
 *     Note that this is a constraint on the simulation engine, not on JEOD.
 */


/**
 * Generate a shutdown report.
 *
 * \par Assumptions and Limitations
 *  - This method is to be called by the destructor only.
 *     It freely accesses tabular data, the assumption being that the
 *     mutex and flags that protect that data are now gone.
 */


/*
Purpose:
  (Wipe out all allocated memory in anticipation of restoring the
   memory in some previously recording checkpoint file.)
Assumptions and limitations:
  ((If the restore doesn't work the sim will be knee deep in alligators.))
*/


/**
 * Restore one chunk of allocated memory per a checkpoint file entry.
 *
 * \par Assumptions and Limitations
 *  - This restores the allocation, but not the contents. The contents will soon
 *     be restored by the simulation engine.
 * \param[in] mangled_type_name Mangled type name
 * \param[in] unique_id Unique id
 * \param[in] nelements Number of elements
 * \param[in] is_array True => an array
 */


/*
Purpose:
  (Allocate memory for use with placement new and register that memory with
   with the memory manager and with the simulation engine.)
Assumptions and limitations:
  ((This method will be invoked via the JEOD memory allocation macros.
    Use in any other context is a case of caveat emptor.)
   (The type descriptor index must index the type descriptor that describes the
    type to be created.)
   (The memory is allocated but not constructed. Construction is the
    responsibility of the caller. The JEOD memory allocation macros construct
    the allocated memory via placement new.))
*/


/**
 * Allocate memory if that was not already done by the caller and
 * register the memory with JEOD and with an external agent.
 *
 * \par Assumptions and Limitations
 *  - This method will be invoked via the JEOD memory allocation macros.
 *     Use in any other context is caveat emptor.
 *  - The corresponding delete macro will be used to delete the memory.
 *     Using the C free function or the C++ delete operator can cause *big*
 *     problems.
 *  - The delete macro will be expanded with the same placement new option
 *     as was used in the allocation macro that resulted in this call.
 *  - The memory is not constructed.
 *     That is the job of the expansion of the JEOD_ALLOC macro.
 * \param[in] addr Memory to be registered
 * \param[in] unique_id Unique id
 * \param[in] placement_new Was memory allocated by this model?
 * \param[in] is_array Was memory allocated as an array?
 * \param[in] nelems Array size
 * \param[in] tentry Type entry
 * \param[in] file Source file containing JEOD_ALLOC
 * \param[in] line Line number containing JEOD_ALLOC
 */


/**
 * Query whether some address was allocated by JEOD.
 * @return True if the address in question was allocated by JEOD
 * \param[in] addr Memory to be queried
 * \param[in] file Source file containing query
 * \param[in] line Line number containing query
 */


/**
 * Destroy a chunk of memory and knowledge about it.
 * This includes
 *  - De-registering the memory with JEOD and with an external agent.
 *  - Invoking the destructor in the case of a structured type.
 *  - Releasing the memory to the system.
 * \param[in,out] addr Memory to be destroyed
 * \param[in] delete_array DELETE_ARRAY (true) vs. DELETE_OBJECT
 * \param[in] file Source file containing delete
 * \param[in] line Line number containing delete
 */


/*
Purpose:
  (Allocate memory.)
Assumptions and limitations:
  ((This is a low-level allocation function. It does not
     - Register the allocated memory with JEOD or with an external agent.
     - Construct the newly-allocated memory.)
   (The returned address should not be released using the C free function
    or C++ delete operator.\n
    Failure to obey this restriction will result in big problems.))
*/


/**
 * Release memory.
 *
 * \par Assumptions and Limitations
 *  - This is a low-level de-allocation function.
 *     It does not
 *      - De-register the memory with JEOD or with an external agent.
 *      - Destruct the memory.
 * \param[in,out] addr Memory to be freed
 * \param[in] length Buffer size
 * \param[in] guard Memory was guarded if set
 * \param[in] alloc_idx Allocation index
 * \param[in] file Source file containing delete
 * \param[in] line Line number containing delete
 */


/**
 * The jeod_alloc.hh macros insert a space between the type name and the
 * asterisks. Delete that space.
 * @return Name, as c++ string
 * \param[in] type_name Name, as C string
 */


/**
 * Get the pointer dimensionality of the type.
 */


/**
 * Get the descriptor for the base (non-pointer) of some pointer type.
 * @note
 * Assumes GNU c++ name mangling, where 'const' is always preceded by a space.
 */


/**
 * Non-default constructor.
 * Note that construction is via a char* as that is what the C preprocessor
 * creates when it stringifies a token.
 * \param[in] obj_typeid Type ID for type
 * \param[in] type_attr Type attributes
 * \param[in] type_size Type size
 * \param[in] is_exportable Register instances?
 */


/**
 * Construct a type specification string.
 * @return Type string
 * \param[in] item Item descriptor
 */


/**
 * Construct the flags for a new JeodMemoryItem.
 * @return Constructed flags
 * \param[in] placement_new Constructed with placement new?
 * \param[in] is_array Constructed with new []?
 * \param[in] is_guarded Is the item an array?
 * \param[in] is_structured Is the item a structured data type?
 */


/**
 * Construct a JeodMemoryItem.
 * The data are essentially constant, so the only viable way to set elements
 * to meaningful values is via this non-default constructor.
 * \param[in] placement_new Constructed with placement new?
 * \param[in] is_array Constructed with new []?
 * \param[in] is_guarded Is the item an array?
 * \param[in] is_structured Is the item a structured data type?
 * \param[in] nelems_in Number of elements
 * \param[in] type_idx Type descriptor (index)
 * \param[in] alloc_idx Macro invocation info (index)
 */


/**
 * Set the unique identifier.
 * \param[in] id Unique identifier
 */


/**
 * Set the is_registered flag.
 * \param[in] value New value of the is_registered flag
 */


/**
     * Construct a JEOD_ATTRIBUTES_TYPE that represents a primitive type.
     * @return Constructed attributes object.
     */


/**
     * Construct a JEOD_ATTRIBUTES_TYPE that represents a pointer type.
     * @param is_exportable  True => type is exportable.
     * @return Constructed attributes object.
     */


/**
     * Construct a JEOD_ATTRIBUTES_TYPE that represents a void pointer.
     * @return Constructed attributes object.
     */


/**
     * Construct a JEOD_ATTRIBUTES_TYPE that represents a structured type.
     * @param is_exportable  True => type is exportable.
     * @return Constructed attributes object.
     */


/**
     * Construct an array of objects.
     * @return         Constructed array.
     * @param  nelem   Number of elements in the array
     * @param  addr    Address to be constructed
     */


/**
     * Destruct an array of objects.
     * @param  nelem   Number of elements in the array
     * @param  addr    Address to be destructed
     */


/**
     * Default constructor.
     * Note that JEOD reserves table index 0 as meaning nothing.
     */


/**
     * Find the index number at which key/value pair is stored in the table.
     * \return         Index number mapped by the key
     * \param[in] key  Key
     */


/**
     * Add a key/value pair to the table.
     * \return         Index number mapped by the key
     * \param[in] key  Key
     * \param[in] val  Value
     */


/**
     * Delete the key and associated data from the table.
     * Use with care.
     * \param[in] key  Key
     * \throw std::invalid_argument on attempting to delete an element that
     *    is not in the table.
     */


/**
     * Destroy memory.
     * @param[in] placement_new  Constructed with placement new?
     * @param[in] is_array       Allocated as an array?
     * @param[in] nelem          Number of elements
     * @param[in,out] addr       Address to destroy
     */


/**
     * Create a copy of the descriptor.
     * @return Copy.
     */


/**
     * Find the most-derived object corresponding to the input pointer.
     * @param[in] addr Pointer to be examined
     * @return Pointer to most-derived object.
     */


/**
     * Delete an array of instances of type @a Type.
     * In other words, delete[] addr.
     * @param[in,out] addr Address to be deleted
     */


/**
     * Delete a single instance of type @a Type.
     * In other words, delete addr.
     * @param[in,out] addr Address to be deleted
     */


/*******************************************************************************
  function: update_articulation_internal
  purpose: (A FlatPlate specific version of update_articulation_internal.
            Updates the direction of the normal from the local struct
            frame to the global, user set one)
*******************************************************************************/


/**
 * Used to add an interaction facet factory for use in the
 * surface factory
 * \param[in] to_add The interaction facet factory to add
 */


/**
 * Add a set of facet parameters for use in the interaction
 * surface factory
 * \param[in] to_add The facet parameters to add
 */


/*******************************************************************************
  function: add_facets
  purpose: (copies an array of facet pointers into the surface model)
*******************************************************************************/


/*******************************************************************************
  function: add_facet
  purpose: (copies a single facet pointer into the surface model.)
*******************************************************************************/


/*******************************************************************************
  function: initialize_mass_connections
  purpose: (Initialize mass connections in all contained facets)
*******************************************************************************/


/*******************************************************************************
  function: update_articulation
  purpose: (update the global zeroth order state, in the vehicle structural
            frame, of the facets in this surface model)
*******************************************************************************/


/*******************************************************************************
  function: initialize_mass_connection
  purpose: (Connects the facet, through
            a user set name in the facet, to a mass body in
            the supplied tree of mass bodies)
*******************************************************************************/


/*******************************************************************************
  function: update_articulation
  purpose: (The per-facet function to update articulation. Calls the virtual
            and protected method update_articulation_internal on each facet,
            which is the function that should be overridden in inheritence
            situations.)
*******************************************************************************/


/*******************************************************************************
  function: update_articulation_internal
  purpose: (A version of update_articulation_internal specific to
            FlatPlate)
*******************************************************************************/


/**
Set non-default values.
*/


/**
     * Copy constructor.
     * @note
     * This copies the source's ContainerType contents only.
     * The Checkpointable contents and the added checkpoint members are
     * not copied.
     * @param source Container to be copied.
     */


/**
     * Perform a checkpoint-restart action that will, in part, restore the object
     * to its state at the time of the checkpoint.
     *
     * In the case of a JeodContainer, the actions are "clear", "insert", and
     * "cleanup". The checkpoint writer automatically creates an initial "clear"
     * entry as the first entry in the checkpoint file for a JeodCheckpointable
     * object and a "cleanup" entry as the final entry. An "insert" entry is
     * created for each element in the container's contents.
     */


/**
     * Construct a JeodPointerContainer.
     */