/**
 * Java Settlers - An online multiplayer version of the game Settlers of Catan
 * This file Copyright (C) 2014-2017,2019-2020 Jeremy D Monin <jeremy@nand.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * The maintainer of this program can be reached at jsettlers@nand.net
 **/
package soc.game;

import java.util.ArrayList;
import java.util.List;

import soc.message.SOCMessage;  // strictly for isSingleLineAndSafe

/**
 * A Special Item in a game that uses Settlers scenarios or expansions.
 * An item may be usable game-wide, or held by/associated with a player.
 * During game play, players may be allowed to {@code PICK} (choose), {@code SET}, or {@code CLEAR} special items;
 * the meaning of these items and actions is scenario-specific. See {@code typeKey} list below for usage and meaning.
 * See {@link #playerPickItem(String, SOCGame, SOCPlayer, int, int)} and
 * {@link #playerSetItem(String, SOCGame, SOCPlayer, int, int, boolean)} for API details.
 *

 * Special Items are unrelated to {@link SOCInventoryItem}s.
 *

 * Example use: The Wonders chosen by players in the {@link SOCGameOption#K_SC_WOND _SC_WOND} scenario.
 *

 * Special Items are per-game and/or per-player.  In {@link SOCGame} and {@link SOCPlayer}
 * they're accessed by an item type key.  For compatibility among scenarios and expansions,
 * this key should be a {@link SOCGameOption} keyname; if an option has more than one
 * special item type, {@code typeKey} should be optionName + "/" + a short alphanumeric key.
 * Please document the Special Item type(s) in the SOCGameOption's javadoc, including
 * whether each is per-game, per-player, or both (for more convenient access).
 * If the game option is for a scenario, instead mention the Special Item in the game option's javadoc
 * and document its use in the {@link SOCScenario} constant's javadoc.
 *

 * In some scenarios, Special Items may have requirements for players to build or use them.
 * See {@link SOCSpecialItem.Requirement} javadoc for more details.  To check requirements,
 * call {@link SOCSpecialItem#checkRequirements(SOCPlayer, boolean)}.
 *

 * All Special Items are currently "public" and their details are known to all players,
 * not hidden by a player like Victory Point dev cards. If a future use would need some items to
 * be hidden or "private", at that time a flag field would need to be added to the object and
 * set in {@link #makeKnownItem(String, int)}.
 *
 *
Optional Fields:

 * Some {@code typeKey}s may use the {@link #getLevel()} and {@link #getStringValue()} fields;
 * their meaning is type-specific.
 *
 *
Non-Networked Fields:

 * During game setup, {@link #makeKnownItem(String, int)} can be called for convenience at both the
 * server and client from {@link SOCGame#updateAtBoardLayout()}:
 *

 * The cost and requirement constant fields are initialized at the server and at the client, not sent over the network.
 * Because of their specific scope and known use, it's easier to set them up in a factory method here than to create,
 * send, and parse messages with all details of the game's Special Items.  If a new Special Item type is created
 * for a new scenario or expansion, the client would most likely need new code to handle that scenario or
 * expansion, so the new item type's field initialization can be added to the factory at that time.
 * See {@link #makeKnownItem(String, int)}.
 *

 * Locks: Field values are not synchronized here. If a specific item type or access pattern
 * requires synchronization, do so outside this class and document the details.  Some methods here
 * require locking as described in their javadocs.
 *

 * Special items must be {@link Cloneable} for use in copy constructors; see {@link #clone()} for details.
 *
 *
Current scenarios and {@code typeKey}s:

 *
 *
{@link SOCGameOption#K_SC_WOND _SC_WOND} - Wonders

 *
 *  In this scenario, the game has a list of unique "Wonders", indexed 1 to {@link SOCGame#maxPlayers} + 1.
 *  (The 6-player game includes another copy of the first two wonders.)
 *  To win the game, a player must take ownership of exactly one of these, and build 4 levels of it.
 *

 *  A reference to the player's {@code SOCSpecialItem} is kept in the game's Special Item list, and also placed
 *  at index 0 of the player's Special Item list.
 *

 *  This scenario uses the {@link #getStringValue()} field to identify the wonder object with a localized name:
 *  "w1" is the Theater, "w5" is the Cathedral, etc. The 6-player game includes another copy of
 *  the first two wonders: 2 special items will have "w1", 2 will have "w2".
 *
 *

 *
 On their own turn, a player can {@code PICK} a wonder from the game's list.  Each player can pick at most 1;
 *    no other player can pick the same one.  If they are able to pick that wonder, doing so builds its first level.
 *    When sending a PICK request, the wonder's game item index and player item index must meet the requirements
 *    of {@link SOCScenario#K_SC_WOND}.
 *
 Game state must be {@link SOCGame#PLAY1 PLAY1}
 *
 There are requirements ({@link #req}) to pick each wonder; different wonders have different requirements
 *
 There is a resource cost to build each level; different wonders have different costs
 *
 When the player first picks a Wonder to build its first level, player loses 1 ship.
 *    (In the physical game, the ship becomes an ownership marker on the Wonders card.) This "starting piece cost"
 *    is {@link #getStartingCostPiecetype()}. All wonders have the same piece type cost: {@link SOCPlayingPiece#SHIP}.
 *
 Can build several levels per turn; each level is built with a {@code PICK} request
 *
 When level 4 is built, player wins the game, even if they have less than 10 VP
 *
 When a player reaches 10 VP, and has a higher level of wonder than any other player (no ties), they win
 *    on their turn.
 *

 *  For more details see {@link SOCScenario#K_SC_WOND}.
 *
 * @since 2.0.00
 */
public class SOCSpecialItem
    implements Cloneable
{

    // Per-scenario static data:

    // SC_WOND: Wonders

    /**
     * To win the game in {@link SOCGameOption#K_SC_WOND _SC_WOND}, player can build this many
     * levels (4) of their Wonder.
     */
    public static final int SC_WOND_WIN_LEVEL = 4;

    /**
     * Requirements for the Wonders in the {@link SOCGameOption#K_SC_WOND _SC_WOND} scenario.
     * Index 0 unused.  The 6-player game includes another copy of the first two wonders.
     * Used by {@link #makeKnownItem(String, int)}.
     *

     * Parsing each of these is tested in {@link soctest.game.TestSpecialItem#testRequirementParseGood()};
     * if you change the contents here, also update the test cases in that method.
     */
    private static final String[] REQ_SC_WOND = { null, "2C", "S@N2", "C@P,5L", "S@N1", "C,6V", "2C", "S@N2" };

    /**
     * Costs for the Wonders in the {@link SOCGameOption#K_SC_WOND _SC_WOND} scenario.
     * Index 0 unused.  The 6-player game includes another copy of the first two wonders.
     * Each 5-element array is { clay, ore, sheep, wheat, wood }. Used by {@link #makeKnownItem(String, int)}.
     */
    private static final int[][] COST_SC_WOND =
    {
        null,
        // clay, ore, sheep, wheat, wood
        { 1, 0, 3, 0, 1 },  // theater
        { 0, 0, 1, 1, 3 },  // great bridge
        { 0, 2, 0, 3, 0 },  // monument
        { 3, 0, 0, 1, 1 },  // great wall
        { 1, 3, 0, 1, 0 },  // cathedral
        { 1, 0, 3, 0, 1 },  // theater
        { 0, 0, 1, 1, 3 }   // great bridge
    };

    /**
     * {@link #sv} string keys for the Wonders in the {@link SOCGameOption#K_SC_WOND _SC_WOND} scenario.
     * {@code sv} is used in this scenario to identify the wonder with a localized name.
     * Index 0 unused.  The 6-player game includes another copy of the first two wonders.
     * Used by {@link #makeKnownItem(String, int)}.
     */
    private static final String[] SV_SC_WOND = { null, "w1", "w2", "w3", "w4", "w5", "w1", "w2" };

    // End of per-scenario static data

    /**
     * Item's optional game item index, or -1, as used with {@link SOCGame#getSpecialItem(String, int, int, int)}.
     */
    protected int gameItemIndex;

    /**
     * The player who owns this item, if any. Will be null for certain items
     * which belong to the game and not to players.
     */
    protected SOCPlayer player;

    /** Optional coordinates on the board for this item, or -1. An edge or a node, depending on item type. */
    protected int coord;

    /** Optional level of construction or strength, or 0. */
    protected int level;

    /**
     * Optional string value field, or null; this field's meaning is specific to the item's {@code typeKey}.
     * See {@link #getStringValue()} for details.
     */
    protected String sv;

    /**
     * Optional constant cost to buy, use, or build the next level, or {@code null}.
     * Not sent over the network; see {@link SOCSpecialItem class javadoc}
     * and {@link #makeKnownItem(String, int)}.
     * @see #startingCostPiecetype
     */
    protected SOCResourceSet cost;

    /**
     * Optional constant extra starting "cost" piece: A type of {@link SOCPlayingPiece}
     * the player must give up to pick (buy, use, or build) the first level, or -1 if unused.
     * See {@link #getStartingCostPiecetype()} for details.
     */
    protected int startingCostPiecetype = -1;

    /**
     * Optional requirements to buy, use, or build the next level, or {@code null}.
     * Not sent over the network; see {@link SOCSpecialItem class javadoc}
     * and {@link #makeKnownItem(String, int)}.
     */
    public final List<Requirement> req;

    /**
     * Create a scenario/expansion's special item if known. This is a factory method for game setup convenience.
     * The known item's {@link #req requirements} and cost will be filled from static data.
     * Sets {@link #getGameIndex()} to {@code idx}.
     *

     * Currently known {@code typeKey}s:
     *

     *
 {@link SOCGameOption#K_SC_WOND _SC_WOND}: Wonders
     *

     * If {@code typeKey} is unknown, the item will be created with {@code null} cost and requirements,
     * equivalent to calling {@link #SOCSpecialItem(SOCPlayer, int, SOCResourceSet, String) new SOCSpecialItem}
     * {@code (null, -1, null, null)}.
     *
     * @param typeKey  Special item type.  Typically a {@link SOCGameOption} keyname;
     *    see {@link SOCSpecialItem class javadoc} for details.
     * @param idx  Index within game's Special Item list, or -1 if not part of that list
     * @return A Special Item at no coordinate (-1) and unowned by any player, with cost/requirements if known,
     *     or {@code null} cost and requirements otherwise.
     */
    public static final SOCSpecialItem makeKnownItem(final String typeKey, final int idx)
    {
        // If you update this method or add a scenario here, update soctest.game.TestSpecialItem method testMakeKnownItem.

        final String[] typeReqs, typeSV;  // Per-index requirements and SV, or null
        final int[][] typeCosts;    // Per-index costs, or null
        final int itemLevel;    // initial level
        final int startingCostPiecetype;  // piece type required for level 1, or -1

        if (typeKey.equals(SOCGameOption.K_SC_WOND))
        {
            typeReqs = REQ_SC_WOND;
            typeSV = SV_SC_WOND;
            typeCosts = COST_SC_WOND;
            itemLevel = 0;
            startingCostPiecetype = SOCPlayingPiece.SHIP;
                // note: client SOCSpecialItemDialog assumes all items have same startingCostPiecetype; true for SC_WOND
        } else {
            return new SOCSpecialItem(null, -1, null, null);  // <--- Early return: Unknown typeKey ---
        }

        final SOCResourceSet costRS;
        if ((typeCosts == null) || (idx < 0) || (idx >= typeCosts.length))
        {
            costRS = null;
        } else {
            final int[] cost = typeCosts[idx];
            costRS = (cost == null) ? null : new SOCResourceSet(cost);
        }

        final String req =
            (typeReqs != null)
            ? (((idx < 0) || (idx >= typeReqs.length)) ? null : typeReqs[idx])
            : null;
        final String sv =
            (typeSV != null)
            ? (((idx < 0) || (idx >= typeSV.length)) ? null : typeSV[idx])
            : null;

        final SOCSpecialItem si = new SOCSpecialItem(null, -1, itemLevel, sv, costRS, req);
        si.startingCostPiecetype = startingCostPiecetype;
        si.setGameIndex(idx);

        return si;
    }

    /**
     * Process a request from a player to {@code PICK} a known special item.
     * Implements scenario-specific rules and behavior for the item.
     * Called at server, not at client.
     *

     * In some scenarios, calls {@link SOCGame#checkForWinner()}; after calling
     * this method, check {@link SOCGame#getGameState()} >= {@link SOCGame#OVER}.
     *

     * When both {@code gi} and {@code pi} are specified, the item is retrieved
     * by calling {@link SOCGame#getSpecialItem(String, int, int, int)} before
     * making any changes.  That object's {@link #getCost()}, if any, is what was
     * paid if this method returns {@code true}.  If the caller needs to know
     * the cost paid, call that method before this one.
     *

     * If this Pick is to take ownership and build the first level of the item,
     * this method checks {@link #getStartingCostPiecetype()}: If any, player must have at least
     * 1 available piece of that type, which is used up by the start of building.
     *

     * Currently only {@link SOCGameOption#K_SC_WOND _SC_WOND} is recognized as a {@code typeKey} here.
     * To see which scenario and option {@code typeKey}s use this method, and scenario-specific usage details,
     * see the {@link SOCSpecialItem} class javadoc.
     *

     * Locks: Call {@link SOCGame#takeMonitor()} before calling this method.
     *
     * @param typeKey  Item's {@code typeKey}, as described in the {@link SOCSpecialItem} class javadoc
     * @param ga  Game containing {@code pl} and special items
     * @param pl  Requesting player; never {@code null}
     * @param gi  Pick this index within game's Special Item list, or -1
     * @param pi  Pick this index within {@code pl}'s Special Item list, or -1
     * @return  true if the item's cost was deducted from {@code pl}'s resources,
     *     false if no cost ({@link #getCost()} is null)
     * @throws IllegalStateException if {@code pl} cannot set or clear this item right now (due to
     *     cost, requirements, game state, missing a "starting cost" piece, is not their turn, or anything else),
     *     or if {@code typeKey} is unknown here, or if this {@code typeKey} doesn't
     *     use {@code PICK} requests from client players.
     * @see #playerSetItem(String, SOCGame, SOCPlayer, int, int, boolean)
     * @see #checkCost(SOCPlayer)
     * @see #checkRequirements(SOCPlayer, boolean)
     * @see #checkStartingCostPiecetype(SOCPlayer, boolean)
     */
    public static boolean playerPickItem
        (final String typeKey, final SOCGame ga, final SOCPlayer pl, final int gi, final int pi)
        throws IllegalStateException
    {
        if ((pl.getPlayerNumber() != ga.getCurrentPlayerNumber())
            || ((ga.getGameState() != SOCGame.PLAY1) && (ga.getGameState() != SOCGame.SPECIAL_BUILDING)))
            throw new IllegalStateException();

        if (! SOCGameOption.K_SC_WOND.equals(typeKey))
            throw new IllegalStateException("unknown typeKey: " + typeKey);

        // _SC_WOND

        if ((gi < 1) || (pi != 0))
            throw new IllegalStateException();

        SOCSpecialItem itm = ga.getSpecialItem(typeKey, gi);
            // same logic for _SC_WOND as getSpecialItem(typeKey,gi,pi)
            // because that method checks gi before pi, and for this
            // scenario the item at valid gi will never be null.

        if ((itm == null) || ((itm.player != null) && (itm.player != pl)))
            throw new IllegalStateException();  // another player owns it, or item not found

        SOCSpecialItem plWonder = pl.getSpecialItem(typeKey, 0);
        if ((plWonder != null) && (plWonder != itm))
            throw new IllegalStateException();  // player already has a different wonder

        // check costs at each level
        SOCResourceSet cost = itm.cost;
        if ((cost != null) && ! pl.getResources().contains(cost))
            throw new IllegalStateException("cost");

        // if unowned (first level), check requirements and then acquire item if met
        if (itm.player == null)
        {
            if (! itm.checkRequirements(pl, false))
                throw new IllegalStateException("requirements");

            final int startCostPT = itm.getStartingCostPiecetype();
            if (startCostPT != -1)
            {
                itm.checkStartingCostPiecetype(pl, true);  // if player out of pieces, throws IllegalStateException
                pl.setNumPieces(startCostPT, pl.getNumPieces(startCostPT) - 1);
            }

            itm.setPlayer(pl);
            pl.setSpecialItem(typeKey, 0, itm);
        }

        if (cost != null)
            pl.getResources().subtract(cost);

        itm.level++;

        // win condition: check for level 4
        // win condition: check for >= 10 VP and highest build level (no ties)
        if ((itm.level >= SC_WOND_WIN_LEVEL) || (pl.getTotalVP() >= ga.vp_winner))
            ga.checkForWinner();

        return (cost != null);
    }

    /**
     * Process a request from a player to {@code SET} or {@code CLEAR} a known special item.
     * Implements scenario-specific rules and behavior for the item.
     * Called at server, not at client.
     *

     * In some scenarios, calls {@link SOCGame#checkForWinner()}; after calling
     * this method, check {@link SOCGame#getGameState()} >= {@link SOCGame#OVER}.
     *

     * To see which scenario and option {@code typeKey}s use this method, and scenario-specific usage details,
     * see the {@link SOCSpecialItem} class javadoc.
     *

     * Locks: Call {@link SOCGame#takeMonitor()} before calling this method.
     *
     * @param typeKey  Item's {@code typeKey}, as described in the {@link SOCSpecialItem} class javadoc
     * @param ga  Game containing {@code pl} and special items
     * @param pl  Requesting player; never {@code null}
     * @param gi  Set or clear this index within game's Special Item list, or -1
     * @param pi  Set or clear this index within {@code pl}'s Special Item list, or -1
     * @param isSet  True if player wants to set, false if player wants to clear, this item index
     * @return  true if the item's cost was deducted from {@code pl}'s resources
     * @throws IllegalStateException if {@code pl} cannot set or clear this item right now
     *     (due to cost, requirements, game state, or anything else), or if {@code typeKey} is unknown here,
     *     or if this {@code typeKey} doesn't use {@code SET} or {@code CLEAR} requests from client players.
     * @see #playerPickItem(String, SOCGame, SOCPlayer, int, int)
     */
    public static boolean playerSetItem
        (final String typeKey, final SOCGame ga, final SOCPlayer pl, final int gi, final int pi, final boolean isSet)
        throws IllegalStateException
    {
        throw new IllegalStateException("SET/CLEAR requests not used with this typeKey: " + typeKey);
    }

    /**
     * Make a new item, optionally owned by a player.
     * Its optional Level will be 0, string value will be {@code null}.
     *
     * @param pl  player who owns the item, or {@code null}
     * @param co  coordinates, or -1
     * @param cost  cost to buy, use, or build the next level, or null
     * @param req  requirements to buy, use, or build the next level, or null.
     *      If provided, this requirement specification string will be
     *      parsed by {@link SOCSpecialItem.Requirement#parse(String)}.
     * @throws IllegalArgumentException  if {@code req != null} but isn't a syntactically valid specification
     */
    public SOCSpecialItem(SOCPlayer pl, final int co, SOCResourceSet cost, final String req)
        throws IllegalArgumentException
    {
        this(pl, co, 0, null, cost, req);
    }

    /**
     * Make a new item, optionally owned by a player, with an optional level and string value.
     *
     * @param pl  player who owns the item, or {@code null}
     * @param co  coordinates, or -1
     * @param lv  current level of construction or strength, or 0
     * @param sv  current string value (optional), or {@code null}.
     *      Meaning is type-specific, see {@link #getStringValue()}.
     *      If not {@code null}, must pass {@link SOCMessage#isSingleLineAndSafe(String)}.
     * @param cost  cost to buy, use, or build the next level, or null
     * @param req  requirements to buy, use, or build the next level, or null.
     *      If provided, this requirement specification string will be
     *      parsed by {@link SOCSpecialItem.Requirement#parse(String)}.
     * @throws IllegalArgumentException  if {@code req != null} but isn't a syntactically valid specification,
     *      or if {@code sv} fails {@link SOCMessage#isSingleLineAndSafe(String)}
     */
    public SOCSpecialItem
        (SOCPlayer pl, final int co, final int lv, final String sv, SOCResourceSet cost, final String req)
        throws IllegalArgumentException
    {
        player = pl;
        coord = co;
        level = lv;
        this.sv = sv;
        this.cost = cost;
        this.req = (req != null) ? Requirement.parse(req) : null;

        if ((sv != null) && ! SOCMessage.isSingleLineAndSafe(sv))
            throw new IllegalArgumentException("sv");
    }

    /**
     * Get this item's optional game item index, or -1 if none,
     * as used with {@link SOCGame#getSpecialItem(String, int, int, int)}.
     * @see #getPlayer()
     */
    public int getGameIndex()
    {
        return gameItemIndex;
    }

    /** Set this item's {@link #getGameIndex()}. Use -1 to clear to "none". */
    public void setGameIndex(final int gi)
    {
        gameItemIndex = gi;
    }

    /**
     * Get the player who owns this item, if any.
     * @return the owner of the item, or {@code null}
     * @see #getGameIndex()
     */
    public SOCPlayer getPlayer()
    {
        return player;
    }

    /**
     * Set or clear the player who owns this item.
     * @param pl  the owner of this item, or {@code null}
     */
    public void setPlayer(SOCPlayer pl)
    {
        player = pl;
    }

    /**
     * @return the node or edge coordinate for this item, or -1 if none
     */
    public int getCoordinates()
    {
        return coord;
    }

    /**
     * @param co the node or edge coordinate for this item, or -1 if none
     */
    public void setCoordinates(final int co)
    {
        coord = co;
    }

    /**
     * Get the current construction level or strength of this item.
     * @return  Current level
     */
    public int getLevel()
    {
        return level;
    }

    /**
     * Set the current level of this special item.
     * @param lv  New level
     */
    public void setLevel(final int lv)
    {
        level = lv;
    }

    /**
     * Get the current string value, if any, of this special item.
     * This is an optional field whose meaning is specific to the item type (typeKey):
     *

     *
 {@link SOCGameOption#K_SC_WOND _SC_WOND}:
     *     At client, localized i18n string key is {@code "game.specitem.sc_wond." + item.getStringValue()}
     *

     *
     * @return  Current string value, or {@code null}
     */
    public String getStringValue()
    {
        return sv;
    }

    /**
     * Set or clear the current string value of this special item.
     * @param sv  New value, or {@code null} to clear
     */
    public void setStringValue(final String sv)
    {
        this.sv = sv;
    }

    /**
     * Get the optional constant cost to buy, use, or build the next level.
     * Not sent over the network; see {@link SOCSpecialItem class javadoc}.
     * @return  Cost, or {@code null} if none
     * @see #checkCost(SOCPlayer)
     * @see #getStartingCostPiecetype()
     */
    public SOCResourceSet getCost()
    {
        return cost;
    }

    /**
     * Set or clear the optional cost to buy, use, or build the next level.
     * Not sent over the network; see {@link SOCSpecialItem class javadoc}.
     * @param co  New cost, or {@code null} to clear
     */
    public void setCost(SOCResourceSet co)
    {
        cost = co;
    }

    /**
     * Does this player have resources for this special item's {@link #getCost()}, if any?
     * @param pl  Player to check
     * @return  True if cost is {@code null} or {@link SOCPlayer#getResources() pl.getResources()} contains the cost.
     *     Always false if {@code pl} is {@code null}.
     * @see #checkRequirements(SOCPlayer, boolean)
     * @see #checkStartingCostPiecetype(SOCPlayer, boolean)
     */
    public final boolean checkCost(final SOCPlayer pl)
    {
        return (pl != null) && ((cost == null) || pl.getResources().contains(cost));
    }

    /**
     * Optional constant extra starting "cost" piece: A type of {@link SOCPlayingPiece}
     * the player must give up to pick (buy, use, or build) the first level, or -1 if unused
     * (0 would be {@link SOCPlayingPiece#ROAD}).
     *

     * In {@link SOCScenario#K_SC_WOND SC_WOND} scenario, value is {@link SOCPlayingPiece#SHIP}.
     *

     * Like {@link #getCost()}, not sent over the network; see {@link SOCSpecialItem class javadoc}
     * and {@link #makeKnownItem(String, int)} code.
     *
     * @see #checkStartingCostPiecetype(SOCPlayer, boolean)
     */
    public final int getStartingCostPiecetype()
    {
        return startingCostPiecetype;
    }

    /**
     * Does this player have an available {@link #getStartingCostPiecetype()}, if any, to pick this item and
     * start its construction? See {@link #playerPickItem(String, SOCGame, SOCPlayer, int, int)} for details.
     *

     * Does not include {@link #checkCost(SOCPlayer)} or {@link #checkRequirements(SOCPlayer, boolean)};
     * must call those separately.
     *
     * @param pl  Player to check
     * @param throwIfUnmet  If true, throw {@code IllegalStateException} if piece needed but player is out of that type
     * @return true if player the piece to give up, or if there is no starting cost piece;
     *     false if player would need but doesn't have that piece
     * @throws IllegalStateException if {@code throwIfUnmet} and player has no such piece
     * @throws ArrayIndexOutOfBoundsException if piece type is invalid:
     *     This is an internal error, should not occur unless bug in {@link #makeKnownItem(String, int)}
     */
    public final boolean checkStartingCostPiecetype(final SOCPlayer pl, final boolean throwIfUnmet)
        throws IllegalStateException, ArrayIndexOutOfBoundsException
    {
        if (startingCostPiecetype == -1)
            return true;

        if (pl.getNumPieces(startingCostPiecetype) >= 1)
        {
            return true;
        } else {
            if (throwIfUnmet)
                throw new IllegalStateException("Must pay starting piece type: " + startingCostPiecetype);

            return false;
        }
    }

    /**
     * Does this player meet this special item's {@link #req} requirements?
     * @param pl  Player to check
     * @param checkCost  If true, also check the cost against player's current resources
     * @return  True if player meets the requirements, false otherwise; true if {@link #req} is null or empty.
     *     If {@code checkCost} and {@link #getCost()} != null, false unless player's resources contain {@code cost}.
     *     Always false if player is {@code null}.
     * @throws IllegalArgumentException if {@link #req} has an unknown requirement type,
     *     or refers to an Added Layout Part {@code "N1"} through {@code "N9"} that isn't defined in the board layout
     * @throws UnsupportedOperationException if requirement type S (Settlement) includes {@code atPort} location;
     *     this is not implemented
     * @see #checkRequirements(SOCPlayer, List)
     * @see #checkCost(SOCPlayer)
     * @see #checkStartingCostPiecetype(SOCPlayer, boolean)
     */
    public final boolean checkRequirements(final SOCPlayer pl, final boolean checkCost)
        throws IllegalArgumentException, UnsupportedOperationException
    {
        if (checkCost && ! checkCost(pl))
            return false;

        return checkRequirements(pl, req);
    }

    /**
     * Does this player meet a special item's requirements?
     *
     * @param pl  Player to check
     * @param reqsList  Requirements list; to parse from a string, use {@link SOCSpecialItem.Requirement#parse(String)}
     * @return  True if player meets the requirements, false otherwise; true if {@code reqsList} is null or empty.
     *     Always false if player is null.
     * @throws IllegalArgumentException if {@code reqsList} has an unknown requirement type,
     *     or refers to an Added Layout Part {@code "N1"} through {@code "N9"} that isn't defined in the board layout
     * @throws UnsupportedOperationException if requirement type S (Settlement) includes {@code atPort} location;
     *     this is not implemented
     * @see #checkRequirements(SOCPlayer, boolean)
     */
    public static boolean checkRequirements(final SOCPlayer pl, final List<SOCSpecialItem.Requirement> reqsList)
        throws IllegalArgumentException, UnsupportedOperationException
    {
        if (pl == null)
            return false;  // no player, can't meet any requirements
        if (reqsList == null)
            return true;   // no requirements, nothing to fail

        for (final Requirement req : reqsList)
        {
            final int count = req.count;
            List<? extends SOCPlayingPiece> pieces = null;

            switch (req.reqType)
            {
            case 'S':
                pieces = pl.getSettlements();
                if (pieces.size() < count)
                    return false;
                break;

            case 'C':
                pieces = pl.getCities();
                if (pieces.size() < count)
                    return false;
                break;

            case 'V':
                if (pl.getTotalVP() < count)
                    return false;
                break;

            case 'L':
                if (pl.getLongestRoadLength() < count)
                    return false;
                break;

            default:
                throw new IllegalArgumentException("Unknown requirement type " + req.reqType);
            }

            if (pieces != null)
            {
                // check for location requirement:

                if (req.atPort && (req.reqType != 'C'))
                    throw new UnsupportedOperationException("atPort reqType " + req.reqType + " not implemented");

                if (req.atCoordList != null)
                {
                    boolean foundAtNode = false;
                    final int[] nodes = ((SOCBoardLarge) pl.getGame().getBoard()).getAddedLayoutPart(req.atCoordList);
                    if (nodes == null)
                        throw new IllegalArgumentException
                            ("Requirement uses undefined Added Layout Part " + req.atCoordList);

                    for (SOCPlayingPiece pp : pieces)
                    {
                        final int node = pp.getCoordinates();
                        for (int i = 0; i < nodes.length; ++i)
                        {
                            if (node == nodes[i])
                            {
                                foundAtNode = true;
                                break;
                            }
                        }

                        if (foundAtNode)
                            break;
                    }

                    if (! foundAtNode)
                        return false;  // no matching piece found
                }
                else if (req.atPort)
                {
                    boolean foundAtNode = false;
                    final SOCBoard board = pl.getGame().getBoard();

                    for (SOCPlayingPiece pp : pieces)
                    {
                        if (board.getPortTypeFromNodeCoord(pp.getCoordinates()) != -1)
                        {
                            foundAtNode = true;
                            break;
                        }
                    }

                    if (! foundAtNode)
                        return false;  // no matching piece found
                }
            }
        }

        return true;  // didn't fail any requirement
    }

    /**
     * @return a human readable form of this object
     */
    @Override
    public String toString()
    {
        return "SOCSpecialItem:player=" + player + "|coord=" + Integer.toHexString(coord) + "|level=" + level
            + "|cost=[" + cost + "]|req=" + req;
    }

    /**
     * Compare this SOCSpecialItem to another SOCSpecialItem, or another object.
     * Comparison method:
     *

     *
 If other is null, false.
     *
 If other is not a SOCSpecialItem, false.
     *
 SOCSpecialItem are equal with the same coordinate, player, and level.
     *

     *
     * @param other The object to compare with, or null
     */
    @Override
    public boolean equals(Object other)
    {
        if ((other == null) || ! (other instanceof SOCSpecialItem))
            return false;

        return ((coord == ((SOCSpecialItem) other).coord)
            &&  (player == ((SOCSpecialItem) other).player)
            &&  (level == ((SOCSpecialItem) other).level));
    }

    /**
     * For use in set copy constructors, create and return a clone of this {@link SOCSpecialItem}.
     * The {@code SOCSpecialItem} implementation just calls {@code super.clone()}.
     * If subclasses have any lists or structures, be sure to deeply copy them.
     * Requirements aren't deep-copied, because they are final and won't change.
     * @throws CloneNotSupportedException  Declared from super.clone(), should not occur
     *     since SOCSpecialItem implements Cloneable.
     * @return a clone of this item
     */
    public SOCSpecialItem clone()
        throws CloneNotSupportedException
    {
        SOCSpecialItem cl = (SOCSpecialItem) super.clone();
        cl.cost = cost.copy();
        return cl;
    }

    /**
     * Data structure and parser for a special item's requirements.
     *

     * A requirement is a minimum count of items (Settlements, Cities, Victory Points, or Length of player's longest
     * route) with an optional required position (at a Port, or at a list of special nodes) for at least one of the
     * Settlement or City items.
     *

     * At the client, requirements are rendered in {@code SOCSpecialItemDialog.buildRequirementsText};
     * if new fields or requirement types are added, please update that method.
     *
     * @see #parse(String)
     * @see SOCSpecialItem#checkRequirements(SOCPlayer, boolean)
     */
    public static final class Requirement
    {
        /**
         * 'S' for settlement, 'C' for city, 'V' for victory points, 'L' for length of player's longest route.
         * If {@link #atPort} is true, must be 'C'.
         */
        public final char reqType;

        /**
         * Number of pieces, victory points, or length of route required. Default is 1.
         * If {@link #atPort} or {@link #atCoordList} is specified, at least 1 of the pieces (not all)
         * must be at a port or a listed coordinate.
         */
        public final int count;

        /**
         * If true, a {@code reqType} piece must be at a 3:1 or 2:1 port.
         * See notes for {@link #count}. Currently supports only {@code reqType} C (City),
         * not S, because no current scenario justified the extra coding for a combined set of
         * Settlements and Cities.
         */
        public final boolean atPort;

        /**
         * Board layout coordinate list such as "N1", or null.  If non-null, a reqType piece must
         * be at a node coordinate in this named list within the board layout's {@code getAddedLayoutPart}s.
         */
        public final String atCoordList;

        /**
         * Parse a requirement specification string into {@link Requirement} objects.
         *

         * Requirements are a comma-separated list of items, each item having this syntax:

         * [count] itemType [@ location]
         *

         *
 Count is an optional integer, otherwise 1 is the default
         *
 ItemType is a letter for the requirement type:
         *    C for Cities, S for Settlements (those upgraded to cities don't count),
         *    V for total Victory Points, or L for length of player's longest trade route.
         *
 Location is an optional location that at least one of the player's {@code ItemType} pieces must be at:
         *

         *
 P for any 3:1 or 2:1 trade port; ItemType must be C (cities).
         *
 N1 through N9 for a Node List in the board layout
         *      ({@link SOCBoardLarge#getAddedLayoutPart(String) board.getAddedLayoutPart("N1")} etc).
         *

         *

         *
         *
Examples:

         *

         *
{@code 3S} = 3 settlements
         *
{@code 2C,8V} = 2 cities, 8 victory points
         *
{@code 6L} = trade route length 6
         *
{@code C@P} = city at any port
         *
{@code 2C@N2} = 2 cities, at least one of which is in node list 2 ({@code "N2"}) in the board layout
         *

         *
         * @param req  Requirements string following the syntax given above
         * @return List of {@link Requirement}s, or {@code null} if {@code req} is ""
         * @throws IllegalArgumentException  if {@code req} isn't a syntactically valid specification
         */
        @SuppressWarnings("fallthrough")
        public static List<Requirement> parse(final String req)
            throws IllegalArgumentException
        {
            final int L = req.length();
            if (L == 0)
                return null;

            ArrayList<Requirement> ret = new ArrayList<Requirement>();

            int i = 0;
            char c;  // in parsing loop, c == req.charAt(i)

            // Loop for each comma-separated requirement
            while (i < L)
            {
                c = req.charAt(i);

                // first: optional digit(s), then item-type letter
                int itemCount;
                if (Character.isDigit(c))
                {
                    int j = i + 1;
                    while (j < req.length())
                    {
                        c = req.charAt(j);
                        if (! Character.isDigit(c))
                            break;

                        ++j;
                    }
                    if (j == req.length())
                        throw new IllegalArgumentException("Must follow item count with item type in " + req);
                    // postcondition: j is 1 char past end of digits

                    itemCount = Integer.parseInt(req.substring(i, j));
                    i = j;
                    // c was req.charAt(j) already
                } else {
                    itemCount = 1;
                }

                final char reqType = c;  // 'S', 'C', 'V', 'L'
                if ((c < 'A') || (c > 'Z'))
                    throw new IllegalArgumentException("Expected item-type letter at position " + i + " in " + req);

                ++i;
                if (i >= L)
                {
                    // This req is done, comma separates it from next req
                    ret.add(new Requirement(reqType, itemCount, false, null));

                    break;  // <--- Finished last req ---
                }

                c = req.charAt(i);

                if (c == ',')
                {
                    // This req is done: comma separates it from next req
                    ret.add(new Requirement(reqType, itemCount, false, null));

                    ++i;
                    if (i >= L)
                        throw new IllegalArgumentException("ends with ',': " + req);

                    continue;  // <--- completed this req ---
                }

                if (c != '@')
                    throw new IllegalArgumentException("Expected @ or , at position " + i + " in " + req);

                ++i;
                if (i >= L)
                    throw new IllegalArgumentException("Must follow @ with P or N# in " + req);

                c = req.charAt(i);

                // Currently valid after '@': N#, or P for Port
                switch (c)
                {
                case 'P':
                    ret.add(new Requirement(reqType, itemCount, true, null));
                    ++i;
                    break;

                case 'N':
                    ++i;
                    if (i < L)
                        c = req.charAt(i);
                    if ((i < L) && Character.isDigit(c))
                    {
                        ret.add(new Requirement(reqType, itemCount, false, "N" + c));
                        ++i;
                        break;
                    }
                    // else, will fall through to default and throw exception

                default:
                    throw new IllegalArgumentException("Must follow @ with P or N# in " + req);
                }

                // If we got here, we've parsed the req and i should be at end or comma
                if (i < L)
                {
                    if (req.charAt(i) != ',')
                        throw new IllegalArgumentException
                            ("Extra characters in spec: Expected , or end of string at position " + i + " in " + req);

                    ++i;
                    // top of main loop will parse the requirement that follows the comma
                }
            }

            return ret;
        }

        /**
         * Create a Requirement item with these field values.
         * See each field's javadoc for meaning of parameter named from that field.
         * Except for {@code atPort} interactions, parameter values are not validated here.
         * @param reqType  See {@link #reqType}
         * @param count    See {@link #count}
         * @param atPort   See {@link #atPort}
         * @param atCoordList  See {@link #atCoordList}
         * @throws IllegalArgumentException if {@code atPort} and either {@code reqType != 'C'}
         *     or {@code atCoordList != null}
         */
        public Requirement(final char reqType, final int count, final boolean atPort, final String atCoordList)
            throws IllegalArgumentException
        {
            if (atPort)
            {
                if (reqType != 'C')
                    throw new IllegalArgumentException("atPort not implemented for reqType " + reqType);
                if (atCoordList != null)
                    throw new IllegalArgumentException("can't have atPort and atCoordList");
            }

            this.reqType = reqType;
            this.count = count;
            this.atPort = atPort;
            this.atCoordList = atCoordList;
        }

        /**
         * Equality test, mostly for testing/debugging.
         * @return true if {@code other} is a {@link Requirement} with same field contents
         */
        public final boolean equals(final Object other)
        {
            if (! (other instanceof Requirement))
                return false;
            final Requirement oth = (Requirement) other;
            return (reqType == oth.reqType)
                && (count == oth.count)
                && (atPort == oth.atPort)
                && ((atCoordList == null)
                    ? (oth.atCoordList == null)
                    : atCoordList.equals(oth.atCoordList));
        }

        /** String representation for debugging; same format as {@link #parse(String)}. */
        public final String toString()
        {
            StringBuilder sb = new StringBuilder();
            if (count != 1)
                sb.append(count);
            sb.append(reqType);
            if (atPort || (atCoordList != null))
            {
                sb.append('@');
                if (atPort)
                    sb.append('P');
                else
                    sb.append(atCoordList);
            }

            return sb.toString();
        }
    }

}

{'repo_name': 'jdmonin/JSettlers2', 'stars': '102', 'repo_language': 'Java', 'file_name': 'readme.htm', 'mime_type': 'text/html', 'hash': 3543994611133125705, 'source_dataset': 'data'}


// Copyright David Abrahams 2004. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef UNWRAP_WRAPPER_DWA2004723_HPP
# define UNWRAP_WRAPPER_DWA2004723_HPP

# include <boost/python/detail/prefix.hpp>
# include <boost/python/detail/is_wrapper.hpp>
# include <boost/mpl/eval_if.hpp>
# include <boost/mpl/identity.hpp>

namespace boost { namespace python { namespace detail {

template <class T>
struct unwrap_wrapper_helper
{
    typedef typename T::_wrapper_wrapped_type_ type;
};

template <class T>
struct unwrap_wrapper_
  : mpl::eval_if<is_wrapper<T>,unwrap_wrapper_helper<T>,mpl::identity<T> >
{};

template <class T>
typename unwrap_wrapper_<T>::type*
unwrap_wrapper(T*)
{
    return 0;
}

}}} // namespace boost::python::detail

#endif // UNWRAP_WRAPPER_DWA2004723_HPP

{'repo_name': 'Source-Python-Dev-Team/Source.Python', 'stars': '107', 'repo_language': 'Python', 'file_name': 'readme.md', 'mime_type': 'text/plain', 'hash': -8682906268974708358, 'source_dataset': 'data'}


{'repo_name': 'dufferzafar/geeksforgeeks.pdf', 'stars': '389', 'repo_language': 'Python', 'file_name': 'Combinatorial.json', 'mime_type': 'text/plain', 'hash': 2550135094593511734, 'source_dataset': 'data'}


/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
   See the file COPYING for copying permission.
*/

/* Like asciitab.h, except that 0xD has code BT_S rather than BT_CR */
/* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML,
/* 0x0C */ BT_NONXML, BT_S, BT_NONXML, BT_NONXML,
/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM,
/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS,
/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS,
/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL,
/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI,
/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST,
/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB,
/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT,
/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER,

{'repo_name': 'audacity/audacity', 'stars': '3053', 'repo_language': 'C', 'file_name': 'UI.txt', 'mime_type': 'text/plain', 'hash': 3593131324924386206, 'source_dataset': 'data'}


################################################################################
## Initialization
################################################################################

## The init offset statement causes the initialization statements in this file
## to run before init statements in any other file.
init offset = -2

## Calling gui.init resets the styles to sensible default values, and sets the
## width and height of the game.
init python:
    gui.init(1280, 720)

################################################################################
## GUI Configuration Variables
################################################################################

## Colors ######################################################################
##
## The colors of text in the interface.

## An accent color used throughout the interface to label and highlight
## text.
define gui.accent_color = "#00b8c3"

## The color used for a text button when it is neither selected nor hovered.
define gui.idle_color = "#888888"

## The small color is used for small text, which needs to be
## brighter/darker to achieve the same effect.
define gui.idle_small_color = "#aaaaaa"

## The color that is used for buttons and bars that are hovered.
define gui.hover_color = Color(gui.accent_color).tint(.6)

## The color used for a text button when it is selected but not focused.
## A button is selected if it is the current screen or preference value.
define gui.selected_color = "#ffffff"

## The color used for a text button when it cannot be selected.
define gui.insensitive_color = "#55555580"

## Colors used for the portions of bars that are not filled in. These are
## not used directly, but are used when re-generating bar image files.
define gui.muted_color = "#004e49"
define gui.hover_muted_color = "#006e75"

## The colors used for dialogue and menu choice text.
define gui.text_color = "#ffffff"
define gui.interface_text_color = "#ffffff"

## Fonts and Font Sizes ########################################################

## The font used for in-game text.
define gui.text_font = "DejaVuSans.ttf"

## The font used for character names.
define gui.name_text_font = "DejaVuSans.ttf"

## The font used for out-of-game text.
define gui.interface_text_font = "DejaVuSans.ttf"

## The size of normal dialogue text.
define gui.text_size = gui.scale(22)

## The size of character names.
define gui.name_text_size = gui.scale(30)

## The size of text in the game's user interface.
define gui.interface_text_size = gui.scale(22)

## The size of labels in the game's user interface.
define gui.label_text_size = gui.scale(24)

## The size of text on the notify screen.
define gui.notify_text_size = gui.scale(16)

## The size of the game's title.
define gui.title_text_size = gui.scale(50)

## Main and Game Menus #########################################################

## The images used for the main and game menus.
define gui.main_menu_background = "gui/main_menu.png"
define gui.game_menu_background = "gui/game_menu.png"

## Dialogue ####################################################################
##
## These variables control how dialogue is displayed on the screen one line
## at a time.

## The height of the textbox containing dialogue.
define gui.textbox_height = gui.scale(185)

## The placement of the textbox vertically on the screen. 0.0 is the top, 0.5 is
## center, and 1.0 is the bottom.
define gui.textbox_yalign = 1.0

## The placement of the speaking character's name, relative to the textbox.
## These can be a whole number of pixels from the left or top, or 0.5 to center.
define gui.name_xpos = gui.scale(240)
define gui.name_ypos = gui.scale(0)

## The horizontal alignment of the character's name. This can be 0.0 for
## left-aligned, 0.5 for centered, and 1.0 for right-aligned.
define gui.name_xalign = 0.0

## The width, height, and borders of the box containing the character's
## name, or None to automatically size it.
define gui.namebox_width = None
define gui.namebox_height = None

## The borders of the box containing the character's name, in left, top,
## right, bottom order.
define gui.namebox_borders = Borders(5, 5, 5, 5)

## If True, the background of the namebox will be tiled, if False, the background
## of the namebox will be scaled.
define gui.namebox_tile = False

## The placement of dialogue relative to the textbox. These can be a whole
## number of pixels relative to the left or top side of the textbox, or 0.5
## to center.
define gui.dialogue_xpos = gui.scale(268)
define gui.dialogue_ypos = gui.scale(50)

## The maximum width of dialogue text, in pixels.
define gui.dialogue_width = gui.scale(744)

## The horizontal alignment of the dialogue text. This can be 0.0 for
## left-aligned, 0.5 for centered, and 1.0 for right-aligned.
define gui.dialogue_text_xalign = 0.0

## Buttons #####################################################################
##
## These variables, along with the image files in gui/button, control aspects
## of how buttons are displayed.

## The width and height of a button, in pixels. If None, Ren'Py computes a size.
define gui.button_width = None
define gui.button_height = None

## The borders on each side of the button, in left, top, right, bottom order.
define gui.button_borders = Borders(gui.scale(4), gui.scale(4), gui.scale(4), gui.scale(4))

## If True, the background image will be tiled. If False, the background image
## will be linearly scaled.
define gui.button_tile = False

## The font used by the button.
define gui.button_text_font = gui.interface_text_font

## The size of the text used by the button.
define gui.button_text_size = gui.interface_text_size

## The color of button text in various states.
define gui.button_text_idle_color = gui.idle_color
define gui.button_text_hover_color = gui.hover_color
define gui.button_text_selected_color = gui.selected_color
define gui.button_text_insensitive_color = gui.insensitive_color

## The horizontal alignment of the button text. (0.0 is left, 0.5 is center,
## 1.0 is right).
define gui.button_text_xalign = 0.0

## These variables override settings for different kinds of buttons. Please
## see the gui documentation for the kinds of buttons available, and what
## each is used for.
##
## These customizations are used by the default interface:

define gui.radio_button_borders = Borders(gui.scale(18), gui.scale(4), gui.scale(4), gui.scale(4))

define gui.check_button_borders = Borders(gui.scale(18), gui.scale(4), gui.scale(4), gui.scale(4))

define gui.confirm_button_text_xalign = 0.5

define gui.page_button_borders = Borders(gui.scale(10), gui.scale(4), gui.scale(10), gui.scale(4))

define gui.quick_button_borders = Borders(gui.scale(10), gui.scale(4), gui.scale(10), gui.scale(0))
define gui.quick_button_text_size = gui.scale(14)
define gui.quick_button_text_idle_color = gui.idle_small_color
define gui.quick_button_text_selected_color = gui.accent_color

## You can also add your own customizations, by adding properly-named variables.
## For example, you can uncomment the following line to set the width of a
## navigation button.

# define gui.navigation_button_width = 250

## Choice Buttons ##############################################################
##
## Choice buttons are used in the in-game menus.

define gui.choice_button_width = gui.scale(790)
define gui.choice_button_height = None
define gui.choice_button_tile = False
define gui.choice_button_borders = Borders(gui.scale(100), gui.scale(5), gui.scale(100), gui.scale(5))
define gui.choice_button_text_font = gui.text_font
define gui.choice_button_text_size = gui.text_size
define gui.choice_button_text_xalign = 0.5
define gui.choice_button_text_idle_color = "#cccccc"
define gui.choice_button_text_hover_color = "#ffffff"
define gui.choice_button_text_insensitive_color = "#444444"

## File Slot Buttons ###########################################################
##
## A file slot button is a special kind of button. It contains a thumbnail
## image, and text describing the contents of the save slot. A save slot
## uses image files in gui/button, like the other kinds of buttons.

## The save slot button.
define gui.slot_button_width = gui.scale(276)
define gui.slot_button_height = gui.scale(206)
define gui.slot_button_borders = Borders(gui.scale(10), gui.scale(10), gui.scale(10), gui.scale(10))
define gui.slot_button_text_size = gui.scale(14)
define gui.slot_button_text_xalign = 0.5
define gui.slot_button_text_idle_color = gui.idle_small_color
define gui.slot_button_text_selected_idle_color = gui.selected_color
define gui.slot_button_text_selected_hover_color = gui.hover_color

## The width and height of thumbnails used by the save slots.
define config.thumbnail_width = gui.scale(256)
define config.thumbnail_height = gui.scale(144)

## The number of columns and rows in the grid of save slots.
define gui.file_slot_cols = 3
define gui.file_slot_rows = 2

## Positioning and Spacing #####################################################
##
## These variables control the positioning and spacing of various user interface
## elements.

## The position of the left side of the navigation buttons, relative
## to the left side of the screen.
define gui.navigation_xpos = gui.scale(40)

## The vertical position of the skip indicator.
define gui.skip_ypos = gui.scale(10)

## The vertical position of the notify screen.
define gui.notify_ypos = gui.scale(45)

## The spacing between menu choices.
define gui.choice_spacing = gui.scale(22)

## Buttons in the navigation section of the main and game menus.
define gui.navigation_spacing = gui.scale(4)

## Controls the amount of spacing between preferences.
define gui.pref_spacing = gui.scale(10)

## Controls the amount of spacing between preference buttons.
define gui.pref_button_spacing = gui.scale(0)

## The spacing between file page buttons.
define gui.page_spacing = gui.scale(0)

## The spacing between file slots.
define gui.slot_spacing = gui.scale(10)

## The position of the main menu text.
define gui.main_menu_text_xalign = 1.0

## Frames ######################################################################
##
## These variables control the look of frames that can contain user interface
## components when an overlay or window is not present.

## Generic frames.
define gui.frame_borders = Borders(gui.scale(4), gui.scale(4), gui.scale(4), gui.scale(4))

## The frame that is used as part of the confirm screen.
define gui.confirm_frame_borders = Borders(gui.scale(40), gui.scale(40), gui.scale(40), gui.scale(40))

## The frame that is used as part of the skip screen.
define gui.skip_frame_borders = Borders(gui.scale(16), gui.scale(5), gui.scale(50), gui.scale(5))

## The frame that is used as part of the notify screen.
define gui.notify_frame_borders = Borders(gui.scale(16), gui.scale(5), gui.scale(40), gui.scale(5))

## Should frame backgrounds be tiled?
define gui.frame_tile = False

## Bars, Scrollbars, and Sliders ###############################################
##
## These control the look and size of bars, scrollbars, and sliders.
##
## The default GUI only uses sliders and vertical scrollbars.
## All of the other bars are only used in creator-written screens.

## The height of horizontal bars, scrollbars, and sliders. The width of
## vertical bars, scrollbars, and sliders.
define gui.bar_size = gui.scale(25)
define gui.scrollbar_size = gui.scale(12)
define gui.slider_size = gui.scale(25)

## True if bar images should be tiled. False if they should be linearly scaled.
define gui.bar_tile = False
define gui.scrollbar_tile = False
define gui.slider_tile = False

## Horizontal borders.
define gui.bar_borders = Borders(gui.scale(4), gui.scale(4), gui.scale(4), gui.scale(4))
define gui.scrollbar_borders = Borders(gui.scale(4), gui.scale(4), gui.scale(4), gui.scale(4))
define gui.slider_borders = Borders(gui.scale(4), gui.scale(4), gui.scale(4), gui.scale(4))

## Vertical borders.
define gui.vbar_borders = Borders(gui.scale(4), gui.scale(4), gui.scale(4), gui.scale(4))
define gui.vscrollbar_borders = Borders(gui.scale(4), gui.scale(4), gui.scale(4), gui.scale(4))
define gui.vslider_borders = Borders(gui.scale(4), gui.scale(4), gui.scale(4), gui.scale(4))

## What to do with unscrollable scrollbars in the gui. "hide" hides them, while
## None shows them.
define gui.unscrollable = "hide"

## History #####################################################################
##
## The history screen displays dialogue that the player has already dismissed.

## The number of blocks of dialogue history Ren'Py will keep.
define config.history_length = 250

## The height of a history screen entry, or None to make the height variable
## at the cost of performance.
define gui.history_height = gui.scale(140)

## The position, width, and alignment of the label giving the name of the
## speaking character.
define gui.history_name_xpos = gui.scale(155)
define gui.history_name_ypos = 0
define gui.history_name_width = gui.scale(155)
define gui.history_name_xalign = 1.0

## The position, width, and alignment of the dialogue text.
define gui.history_text_xpos = gui.scale(170)
define gui.history_text_ypos = gui.scale(2)
define gui.history_text_width = gui.scale(740)
define gui.history_text_xalign = 0.0

## NVL-Mode ###################################################################
##
## The NVL-mode screen displays the dialogue spoken by NVL-mode characters.

## The borders of the background of the NVL-mode background window.
define gui.nvl_borders = Borders(0, gui.scale(10), 0, gui.scale(20))

## The maximum number of NVL-mode entries Ren'Py will display. When more
## entries than this are to be show, the oldest entry will be removed.
define gui.nvl_list_length = 6

## The height of an NVL-mode entry. Set this to None to have the entries
## dynamically adjust height.
define gui.nvl_height = gui.scale(115)

## The spacing between NVL-mode entries when gui.nvl_height is None, and
## between NVL-mode entries and an NVL-mode menu.
define gui.nvl_spacing = gui.scale(10)

## The position, width, and alignment of the label giving the name of the
## speaking character.
define gui.nvl_name_xpos = gui.scale(430)
define gui.nvl_name_ypos = 0
define gui.nvl_name_width = gui.scale(150)
define gui.nvl_name_xalign = 1.0

## The position, width, and alignment of the dialogue text.
define gui.nvl_text_xpos = gui.scale(450)
define gui.nvl_text_ypos = gui.scale(8)
define gui.nvl_text_width = gui.scale(590)
define gui.nvl_text_xalign = 0.0

## The position, width, and alignment of nvl_thought text (the text said by
## the nvl_narrator character.)
define gui.nvl_thought_xpos = gui.scale(240)
define gui.nvl_thought_ypos = gui.scale(0)
define gui.nvl_thought_width = gui.scale(780)
define gui.nvl_thought_xalign = 0.0

## The position of nvl menu_buttons.
define gui.nvl_button_xpos = gui.scale(450)
define gui.nvl_button_xalign = 0.0

## Localization ################################################################

## This controls where a line break is permitted. The default is suitable for
## most languages. A list of available values can be found at
## https://www.renpy.org/doc/html/style_properties.html#style-property-language

define gui.language = "unicode"

################################################################################
## Mobile devices
################################################################################

init python:

    ## This increases the size of the quick buttons to make them easier to
    ## touch on tablets and phones.
    if renpy.variant("touch"):

        gui.quick_button_borders = Borders(gui.scale(40), gui.scale(14), gui.scale(40), gui.scale(0))

    ## This changes the size and spacing of various GUI elements to ensure
    ## they are easily visible on phones.
    if renpy.variant("small"):

        ## Font sizes.
        gui.text_size = gui.scale(30)
        gui.name_text_size = gui.scale(36)
        gui.notify_text_size = gui.scale(25)
        gui.interface_text_size = gui.scale(30)
        gui.button_text_size = gui.scale(30)
        gui.label_text_size = gui.scale(34)

        ## Adjust the location of the textbox.
        gui.textbox_height = gui.scale(240)
        gui.name_xpos = gui.scale(80)
        gui.dialogue_xpos = gui.scale(90)
        gui.dialogue_width = gui.scale(1100)

        ## Change the size and spacing of various things.
        gui.slider_size = gui.scale(36)

        gui.choice_button_width = gui.scale(1240)

        gui.navigation_spacing = gui.scale(20)
        gui.pref_button_spacing = gui.scale(10)

        gui.history_height = gui.scale(190)
        gui.history_text_width = gui.scale(690)

        gui.quick_button_text_size = gui.scale(20)

        ## File button layout.
        gui.file_slot_cols = 2
        gui.file_slot_rows = 2

        ## NVL-mode.
        gui.nvl_height = gui.scale(170)

        gui.nvl_name_width = gui.scale(305)
        gui.nvl_name_xpos = gui.scale(325)

        gui.nvl_text_width = gui.scale(915)
        gui.nvl_text_xpos = gui.scale(345)
        gui.nvl_text_ypos = gui.scale(5)

        gui.nvl_thought_width = gui.scale(1240)
        gui.nvl_thought_xpos = gui.scale(20)

        gui.nvl_button_width = gui.scale(1240)
        gui.nvl_button_xpos = gui.scale(20)

{'repo_name': 'renpy/renpy', 'stars': '1950', 'repo_language': "Ren'Py", 'file_name': 'options.rpy', 'mime_type': 'text/plain', 'hash': -3399181582117384102, 'source_dataset': 'data'}


/**
  ******************************************************************************
  * @file    stm32f4xx_ll_rtc.c
  * @author  MCD Application Team
  * @brief   RTC LL module driver.
  ******************************************************************************
  * @attention
  *
  *
© COPYRIGHT(c) 2017 STMicroelectronics

  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */
#if defined(USE_FULL_LL_DRIVER)

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_ll_rtc.h"
#include "stm32f4xx_ll_cortex.h"
#ifdef  USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif

/** @addtogroup STM32F4xx_LL_Driver
  * @{
  */

#if defined(RTC)

/** @addtogroup RTC_LL
  * @{
  */

/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup RTC_LL_Private_Constants
  * @{
  */
/* Default values used for prescaler */
#define RTC_ASYNCH_PRESC_DEFAULT     0x0000007FU
#define RTC_SYNCH_PRESC_DEFAULT      0x000000FFU

/* Values used for timeout */
#define RTC_INITMODE_TIMEOUT         1000U /* 1s when tick set to 1ms */
#define RTC_SYNCHRO_TIMEOUT          1000U /* 1s when tick set to 1ms */
/**
  * @}
  */

/* Private macros ------------------------------------------------------------*/
/** @addtogroup RTC_LL_Private_Macros
  * @{
  */

#define IS_LL_RTC_HOURFORMAT(__VALUE__) (((__VALUE__) == LL_RTC_HOURFORMAT_24HOUR) \
                                      || ((__VALUE__) == LL_RTC_HOURFORMAT_AMPM))

#define IS_LL_RTC_ASYNCH_PREDIV(__VALUE__)   ((__VALUE__) <= 0x7FU)

#define IS_LL_RTC_SYNCH_PREDIV(__VALUE__)    ((__VALUE__) <= 0x7FFFU)

#define IS_LL_RTC_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_FORMAT_BIN) \
                                  || ((__VALUE__) == LL_RTC_FORMAT_BCD))

#define IS_LL_RTC_TIME_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_TIME_FORMAT_AM_OR_24) \
                                       || ((__VALUE__) == LL_RTC_TIME_FORMAT_PM))

#define IS_LL_RTC_HOUR12(__HOUR__)            (((__HOUR__) > 0U) && ((__HOUR__) <= 12U))
#define IS_LL_RTC_HOUR24(__HOUR__)            ((__HOUR__) <= 23U)
#define IS_LL_RTC_MINUTES(__MINUTES__)        ((__MINUTES__) <= 59U)
#define IS_LL_RTC_SECONDS(__SECONDS__)        ((__SECONDS__) <= 59U)

#define IS_LL_RTC_WEEKDAY(__VALUE__) (((__VALUE__) == LL_RTC_WEEKDAY_MONDAY) \
                                   || ((__VALUE__) == LL_RTC_WEEKDAY_TUESDAY) \
                                   || ((__VALUE__) == LL_RTC_WEEKDAY_WEDNESDAY) \
                                   || ((__VALUE__) == LL_RTC_WEEKDAY_THURSDAY) \
                                   || ((__VALUE__) == LL_RTC_WEEKDAY_FRIDAY) \
                                   || ((__VALUE__) == LL_RTC_WEEKDAY_SATURDAY) \
                                   || ((__VALUE__) == LL_RTC_WEEKDAY_SUNDAY))

#define IS_LL_RTC_DAY(__DAY__)    (((__DAY__) >= 1U) && ((__DAY__) <= 31U))

#define IS_LL_RTC_MONTH(__VALUE__) (((__VALUE__) == LL_RTC_MONTH_JANUARY) \
                                 || ((__VALUE__) == LL_RTC_MONTH_FEBRUARY) \
                                 || ((__VALUE__) == LL_RTC_MONTH_MARCH) \
                                 || ((__VALUE__) == LL_RTC_MONTH_APRIL) \
                                 || ((__VALUE__) == LL_RTC_MONTH_MAY) \
                                 || ((__VALUE__) == LL_RTC_MONTH_JUNE) \
                                 || ((__VALUE__) == LL_RTC_MONTH_JULY) \
                                 || ((__VALUE__) == LL_RTC_MONTH_AUGUST) \
                                 || ((__VALUE__) == LL_RTC_MONTH_SEPTEMBER) \
                                 || ((__VALUE__) == LL_RTC_MONTH_OCTOBER) \
                                 || ((__VALUE__) == LL_RTC_MONTH_NOVEMBER) \
                                 || ((__VALUE__) == LL_RTC_MONTH_DECEMBER))

#define IS_LL_RTC_YEAR(__YEAR__) ((__YEAR__) <= 99U)

#define IS_LL_RTC_ALMA_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMA_MASK_NONE) \
                                     || ((__VALUE__) == LL_RTC_ALMA_MASK_DATEWEEKDAY) \
                                     || ((__VALUE__) == LL_RTC_ALMA_MASK_HOURS) \
                                     || ((__VALUE__) == LL_RTC_ALMA_MASK_MINUTES) \
                                     || ((__VALUE__) == LL_RTC_ALMA_MASK_SECONDS) \
                                     || ((__VALUE__) == LL_RTC_ALMA_MASK_ALL))

#define IS_LL_RTC_ALMB_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMB_MASK_NONE) \
                                     || ((__VALUE__) == LL_RTC_ALMB_MASK_DATEWEEKDAY) \
                                     || ((__VALUE__) == LL_RTC_ALMB_MASK_HOURS) \
                                     || ((__VALUE__) == LL_RTC_ALMB_MASK_MINUTES) \
                                     || ((__VALUE__) == LL_RTC_ALMB_MASK_SECONDS) \
                                     || ((__VALUE__) == LL_RTC_ALMB_MASK_ALL))

#define IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) || \
                                                  ((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_WEEKDAY))

#define IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) || \
                                                  ((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_WEEKDAY))

/**
  * @}
  */
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup RTC_LL_Exported_Functions
  * @{
  */

/** @addtogroup RTC_LL_EF_Init
  * @{
  */

/**
  * @brief  De-Initializes the RTC registers to their default reset values.
  * @note   This function doesn't reset the RTC Clock source and RTC Backup Data
  *         registers.
  * @param  RTCx RTC Instance
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: RTC registers are de-initialized
  *          - ERROR: RTC registers are not de-initialized
  */
ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx)
{
  ErrorStatus status = ERROR;

  /* Check the parameter */
  assert_param(IS_RTC_ALL_INSTANCE(RTCx));

  /* Disable the write protection for RTC registers */
  LL_RTC_DisableWriteProtection(RTCx);

  /* Set Initialization mode */
  if (LL_RTC_EnterInitMode(RTCx) != ERROR)
  {
    /* Reset TR, DR and CR registers */
    LL_RTC_WriteReg(RTCx, TR,       0x00000000U);
#if defined(RTC_WAKEUP_SUPPORT)
    LL_RTC_WriteReg(RTCx, WUTR,     RTC_WUTR_WUT);
#endif /* RTC_WAKEUP_SUPPORT */
    LL_RTC_WriteReg(RTCx, DR  ,     (RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0));
    /* Reset All CR bits except CR[2:0] */
#if defined(RTC_WAKEUP_SUPPORT)
    LL_RTC_WriteReg(RTCx, CR, (LL_RTC_ReadReg(RTCx, CR) & RTC_CR_WUCKSEL));
#else
    LL_RTC_WriteReg(RTCx, CR, 0x00000000U);
#endif /* RTC_WAKEUP_SUPPORT */
    LL_RTC_WriteReg(RTCx, PRER,     (RTC_PRER_PREDIV_A | RTC_SYNCH_PRESC_DEFAULT));
    LL_RTC_WriteReg(RTCx, ALRMAR,   0x00000000U);
    LL_RTC_WriteReg(RTCx, ALRMBR,   0x00000000U);
    LL_RTC_WriteReg(RTCx, SHIFTR,   0x00000000U);
    LL_RTC_WriteReg(RTCx, CALR,     0x00000000U);
    LL_RTC_WriteReg(RTCx, ALRMASSR, 0x00000000U);
    LL_RTC_WriteReg(RTCx, ALRMBSSR, 0x00000000U);

    /* Reset ISR register and exit initialization mode */
    LL_RTC_WriteReg(RTCx, ISR,      0x00000000U);

    /* Reset Tamper and alternate functions configuration register */
    LL_RTC_WriteReg(RTCx, TAFCR, 0x00000000U);

    /* Wait till the RTC RSF flag is set */
    status = LL_RTC_WaitForSynchro(RTCx);
  }

  /* Enable the write protection for RTC registers */
  LL_RTC_EnableWriteProtection(RTCx);

  return status;
}

/**
  * @brief  Initializes the RTC registers according to the specified parameters
  *         in RTC_InitStruct.
  * @param  RTCx RTC Instance
  * @param  RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure that contains
  *         the configuration information for the RTC peripheral.
  * @note   The RTC Prescaler register is write protected and can be written in
  *         initialization mode only.
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: RTC registers are initialized
  *          - ERROR: RTC registers are not initialized
  */
ErrorStatus LL_RTC_Init(RTC_TypeDef *RTCx, LL_RTC_InitTypeDef *RTC_InitStruct)
{
  ErrorStatus status = ERROR;

  /* Check the parameters */
  assert_param(IS_RTC_ALL_INSTANCE(RTCx));
  assert_param(IS_LL_RTC_HOURFORMAT(RTC_InitStruct->HourFormat));
  assert_param(IS_LL_RTC_ASYNCH_PREDIV(RTC_InitStruct->AsynchPrescaler));
  assert_param(IS_LL_RTC_SYNCH_PREDIV(RTC_InitStruct->SynchPrescaler));

  /* Disable the write protection for RTC registers */
  LL_RTC_DisableWriteProtection(RTCx);

  /* Set Initialization mode */
  if (LL_RTC_EnterInitMode(RTCx) != ERROR)
  {
    /* Set Hour Format */
    LL_RTC_SetHourFormat(RTCx, RTC_InitStruct->HourFormat);

    /* Configure Synchronous and Asynchronous prescaler factor */
    LL_RTC_SetSynchPrescaler(RTCx, RTC_InitStruct->SynchPrescaler);
    LL_RTC_SetAsynchPrescaler(RTCx, RTC_InitStruct->AsynchPrescaler);

    /* Exit Initialization mode */
    LL_RTC_DisableInitMode(RTCx);

    status = SUCCESS;
  }
  /* Enable the write protection for RTC registers */
  LL_RTC_EnableWriteProtection(RTCx);

  return status;
}

/**
  * @brief  Set each @ref LL_RTC_InitTypeDef field to default value.
  * @param  RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure which will be initialized.
  * @retval None
  */
void LL_RTC_StructInit(LL_RTC_InitTypeDef *RTC_InitStruct)
{
  /* Set RTC_InitStruct fields to default values */
  RTC_InitStruct->HourFormat      = LL_RTC_HOURFORMAT_24HOUR;
  RTC_InitStruct->AsynchPrescaler = RTC_ASYNCH_PRESC_DEFAULT;
  RTC_InitStruct->SynchPrescaler  = RTC_SYNCH_PRESC_DEFAULT;
}

/**
  * @brief  Set the RTC current time.
  * @param  RTCx RTC Instance
  * @param  RTC_Format This parameter can be one of the following values:
  *         @arg @ref LL_RTC_FORMAT_BIN
  *         @arg @ref LL_RTC_FORMAT_BCD
  * @param  RTC_TimeStruct pointer to a RTC_TimeTypeDef structure that contains
  *                        the time configuration information for the RTC.
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: RTC Time register is configured
  *          - ERROR: RTC Time register is not configured
  */
ErrorStatus LL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef *RTC_TimeStruct)
{
  ErrorStatus status = ERROR;

  /* Check the parameters */
  assert_param(IS_RTC_ALL_INSTANCE(RTCx));
  assert_param(IS_LL_RTC_FORMAT(RTC_Format));

  if (RTC_Format == LL_RTC_FORMAT_BIN)
  {
    if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR)
    {
      assert_param(IS_LL_RTC_HOUR12(RTC_TimeStruct->Hours));
      assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat));
    }
    else
    {
      RTC_TimeStruct->TimeFormat = 0x00U;
      assert_param(IS_LL_RTC_HOUR24(RTC_TimeStruct->Hours));
    }
    assert_param(IS_LL_RTC_MINUTES(RTC_TimeStruct->Minutes));
    assert_param(IS_LL_RTC_SECONDS(RTC_TimeStruct->Seconds));
  }
  else
  {
    if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR)
    {
      assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours)));
      assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat));
    }
    else
    {
      RTC_TimeStruct->TimeFormat = 0x00U;
      assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours)));
    }
    assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes)));
    assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds)));
  }

  /* Disable the write protection for RTC registers */
  LL_RTC_DisableWriteProtection(RTCx);

  /* Set Initialization mode */
  if (LL_RTC_EnterInitMode(RTCx) != ERROR)
  {
    /* Check the input parameters format */
    if (RTC_Format != LL_RTC_FORMAT_BIN)
    {
      LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, RTC_TimeStruct->Hours,
                         RTC_TimeStruct->Minutes, RTC_TimeStruct->Seconds);
    }
    else
    {
      LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Hours),
                         __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Minutes),
                         __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Seconds));
    }

    /* Exit Initialization mode */
    LL_RTC_DisableInitMode(RTC);

    /* If  RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
    if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U)
    {
      status = LL_RTC_WaitForSynchro(RTCx);
    }
    else
    {
      status = SUCCESS;
    }
  }
  /* Enable the write protection for RTC registers */
  LL_RTC_EnableWriteProtection(RTCx);

  return status;
}

/**
  * @brief  Set each @ref LL_RTC_TimeTypeDef field to default value (Time = 00h:00min:00sec).
  * @param  RTC_TimeStruct pointer to a @ref LL_RTC_TimeTypeDef structure which will be initialized.
  * @retval None
  */
void LL_RTC_TIME_StructInit(LL_RTC_TimeTypeDef *RTC_TimeStruct)
{
  /* Time = 00h:00min:00sec */
  RTC_TimeStruct->TimeFormat = LL_RTC_TIME_FORMAT_AM_OR_24;
  RTC_TimeStruct->Hours      = 0U;
  RTC_TimeStruct->Minutes    = 0U;
  RTC_TimeStruct->Seconds    = 0U;
}

/**
  * @brief  Set the RTC current date.
  * @param  RTCx RTC Instance
  * @param  RTC_Format This parameter can be one of the following values:
  *         @arg @ref LL_RTC_FORMAT_BIN
  *         @arg @ref LL_RTC_FORMAT_BCD
  * @param  RTC_DateStruct pointer to a RTC_DateTypeDef structure that contains
  *                         the date configuration information for the RTC.
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: RTC Day register is configured
  *          - ERROR: RTC Day register is not configured
  */
ErrorStatus LL_RTC_DATE_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_DateTypeDef *RTC_DateStruct)
{
  ErrorStatus status = ERROR;

  /* Check the parameters */
  assert_param(IS_RTC_ALL_INSTANCE(RTCx));
  assert_param(IS_LL_RTC_FORMAT(RTC_Format));

  if ((RTC_Format == LL_RTC_FORMAT_BIN) && ((RTC_DateStruct->Month & 0x10U) == 0x10U))
  {
    RTC_DateStruct->Month = (RTC_DateStruct->Month & (uint32_t)~(0x10U)) + 0x0AU;
  }
  if (RTC_Format == LL_RTC_FORMAT_BIN)
  {
    assert_param(IS_LL_RTC_YEAR(RTC_DateStruct->Year));
    assert_param(IS_LL_RTC_MONTH(RTC_DateStruct->Month));
    assert_param(IS_LL_RTC_DAY(RTC_DateStruct->Day));
  }
  else
  {
    assert_param(IS_LL_RTC_YEAR(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Year)));
    assert_param(IS_LL_RTC_MONTH(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Month)));
    assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Day)));
  }
  assert_param(IS_LL_RTC_WEEKDAY(RTC_DateStruct->WeekDay));

  /* Disable the write protection for RTC registers */
  LL_RTC_DisableWriteProtection(RTCx);

  /* Set Initialization mode */
  if (LL_RTC_EnterInitMode(RTCx) != ERROR)
  {
    /* Check the input parameters format */
    if (RTC_Format != LL_RTC_FORMAT_BIN)
    {
      LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, RTC_DateStruct->Day, RTC_DateStruct->Month, RTC_DateStruct->Year);
    }
    else
    {
      LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Day),
                         __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Month), __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Year));
    }

    /* Exit Initialization mode */
    LL_RTC_DisableInitMode(RTC);

    /* If  RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
    if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U)
    {
      status = LL_RTC_WaitForSynchro(RTCx);
    }
    else
    {
      status = SUCCESS;
    }
  }
  /* Enable the write protection for RTC registers */
  LL_RTC_EnableWriteProtection(RTCx);

  return status;
}

/**
  * @brief  Set each @ref LL_RTC_DateTypeDef field to default value (date = Monday, January 01 xx00)
  * @param  RTC_DateStruct pointer to a @ref LL_RTC_DateTypeDef structure which will be initialized.
  * @retval None
  */
void LL_RTC_DATE_StructInit(LL_RTC_DateTypeDef *RTC_DateStruct)
{
  /* Monday, January 01 xx00 */
  RTC_DateStruct->WeekDay = LL_RTC_WEEKDAY_MONDAY;
  RTC_DateStruct->Day     = 1U;
  RTC_DateStruct->Month   = LL_RTC_MONTH_JANUARY;
  RTC_DateStruct->Year    = 0U;
}

/**
  * @brief  Set the RTC Alarm A.
  * @note   The Alarm register can only be written when the corresponding Alarm
  *         is disabled (Use @ref LL_RTC_ALMA_Disable function).
  * @param  RTCx RTC Instance
  * @param  RTC_Format This parameter can be one of the following values:
  *         @arg @ref LL_RTC_FORMAT_BIN
  *         @arg @ref LL_RTC_FORMAT_BCD
  * @param  RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that
  *                         contains the alarm configuration parameters.
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: ALARMA registers are configured
  *          - ERROR: ALARMA registers are not configured
  */
ErrorStatus LL_RTC_ALMA_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct)
{
  /* Check the parameters */
  assert_param(IS_RTC_ALL_INSTANCE(RTCx));
  assert_param(IS_LL_RTC_FORMAT(RTC_Format));
  assert_param(IS_LL_RTC_ALMA_MASK(RTC_AlarmStruct->AlarmMask));
  assert_param(IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel));

  if (RTC_Format == LL_RTC_FORMAT_BIN)
  {
    if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR)
    {
      assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours));
      assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat));
    }
    else
    {
      RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U;
      assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours));
    }
    assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes));
    assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds));

    if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE)
    {
      assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay));
    }
    else
    {
      assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay));
    }
  }
  else
  {
    if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR)
    {
      assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours)));
      assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat));
    }
    else
    {
      RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U;
      assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours)));
    }

    assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes)));
    assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds)));

    if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE)
    {
      assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay)));
    }
    else
    {
      assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay)));
    }
  }

  /* Disable the write protection for RTC registers */
  LL_RTC_DisableWriteProtection(RTCx);

  /* Select weekday selection */
  if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE)
  {
    /* Set the date for ALARM */
    LL_RTC_ALMA_DisableWeekday(RTCx);
    if (RTC_Format != LL_RTC_FORMAT_BIN)
    {
      LL_RTC_ALMA_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay);
    }
    else
    {
      LL_RTC_ALMA_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay));
    }
  }
  else
  {
    /* Set the week day for ALARM */
    LL_RTC_ALMA_EnableWeekday(RTCx);
    LL_RTC_ALMA_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay);
  }

  /* Configure the Alarm register */
  if (RTC_Format != LL_RTC_FORMAT_BIN)
  {
    LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours,
                           RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds);
  }
  else
  {
    LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat,
                           __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours),
                           __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes),
                           __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds));
  }
  /* Set ALARM mask */
  LL_RTC_ALMA_SetMask(RTCx, RTC_AlarmStruct->AlarmMask);

  /* Enable the write protection for RTC registers */
  LL_RTC_EnableWriteProtection(RTCx);

  return SUCCESS;
}

/**
  * @brief  Set the RTC Alarm B.
  * @note   The Alarm register can only be written when the corresponding Alarm
  *         is disabled (@ref LL_RTC_ALMB_Disable function).
  * @param  RTCx RTC Instance
  * @param  RTC_Format This parameter can be one of the following values:
  *         @arg @ref LL_RTC_FORMAT_BIN
  *         @arg @ref LL_RTC_FORMAT_BCD
  * @param  RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that
  *                         contains the alarm configuration parameters.
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: ALARMB registers are configured
  *          - ERROR: ALARMB registers are not configured
  */
ErrorStatus LL_RTC_ALMB_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct)
{
  /* Check the parameters */
  assert_param(IS_RTC_ALL_INSTANCE(RTCx));
  assert_param(IS_LL_RTC_FORMAT(RTC_Format));
  assert_param(IS_LL_RTC_ALMB_MASK(RTC_AlarmStruct->AlarmMask));
  assert_param(IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel));

  if (RTC_Format == LL_RTC_FORMAT_BIN)
  {
    if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR)
    {
      assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours));
      assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat));
    }
    else
    {
      RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U;
      assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours));
    }
    assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes));
    assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds));

    if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE)
    {
      assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay));
    }
    else
    {
      assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay));
    }
  }
  else
  {
    if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR)
    {
      assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours)));
      assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat));
    }
    else
    {
      RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U;
      assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours)));
    }

    assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes)));
    assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds)));

    if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE)
    {
      assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay)));
    }
    else
    {
      assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay)));
    }
  }

  /* Disable the write protection for RTC registers */
  LL_RTC_DisableWriteProtection(RTCx);

  /* Select weekday selection */
  if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE)
  {
    /* Set the date for ALARM */
    LL_RTC_ALMB_DisableWeekday(RTCx);
    if (RTC_Format != LL_RTC_FORMAT_BIN)
    {
      LL_RTC_ALMB_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay);
    }
    else
    {
      LL_RTC_ALMB_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay));
    }
  }
  else
  {
    /* Set the week day for ALARM */
    LL_RTC_ALMB_EnableWeekday(RTCx);
    LL_RTC_ALMB_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay);
  }

  /* Configure the Alarm register */
  if (RTC_Format != LL_RTC_FORMAT_BIN)
  {
    LL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours,
                           RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds);
  }
  else
  {
    LL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat,
                           __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours),
                           __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes),
                           __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds));
  }
  /* Set ALARM mask */
  LL_RTC_ALMB_SetMask(RTCx, RTC_AlarmStruct->AlarmMask);

  /* Enable the write protection for RTC registers */
  LL_RTC_EnableWriteProtection(RTCx);

  return SUCCESS;
}

/**
  * @brief  Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec /
  *         Day = 1st day of the month/Mask = all fields are masked).
  * @param  RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized.
  * @retval None
  */
void LL_RTC_ALMA_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct)
{
  /* Alarm Time Settings : Time = 00h:00mn:00sec */
  RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMA_TIME_FORMAT_AM;
  RTC_AlarmStruct->AlarmTime.Hours      = 0U;
  RTC_AlarmStruct->AlarmTime.Minutes    = 0U;
  RTC_AlarmStruct->AlarmTime.Seconds    = 0U;

  /* Alarm Day Settings : Day = 1st day of the month */
  RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMA_DATEWEEKDAYSEL_DATE;
  RTC_AlarmStruct->AlarmDateWeekDay    = 1U;

  /* Alarm Masks Settings : Mask =  all fields are not masked */
  RTC_AlarmStruct->AlarmMask           = LL_RTC_ALMA_MASK_NONE;
}

/**
  * @brief  Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec /
  *         Day = 1st day of the month/Mask = all fields are masked).
  * @param  RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized.
  * @retval None
  */
void LL_RTC_ALMB_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct)
{
  /* Alarm Time Settings : Time = 00h:00mn:00sec */
  RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMB_TIME_FORMAT_AM;
  RTC_AlarmStruct->AlarmTime.Hours      = 0U;
  RTC_AlarmStruct->AlarmTime.Minutes    = 0U;
  RTC_AlarmStruct->AlarmTime.Seconds    = 0U;

  /* Alarm Day Settings : Day = 1st day of the month */
  RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMB_DATEWEEKDAYSEL_DATE;
  RTC_AlarmStruct->AlarmDateWeekDay    = 1U;

  /* Alarm Masks Settings : Mask =  all fields are not masked */
  RTC_AlarmStruct->AlarmMask           = LL_RTC_ALMB_MASK_NONE;
}

/**
  * @brief  Enters the RTC Initialization mode.
  * @note   The RTC Initialization mode is write protected, use the
  *         @ref LL_RTC_DisableWriteProtection before calling this function.
  * @param  RTCx RTC Instance
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: RTC is in Init mode
  *          - ERROR: RTC is not in Init mode
  */
ErrorStatus LL_RTC_EnterInitMode(RTC_TypeDef *RTCx)
{
  __IO uint32_t timeout = RTC_INITMODE_TIMEOUT;
  ErrorStatus status = SUCCESS;
  uint32_t tmp = 0U;

  /* Check the parameter */
  assert_param(IS_RTC_ALL_INSTANCE(RTCx));

  /* Check if the Initialization mode is set */
  if (LL_RTC_IsActiveFlag_INIT(RTCx) == 0U)
  {
    /* Set the Initialization mode */
    LL_RTC_EnableInitMode(RTCx);

    /* Wait till RTC is in INIT state and if Time out is reached exit */
    tmp = LL_RTC_IsActiveFlag_INIT(RTCx);
    while ((timeout != 0U) && (tmp != 1U))
    {
      if (LL_SYSTICK_IsActiveCounterFlag() == 1U)
      {
        timeout --;
      }
      tmp = LL_RTC_IsActiveFlag_INIT(RTCx);
      if (timeout == 0U)
      {
        status = ERROR;
      }
    }
  }
  return status;
}

/**
  * @brief  Exit the RTC Initialization mode.
  * @note   When the initialization sequence is complete, the calendar restarts
  *         counting after 4 RTCCLK cycles.
  * @note   The RTC Initialization mode is write protected, use the
  *         @ref LL_RTC_DisableWriteProtection before calling this function.
  * @param  RTCx RTC Instance
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: RTC exited from in Init mode
  *          - ERROR: Not applicable
  */
ErrorStatus LL_RTC_ExitInitMode(RTC_TypeDef *RTCx)
{
  /* Check the parameter */
  assert_param(IS_RTC_ALL_INSTANCE(RTCx));

  /* Disable initialization mode */
  LL_RTC_DisableInitMode(RTCx);

  return SUCCESS;
}

/**
  * @brief  Waits until the RTC Time and Day registers (RTC_TR and RTC_DR) are
  *         synchronized with RTC APB clock.
  * @note   The RTC Resynchronization mode is write protected, use the
  *         @ref LL_RTC_DisableWriteProtection before calling this function.
  * @note   To read the calendar through the shadow registers after Calendar
  *         initialization, calendar update or after wakeup from low power modes
  *         the software must first clear the RSF flag.
  *         The software must then wait until it is set again before reading
  *         the calendar, which means that the calendar registers have been
  *         correctly copied into the RTC_TR and RTC_DR shadow registers.
  * @param  RTCx RTC Instance
  * @retval An ErrorStatus enumeration value:
  *          - SUCCESS: RTC registers are synchronised
  *          - ERROR: RTC registers are not synchronised
  */
ErrorStatus LL_RTC_WaitForSynchro(RTC_TypeDef *RTCx)
{
  __IO uint32_t timeout = RTC_SYNCHRO_TIMEOUT;
  ErrorStatus status = SUCCESS;
  uint32_t tmp = 0U;

  /* Check the parameter */
  assert_param(IS_RTC_ALL_INSTANCE(RTCx));

  /* Clear RSF flag */
  LL_RTC_ClearFlag_RS(RTCx);

  /* Wait the registers to be synchronised */
  tmp = LL_RTC_IsActiveFlag_RS(RTCx);
  while ((timeout != 0U) && (tmp != 0U))
  {
    if (LL_SYSTICK_IsActiveCounterFlag() == 1U)
    {
      timeout--;
    }
    tmp = LL_RTC_IsActiveFlag_RS(RTCx);
    if (timeout == 0U)
    {
      status = ERROR;
    }
  }

  if (status != ERROR)
  {
    timeout = RTC_SYNCHRO_TIMEOUT;
    tmp = LL_RTC_IsActiveFlag_RS(RTCx);
    while ((timeout != 0U) && (tmp != 1U))
    {
      if (LL_SYSTICK_IsActiveCounterFlag() == 1U)
      {
        timeout--;
      }
      tmp = LL_RTC_IsActiveFlag_RS(RTCx);
      if (timeout == 0U)
      {
        status = ERROR;
      }
    }
  }

  return (status);
}

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

#endif /* defined(RTC) */

/**
  * @}
  */

#endif /* USE_FULL_LL_DRIVER */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

{'repo_name': 'KitSprout/SmartIMU', 'stars': '217', 'repo_language': 'C', 'file_name': 'SmartIMU.OutJob', 'mime_type': 'text/plain', 'hash': -8072018904546360518, 'source_dataset': 'data'}