code:
## Basic documentation for the limb access functions in the new limb system.

### ID system

The new system uses new IDs instead of the old ones.
```
limb       new  old
no limb:    0    1
natural:    1    0
basic:      2   -1
sex:        3   -2
beauty:     4   -3
combat:     5   -4
cybernetic: 6   -5
```

### Usage example:

```
<<if isAmputee($activeSlave)>>
    Slave is full amputee.
<</if>>
```

Most functions can be used like this, though some are more specialized.

### Functions:

#### Read-only functions:

* `isAmputee(slave)`:
    True if slave has no limbs, neither natural nor prosthetic.

* `hasAnyNaturalLimbs(slave)`:
    True if slave has at least one natural limb.

* `hasAnyProstheticLimbs(slave)`:
    True if slave has at least one prosthetic limb.

* `hasAnyLegs(slave)`:
    True if slave has at least one leg.

* `hasAnyArms(slave)`:
    True if slave has at least one arm.

* `hasAnyNaturalLegs(slave)`:
    True if slave has at least one leg that is natural

* `hasAnyNaturalArms(slave)`:
    True if slave has at least one arm that is natural

* `hasAnyProstheticArms(slave)`:
    True if slave has at least one arm that is prosthetic

* `hasBothLegs(slave)`:
    True if slave has both legs.

* `hasBothArms(slave)`:
    True if slave has both arms.

* `hasBothNaturalLegs(slave)`:
    True if slave has both legs and they are natural.

* `hasBothNaturalArms(slave)`:
    True if slave has both arms and they are natural.

* `hasAllLimbs(slave)`:
    True if slave has all limbs.

* `hasAllNaturalLimbs(slave)`:
    True if slave has all limbs and all are natural.

* `hasLeftArm(slave)`:
    True if slave has a left arm.

* `hasRightArm(slave)`:
    True if slave has a right arm.

* `hasLeftLeg(slave)`:
    True if slave has a left leg.

* `hasRightLeg(slave)`:
    True if slave has a right leg.

* `getLeftArmID(slave)`:
    Returns limb ID of the left arm.

* `getRightArmID(slave)`:
    Returns limb ID of the right arm.

* `getLeftLegID(slave)`:
    Returns limb ID of the left leg.

* `getRightLegID(slave)`:
    Returns limb ID of the right leg.

* `getLimbCount(slave, id)`:
    Returns count of specified limb ID.
    Can also be used to check for groups:
    101: any limbs that are not amputated
    102: prosthetic limbs off all kind
    103: sex-prosthetic
    104: beauty-prosthetic
    105: combat-prosthetic

    103-105 mean the sum of 3-5 and 6 respectfully.

* `getLegCount(slave, id)`:
    Returns count of legs with specified limb ID.

* `getArmCount(slave, id)`:
    Returns count of arms with specified limb ID.

#### String functions

* `idToDescription(id)`:
    Returns a very short description of the specified limb ID.
    0: "amputated";
    1: "healthy";
    2: "modern prosthetic";
    3: "advanced, sex-focused prosthetic";
    4: "advanced, beauty-focused prosthetic";
    5: "advanced, combat-focused prosthetic";
    6: "highly advanced cybernetic";

* `armsAndLegs(slave, arms, arm, legs, leg)`:
    Returns a string depending on the limbs a slave has. By default this is a
    variation of `arms and legs`, but this can be changed via parameters.

    Examples:
    `armsAndLegs(slave, "hands", "hand", "feet", foot)` returns `hands and feet` for a slave with all limbs,
    `hand and foot` for a slave with one limb each and `feet` for a slave with two legs, but no arms.

    Expects the slave to have at least one limb. Only the first parameter is mandatory, the rest defaults to the
    equivalent of `armsAndLegs(slave, "arms", "arm", "legs", "leg")`

#### Write-only functions

* `removeLimbs(slave, limb`:
    Removes a slave's limbs. Allowed values for limb: `"left arm"`, `"right arm"`, `"left leg"`, `"right leg"`, `"all"`.

* `attachLimbs(slave, limb, id)`:
    Attaches a limb of the specified id. Expects amputated limbs. Will overwrite existing limbs.
    Allowed values for limb: `"left arm"`, `"right arm"`, `"left leg"`, `"right leg"`, `"all"`.

* `configureLimbs(slave, limb, id)`:
    Sets the slave's limb to the specified id and sets all limb related variables to their correct values.
    Intended for use during slave generation and events.
    Allowed values for limb: `"left arm"`, `"right arm"`, `"left leg"`, `"right leg"`, `"all"`.


code:
# The Sanity Check

## Structure

The sanity check consists of two parts: The first part is a script with a number
of `git grep` calls using regex to find typical errors. The second parts is a java program that checks for correct closure of all SugarCube macros and HTML tags and has some additional functionality.

## The Java Check

### Structure

The java check has 3 main parts:

1.  A checks for correct closure of all SugarCube macros and HTML tags in the
    .tw files.

2.  A check to find variable names that are only used once to find misspelled
    variables and leftovers from removed variables.

3.  A search through all files against a dictionary to find common misspellings
    and deprecated code.

### Maintenance

In order to keep the number of false positives to a minimum this check has to be
regularly maintained:

1.  When new macros or HTML tags are introduced in the project code they have to
    be added to `devTools/javaSanityCheck/twineTags` or
    `devTools/javaSanityCheck/htmlTags`.

2.  When removing variables they often have a reference left in some kind of BC
    related code. This is a common example when a false positive occurs and that
    variable has to be added to `devTools/javaSanityCheck/ignoredVariables`.

3.  When fully removing variables that were ignored, they have to be removed
    from `devTools/javaSanityCheck/ignoredVariables` too.

4.  When adding variables it can happen that only one usage is identified by the
    check, which means that it throws a false positive. To remove this add the
    variable to `devTools/javaSanityCheck/ignoredVariables`. When the variable
    is used in more places later and found more than once it has to be removed
    again to keep the check as efficient as possible.

5.  When you find common misspellings you can add them to
    `devTools/dictionary_phrases.txt` or `devTools/dictionary_wholeWord.txt`.

6.  When a file produces so many false positives that they are impossible to
    clean up it may be added to `devTools/javaSanityCheck/excluded`.

### Source code

The source code can be found at [gitgud.io](https://gitgud.io/Arkerthan/twine-sanitycheck).

repo_name: Nithhogg/fc

license: mit


code:
<!-- cSpell:ignore cond -->

# Writing scenes

Most writing is basically just plain text with branches for different cases.
Important cases to remember:

- Does the slave have a dick/vagina/tits?
- Does the PC have a dick/tits/vagina?
- If the slave has a dick and you plan to use it, can they get erect on their own?
- Is the PC pregnant?
- Is the slave mindbroken?
- Is the slave blind?
- Is the slave pregnant?
- If you penetrate an orifice, is the slave a virgin in that orifice?
- Can the slave move (i.e. is the slave amputated and/or have massive tits and/or a massive dick)?
- Does the slave like/hate trust/fear you?
- Does the slave have fetishes or personality/sexual quirks/flaws that would impact how they react?

It's important to handle every RELEVANT variation of the above cases. Depending on what you're writing, other cases may also warrant consideration; e.g. a breast-play scene will probably need to account for breast size and lactation a lot more than a generic fuck scene. If a scene only applies to a specific type of slave, you can restrict the cases you account for to the ones that are only possible for that type of slave.

There are, broadly speaking, two main ways to do this:

1. Write the same big block of text and then copy/paste it into each relevant case, and tweak the wording slightly.
 ++Less thinking required
 --LOTS of duplicate text; if you need to change something later, you have to change it in many places
2. Decompose the scene into smaller segments or sections that can each be swapped out for the slave type in question.
 ++MUCH easier maintenance
 --Have to figure out how to phrase the scene in a way that can be broken down into discrete chunks

You can also combine the two cases. For example, you may want a complex, interleaved set of <<if>> conditions for the common cases, and then have big blobs for the corner cases that are hard to handle.

It can also be easier if you split the scene into a "prep", "main", and "finish" section (these would all be the same writing block, just 2-3 <<if>> chains in sequence); that way, you could, for example, take all the various possible cases that aren't really unique, and narrate them so that, in the main section, you don't have to do so much explanatory writing for the scene to make sense overall. Then, if necessary, wrap up with the finish section. (See src/pregmod/fSlaveSelfImpreg.tw for an example of this approach)

All the variables for you and the slave are, generally, held in the variables $PC and $activeSlave, respectively. When the PC and the slave have the same attributes, they usually have the same name, but exactly what they do and mean can vary a little bit. RTFM for details. To access a specific variable, you do $var.attribName, so e.g. pregnancy is checked by $activeSlave.preg or $PC.preg. In rarer cases, you'll be dealing with an indexed entry in the $slaves array; if that's the case, you'd use $slaves[_u] or $slaves[$i] (or whatever) instead of $activeSlave. If a second (or third?) slave is present, it will be stored in another variable, the name of which will depend on the scene; for example, when impregnating a slave with another slave, the sperm donor is in $impregnatrix

Conditions are usually checked by

```sugarcube
<<if CONDITION>>
    SHOW THIS TEXT
<<elseif CONDITION2>>
    SHOW THIS TEXT INSTEAD
<<else>>
    IF NEITHER CONDITION IS MET, SHOW THIS
<</if>>
```

Conditions are usually comparative (i.e. `$a < $b or $b == 5 or $c != $d.e`) and can be chained together with `&&` (AND) or `||` (OR) and grouped with `()` - for example:
`<<if($a > 1 || ($b == 2 && $c != $a))>>`
lets you check that either variable A is greater than one, or both B equals two and C is not equal to A.
There are also a few miscellaneous functions that let you check things like whether a slave can get pregnant or whether two slaves are mutually fertile

Variable names are interpolated straight into the text, so if you have a slave named "Beth" then the text
"You fuck $activeSlave.slaveName" becomes "You fuck Beth"
You can also explicitly print a variable by doing <<print _varName>> (for temp variables) or <<print $varName>> (for global variables) which can be useful in various situations; it also lets you print the output of code expressions, like <<print $someNumericVar * 10>>.
If you want to change a variable, you do something like
`<<set $activeSlave.devotion += 5>>`
Which would, in this case, give a devotion increase of 5.

Color is changed with YOUR @@.colorname;COLORED TEXT@@ HERE

So a random (really stupid) example might be:

```sugarcube
<<if $activeSlave.fetish == 'mindbroken'>>
    Special big block of mindbroken text here.
<<elseif isAmputee($activeSlave)>>
    Special big block of amputee text here.
<<if $PC.dick > 0>>
    <<set _wasVirgin = ''>>
    <<if $activeSlave.vagina > -1>>
        <<set _orifice = 'vagina'>>
        <<if $activeSlave.vagina == 0>>
            <<set _wasVirgin = 'vaginal'>>
        <</if>>
    <<else>>
        <<set _orifice = 'ass'>>
        <<if $activeSlave.anus == 0>>
            <<set _wasVirgin = "anal">>
        <</if>>
    <</if>>
    You fuck $activeSlave.slaveName's _orifice.
    <<if _wasVirgin != ''>>
        <<if $activeSlave.devotion > 50>>
            $He @@.hotpink;loves@@ losing $his <<print _wasVirgin>> virginity to you.
            <<set $activeSlave.devotion += 5>>
        <<else>>
            $He @@.mediumorchid;@@dislikes losing $his <<print _wasVirgin>> virginity to you.
            <<set $activeSlave.devotion -= 5>>
        <</if>>
    <</if>>
<<elseif $PC.vagina > 0 && $activeSlave.dick > 0>>
    $activeSlave.slaveName
    <<if $activeSlave.devotion > 50>>
        @@.hotpink;lovingly penetrates@@
        <<set $activeSlave.devotion += 5>>
    <<else>>
        indifferently hammers
    <</if>>
    your pussy.
<<elseif $activeSlave.vagina > -1>>
    Lesbian sex here.
<<else>>
    ERROR - PC doesn't have dick or vagina?
<</if>>
```

If you need to set a temp variable, prefix it with _ instead of $. This way, you don't go cluttering up the world with variables that only matter inside your little writing segment.

You can "hot-test" stuff by text editing your HTML copy of FC, but it's a little more tedious because you have to "escape" double quotes, <, >, and & with " < > and & respectively.

Some tips:

- Write your logic first, so you don't forget to close tags. In other words, it's better to do

```sugarcube
<<if $cond>
    TODO
<<else>>
    TODO
<</if>>
```

And then fill it in later than it is to end up with a situation where you have a dozen unclosed tags and you can't remember where they are or what they do.

- For very simple stuff, it's fine to "inline" your stuff. For example, when penetrating a slave, doing `"you fuck $his <<if $activeSlave.vagina > -1>>pussy<<else>>ass<</if>>"` to show "pussy" or "ass" as necessary. However, if you need to do the same comparison a bunch of times, do something like

```sugarcube
<<if $activeSlave.vagina > -1>>
    <<set _targetOrifice = "vagina">>
<<else>>
    <<set _targetOrifice = "asshole">>
<</if>>
```

And then, when you need it, do `"you fuck $his _targetOrifice"` in sixteen different places without having the pain in the ass of copy/pasting the same if/else clause every time.

- INDENT YOUR LOGIC. USE TABS. I'm serious. Don't question me. It will make EVERYONE hate you, when they have to deal with your code, if it's not indented properly.
This is much easier to read:

```sugarcube
<<if $cond1>>
    <<if $cond2>>
        whatever
    <<elseif $cond3>>
        whatever
    <<elseif $cond4>>
        <<if $cond5>>
            whatever
        <<else>>
            <<if $cond6>>
                whatever
            <</if>>
        <</if>>
    <<else>>
        whatever
        <<if $cond7>>
            <<if $cond8>>
                whatever
            <</if>>
        <</if>>
    <</if>>
<</if>>
```

than this:

```sugarcube
<<if $cond1>>
<<if $cond2>>
whatever
<<elseif $cond3>>
whatever
<<elseif $cond4>>
<<if $cond5>>
whatever
<<else>>
<<if $cond6>>
whatever
<</if>>
<</if>>
<<else>>
whatever
<<if $cond7>>
<<if $cond8>>
whatever
<</if>>
<</if>>
<</if>>
<</if>>
```

- Proof-read your shit before posting it. Spell-check wouldn't hurt.


code:
# Producing slave lists

The namespace `App.UI.SlaveList` provides functions for displaying lists of slaves and interacting with the slaves in those lists. These functions supersede (and extend) the `Slave Summary` passage. They provide a way to display a list, select a slave from a list, generate standard lists for a facility or a leader selection, as well as provide a way to customize output and interaction.

## General concept

The core function is `App.UI.SlaveList.render()`. It renders the list, assembling it from four pieces. The function is declared as follows:

```js
/**
 * @param {number[]} indices
 * @param {Array.<{index: number, rejects: string[]}>} rejectedSlaves
 * @param {slaveTextGenerator} interactionLink
 * @param {slaveTextGenerator} [postNote]
 * @returns {string}
 */
function (indices, rejectedSlaves, interactionLink, postNote)
```

and the type of the `slaveTextGenerator` callback is:

```js
/**
 * @callback slaveTextGenerator
 * @param {App.Entity.SlaveState} slave
 * @param {number} index
 * @return {string}
 */
```

To build the output, the `render()` function iterates over the `indices` array, which must contain indices from the `$slaves` array, and outputs each slave using the two callbacks. The first one (`interactionLink`) is used to generate the hyperlink for the slave name. Output from the second callback (if defined) will be printed after each slave summary. The array of rejected slaves is processed after that and its contents are printed out in a simple fashion. The function *does not sort* both arrays, neither `indices` nor `rejectedSlaves`; their elements are printed in the order, specified by the caller. The function' output has to be passed via the SugarCube wikifier, for example by printing in out using the `<<print>>` macro.

Let's consider a few examples.

## Implementation examples

### Basic printing

The most common behavior for the slave name links is to go to the `Slave Interact` passage after clicking its name. This is implemented by the `App.UI.SlaveList.SlaveInteract.stdInteract` function:

```js
/**
 * @param {App.Entity.SlaveState} slave
 * @param {number} index
 * @return {string}
 */
App.UI.SlaveList.SlaveInteract.stdInteract = (slave, index) =>
   App.UI.passageLink(SlaveFullName(slave), 'Slave Interact', `$activeSlave = $slaves[${index}]`);
```

The function gets both the slave object and its index in the `$slaves` array for convenience, and outputs a hyperlink in the HTML markup. which points to the `Slave Interact` passage and sets active slave to the slave with the given index, because `Slave Interact` operates with the current slave. In the SugarCube markup the function could look as follows:

```js
/**
 * @param {App.Entity.SlaveState} slave
 * @param {number} index
 * @return {string}
 */
App.UI.SlaveList.SlaveInteract.stdInteract = (slave, index) =>
  `<<link "${SlaveFullName(slave)}" "Slave Interact">><<set $activeSlave = $slaves[${index}]`;
```
Now we can print slave lists. Let's print first three from the `$slaves` array:

```
<<print App.UI.SlaveList.render(
   [0, 1, 2], [].
   App.UI.SlaveList.SlaveInteract.stdInteract
)>>
```

Let's print them in the reverse order:

```
<<print App.UI.SlaveList.render(
   [2, 1, 0], [].
   App.UI.SlaveList.SlaveInteract.stdInteract
)>>
```

and one more time omitting the second slave:

```
<<print App.UI.SlaveList.render(
   [0, 2],
   [{index: 1, rejects: ['Omitted for testing purposes']}].
   App.UI.SlaveList.SlaveInteract.stdInteract
)>>
```

### Post-notes

The post notes are little text pieces, printed after each slave. They can contain simple text, for example to inform that particular slave is special in a way, or provide additional action hyperlinks. The most common type of the post notes is a hyperlink for assigning or retrieving s slave from a facility. Here are their implementations:

```js
(slave, index) => App.UI.passageLink(`Send ${slave.object} to ${facility.name}`, "Assign", `$i = ${index}`);

(slave, index) => App.UI.passageLink(`Retrieve ${slave.object} from ${facility.name}`, "Retrieve", `$i = ${index}`);
```

With these blocks we can easily produce a list of slaves, working at a given facility `facility`.

First, let's get the indices of the workers:

```js
let facilitySlaves = facility.job().employeesIndices();
```

The `App.Entity.Facilities.Facility.job()` call returns a named job if it was given an argument, or the default job when argument was omitted. Pretty much every facility except the penthouse provides only a single job and we can safely omit the job name here.

Now just call the `render()` function:

```js
App.UI.SlaveList.render(facilitySlaves, [],
	App.UI.SlaveList.SlaveInteract.stdInteract,
   (slave, index) => App.UI.passageLink(`Retrieve ${slave.object} from ${facility.name}`, "Retrieve", `$i = ${index}`));
```

That's it, works with any facility.

Here we omitted a few details, like setting the `$returnTo` bookmark for the `Assign` and `Retrieve` passages, sorting the slaves lists, and a few more.

### Templates for common use cases

There are functions in the `App.UI.SlaveList` namespace for a few typical use cases.

Function | Purpose
----- | ----
`listSJFacilitySlaves()` | Creates a tabbed list for assigning and retrieving slaves t0/from a facility with a single job
`displayManager()` | Displays a facility manager with a link to change it or a note with a link to assign a manager
`stdFacilityPage()` | Combines the previous two functions to render the manager and employees
`penthousePage()` | Displays tabs with workers for the penthouse
`slaveSelectionList()` | Displays a list with filtering and sorting links for selecting a slave
`facilityManagerSelection()` | Specialization of the `slaveSelectionList()` to select a manager for a facility, which implements position requirements tests and highlights experienced slaves

### Fully custom lists

There are use cases that stand apart from all other, and there is no point in providing a template for them. In that case you can generate a totally custom list. Here is an example:

```
<<print App.UI.SlaveList.slaveSelectionList(
	s => !ruleSlaveExcluded(s, $currentRule),
	(s, i) => `<u><strong>${App.UI.passageLink(SlaveFullName(s), 'Rules Slave Exclude Workaround', `$activeSlave = $slaves[${i}]`)}</strong></u>`
)>>
```


code:
# Obtaining and building SugarCube for FC

## Intro

This brief how-to guides through patching and building [SugarCube](https://github.com/tmedwards/sugarcube-2)
for the Free Cities. SugarCube sources can be obtained locally by cloning its Git repository.

Prerequisites (listed NOT in the installation order, please read the list to the end first):

1. [Node.js](https://nodejs.org) with npm.
2. To build some packages, Node.js requires python and a C/C++ compiler. On Windows you may want to
install Visual Studio (or just the build tools) and Python 2.7 first. As of now, SugarCube does not
depend on any of such packages.

Windows: please choose to make the tools accessible from anywhere by allowing installers to modify
the PATH environment variable.

## Retrieving SugarCube sources and preparing build environment for it

The SC2 sources are a git submodule.

1. Get the sources: If it's the first time: `git submodule update --init --recursive`, afterwards `git submodule update` is enough.

2. Download required JavaScript libraries that are used during the build.
    Run the node package manager (npm) in the repository: `npm install` or `npm update`.
    * You need to navigate into `submodules/sugarcube-2` first.

## Building

Run the build.js script. If you use Git bash, you can run the `build.js` file directly, otherwise run
it as `node build.js`. See `build.js -h` for options, but reasonable sets are the following.

* for release version: `node build.js -n -b 2`
* for debug version: `node build.js -n -b 2 -u -d`

Find result files in the `build` directory. After each build you have  to copy the release `format.js` to
`devTools/tweeGo/storyFormats/sugarcube-2`. Do not forget to `git add` the file.

Linux: If you have make installed, `make sugarcube` automatically builds and copies `format.js` to
`devTools/tweeGo/storyFormats/sugarcube-2` for easy testing.

## Contributing

1. Fork the [SC2 repo](https://gitgud.io/Arkerthan/sugarcube-2)
2. Navigate into submodules/sugarcube-2
    * Tip: Use two terminals, one in the main repo and one in the submodule.
    * You are now in the root of the submodule. Git works here (almost) the same as in the root of a standalone repo.
3. Add your fork as remote
4. `git submodule update` leaves you in a detached head state, so checkout fc and pull recent changes
5. Branch, modify, commit, push as usual.
6. Build and replace `devTools/tweeGo/storyFormats/sugarcube-2/format.js`
7. Create a new patch `git diff master <your branch> > sugarcube-fc-changes.patch` and move it to
    `devNotes/sugarcube stuff/`.
8. Commit and push in the main repo.
9. Open an MR in the SC2 repo **AND** in the main repo. Mark the MR in the main repo as **WIP**.
10. Once the MR in the SC2 repo is accepted do:
    *  In the submodule
    1. `git checkout fc`
    2. `git pull`
    *  In the main repo
    1. `git add submodules/sugarcube-2`
    2. `git commit --amend --no-edit`
    3. `git push -f`
11. Remove WIP flag from main repo.

Repeat steps 4 - 11.

## (OLD) Retrieving SugarCube sources and preparing build environment for it

Note: This is **NOT** recommended. Everything below is for documentation purposes only.

1. Open a terminal window where you want to clone the repository, and run the following command: `git clone https://github.com/tmedwards/sugarcube-2.git`. Change working directory into the cloned repository.

2. The last step we need is downloading required JavaScript libraries that are used during the build.
Run the node package manager (npm) in the repository: `npm install` or `npm update`

*CAUTION*: dependencies list (located in the package.json file in the repository root) may change from
commit to commit and it differs between branches! Make sure to install correct dependencies after switching working branch.

## Applying the FC patch

The FreeCities game relies on a few changes to the vanilla SugarCube code. The modified SC2 can be found [here](https://gitgud.io/Arkerthan/sugarcube-2).

If unavailable, it is possible to patch the official SC2 sources using the patch file. The SugarCube code changes from version to version that requires modification to the patch file, and therefore there are several of them, named after the highest SugarCube version they applies to. There are at least two different ways to manage the patches/changes, with the first one suitable for occasional users, while the second one works best if you maintain the SugarCube patch for the FC project or just want to keep building for more than a single SugarCube version.

### Single time patching

Find the correct patch in this repo and apply it to the sources:
`git apply <full path to sugarcube-fc-changes.patch>`

You are ready to build provided no errors were returned by `git apply`

### Maintaining the patch

#### Crating git branch with patched SugarCube sources

For this purpose we will create a git branch with the changes and then update it, [rebasing](https://git-scm.com/book/en/v2/Git-Branching-Rebasing) it on top of the SugarCube master branch when updating is needed.

To start over, create a branch for the patched version (here it will be named "fc") and checkout it: `git checkout -b fc`. Now apply FC changes as in the previous section using `git apply`, but afterwards commit the changes.

*Caveat*: to apply the patch you have to use the version of the SugarCube sources it applies to. If the latest patch does not apply to the current SugarCube master branch, check the `git log` to find the commit id of the SugarCube release you have the patch for. Then branch from that commit: `git branch fc <commit-id>` and checkout the "fc" branch: `git checkout fc`. To update the "fc" branch to the latest SugarCube see below.

#### Updating git branch

To update the branch we will use rebasing. First, fetch changes from the remote SugarCube repo: `git fetch origin`. Check that you are on the "fc" branch (`git checkout fc` if you are not). Now try to rebase your "fc" branch on top of the upstream master branch: `git rebase origin/master`. If that succeeds, the new patched SugarCube sources are ready in the "fc" branch. Proceed to building.

If the rebasing resulted in a conflict, you have to resolve it first. Issue `git rebase --continue` to get the list of files with conflicts, look for conflict markers ('<<<<') in those files, make required changes, do not forget to save the files, and follow advices from `git rebase --continue` until you finally resolve all the conflicts and obtain a new patched sources.

Now you need to update the patch files in the FC repo. First, rename the old patch file: `git mv sugarcube-fc-changes.patch sugarcube-fc-changes-<the last version it applies to>.patch`. Now create an new patch and add it to the repository: `git diff master fc > sugarcube-fc-changes.patch`, copy it to this dir and `git add sugarcube-fc-changes.patch`.

## APPENDIX Lists required steps very briefly

1. Clone SugarCube repo: `git clone https://github.com/tmedwards/sugarcube-2.git`
2. Change active directory into the directory of the sugarcube clone.
3. Set active branch to "master": git checkout master
4. Run npm install in the repo dir.

*CAUTION*: Requited dependencies change during the project lifetime and vary from branch to branch;
you may need to run npm install again after some time, or after branch/tag change. Try to run it in
case of strange build errors.

The next is done in the directory where SC repo was cloned. Loop over required SugarCube versions:

### Setup:

1. `git reset --hard` to clean any local changes.
2. `git branch fc v2.30.1` (the tag for the version you have the latest patch for).
3. `git checkout fc`

### Update loop

1. `git fetch origin`
2. `git checkout fc`
3. `git rebase origin/master`
4. Conflict resolving, `git rebase --continue` and `git add` are needed.
5. `git diff master fc > sugarcube-fc-changes.patch`; `git add sugarcube-fc-changes.patch`.

### Build

1. `node build.js -6 -b 2` to build release version
2. `cp build/twine2/sugarcube-2/format.js <whenever you want>`
3. `node build.js -6 -b 2 -u -d` to build debug version
4. `cp dist/twine2/sugarcube-2/format.js <whenever you want to place the debug header>`