Full Code of RocketRobz/hiyaCFW for AI

unlaunch a9a6027489c8 cached
55 files
204.7 KB
60.6k tokens
103 symbols
1 requests
Download .txt
Showing preview only (218K chars total). Download the full file or copy to clipboard to get everything.
Repository: RocketRobz/hiyaCFW
Branch: unlaunch
Commit: a9a6027489c8
Files: 55
Total size: 204.7 KB

Directory structure:
gitextract_sb4kvjyr/

├── .gitattributes
├── .github/
│   └── workflows/
│       └── build.yml
├── .gitignore
├── .gitmodules
├── LICENSE
├── Makefile
├── README.md
├── arm7/
│   ├── Makefile
│   └── source/
│       └── main.c
├── arm9/
│   ├── Makefile
│   ├── ds_arm9_hiya.mem
│   ├── ds_arm9_hiya.specs
│   ├── graphics_xcf/
│   │   ├── credits.xcf
│   │   └── topSplash.xcf
│   └── source/
│       ├── bios_decompress_callback.c
│       ├── bios_decompress_callback.h
│       ├── dsi_only.cpp
│       ├── fileOperations.cpp
│       ├── fileOperations.h
│       ├── gif.cpp
│       ├── gif.hpp
│       ├── inifile.cpp
│       ├── inifile.h
│       ├── lzw.cpp
│       ├── lzw.hpp
│       ├── main.cpp
│       ├── nds_loader_arm9.c
│       ├── nds_loader_arm9.h
│       ├── stringtool.cpp
│       ├── stringtool.h
│       ├── tonccpy.c
│       └── tonccpy.h
├── bootloader/
│   ├── Makefile
│   ├── arm9code/
│   │   └── mpu_reset.s
│   ├── load.ld
│   └── source/
│       ├── arm7clear.s
│       ├── arm9clear.arm.c
│       ├── arm9mpu_reset.s
│       ├── bios.s
│       ├── boot.c
│       ├── boot.h
│       ├── card.h
│       ├── disc_io.h
│       ├── fat.c
│       ├── fat.h
│       ├── io_dldi.h
│       ├── io_dldi.s
│       ├── load_crt0.s
│       ├── sdmmc.c
│       └── sdmmc.h
├── fix_ndsheader.py
├── hiyaCFW.pnproj
├── hiyaCFW.pnps
├── hiyacfw_helper.py
└── logo/
    └── logo.xcf

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitattributes
================================================
# Auto detect text files and perform LF normalization
* text=auto

# Custom for Visual Studio
*.cs     diff=csharp

# Standard to msysgit
*.doc	 diff=astextplain
*.DOC	 diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot  diff=astextplain
*.DOT  diff=astextplain
*.pdf  diff=astextplain
*.PDF	 diff=astextplain
*.rtf	 diff=astextplain
*.RTF	 diff=astextplain


================================================
FILE: .github/workflows/build.yml
================================================
name: Build hiyaCFW

on:
  push:
    branches: ["*"]
    paths-ignore:
      - 'README.md'
  pull_request:
    branches: ["*"]
    paths-ignore:
      - 'README.md'
  release:
    types: [created]
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    container: devkitpro/devkitarm:20241104
    name: Build with Docker using devkitARM
    steps:
      - name: Checkout repo
        uses: actions/checkout@v4
        with:
          submodules: recursive
      - name: Install tools
        run: |
          sudo apt-get update
          sudo apt-get install p7zip-full python -y
      - name: Silence all git safe directory warnings
        run: |
          git config --system --add safe.directory '*'
          git fetch --prune --unshallow --tags
      - name: Build
        id: build
        run: |
          make
      - name: Pack 7z for nightly
        if: ${{ !startsWith(github.ref, 'refs/tags') }}
        run: |
          mkdir hiyaCFW
          cp hiya.dsi hiyaCFW
          7z a hiyaCFW.7z hiyaCFW
      - name: Pack 7z for release
        if: ${{ startsWith(github.ref, 'refs/tags') }}
        run: |
          mkdir "for SDNAND SD card"
          cp hiya.dsi "for SDNAND SD card"
          7z a template.7z "for SDNAND SD card"
          mv template.7z hiyaCFW.7z
      - name: Publish build to GH Actions
        uses: actions/upload-artifact@main
        with:
          path: hiyaCFW.7z
          name: build

  # Only run this for non-PR jobs.
  publish_build:
    runs-on: ubuntu-latest
    name: Publish build to release
    if: ${{ success() && !startsWith(github.ref, 'refs/pull') }}
    needs: build
    steps:
      - name: Download artifacts
        uses: actions/download-artifact@main
        with:
          name: build
          path: build
      - name: Upload to ${{ github.repository }} release
        if: ${{ startsWith(github.ref, 'refs/tags') }}
        run: |
          ID=$(jq --raw-output '.release.id' $GITHUB_EVENT_PATH)

          for file in ${{ github.workspace }}/build/*; do
            AUTH_HEADER="Authorization: token ${{ secrets.GITHUB_TOKEN }}"
            CONTENT_LENGTH="Content-Length: $(stat -c%s $file)"
            CONTENT_TYPE="Content-Type: application/7z-x-compressed"
            UPLOAD_URL="https://uploads.github.com/repos/${{ github.repository }}/releases/$ID/assets?name=$(basename $file)"

            curl -XPOST -H "$AUTH_HEADER" -H "$CONTENT_LENGTH" -H "$CONTENT_TYPE" --upload-file "$file" "$UPLOAD_URL"
          done


================================================
FILE: .gitignore
================================================
*/build
*.nds
*.dsi
*.cia
*.elf
data/*
*.DS_Store
.vscode
arm9/include/version.h


================================================
FILE: .gitmodules
================================================
[submodule "libs/libslim"]
	path = libs/libslim
	url = https://github.com/DS-Homebrew/libslim.git


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    {one line to give the program's name and a brief idea of what it does.}
    Copyright (C) {year}  {name of author}

    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/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    {project}  Copyright (C) {year}  {fullname}
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: Makefile
================================================
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
.SECONDARY:

ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif

ifneq (,$(shell which python3))
PYTHON	:= python3
else ifneq (,$(shell which python2))
PYTHON	:= python2
else ifneq (,$(shell which python))
PYTHON	:= python
else
$(error "Python not found in PATH, please install it.")
endif

export TARGET	:=	$(shell basename $(CURDIR))
export TOPDIR	:=	$(CURDIR)

# specify a directory which contains the nitro filesystem
# this is relative to the Makefile
NITRO_FILES	:=

# These set the information text in the nds file
GAME_ICON	:= icon.bmp
GAME_TITLE	:= hiyaCFW
GAME_SUBTITLE1	:= CFW for Nintendo DSi
GAME_SUBTITLE2	:= made by Apache Thunder

include $(DEVKITARM)/ds_rules

.PHONY: bootloader checkarm7 checkarm9 clean libslim

#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
all: libslim bootloader checkarm7 checkarm9 $(TARGET).nds

#---------------------------------------------------------------------------------
bootloader:
	$(MAKE) -C bootloader "EXTRA_CFLAGS= -DNO_DLDI"

#---------------------------------------------------------------------------------
checkarm7:
	$(MAKE) -C arm7
	
#---------------------------------------------------------------------------------
checkarm9:
	$(MAKE) -C arm9

#---------------------------------------------------------------------------------
$(TARGET).nds	: $(NITRO_FILES) arm7/$(TARGET).elf arm9/$(TARGET).elf
	ndstool	-c $(TARGET).nds -7 arm7/$(TARGET).elf -9 arm9/$(TARGET).elf -r9 00080002 \
			-b $(GAME_ICON) "$(GAME_TITLE);$(GAME_SUBTITLE1);$(GAME_SUBTITLE2)" \
			-g HIYA 01 "HIYACFW" -z 80040000 -u 00030004 $(_ADDFILES)
	$(PYTHON) fix_ndsheader.py $(TARGET).nds
	cp $(TARGET).nds hiya.dsi

#---------------------------------------------------------------------------------
arm7/$(TARGET).elf:
	$(MAKE) -C arm7
	
#---------------------------------------------------------------------------------
arm9/$(TARGET).elf:
	$(MAKE) -C arm9

#---------------------------------------------------------------------------------
clean:
	@echo clean ...
	@$(MAKE) -C arm9 clean
	@$(MAKE) -C arm7 clean
	@$(MAKE) -C bootloader clean
	@$(MAKE) -C libs/libslim clean
	@rm -f $(TARGET).nds $(TARGET).nds.orig.nds hiya.dsi

libslim:
	$(MAKE) -C libs/libslim/libslim


================================================
FILE: README.md
================================================
<p align="center">
  <img src="https://github.com/RocketRobz/hiyaCFW/blob/master/logo/logo.png"><br>
  <a href="https://gbatemp.net/threads/release-hiyacfw-worlds-first-nintendo-dsi-cfw.502631/">
   <img src="https://img.shields.io/badge/GBAtemp-Thread-blue.svg" alt="GBAtemp Thread">
  </a>
  <a href="https://discord.gg/fCzqcWteC4">
   <img src="https://img.shields.io/badge/Discord%20Server-%23other--nds--homebrew-green.svg" alt="Discord Server">
  </a>
  <a href="https://github.com/RocketRobz/hiyaCFW/actions?query=workflow%3A%22Build+hiyaCFW%22">
    <img src="https://github.com/RocketRobz/hiyaCFW/workflows/Build%20hiyaCFW/badge.svg" alt="Build status on GitHub Actions">
  </a>
</p>

HiyaCFW is the world's FIRST Nintendo DSi CFW, made by the talented folks over on our Discord server.

# Features

- Run custom DSiWare
- NAND to SD card redirection
- Run NAND backups from any console
- Replace the system menu with **TW**i**L**ight Menu++
- Run blocked flashcards (such as R4 Ultra)
- Remove region-locking
- Change the NAND region (Not compatible with CHN and KOR NANDs)
- Run 3DS-exclusive DSiWare (such as WarioWare Touched)
- Custom splash screens

# Compiling

In order to compile this on your own, you will need [devkitPro](https://devkitpro.org/)'s toolchains with the devkitARM, plus the necessary tools and libraries. `dkp-pacman` is included for easy installation of all components:

```
 $ dkp-pacman -Syu devkitARM general-tools dstools ndstool libnds
```

Once everything is downloaded and installed, `git clone` this repository, navigate to the folder, and run `make` to compile HiyaCFW. If there is an error, let us know.

# Credits
- Apache Thunder, NoCash, StuckPixel, Shutterbug2000, and Gericom.
- Drenn: .bmp loading code from GameYob, for custom splash screens.
- Pk11: .gif loading code for animated splash screens.
- Rocket Robz: Logo graphic, settings screen, support for region-changing and any NAND backup.
- devkitPro: For the majority of the base code like nds-bootloader which this loader uses.


================================================
FILE: arm7/Makefile
================================================
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif

include $(DEVKITARM)/ds_rules

#---------------------------------------------------------------------------------
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# INCLUDES is a list of directories containing extra header files
# DATA is a list of directories containing binary files
# all directories are relative to this makefile
#---------------------------------------------------------------------------------
BUILD		:=	build
SOURCES		:=	source
INCLUDES	:=	include build
DATA		:=

#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH	:=	-march=armv4t -mthumb -mthumb-interwork

CFLAGS	:=	-g -Wall -O2\
		-mcpu=arm7tdmi -mtune=arm7tdmi -fomit-frame-pointer\
		-ffast-math \
		$(ARCH)

CFLAGS	+=	$(INCLUDE) -DARM7
CXXFLAGS	:=	$(CFLAGS) -fno-rtti -fno-exceptions -fno-rtti


ASFLAGS	:=	-g $(ARCH)
LDFLAGS	=	-specs=ds_arm7.specs -g $(ARCH) -Wl,--nmagic -Wl,-Map,$(notdir $*).map

LIBS	:=	-lnds7

#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS	:=	$(LIBNDS)


#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------

export ARM7ELF	:=	$(CURDIR)/$(TARGET).elf
export DEPSDIR	:=	$(CURDIR)/$(BUILD)

export VPATH	:=	$(foreach dir,$(SOURCES),$(CURDIR)/$(dir))

CFILES		:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES	:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES		:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES	:=	$(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))

export OFILES	:=	$(addsuffix .o,$(BINFILES)) \
					$(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)

export INCLUDE	:=	$(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
					$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
					-I$(CURDIR)/$(BUILD)

export LIBPATHS	:=	$(foreach dir,$(LIBDIRS),-L$(dir)/lib)

#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
	export LD	:=	$(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
	export LD	:=	$(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------

.PHONY: $(BUILD) clean

#---------------------------------------------------------------------------------
$(BUILD):
	@[ -d $@ ] || mkdir -p $@
	@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile

#---------------------------------------------------------------------------------
clean:
	@echo clean ...
	@rm -fr $(BUILD) *.elf

#---------------------------------------------------------------------------------
else

DEPENDS	:=	$(OFILES:.o=.d)

#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
$(ARM7ELF)	:	$(OFILES)
	@echo linking $(notdir $@)
	@$(LD) $(LDFLAGS) $(OFILES) $(LIBPATHS) $(LIBS) -o $@

#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o	:	%.bin
#---------------------------------------------------------------------------------
	@echo $(notdir $<)
	@$(bin2o)

-include $(DEPENDS)

#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------


================================================
FILE: arm7/source/main.c
================================================
/*---------------------------------------------------------------------------------

default ARM7 core

Copyright (C) 2005 - 2010
	Michael Noland (joat)
	Jason Rogers (dovoto)
	Dave Murphy (WinterMute)

This software is provided 'as-is', without any express or implied
warranty.  In no event will the authors be held liable for any
damages arising from the use of this software.

Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:

1.	The origin of this software must not be misrepresented; you
	must not claim that you wrote the original software. If you use
	this software in a product, an acknowledgment in the product
	documentation would be appreciated but is not required.

2.	Altered source versions must be plainly marked as such, and
	must not be misrepresented as being the original software.

3.	This notice may not be removed or altered from any source
	distribution.

---------------------------------------------------------------------------------*/
#include <nds.h>

#define SD_IRQ_STATUS (*(vu32*)0x400481C)

void VcountHandler() { inputGetAndSend(); }

int main(void) {

	irqInit();

	readUserSettings();

	initClockIRQ();

	fifoInit();

	SetYtrigger(80);

	installSystemFIFO();

	fifoSendValue32(FIFO_USER_01, SD_IRQ_STATUS);
	fifoSendValue32(FIFO_USER_02, i2cReadRegister(0x4A, 0x70));

	irqSet(IRQ_VCOUNT, VcountHandler);

	irqEnable( IRQ_VBLANK | IRQ_VCOUNT | IRQ_NETWORK );

	while (1) {
		/* if (*(u32*)0x02FFFD0C == 0x54534453) { // 'SDST'
			fifoSendValue32(FIFO_USER_01, SD_IRQ_STATUS);
			*(u32*)0x02FFFD0C = 0;
		} */
		if(fifoCheckValue32(FIFO_USER_04)) {
			if(fifoCheckValue32(FIFO_USER_03)) {
				i2cWriteRegister(0x4A, 0x70, 0x01);	// Bootflag = Warmboot/SkipHealthSafety
			}
			// After writing i2c, set FIFO_USER_04 back to 0 so arm7 doesn't repeatedly run i2c code.
			fifoSendValue32(FIFO_USER_04, 0);
		}
		swiWaitForVBlank();
	}
}



================================================
FILE: arm9/Makefile
================================================
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif

export LIBSLIM	:=	$(CURDIR)/../libs/libslim/libslim

include $(DEVKITARM)/ds_rules

#---------------------------------------------------------------------------------

# If on a tagged commit, use the tag instead of the commit
ifneq ($(shell echo $(shell git tag -l --points-at HEAD) | head -c 1),)
GIT_VER := $(shell git tag -l --points-at HEAD)
else
GIT_VER := $(shell git describe --tags --match v[0-9]* --abbrev=7 | sed 's/-[0-9]*-g/-/')
endif

# Ensure version.h exists
ifeq (,$(wildcard include/version.h))
$(shell mkdir -p include)
$(shell touch include/version.h)
endif

# Print new version if changed
ifeq (,$(findstring $(GIT_VER), $(shell cat include/version.h)))
$(shell printf "#ifndef VERSION_HPP\n#define VERSION_HPP\n\n#define VER_NUMBER \"$(GIT_VER)\"\n\n#endif\n" > include/version.h)
endif

#---------------------------------------------------------------------------------
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# INCLUDES is a list of directories containing extra header files
# DATA is a list of directories containing binary files
# GRAPHICS is a list of directories containing image files to be converted with grit
# all directories are relative to this makefile
#---------------------------------------------------------------------------------
BUILD		:=	build
SOURCES		:=	source
INCLUDES	:=	include
DATA		:=	../data
GRAPHICS	:=	graphics

#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH	:=	-mthumb -mthumb-interwork

CFLAGS	:=	-g -Wall -O2\
			-march=armv5te -mtune=arm946e-s -fomit-frame-pointer\
			-ffast-math \
			$(ARCH)

CFLAGS	+=	$(INCLUDE) -DARM9
CXXFLAGS	:=	$(CFLAGS) -fno-rtti -fno-exceptions

ASFLAGS	:=	-g $(ARCH) -march=armv5te -mtune=arm946e-s

LDFLAGS	=	-specs=../ds_arm9_hiya.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)

#---------------------------------------------------------------------------------
# any extra libraries we wish to link with the project
#---------------------------------------------------------------------------------
LIBS	:=	-lslim -lnds9

#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS	:=	$(LIBSLIM) $(LIBNDS)

#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------

export ARM9ELF	:=	$(CURDIR)/$(TARGET).elf
export DEPSDIR	:=	$(CURDIR)/$(BUILD)

export VPATH	:=	$(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
					$(foreach dir,$(DATA),$(CURDIR)/$(dir)) \
					$(foreach dir,$(GRAPHICS),$(CURDIR)/$(dir))

CFILES		:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES	:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES		:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES	:=	$(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
BMPFILES	:=	$(foreach dir,$(GRAPHICS),$(notdir $(wildcard $(dir)/*.bmp)))

#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
	export LD	:=	$(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
	export LD	:=	$(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------

export OFILES	:=	$(addsuffix .o,$(BINFILES)) \
					$(BMPFILES:.bmp=.o) \
					$(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)

export INCLUDE	:=	$(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
					$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
					-I$(CURDIR)/$(BUILD)

export LIBPATHS	:=	$(foreach dir,$(LIBDIRS),-L$(dir)/lib)

.PHONY: $(BUILD) clean

#---------------------------------------------------------------------------------
$(BUILD):
	@[ -d $@ ] || mkdir -p $@
	@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile

#---------------------------------------------------------------------------------
clean:
	@echo clean ...
	@rm -fr $(BUILD) *.elf *.nds* *.bin

#---------------------------------------------------------------------------------
else

#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
$(ARM9ELF)	:	$(OFILES)
	@echo linking $(notdir $@)
	@$(LD) $(LDFLAGS) $(OFILES) $(LIBPATHS) $(LIBS) -o $@

#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o	:	%.bin
#---------------------------------------------------------------------------------
	@echo $(notdir $<)
	@$(bin2o)

#---------------------------------------------------------------------------------
%.s %.h	: %.bmp
#---------------------------------------------------------------------------------
	grit $< -gb -gB8 -gzl -gT! -fts -o$*

-include $(DEPSDIR)/*.d

#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------


================================================
FILE: arm9/ds_arm9_hiya.mem
================================================
/*--------------------------------------------------------------------------------
	This Source Code Form is subject to the terms of the Mozilla Public License,
	v. 2.0. If a copy of the MPL was not distributed with this file, You can
	obtain one at https://mozilla.org/MPL/2.0/.
--------------------------------------------------------------------------------*/
MEMORY {
	ewram	: ORIGIN = 0x02004000, LENGTH = 3M + 512K - 0x4000
	dtcm	: ORIGIN = 0x0b000000, LENGTH = 16K
	vectors	: ORIGIN = 0x01000000, LENGTH = 256
	itcm	: ORIGIN = 0x01000100, LENGTH = 32K - 256
}


================================================
FILE: arm9/ds_arm9_hiya.specs
================================================
%rename link                old_link

*link:
%(old_link) -T ../ds_arm9_hiya.mem%s -T ds_arm9.ld%s --gc-sections

*startfile:
ds_arm9_crt0%O%s crti%O%s crtbegin%O%s



================================================
FILE: arm9/source/bios_decompress_callback.c
================================================
/*
    NitroHax -- Cheat tool for the Nintendo DS
    Copyright (C) 2008  Michael "Chishm" Chisholm

    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/>.
*/

#include "bios_decompress_callback.h"

static int getSizeBiosCallback (uint8 * source, uint16 * dest, uint32 r2)
{
	(void)dest;
	(void)r2;
	return *((int*)source);
}

static uint8 readByteBiosCallback (uint8 * source)
{
	return *source;
}

TDecompressionStream decompressBiosCallback =
{
  getSizeBiosCallback,
  (void*)0,
  readByteBiosCallback
} ;




================================================
FILE: arm9/source/bios_decompress_callback.h
================================================
/*
    NitroHax -- Cheat tool for the Nintendo DS
    Copyright (C) 2008  Michael "Chishm" Chisholm

    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/>.
*/

#ifndef BIOS_DECOMPRESS_CALLBACK_H
#define BIOS_DECOMPRESS_CALLBACK_H

#ifdef __cplusplus
extern "C" {
#endif

#include <nds/bios.h>
#include <nds/ndstypes.h>

extern TDecompressionStream decompressBiosCallback;



#ifdef __cplusplus
}
#endif

#endif // BIOS_DECOMPRESS_CALLBACK_H



================================================
FILE: arm9/source/dsi_only.cpp
================================================
#include <nds.h>
#include "dsiOnly_top.h"
#include "dsiOnly_bot.h"

static void dsiOnly_setBrightness(u8 screen, s8 bright) {
	u16 mode = 1 << 14;

	if (bright < 0) {
		mode = 2 << 14;
		bright = -bright;
	}
	if (bright > 31) {
		bright = 31;
	}
	*(vu16*)(0x0400006C + (0x1000 * screen)) = bright + mode;
}

void dsiOnly(void) {
	if (isDSiMode()) return;	// Proceed running on DSi

	dsiOnly_setBrightness(0, 31);
	dsiOnly_setBrightness(1, 31);

	videoSetMode(MODE_4_2D);
	videoSetModeSub(MODE_4_2D);

	vramSetBankA(VRAM_A_MAIN_BG);
	vramSetBankB(VRAM_B_MAIN_BG);
	vramSetBankC(VRAM_C_SUB_BG);
	vramSetBankD(VRAM_D_LCD);

	// Display DSi Only screen
	int bg3 = bgInit(3, BgType_Bmp8, BgSize_B8_256x256, 1, 0);
	decompress(dsiOnly_topBitmap, bgGetGfxPtr(bg3), LZ77Vram);
	for (int i = 0; i < 16; i++) {
		BG_PALETTE[i] = dsiOnly_topPal[i];
	}

	int bg3sub = bgInitSub(3, BgType_Bmp8, BgSize_B8_256x256, 1, 0);
	decompress(dsiOnly_botBitmap, bgGetGfxPtr(bg3sub), LZ77Vram);
	for (int i = 0; i < 16; i++) {
		BG_PALETTE_SUB[i] = dsiOnly_botPal[i];
	}

	dsiOnly_setBrightness(0, 0);
	dsiOnly_setBrightness(1, 0);

	while (1) {
		swiWaitForVBlank();
	}
}

================================================
FILE: arm9/source/fileOperations.cpp
================================================
#include "fileOperations.h"
#include <nds.h>
#include <slim.h>
#include <stdio.h>
#include <dirent.h>
#include <vector>

using namespace std;

off_t getFileSize(const char *fileName)
{
	FILE* fp = fopen(fileName, "rb");
	off_t fsize = 0;
	if (fp) {
		fseek(fp, 0, SEEK_END);
		fsize = ftell(fp);			// Get source file's size
		fseek(fp, 0, SEEK_SET);
		fclose(fp);
	}

	return fsize;
}


================================================
FILE: arm9/source/fileOperations.h
================================================
#include <nds.h>

#ifndef FILE_COPY
#define FILE_COPY

extern off_t getFileSize(const char *fileName);

#endif // FILE_COPY

================================================
FILE: arm9/source/gif.cpp
================================================
#include "gif.hpp"
#include "lzw.hpp"
#include "tonccpy.h"

#include <stdio.h>

std::vector<Gif *> Gif::_animating;

void Gif::timerHandler(void) {
	for (auto gif : _animating) {
		gif->displayFrame();
	}
}

void Gif::displayFrame(void) {
	if (_paused || ++_currentDelayProgress < _currentDelay)
		return;

	_currentDelayProgress = 0;
	_waitingForInput = false;

	if (_currentFrame >= _frames.size()) {
		_currentFrame = 0;
		_currentLoop++;
	}

	if (_currentLoop > _loopCount) {
		_finished = true;
		_paused = true;
		_currentLoop = 0;
		return;
	}

	Frame &frame = _frames[_currentFrame++];

	if (frame.hasGCE) {
		_currentDelay = frame.gce.delay;
		if (frame.gce.delay == 0) {
			_finished = true;
			_paused = true;
		} else if (frame.gce.userInputFlag) {
			_waitingForInput = true;
		}
	}

	std::vector<u16> &colorTable = frame.descriptor.lctFlag ? frame.lct : _gct;

	tonccpy(_top ? BG_PALETTE : BG_PALETTE_SUB, colorTable.data(), colorTable.size() * 2);

	// Disposal method 2 = fill with bg color
	if (frame.gce.disposalMethod == 2)
		toncset(_top ? BG_GFX : BG_GFX_SUB, header.bgColor, 256 * 192);

	if(_compressed) { // Was left compressed to be able to fit
		int x = 0, y = 0;
		u8 *dst = (u8*)(_top ? BG_GFX : BG_GFX_SUB) + (frame.descriptor.y + y + (192 - header.height) / 2) * 256 + frame.descriptor.x + (256 - header.width) / 2;
		u8 row[frame.descriptor.w];
		auto flush_fn = [&dst, &row, &x, &y, &frame](std::vector<u8>::const_iterator begin, std::vector<u8>::const_iterator end) {
			for (; begin != end; ++begin) {
				if (!frame.gce.transparentColorFlag || *begin != frame.gce.transparentColor)
					row[x] = *begin;
				else
					row[x] = *(dst + x);
				x++;
				if (x >= frame.descriptor.w) {
					tonccpy(dst, row, frame.descriptor.w);
					y++;
					x = 0;
					dst += 256;
				}
			}
		};

		LZWReader reader(frame.image.lzwMinimumCodeSize, flush_fn);
		reader.decode(frame.image.imageData.begin(), frame.image.imageData.end());
	} else { // Already decompressed, just copy
		auto it = frame.image.imageData.begin();
		for(int y = 0; y < frame.descriptor.h; y++) {
			u8 *dst = (u8*)(_top ? BG_GFX : BG_GFX_SUB) + (frame.descriptor.y + y + (192 - header.height) / 2) * 256 + frame.descriptor.x + (256 - header.width) / 2;
			u8 row[frame.descriptor.w];
			for(int x = 0; x < frame.descriptor.w; x++, it++) {
				if (!frame.gce.transparentColorFlag || *it != frame.gce.transparentColor)
					row[x] = *it;
				else
					row[x] = *(dst + x);
			}
			tonccpy(dst, row, frame.descriptor.w);
		}
	}
}

bool Gif::load(const char *path, bool top, bool animate, bool forceDecompress) {
	_top = top;

	FILE *file = fopen(path, "rb");
	if (!file)
		return false;

	if(forceDecompress) {
		_compressed = false;
	} else {
		fseek(file, 0, SEEK_END);
		_compressed = ftell(file) > (/*dsiFeatures()*/true ? 1 << 20 : 1 << 18); // Decompress files bigger than 1MiB (256KiB in DS Mode) while drawing
		fseek(file, 0, SEEK_SET);
	}

	// Reserve space for 2,000 frames
	_frames.reserve(2000);

	// Read header
	fread(&header, 1, sizeof(header), file);

	// Check that this is a GIF
	if (memcmp(header.signature, "GIF87a", sizeof(header.signature)) != 0 && memcmp(header.signature, "GIF89a", sizeof(header.signature)) != 0) {
		fclose(file);
		return false;
	}

	// Load global color table
	if (header.gctFlag) {
		int numColors = (2 << header.gctSize);

		_gct = std::vector<u16>(numColors);
		for (int i = 0; i < numColors; i++) {
			const u8 r = fgetc(file);
			const u8 g = fgetc(file);
			const u8 b = fgetc(file);

			const u16 green = (g >> 2) << 5;
			_gct[i] = r >> 3 | (b >> 3) << 10;
			if (green & BIT(5)) {
				_gct[i] |= BIT(15);
			}
			for (int gBit = 6; gBit <= 10; gBit++) {
				if (green & BIT(gBit)) {
					_gct[i] |= BIT(gBit-1);
				}
			}
		}
	}

	// Set default loop count to 0, uninitialized default is 0xFFFF so it's infinite
	_loopCount = 0;

	Frame frame;
	while (1) {
		switch (fgetc(file)) {
			case 0x21: { // Extension
				switch (fgetc(file)) {
					case 0xF9: { // Graphics Control
						frame.hasGCE = true;
						fread(&frame.gce, 1, fgetc(file), file);
						if(frame.gce.delay < 2) // If delay is less then 2, change it to 10
							frame.gce.delay = 10;
						fgetc(file); // Terminator
						break;
					} case 0x01: { // Plain text
						// Unsupported for now, I can't even find a text GIF to test with
						// frame.hasText = true;
						// fread(&frame.textDescriptor, 1, sizeof(frame.textDescriptor), file);
						fseek(file, 12, SEEK_CUR);
						while (u8 size = fgetc(file)) {
							// char temp[size + 1];
							// fread(temp, 1, size, file);
							// frame.text += temp;
							fseek(file, size, SEEK_CUR);
						}
						// _frames.push_back(frame);
						// frame = Frame();
						break;
					} case 0xFF: { // Application extension
						if (fgetc(file) == 0xB) {
							char buffer[0xC] = {0};
							fread(buffer, 1, 0xB, file);
							if (strcmp(buffer, "NETSCAPE2.0") == 0) { // Check for Netscape loop count
								fseek(file, 2, SEEK_CUR);
								fread(&_loopCount, 1, sizeof(_loopCount), file);
								if(_loopCount == 0) // If loop count 0 is specified, loop forever
									_loopCount = 0xFFFF;
								fgetc(file); //terminator
								break;
							}
						}
					} case 0xFE: { // Comment
						// Skip comments and unsupported application extionsions
						while (u8 size = fgetc(file)) {
							fseek(file, size, SEEK_CUR);
						}
						break;
					}
				}
				break;
			} case 0x2C: { // Image desriptor
				frame.hasImage = true;
				fread(&frame.descriptor, 1, sizeof(frame.descriptor), file);
				if (frame.descriptor.lctFlag) {
					int numColors = 2 << frame.descriptor.lctSize;
					frame.lct = std::vector<u16>(numColors);
					for (int i = 0; i < numColors; i++) {
						const u8 r = fgetc(file);
						const u8 g = fgetc(file);
						const u8 b = fgetc(file);

						const u16 green = (g >> 2) << 5;
						frame.lct[i] = r >> 3 | (b >> 3) << 10;
						if (green & BIT(5)) {
							frame.lct[i] |= BIT(15);
						}
						for (int gBit = 6; gBit <= 10; gBit++) {
							if (green & BIT(gBit)) {
								frame.lct[i] |= BIT(gBit-1);
							}
						}
					}
				}

				frame.image.lzwMinimumCodeSize = fgetc(file);
				if(_compressed) { // Leave compressed to fit more in RAM
					while (u8 size = fgetc(file)) {
						size_t end = frame.image.imageData.size();
						frame.image.imageData.resize(end + size);
						fread(frame.image.imageData.data() + end, 1, size, file);
					}
				} else { // Decompress now for faster draw
					frame.image.imageData = std::vector<u8>(frame.descriptor.w * frame.descriptor.h);
					auto it = frame.image.imageData.begin();
					auto flush_fn = [&it, &frame](std::vector<u8>::const_iterator begin, std::vector<u8>::const_iterator end) {
						std::copy(begin, end, it);
						it += std::distance(begin, end);
					};
					LZWReader reader(frame.image.lzwMinimumCodeSize, flush_fn);

					while (u8 size = fgetc(file)) {
						std::vector<u8> buffer(size);
						fread(buffer.data(), 1, size, file);
						reader.decode(buffer.begin(), buffer.end());
					}
				}

				_frames.push_back(frame);
				frame = Frame();
				break;
			} case 0x3B: { // Trailer
				goto breakWhile;
			}
		}
	}
	breakWhile:

	fclose(file);

	_paused = false;
	_finished = loopForever();
	_frames.shrink_to_fit();
	if(animate)
		_animating.push_back(this);

	return true;
}


================================================
FILE: arm9/source/gif.hpp
================================================
#ifndef GIF_HPP
#define GIF_HPP

#include <nds/ndstypes.h>
#include <vector>
#include <cstddef>

typedef unsigned int uint;

class Gif {
	struct Header {
		char signature[6];
		u16 width;
		u16 height;
		u8 gctSize: 3;
		u8 sortFlag: 1;
		u8 colorResolution: 3;
		u8 gctFlag: 1;
		u8 bgColor;
		u8 pixelAspectRatio;
	} __attribute__ ((__packed__)) header;
	static_assert(sizeof(Header) == 13);

	struct Frame {
		struct GraphicsControlExtension {
			u8 transparentColorFlag: 1;
			u8 userInputFlag: 1;
			u8 disposalMethod: 3;
			u8 reserved: 3;
			u16 delay; // In hundreths (1/100) of a second
			u8 transparentColor;
		} __attribute__ ((__packed__)) gce;
		static_assert(sizeof(GraphicsControlExtension) == 4);

		// Unsupported for now
		// struct PlainText {
		// 	u16 gridX;
		// 	u16 gridY;
		// 	u16 gridW;
		// 	u16 gridH;
		// 	u8 charW;
		// 	u8 charH;
		// 	u8 forgroundIndex;
		// 	u8 backgroundIndex;
		// } __attribute__ ((__packed__)) textDescriptor;
		// static_assert(sizeof(PlainText) == 12);

		struct Descriptor {
			u16 x;
			u16 y;
			u16 w;
			u16 h;
			u8 lctSize: 3;
			u8 reserved: 2;
			u8 sortFlag: 1;
			u8 interlaceFlag: 1;
			u8 lctFlag: 1;
		} __attribute__ ((__packed__)) descriptor;
		static_assert(sizeof(Descriptor) == 9);

		struct Image {
			u8 lzwMinimumCodeSize;
			std::vector<u8> imageData;
		} image;

		std::vector<u16> lct; // In DS format
		// std::string text;
		bool hasGCE = false;
		// bool hasText = false;
		bool hasImage = false;
	};

	std::vector<Frame> _frames;
	std::vector<u16> _gct; // In DS format
	u16 _loopCount = 0xFFFF;
	bool _top = false;
	bool _compressed = false;

	// Animation vairables
	static std::vector<Gif *> _animating;
	uint _currentFrame = 0;
	uint _currentDelay = 0;
	uint _currentDelayProgress = 0;
	u16 _currentLoop = 0;
	bool _paused = true;
	bool _finished = true;

	bool _waitingForInput = false;

	static void animate(bool top);

	void displayFrame(void);

public:
	static void timerHandler(void);

	Gif() {}
	Gif(const char *path, bool top, bool animate, bool forceDecompress) { load(path, top, animate, forceDecompress); }
	~Gif() {}

	bool load(const char *path, bool top, bool animate, bool forceDecompress);

	Frame &frame(int frame) { return _frames[frame]; }
	std::vector<u16> gct() { return _gct; }

	bool paused() { return _paused; }
	void pause() { _paused = true; }
	void unpause() { _paused = false; }
	void toggle() { _paused = !_paused; }

	bool loopForever(void) { return _loopCount == 0xFFFF; }
	bool waitingForInput(void) { return _waitingForInput; }
	void resume(void) { _waitingForInput = false; _currentDelayProgress = _currentDelay; }
	bool finished(void) { return _finished; }

	int currentFrame(void) { return _currentFrame; }
};

#endif


================================================
FILE: arm9/source/inifile.cpp
================================================
/*
    inifile.cpp
    Copyright (C) 2007 Acekard, www.acekard.com
    Copyright (C) 2007-2009 somebody
    Copyright (C) 2009 yellow wood goblin

    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/>.
*/

#include <cstdio>
#include <cstdlib>
#include "inifile.h"
#include "stringtool.h"

static bool freadLine(FILE* f,std::string& str)
{
  str.clear();
__read:
  char p=0;

  size_t readed=fread(&p,1,1,f);
  if(0==readed)
  {
    str="";
    return false;
  }
  if('\n'==p||'\r'==p)
  {
    str="";
    return true;
  }

  while(p!='\n'&&p!='\r'&&readed)
  {
    str+=p;
    readed=fread(&p,1,1,f);
  }

  if(str.empty()||""==str)
  {
    goto __read;
  }

  return true;
}

static void trimString(std::string& str)
{
  size_t first=str.find_first_not_of(" \t"),last;
  if(first==str.npos)
  {
    str="";
  }
  else
  {
    last=str.find_last_not_of(" \t");
    if(first>0||(last+1)<str.length()) str=str.substr(first,last-first+1);
  }
}

CIniFile::CIniFile()
{
  m_bLastResult=false;
  m_bModified=false;
  m_bReadOnly=false;
}

CIniFile::CIniFile(const std::string& filename)
{
  m_sFileName=filename;
  m_bLastResult=false;
  m_bModified=false;
  m_bReadOnly=false;
  LoadIniFile(m_sFileName);
}

CIniFile::~CIniFile()
{
  if(m_FileContainer.size()>0)
  {
    m_FileContainer.clear();
  }
}

void CIniFile::SetString(const std::string& Section,const std::string& Item,const std::string& Value)
{
  if(GetFileString(Section,Item)!=Value)
  {
    SetFileString(Section,Item,Value);
    m_bModified=true;
  }
}

void CIniFile::SetInt(const std::string& Section,const std::string& Item,int Value)
{
  std::string strtemp=formatString("%d",Value);

  if(GetFileString(Section,Item)!=strtemp)
  {
    SetFileString(Section,Item,strtemp);
    m_bModified=true;
  }
}

std::string CIniFile::GetString(const std::string& Section,const std::string& Item)
{
  return GetFileString(Section,Item);
}

std::string CIniFile::GetString(const std::string& Section,const std::string& Item,const std::string& DefaultValue)
{
  std::string temp=GetString(Section,Item);
  if(!m_bLastResult)
  {
    SetString(Section,Item,DefaultValue);
    temp=DefaultValue;
  }
  return temp;
}

void CIniFile::GetStringVector(const std::string& Section,const std::string& Item,std::vector< std::string >& strings,char delimiter)
{
  std::string strValue=GetFileString(Section,Item);
  strings.clear();
  size_t pos;
  while((pos=strValue.find(delimiter),strValue.npos!=pos))
  {
    const std::string string=strValue.substr(0,pos);
    if(string.length())
    {
      strings.push_back(string);
    }
    strValue=strValue.substr(pos+1,strValue.npos);
  }
  if(strValue.length())
  {
    strings.push_back(strValue);
  }
}

void CIniFile::SetStringVector(const std::string& Section,const std::string& Item,std::vector<std::string>& strings,char delimiter)
{
  std::string strValue;
  for(size_t ii=0;ii<strings.size();++ii)
  {
    if(ii) strValue+=delimiter;
    strValue+=strings[ii];
  }
  SetString(Section,Item,strValue);
}

int CIniFile::GetInt(const std::string& Section,const std::string& Item)
{
  std::string value=GetFileString(Section,Item);
  if(value.size()>2&&'0'==value[0]&&('x'==value[1]||'X'==value[1]))
    return strtol(value.c_str(),NULL,16);
  else
    return strtol(value.c_str(),NULL,10);
}

int CIniFile::GetInt(const std::string& Section,const std::string& Item,int DefaultValue)
{
  int temp;
  temp=GetInt(Section,Item);
  if(!m_bLastResult)
  {
    SetInt(Section,Item,DefaultValue);
    temp=DefaultValue;
  }
  return temp;
}

bool CIniFile::LoadIniFile(const std::string& FileName)
{
  //dbg_printf("load %s\n",FileName.c_str());
  if(FileName!="") m_sFileName=FileName;

  FILE* f=fopen(FileName.c_str(),"rb");

  if(NULL==f) return false;

  //check for utf8 bom.
  char bom[3];
  if(fread(bom,3,1,f)==1&&bom[0]==0xef&&bom[1]==0xbb&&bom[2]==0xbf) ;
  else fseek(f,0,SEEK_SET);

  std::string strline("");
  m_FileContainer.clear();

  while(freadLine(f,strline))
  {
    trimString(strline);
    if(strline!=""&&';'!=strline[0]&&'/'!=strline[0]&&'!'!=strline[0]) m_FileContainer.push_back(strline);
  }

  fclose(f);

  m_bLastResult=false;
  m_bModified=false;

  return true;
}

bool CIniFile::SaveIniFileModified(const std::string& FileName)
{
  if(m_bModified==true)
  {
    return SaveIniFile(FileName);
  }

  return true;
}

bool CIniFile::SaveIniFile(const std::string& FileName)
{
  if(FileName!="")
    m_sFileName=FileName;

  FILE* f=fopen(m_sFileName.c_str(),"wb");
  if(NULL==f)
  {
    return false;
  }

  for(size_t ii=0;ii<m_FileContainer.size();ii++)
  {
    std::string& strline=m_FileContainer[ii];
    size_t notSpace=strline.find_first_not_of(' ');
    strline=strline.substr(notSpace);
    if(strline.find('[')==0&&ii>0)
    {
      if(!m_FileContainer[ii-1].empty()&&m_FileContainer[ii-1]!="")
        fwrite("\r\n",1,2,f);
    }
    if(!strline.empty()&&strline!="")
    {
      fwrite(strline.c_str(),1,strline.length(),f);
      fwrite("\r\n",1,2,f);
    }
  }

  fclose(f);

  m_bModified=false;

  return true;
}

std::string CIniFile::GetFileString(const std::string& Section,const std::string& Item)
{
  std::string strline;
  std::string strSection;
  std::string strItem;
  std::string strValue;

  size_t ii=0;
  size_t iFileLines=m_FileContainer.size();

  if(m_bReadOnly)
  {
    cSectionCache::iterator it=m_Cache.find(Section);
    if((it!=m_Cache.end())) ii=it->second;
  }

  m_bLastResult=false;

  if(iFileLines>=0)
  {
    while(ii<iFileLines)
    {
      strline=m_FileContainer[ii++];

      size_t rBracketPos=0;
      if('['==strline[0]) rBracketPos=strline.find(']');
      if(rBracketPos>0&&rBracketPos!=std::string::npos)
      {
        strSection=strline.substr(1,rBracketPos-1);
        if(m_bReadOnly) m_Cache.insert(std::make_pair(strSection,ii-1));
        if(strSection==Section)
        {
          while(ii<iFileLines)
          {
            strline=m_FileContainer[ii++];
            size_t equalsignPos=strline.find('=');
            if(equalsignPos!=strline.npos)
            {
              size_t last=equalsignPos?strline.find_last_not_of(" \t",equalsignPos-1):strline.npos;
              if(last==strline.npos) strItem="";
              else strItem=strline.substr(0,last+1);

              if(strItem==Item)
              {
                size_t first=strline.find_first_not_of(" \t",equalsignPos+1);
                if(first==strline.npos) strValue="";
                else strValue=strline.substr(first);
                m_bLastResult=true;
                return strValue;
              }
            }
            else if('['==strline[0])
            {
              break;
            }
          }
          break;
        }
      }
    }
  }
  return std::string("");
}

void CIniFile::SetFileString(const std::string& Section,const std::string& Item,const std::string& Value)
{
  std::string strline;
  std::string strSection;
  std::string strItem;

  if(m_bReadOnly) return;

  size_t ii=0;
  size_t iFileLines=m_FileContainer.size();

  while(ii<iFileLines)
  {
    strline=m_FileContainer[ii++];

    size_t rBracketPos=0;
    if('['==strline[0]) rBracketPos=strline.find(']');
    if(rBracketPos>0&&rBracketPos!=std::string::npos)
    {
      strSection=strline.substr(1,rBracketPos-1);
      if(strSection==Section)
      {
        while(ii<iFileLines)
        {
          strline=m_FileContainer[ii++];
          size_t equalsignPos=strline.find('=');
          if(equalsignPos!=strline.npos)
          {
              size_t last=equalsignPos?strline.find_last_not_of(" \t",equalsignPos-1):strline.npos;
              if(last==strline.npos) strItem="";
              else strItem=strline.substr(0,last+1);

              if(Item==strItem)
              {
                ReplaceLine(ii-1,Item+" = "+Value);
                return;
              }
          }
          else if('['==strline[0])
          {
            InsertLine(ii-1,Item+" = "+Value);
            return;
          }
        }
        InsertLine(ii,Item+" = "+Value);
        return;
      }
    }
  }

  InsertLine(ii,"["+Section+"]");
  InsertLine(ii+1,Item+" = "+Value);
  return;
}



bool CIniFile::InsertLine(size_t line,const std::string& str)
{
  m_FileContainer.insert(m_FileContainer.begin()+line,str);
  return true;
}

bool CIniFile::ReplaceLine(size_t line,const std::string& str)
{
  m_FileContainer[line]=str;
  return true;
}


================================================
FILE: arm9/source/inifile.h
================================================
/*
    inifile.h
    Copyright (C) 2007 Acekard, www.acekard.com
    Copyright (C) 2007-2009 somebody
    Copyright (C) 2009-2010 yellow wood goblin

    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/>.
*/

#ifndef _INIFILE_H_
#define _INIFILE_H_

#include <string>
#include <vector>
#include <map>

class CIniFile
{
  public:
    CIniFile();
    CIniFile(const std::string& filename);
    virtual ~CIniFile();

  public:
    bool LoadIniFile(const std::string& FileName);
    bool SaveIniFile(const std::string& FileName);
    bool SaveIniFileModified(const std::string& FileName);

    std::string GetString(const std::string& Section,const std::string& Item,const std::string& DefaultValue);
    void SetString(const std::string& Section,const std::string& Item,const std::string& Value);
    int GetInt(const std::string& Section,const std::string& Item,int DefaultValue);
    void SetInt(const std::string& Section,const std::string& Item,int Value);
    void GetStringVector(const std::string& Section,const std::string& Item,std::vector<std::string>& strings,char delimiter=',');
    void SetStringVector(const std::string& Section,const std::string& Item,std::vector<std::string>& strings,char delimiter=',');
  protected:
    std::string m_sFileName;
    typedef std::vector<std::string> cStringArray;
    cStringArray m_FileContainer;
    bool m_bLastResult;
    bool m_bModified;
    bool m_bReadOnly;
    typedef std::map<std::string,size_t> cSectionCache;
    cSectionCache m_Cache;

    bool InsertLine(size_t line,const std::string& str);
    bool ReplaceLine(size_t line,const std::string& str);

    void SetFileString(const std::string& Section,const std::string& Item,const std::string& Value);
    std::string GetFileString(const std::string& Section,const std::string& Item);

    std::string GetString(const std::string& Section,const std::string& Item);
    int GetInt(const std::string& Section,const std::string& Item);
};

#endif // _INIFILE_H_


================================================
FILE: arm9/source/lzw.cpp
================================================
#include "lzw.hpp"

u16 LZWReader::readLSB(std::vector<u8>::iterator &begin, const std::vector<u8>::iterator &end) {
	while (nBits < width) {
		if (begin == end) {
			err = true;
			return 0;
		}
		u8 x = *(begin++);
		bits |= x << nBits;
		nBits += 8;
	}
	u16 code = bits & ((1 << width) - 1);
	bits >>= width;
	nBits -= width;
	return code;
}

bool LZWReader::decode(std::vector<u8>::iterator begin, std::vector<u8>::iterator end) {
	o = 0;
	err = false;
	// Loop over the code stream, converting codes into decompressed bytes.
	while (begin != end) {
		u16 code = readLSB(begin, end);
		if (err) {
			flush();
			return false;
		}

		if (code < clear) { // Literal
			output[o++] = code;
			if (last != DECODER_INVALID_CODE) {
				// Save what the hi code expands to.
				suffix[hi] = code;
				prefix[hi] = last;
			}
		} else if (code == clear) { // Clear
			width = 1 + litWidth;
			hi = eof;
			overflow = 1 << width;
			last = DECODER_INVALID_CODE;
			continue;
		} else if (code == eof) { // End
			flush();
			return true;
		} else if (code <= hi) {
			u16 c = code;
			uint i = output.size() - 1;
			if (code == hi && last != DECODER_INVALID_CODE) {
				// code == hi is a special case which expands to the last expansion
				// followed by the head of the last expansion. To find the head, we walk
				// the prefix chain until we find a literal code.
				c = last;
				while (c >= clear)
					c = prefix[c];
				output[i] = c;
				i--;
				c = last;
			}
			// Copy the suffix chain into output and then write that to w.
			while (c >= clear) {
				output[i] = suffix[c];
				i--;
				c = prefix[c];
			}
			output[i] = c;
			std::copy(output.begin() + i, output.end(), output.begin() + o);
			o += std::distance(output.begin() + i, output.end());
			if (last != DECODER_INVALID_CODE) {
				// Save what the hi code expands to
				suffix[hi] = c;
				prefix[hi] = last;
			}
		} else { // Error
			flush();
			return false;
		}

		last = code;
		hi++;
		if (hi >= overflow) {
			if (hi > overflow) {
				flush();
				return false;
			}

			if (width == MAX_WIDTH) {
				last = DECODER_INVALID_CODE;
				// Undo the d.hi++ a few lines above, so that (1) we maintain
				// the invariant that d.hi < d.overflow, and (2) d.hi does not
				// eventually overflow a uint16.
				hi--;
			} else {
				width++;
				overflow = 1 << width;
			}
		}
		if (o >= FLUSH_BUFFER) {
			flush();
		}
	}

	flush();
	return true;
}

LZWReader::LZWReader(int minCodeSize, std::function<void(u8_itr, u8_itr)> flushFunction) : litWidth(minCodeSize), flushFn(flushFunction) {
	width = 1 + litWidth;
	clear = 1 << litWidth;
	eof = clear + 1;
	hi = clear + 1;
	overflow = 1 << width;
	last = DECODER_INVALID_CODE;

	suffix = std::vector<u8>(1 << MAX_WIDTH);
	prefix = std::vector<u16>(1 << MAX_WIDTH);
	output = std::vector<u8>(2 * (1 << MAX_WIDTH));
}

void LZWReader::flush(void) {
	if (flushFn && o > 0) {
		flushFn(output.begin(), output.begin() + o);
	}
	o = 0;
}


================================================
FILE: arm9/source/lzw.hpp
================================================
#ifndef LZW_HPP
#define LZW_HPP

#include <nds.h>
#include <functional>
#include <vector>

typedef unsigned int uint;
typedef std::vector<u8>::const_iterator u8_itr;

class LZWReader {
	constexpr static u16 MAX_WIDTH = 12;
	constexpr static u16 DECODER_INVALID_CODE = 0xFFFF;
	constexpr static u16 FLUSH_BUFFER = 1 << MAX_WIDTH;

	int litWidth;
	std::function<void(u8_itr, u8_itr)> flushFn;
	u32 bits = 0;
	uint nBits = 0;
	uint width;
	bool err = false;

	u16 clear, eof, hi, overflow, last;

	std::vector<u8> suffix;
	std::vector<u16> prefix;

	std::vector<u8> output;
	int o = 0;
	// std::vector<u8> toRead;

	u16 readLSB(std::vector<u8>::iterator &it, const std::vector<u8>::iterator &end);

	int read(std::vector<u8> &buffer);

	void flush(void);

public:
	LZWReader(int minCodeSize, std::function<void(u8_itr, u8_itr)> flushFunction);

	bool decode(std::vector<u8>::iterator begin, std::vector<u8>::iterator end);
};

#endif


================================================
FILE: arm9/source/main.cpp
================================================
#include <dirent.h>
#include <nds.h>
#include <slim.h>
#include <stdarg.h>
#include <stdio.h>

#include "bios_decompress_callback.h"
#include "fileOperations.h"
#include "gif.hpp"
#include "inifile.h"
#include "nds_loader_arm9.h"
#include "tonccpy.h"
#include "version.h"

#include "topLoad.h"
#include "subLoad.h"
// #include "topError.h"
// #include "subError.h"

#define CONSOLE_SCREEN_WIDTH 32
#define CONSOLE_SCREEN_HEIGHT 24

#define SETTINGS_INI_PATH "sd:/hiya/settings.ini"

#define TMD_SIZE 0x208

static char tmdBuffer[TMD_SIZE];

bool splash = true;
bool dsiSplash = false;
bool titleAutoboot = false;
bool eraseUnlaunch = true;

bool splashFound[2] = {false};
bool splashBmp[2] = {false};
bool rgb565BmpDisplayMode = false;
u16* dsImageBuffer[2];

Gif gif[2];

void hBlankHandler() {
	int scanline = REG_VCOUNT;
	if (scanline > 192) {
		return;
	} else if (scanline == 192) {
		if (splashBmp[0]) {
			dmaCopyWordsAsynch(0, dsImageBuffer[0], BG_PALETTE_SUB, 256*2);
		}
		if (splashBmp[1]) {
			dmaCopyWordsAsynch(1, dsImageBuffer[1], BG_PALETTE, 256*2);
		}
	} else {
		scanline++;
		if (splashBmp[0]) {
			dmaCopyWordsAsynch(0, dsImageBuffer[0]+(scanline*256), BG_PALETTE_SUB, 256*2);
		}
		if (splashBmp[1]) {
			dmaCopyWordsAsynch(1, dsImageBuffer[1]+(scanline*256), BG_PALETTE, 256*2);
		}
	}
}

bool loadBMP(bool top) {
	FILE* file = fopen((top ? "sd:/hiya/splashtop.bmp" : "sd:/hiya/splashbottom.bmp"), "rb");
	if (!file)
		return false;

	// Read width & height
	fseek(file, 0x12, SEEK_SET);
	u32 width, height;
	fread(&width, 1, sizeof(width), file);
	fread(&height, 1, sizeof(height), file);

	if (width > 256 || height > 192) {
		fclose(file);
		return false;
	}

	if (rgb565BmpDisplayMode) {
		dsImageBuffer[top] = new u16[256*192];
		toncset(dsImageBuffer[top], 0, 256*192);
	}

	fseek(file, 0xE, SEEK_SET);
	u8 headerSize = fgetc(file);
	bool rgb565 = false;
	if(headerSize == 0x38) {
		// Check the upper byte green mask for if it's got 5 or 6 bits
		fseek(file, 0x2C, SEEK_CUR);
		rgb565 = fgetc(file) == 0x07;
		fseek(file, headerSize - 0x2E, SEEK_CUR);
	} else {
		fseek(file, headerSize - 1, SEEK_CUR);
	}
	u16 *bmpImageBuffer = new u16[width * height];
	fread(bmpImageBuffer, 2, width * height, file);
	u16 *src = bmpImageBuffer;
	if (rgb565BmpDisplayMode) {
		u16 *dst = dsImageBuffer[top] + ((191 - ((192 - height) / 2)) * 256) + (256 - width) / 2;
		if (rgb565) {
			for (uint y = 0; y < height; y++, dst -= 256) {
				for (uint x = 0; x < width; x++) {
					u16 val = *(src++);
					const u16 green = ((val) & (0x3F << 5));
					u16 color = ((val >> 11) & 0x1F) | (val & 0x1F) << 10;
					if (green & BIT(5)) {
						color |= BIT(15);
					}
					for (int g = 6; g <= 10; g++) {
						if (green & BIT(g)) {
							color |= BIT(g-1);
						}
					}
					*(dst + x) = color;
				}
			}
		} else {
			for (uint y = 0; y < height; y++, dst -= 256) {
				for (uint x = 0; x < width; x++) {
					u16 val = *(src++);
					*(dst + x) = ((val >> 10) & 0x1F) | ((val) & (0x1F << 5)) | (val & 0x1F) << 10;
				}
			}
		}
	} else {
		u16 *dst = (top ? BG_GFX : BG_GFX_SUB) + ((191 - ((192 - height) / 2)) * 256) + (256 - width) / 2;
		for (uint y = 0; y < height; y++, dst -= 256) {
			for (uint x = 0; x < width; x++) {
				u16 val = *(src++);
				*(dst + x) = ((val >> (rgb565 ? 11 : 10)) & 0x1F) | ((val >> (rgb565 ? 1 : 0)) & (0x1F << 5)) | (val & 0x1F) << 10 | BIT(15);
			}
		}
	}

	delete[] bmpImageBuffer;
	fclose(file);

	if (rgb565BmpDisplayMode) {
		u8* dsImageBuffer8 = new u8[256*192];
		for (int i = 0; i < 256*192; i++) {
			dsImageBuffer8[i] = i;
		}

		dmaCopyWords(3, dsImageBuffer8, top ? BG_GFX : BG_GFX_SUB, 256*192);
		delete[] dsImageBuffer8;
	}
	return true;
}

void bootSplashInit() {
	// Initialize bitmap background
	videoSetMode(MODE_3_2D);
	videoSetModeSub(MODE_3_2D);
	vramSetBankA(VRAM_A_MAIN_BG);
	vramSetBankC(VRAM_C_SUB_BG);
	// Clear these to prevent messing up the main BG
	vramSetBankH(VRAM_H_LCD);
	vramSetBankG(VRAM_G_LCD);

	if (splashFound[true] && splashBmp[true] && !splashBmp[false])
		bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);
	else
		bgInit(3, BgType_Bmp8, BgSize_B8_256x256, 0, 0);

	if (splashFound[false] && !splashBmp[true] && splashBmp[false])
		bgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);
	else
		bgInitSub(3, BgType_Bmp8, BgSize_B8_256x256, 0, 0);

	// Clear backgrounds
	toncset16(BG_PALETTE, 0, 256);
	toncset16(BG_PALETTE_SUB, 0, 256);
	toncset16(BG_GFX, 0, 256 * 256 * 2);
	toncset16(BG_GFX_SUB, 0, 256 * 256 * 2);
}

void loadScreen() {
	bootSplashInit();

	rgb565BmpDisplayMode = ((!splashFound[true] || splashBmp[true]) && (!splashFound[false] || splashBmp[false]));

	// Display Load Screen
	if (splashBmp[true]) {
		loadBMP(true);
	} else if (!splashFound[true]) {
		tonccpy(BG_PALETTE, topLoadPal, topLoadPalLen);
		swiDecompressLZSSVram((void*)topLoadBitmap, BG_GFX, 0, &decompressBiosCallback);
	}
	if (splashBmp[false]) {
		loadBMP(false);
	} else if (!splashFound[false]) {
		tonccpy(BG_PALETTE_SUB, subLoadPal, subLoadPalLen);
		swiDecompressLZSSVram((void*)subLoadBitmap, BG_GFX_SUB, 0, &decompressBiosCallback);
	}

	if ((splashFound[true] || splashFound[false]) && rgb565BmpDisplayMode) {
		irqSet(IRQ_HBLANK, hBlankHandler);
		irqEnable(IRQ_HBLANK);
	}
}

int cursorPosition = 0;

void loadSettings(void) {
	// GUI
	CIniFile settingsini(SETTINGS_INI_PATH);

	splash = settingsini.GetInt("HIYA-CFW", "SPLASH", 0);
	dsiSplash = settingsini.GetInt("HIYA-CFW", "DSI_SPLASH", 0);
	titleAutoboot = settingsini.GetInt("HIYA-CFW", "TITLE_AUTOBOOT", 0);
	eraseUnlaunch = settingsini.GetInt("HIYA-CFW", "ERASE_UNLAUNCH", 1);
}

void saveSettings(void) {
	// GUI
	CIniFile settingsini(SETTINGS_INI_PATH);

	settingsini.SetInt("HIYA-CFW", "SPLASH", splash);
	settingsini.SetInt("HIYA-CFW", "DSI_SPLASH", dsiSplash);
	settingsini.SetInt("HIYA-CFW", "TITLE_AUTOBOOT", titleAutoboot);
	settingsini.SaveIniFile(SETTINGS_INI_PATH);
}

void setupConsole() {
	// Subscreen as a console
	videoSetMode(MODE_0_2D);
	vramSetBankG(VRAM_G_MAIN_BG);
	videoSetModeSub(MODE_0_2D);
	vramSetBankH(VRAM_H_SUB_BG);
}

int main( int argc, char **argv) {
	extern void dsiOnly(void);
	dsiOnly();

	// defaultExceptionHandler();

	/* scanKeys();
	if ((keysHeld() & KEY_RIGHT) && (keysHeld() & KEY_A)) {
		setupConsole();

		consoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);
		consoleClear();

		iprintf("Please remove the SD Card and\n");
		iprintf("insert the SD Card containing\n");
		iprintf("hiyaCFW, then press A\n");
		iprintf("to continue.");

		// Prevent accidential presses
		for (int i = 0; i < 60; i++) {
			swiWaitForVBlank();
		}

		while (1) {
			scanKeys();
			if (keysHeld() & KEY_A) break;
			swiWaitForVBlank();
		}

		for (int i = 0; i < 24; i++) {
			swiWaitForVBlank();
		}
	}

	*(u32*)0x0CFFFD0C = 0x54534453; // 'SDST'
	while (*(u32*)0x0CFFFD0C != 0) { swiDelay(100); } */

	u32 sdIrqStatus = fifoGetValue32(FIFO_USER_01);
	if ((sdIrqStatus & BIT(5)) != 0 && (sdIrqStatus & BIT(7)) == 0) {
		setupConsole();

		consoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);
		consoleClear();

		iprintf("The SD card is write-locked.\n");
		iprintf("Please turn off the POWER,\n");
		iprintf("remove the SD card, move the\n");
		iprintf("write-lock switch up, re-insert\n");
		iprintf("the SD card, then try again.");

		while (1)
			swiWaitForVBlank();
	}

	if (!fatInitDefault()) {
		/* bootSplashInit();

		// Display Error Screen
		swiDecompressLZSSVram((void*)topErrorBitmap, BG_GFX, 0, &decompressBiosCallback);
		swiDecompressLZSSVram((void*)subErrorBitmap, BG_GFX_SUB, 0, &decompressBiosCallback);
		tonccpy(&BG_PALETTE[0], topErrorPal, topErrorPalLen);
		tonccpy(&BG_PALETTE_SUB[0], subErrorPal, subErrorPalLen); */

		setupConsole();

		consoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);
		consoleClear();

		iprintf("FAT init failed!");

		while (1)
			swiWaitForVBlank();
	}

	if ((access("sd:/", F_OK) != 0) && (access("fat:/", F_OK) == 0)) {
		setupConsole();

		consoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);
		consoleClear();

		iprintf("hiyaCFW is not compatible\n");
		iprintf("with flashcards!");

		while (1)
			swiWaitForVBlank();
	}

	u8 oldRegion = 0;
	u8 regionChar = 0;
	FILE* f_hwinfoS = fopen("sd:/sys/HWINFO_S.dat", "rb");
	if (f_hwinfoS) {
		fseek(f_hwinfoS, 0x90, SEEK_SET);
		fread(&oldRegion, 1, 1, f_hwinfoS);
		fseek(f_hwinfoS, 0xA0, SEEK_SET);
		fread(&regionChar, 1, 1, f_hwinfoS);
		fclose(f_hwinfoS);
	} else {
		setupConsole();
		consoleInit(NULL, 0, BgType_Text4bpp, BgSize_T_256x256, 15, 0, true, true);
		consoleClear();
		iprintf("Error!\n");
		iprintf("\n");
		iprintf("HWINFO_S.dat not found!");
		consoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);
		consoleClear();

		while (1)
			swiWaitForVBlank();
	}

	u8 newRegion = oldRegion;
	if (regionChar == 'C') {
		if (newRegion != 4) newRegion = 4;
	} else if (regionChar == 'K') {
		if (newRegion != 5) newRegion = 5;
	} else {
		if (newRegion >= 4) newRegion = 0;
	}

	loadSettings();

	bool gotoSettings = (access(SETTINGS_INI_PATH, F_OK) != 0);

	scanKeys();

	if (keysHeld() & KEY_SELECT) gotoSettings = true;

	if (gotoSettings) {
		setupConsole();

		int optionCount = 2;
		int optionShift = 0;
		if (regionChar != 'C' && regionChar != 'K') {
			optionCount++; // Display region setting
			optionShift++;
		}

		int pressed = 0;
		bool menuprinted = true;

		while (1) {
			if (menuprinted) {
				consoleInit(NULL, 0, BgType_Text4bpp, BgSize_T_256x256, 15, 0, true, true);
				consoleClear();

				iprintf ("\x1B[46m");

				iprintf("hiyaCFW %s%cconfiguration\n", VER_NUMBER, sizeof(VER_NUMBER) > 11 ? '\n' : ' ');
				iprintf("Press A to select, START to save");
				iprintf("\n");

				iprintf ("\x1B[47m");

				if (optionCount > 2) {
					if (cursorPosition == 0) iprintf ("\x1B[41m");
					else iprintf ("\x1B[47m");

					iprintf(" Region: ");
					switch (newRegion) {
						case 0:
							iprintf("JPN(x), USA( ),\n         EUR( ), AUS( )");
							break;
						case 1:
							iprintf("JPN( ), USA(x),\n         EUR( ), AUS( )");
							break;
						case 2:
							iprintf("JPN( ), USA( ),\n         EUR(x), AUS( )");
							break;
						case 3:
							iprintf("JPN( ), USA( ),\n         EUR( ), AUS(x)");
							break;
					}
					iprintf("\n\n");
				}

				if (cursorPosition == 0+optionShift) iprintf ("\x1B[41m");
				else iprintf ("\x1B[47m");

				iprintf(" Splash: ");
				if (splash)
					iprintf("Off( ), On(x)");
				else
					iprintf("Off(x), On( )");
				iprintf("\n\n");

				if (cursorPosition == 1+optionShift) iprintf ("\x1B[41m");
				else iprintf ("\x1B[47m");

				if (dsiSplash)
					iprintf(" (x)");
				else
					iprintf(" ( )");
				iprintf(" DSi Splash/H&S screen\n");

				if (cursorPosition == 2+optionShift) iprintf ("\x1B[41m");
				else iprintf ("\x1B[47m");

				if (titleAutoboot)
					iprintf(" (x)");
				else
					iprintf(" ( )");
				iprintf(" Autoboot title\n");

				consoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);
				consoleClear();

				iprintf("\n");
				if ((cursorPosition == 0) && (optionCount > 2)) {
					iprintf(" Change the SDNAND region.\n");
					iprintf(" \n");
					iprintf(" Changing from the original\n");
					iprintf(" will break apps such as DSi\n");
					iprintf(" Shop and 3DS Transfer Tool.\n");
					if (regionChar == 'J') {
						iprintf(" \n");
						iprintf(" System settings will be reset.\n");
					}
					iprintf(" \n");
					iprintf(" Original region: ");
					if (regionChar == 'J') {
						iprintf("JPN");
					} else if (regionChar == 'E') {
						iprintf("USA");
					} else if (regionChar == 'P') {
						iprintf("EUR");
					} else if (regionChar == 'U') {
						iprintf("AUS");
					}
				} else if (cursorPosition == 0+optionShift) {
					iprintf(" Enable splash screen.");
				} else if (cursorPosition == 1+optionShift) {
					iprintf(" Enable showing the DSi Splash/\n");
					iprintf(" Health & Safety screen.");
				} else if (cursorPosition == 2+optionShift) {
					iprintf(" Load title contained in\n");
					iprintf(" sd:/hiya/autoboot.bin\n");
					iprintf(" instead of the DSi Menu.");
				}

				menuprinted = false;
			}

			do {
				scanKeys();
				pressed = keysDownRepeat();
				swiWaitForVBlank();
			} while (!pressed);

			if (pressed & KEY_L) {
				// Debug code
				FILE* ResetData = fopen("sd:/hiya/ResetData_extract.bin","wb");
				fwrite((void*)0x02000000,1,0x800,ResetData);
				fclose(ResetData);
				for (int i = 0; i < 30; i++) swiWaitForVBlank();
			}

			if (pressed & KEY_A) {
				if (optionCount > 2) {
					switch (cursorPosition){
						case 0:
							newRegion++;
							if (newRegion == 4) newRegion = 0;
							break;
						case 1:
						default:
							splash = !splash;
							break;
						case 2:
							dsiSplash = !dsiSplash;
							break;
						case 3:
							titleAutoboot = !titleAutoboot;
							break;
					}
				} else {
					switch (cursorPosition){
						case 0:
						default:
							splash = !splash;
							break;
						case 1:
							dsiSplash = !dsiSplash;
							break;
						case 2:
							titleAutoboot = !titleAutoboot;
							break;
					}
				}
				menuprinted = true;
			}

			if (pressed & KEY_UP) {
				cursorPosition--;
				menuprinted = true;
			} else if (pressed & KEY_DOWN) {
				cursorPosition++;
				menuprinted = true;
			}

			if (cursorPosition < 0) cursorPosition = optionCount;
			if (cursorPosition > optionCount) cursorPosition = 0;

			if (pressed & KEY_START) {
				saveSettings();
				break;
			}
		}
	}

	if (newRegion != oldRegion) {
		FILE* f_hwinfoS = fopen("sd:/sys/HWINFO_S.dat", "rb+");
		if (f_hwinfoS) {
			u32 supportedLangBitmask = 0x01; // JPN: Japanese
			if (newRegion == 5) { // KOR
				supportedLangBitmask = 0x80; // Korean
			} else if (newRegion == 4) { // CHN
				supportedLangBitmask = 0x40; // Chinese
			} else if (newRegion == 3) { // AUS
				supportedLangBitmask = 0x02; // English
			} else if (newRegion == 2) { // EUR
				supportedLangBitmask = 0x3E; // English, French, German, Italian, Spanish
			} else if (newRegion == 1) { // USA
				supportedLangBitmask = 0x26; // English, French, Spanish
			}
			fseek(f_hwinfoS, 0x88, SEEK_SET);
			fwrite(&supportedLangBitmask, sizeof(u32), 1, f_hwinfoS);
			fseek(f_hwinfoS, 0x90, SEEK_SET);
			fwrite(&newRegion, 1, 1, f_hwinfoS);
			fclose(f_hwinfoS);
			if (regionChar == 'J') {
				// Reset system settings to work around touch inputs not working
				remove("sd:/shared1/TWLCFG0.dat");
				remove("sd:/shared1/TWLCFG1.dat");
			}
		}
	}

	// Create dummy file
	// Check the free space
	struct statvfs st;
	statvfs("sd:/", &st);
	u32 freeSpace = st.f_bsize * st.f_bfree;
	u64 realFreeSpace = st.f_bsize * st.f_bfree;

	// If the free space is bigger than 2GiB (using a u32 so always 0 - 4GiB)
	// or the free space is less than 20MiB (and the actual free space is over 4GiB)
	if(freeSpace > (2u << 30) || (freeSpace < (20u << 20) && realFreeSpace > (4u << 30))) {
		consoleDemoInit();
		size_t oldSize = 0;
		// Check old dummy file size to see if it can just be removed
		FILE *file = fopen("sd:/hiya/dummy.bin", "rb");
		if(file) {
			fseek(file, 0, SEEK_END);
			oldSize = ftell(file);
			fclose(file);
		}

		// Check that dummy file is still needed
		if((freeSpace + oldSize) > (2u << 30) || (freeSpace + oldSize) < (20u << 20)) {
			// Make sure hiya directory exists and make the file
			mkdir("sd:/hiya", 0777);
			iprintf("Making new dummy file...   ");

			// Make sure the file exists
			file = fopen("sd:/hiya/dummy.bin", "wb");
			if(file)
				fclose(file);

			// If free space is less than 20MiB, add free space + 2GiB + 10MiB
			// otherwise add free space - 2GiB + 10MiB
			truncate("sd:/hiya/dummy.bin", (freeSpace < (20u << 20) ? (freeSpace + (2 << 30)) : (freeSpace - (2 << 30))) + (10 << 20));
			iprintf("Done!\n");
		} else {
			iprintf("Removing old dummy file... ");
			remove("sd:/hiya/dummy.bin");
			iprintf("Done!\n");
		}
	}

	if (!gotoSettings && (*(u32*)0x02000300 == 0x434E4C54 || fifoGetValue32(FIFO_USER_02) == 0x01)) {
		// if "CNLT" is found in RAM, or if warmboot flag is set, then don't show splash
		splash = false;
	}

	if ((*(u32*)0x02000300 == 0x434E4C54) && (*(u32*)0x02000310 != 0x00000000)) {
		// if "CNLT" is found, and a title is set to launch, then don't autoboot title in "autoboot.bin"
		titleAutoboot = false;
	}

	if (titleAutoboot) {
		FILE* ResetData = fopen("sd:/hiya/autoboot.bin","rb");
		if (ResetData) {
			fread((void*)0x02000300,1,0x20,ResetData);
			dsiSplash = false;	// Disable DSi splash, so that DSi Menu doesn't appear
			fclose(ResetData);
		}
	}

	if (splash) {
		if (gif[true].load("sd:/hiya/splashtop.gif", true, true, false)) {
			splashFound[true] = true;
			splashBmp[true] = false;
		} else if (access("sd:/hiya/splashtop.bmp", F_OK) == 0) {
			splashFound[true] = true;
			splashBmp[true] = true;
		}

		if (gif[false].load("sd:/hiya/splashbottom.gif", false, true, false)) {
			splashFound[false] = true;
			splashBmp[false] = false;
		} else if (access("sd:/hiya/splashtop.bmp", F_OK) == 0) {
			splashFound[false] = true;
			splashBmp[false] = true;
		}

		loadScreen();

		if (rgb565BmpDisplayMode) {
			for (int i = 0; i < 60 * 3; i++)
				swiWaitForVBlank();
		} else {
			timerStart(0, ClockDivider_1024, TIMER_FREQ_1024(100), Gif::timerHandler);

			// If both GIFs will loop forever (or are not loaded)
			// then show for 3s
			if (gif[true].loopForever() && gif[false].loopForever()) {
				for (int i = 0; i < 60 * 3; i++)
					swiWaitForVBlank();
			} else {
				while (!(gif[true].finished() && gif[false].finished())) {
					swiWaitForVBlank();
					scanKeys();
					u16 down = keysDown();

					for (auto &g : gif) {
						if (g.waitingForInput() && down)
							g.resume();
					}
				}
			}
			timerStop(0);
		}
	}

	if (!dsiSplash) {
		fifoSendValue32(FIFO_USER_03, 1);
		// Tell Arm7 to check FIFO_USER_03 code
		fifoSendValue32(FIFO_USER_04, 1);
		// Small delay to ensure arm7 has time to write i2c stuff
		for (int i = 0; i < 1*3; i++) { swiWaitForVBlank(); }
	} else {
		fifoSendValue32(FIFO_USER_04, 1);
	}

	char tmdpath[256];
	snprintf (tmdpath, sizeof(tmdpath), "sd:/title/00030017/484e41%x/content/title.tmd", regionChar);

	FILE* f_tmd = fopen(tmdpath, "rb");
	if (f_tmd) {
		if ((getFileSize(tmdpath) > TMD_SIZE) && eraseUnlaunch) {
			// Read big .tmd file at the correct size
			f_tmd = fopen(tmdpath, "rb");
			fread(tmdBuffer, 1, TMD_SIZE, f_tmd);
			fclose(f_tmd);

			// Write correct sized .tmd file
			f_tmd = fopen(tmdpath, "wb");
			fwrite(tmdBuffer, 1, TMD_SIZE, f_tmd);
			fclose(f_tmd);
		}
		int err = runNdsFile("sd:/hiya/BOOTLOADER.NDS", 0, NULL);
		if ((splashFound[true] || splashFound[false]) && rgb565BmpDisplayMode) {
			while (dmaBusy(0) || dmaBusy(1));
			irqDisable(IRQ_HBLANK);
		}
		setupConsole();
		consoleInit(NULL, 0, BgType_Text4bpp, BgSize_T_256x256, 15, 0, true, true);
		consoleClear();
		iprintf ("Start failed. Error %i\n", err);
		if (err == 1) printf ("bootloader.nds not found!");
		consoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);
		consoleClear();
	} else {
		if ((splashFound[true] || splashFound[false]) && rgb565BmpDisplayMode) {
			while (dmaBusy(0) || dmaBusy(1));
			irqDisable(IRQ_HBLANK);
		}
		setupConsole();
		consoleInit(NULL, 0, BgType_Text4bpp, BgSize_T_256x256, 15, 0, true, true);
		consoleClear();
		iprintf("Error!\n");
		iprintf("\n");
		iprintf("Launcher's title.tmd was\n");
		iprintf("not found!");
		consoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);
		consoleClear();
	}

	while (1)
		swiWaitForVBlank();
}



================================================
FILE: arm9/source/nds_loader_arm9.c
================================================
/*-----------------------------------------------------------------
 Copyright (C) 2005 - 2010
	Michael "Chishm" Chisholm
	Dave "WinterMute" Murphy

 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 2
 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, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

------------------------------------------------------------------*/
#include <string.h>
#include <nds.h>
#include <sys/stat.h>
#include <limits.h>

#include <unistd.h>
#include <slim.h>

#include "load_bin.h"

#include "nds_loader_arm9.h"
#define LCDC_BANK_C (u16*)0x06840000
#define STORED_FILE_CLUSTER (*(((u32*)LCDC_BANK_C) + 1))
#define INIT_DISC (*(((u32*)LCDC_BANK_C) + 2))

#define STORED_FILE_CLUSTER_OFFSET 4 
#define INIT_DISC_OFFSET 8
#define ARG_START_OFFSET 16
#define ARG_SIZE_OFFSET 20
#define HAVE_DSISD_OFFSET 28
#define DSIMODE_OFFSET 32

typedef signed int addr_t;
typedef unsigned char data_t;

#define FIX_ALL	0x01
#define FIX_GLUE	0x02
#define FIX_GOT	0x04
#define FIX_BSS	0x08

static addr_t readAddr (data_t *mem, addr_t offset) {
	return ((addr_t*)mem)[offset/sizeof(addr_t)];
}

static void writeAddr (data_t *mem, addr_t offset, addr_t value) {
	((addr_t*)mem)[offset/sizeof(addr_t)] = value;
}

static void vramcpy (void* dst, const void* src, int len)
{
	u16* dst16 = (u16*)dst;
	u16* src16 = (u16*)src;
	
	for ( ; len > 0; len -= 2) {
		*dst16++ = *src16++;
	}
}	

int runNds (const void* loader, u32 loaderSize, u32 cluster, bool initDisc, int argc, const char** argv)
{
	char* argStart;
	u16* argData;
	u16 argTempVal = 0;
	int argSize;
	const char* argChar;

	irqDisable(IRQ_ALL);

	// Direct CPU access to VRAM bank C
	VRAM_C_CR = VRAM_ENABLE | VRAM_C_LCD;
	// Load the loader/patcher into the correct address
	vramcpy (LCDC_BANK_C, loader, loaderSize);

	// Set the parameters for the loader
	// STORED_FILE_CLUSTER = cluster;
	writeAddr ((data_t*) LCDC_BANK_C, STORED_FILE_CLUSTER_OFFSET, cluster);
	// INIT_DISC = initDisc;
	writeAddr ((data_t*) LCDC_BANK_C, INIT_DISC_OFFSET, initDisc);

	writeAddr ((data_t*) LCDC_BANK_C, DSIMODE_OFFSET, isDSiMode());
	if(argv[0][0]=='s' && argv[0][1]=='d') {
		writeAddr ((data_t*) LCDC_BANK_C, HAVE_DSISD_OFFSET, 1);
	}

	// Give arguments to loader
	argStart = (char*)LCDC_BANK_C + readAddr((data_t*)LCDC_BANK_C, ARG_START_OFFSET);
	argStart = (char*)(((int)argStart + 3) & ~3);	// Align to word
	argData = (u16*)argStart;
	argSize = 0;
	
	for (; argc > 0 && *argv; ++argv, --argc) 
	{
		for (argChar = *argv; *argChar != 0; ++argChar, ++argSize) 
		{
			if (argSize & 1) 
			{
				argTempVal |= (*argChar) << 8;
				*argData = argTempVal;
				++argData;
			} 
			else 
			{
				argTempVal = *argChar;
			}
		}
		if (argSize & 1)
		{
			*argData = argTempVal;
			++argData;
		}
		argTempVal = 0;
		++argSize;
	}
	*argData = argTempVal;
	
	writeAddr ((data_t*) LCDC_BANK_C, ARG_START_OFFSET, (addr_t)argStart - (addr_t)LCDC_BANK_C);
	writeAddr ((data_t*) LCDC_BANK_C, ARG_SIZE_OFFSET, argSize);

	irqDisable(IRQ_ALL);

	// Give the VRAM to the ARM7
	VRAM_C_CR = VRAM_ENABLE | VRAM_C_ARM7_0x06000000;
	// Reset into a passme loop
	REG_EXMEMCNT |= ARM7_OWNS_ROM | ARM7_OWNS_CARD;
	
	*((vu32*)0x02FFFFFC) = 0;
	*((vu32*)0x02FFFE04) = (u32)0xE59FF018;
	*((vu32*)0x02FFFE24) = (u32)0x02FFFE04;

	resetARM7(0x06000000);

	swiSoftReset(); 
	return true;
}

int runNdsFile (const char* filename, int argc, const char** argv)  {

	struct stat st;
	char filePath[PATH_MAX];
	int pathLen;
	const char* args[1];

	if (stat (filename, &st) < 0) {
		return 1;
	}

	if (argc <= 0 || !argv) {
		// Construct a command line if we weren't supplied with one
		if (!getcwd (filePath, PATH_MAX)) {
			return 2;
		}
		pathLen = strlen (filePath);
		strcpy (filePath + pathLen, filename);
		args[0] = filePath;
		argv = args;
	}

	return runNds (load_bin, load_bin_size, st.st_ino, true, argc, argv);
}



================================================
FILE: arm9/source/nds_loader_arm9.h
================================================
/*-----------------------------------------------------------------
 Copyright (C) 2005 - 2010
	Michael "Chishm" Chisholm
	Dave "WinterMute" Murphy

 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 2
 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, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

------------------------------------------------------------------*/

#ifndef NDS_LOADER_ARM9_H
#define NDS_LOADER_ARM9_H


#ifdef __cplusplus
extern "C" {
#endif

#define LOAD_DEFAULT_NDS 0

int runNds (const void* loader, u32 loaderSize, u32 cluster, bool initDisc, int argc, const char** argv);

int runNdsFile (const char* filename, int argc, const char** argv);

#ifdef __cplusplus
}
#endif

#endif // NDS_LOADER_ARM7_H


================================================
FILE: arm9/source/stringtool.cpp
================================================
/*---------------------------------------------------------------------------------


Copyright (C) 2007 Acekard, www.acekard.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


---------------------------------------------------------------------------------*/









#include "stringtool.h"
#include <cstdarg>
#include <cstdio>
#include <malloc.h>

std::string formatString( const char* fmt, ... )
{
    const char * f = fmt;
    va_list argList;
    va_start(argList, fmt);
    char * ptempStr = NULL;
    size_t max_len = vasiprintf( &ptempStr, f, argList);
    std::string str( ptempStr );
    str.resize( max_len );
    free( ptempStr );
    va_end(argList);
    return str;
}


================================================
FILE: arm9/source/stringtool.h
================================================
/*---------------------------------------------------------------------------------


Copyright (C) 2007 Acekard, www.acekard.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


---------------------------------------------------------------------------------*/









#ifndef _STRINGTOOL_H_
#define _STRINGTOOL_H_

#include <string>

std::string formatString( const char* fmt, ... );



#endif//_STRINGTOOL_H_


================================================
FILE: arm9/source/tonccpy.c
================================================
#include "tonccpy.h"
//# tonccpy.c

//! VRAM-safe cpy.
/*! This version mimics memcpy in functionality, with 
    the benefit of working for VRAM as well. It is also 
    slightly faster than the original memcpy, but faster 
    implementations can be made.
    \param dst  Destination pointer.
    \param src  Source pointer.
    \param size Fill-length in bytes.
    \note   The pointers and size need not be word-aligned.
*/
void tonccpy(void *dst, const void *src, uint size)
{
    if(size==0 || dst==NULL || src==NULL)
        return;

    uint count;
    u16 *dst16;     // hword destination
    u8  *src8;      // byte source

    // Ideal case: copy by 4x words. Leaves tail for later.
    if( ((u32)src|(u32)dst)%4==0 && size>=4)
    {
        u32 *src32= (u32*)src, *dst32= (u32*)dst;

        count= size/4;
        uint tmp= count&3;
        count /= 4;

        // Duff's Device, good friend!
        switch(tmp) {
            do {    *dst32++ = *src32++;
        case 3:     *dst32++ = *src32++;
        case 2:     *dst32++ = *src32++;
        case 1:     *dst32++ = *src32++;
        case 0:     ; } while(count--);
        }

        // Check for tail
        size &= 3;
        if(size == 0)
            return;

        src8= (u8*)src32;
        dst16= (u16*)dst32;
    }
    else        // Unaligned.
    {
        uint dstOfs= (u32)dst&1;
        src8= (u8*)src;
        dst16= (u16*)(dst-dstOfs);

        // Head: 1 byte.
        if(dstOfs != 0)
        {
            *dst16= (*dst16 & 0xFF) | *src8++<<8;
            dst16++;
            if(--size==0)
                return;
        }
    }

    // Unaligned main: copy by 2x byte.
    count= size/2;
    while(count--)
    {
        *dst16++ = src8[0] | src8[1]<<8;
        src8 += 2;
    }

    // Tail: 1 byte.
    if(size&1)
        *dst16= (*dst16 &~ 0xFF) | *src8;
}
//# toncset.c

//! VRAM-safe memset, internal routine.
/*! This version mimics memset in functionality, with 
    the benefit of working for VRAM as well. It is also 
    slightly faster than the original memset.
    \param dst  Destination pointer.
    \param fill Word to fill with.
    \param size Fill-length in bytes.
    \note   The \a dst pointer and \a size need not be 
        word-aligned. In the case of unaligned fills, \a fill 
        will be masked off to match the situation.
*/
void __toncset(void *dst, u32 fill, uint size)
{
    if(size==0 || dst==NULL)
        return;

    uint left= (u32)dst&3;
    u32 *dst32= (u32*)(dst-left);
    u32 count, mask;

    // Unaligned head.
    if(left != 0)
    {
        // Adjust for very small stint.
        if(left+size<4)
        {
            mask= BIT_MASK(size*8)<<(left*8);   
            *dst32= (*dst32 &~ mask) | (fill & mask);
            return;
        }

        mask= BIT_MASK(left*8);
        *dst32= (*dst32 & mask) | (fill&~mask);
        dst32++;
        size -= 4-left;
    }

    // Main stint.
    count= size/4;
    uint tmp= count&3;
    count /= 4;

    switch(tmp) {
        do {    *dst32++ = fill;
    case 3:     *dst32++ = fill;
    case 2:     *dst32++ = fill;
    case 1:     *dst32++ = fill;
    case 0:     ; } while(count--);
    }

    // Tail
    size &= 3;
    if(size)
    {
        mask= BIT_MASK(size*8);
        *dst32= (*dst32 &~ mask) | (fill & mask);
    }
}

================================================
FILE: arm9/source/tonccpy.h
================================================
//# Stuff you may not have yet.

#ifndef TONCCPY_H
#define TONCCPY_H


#ifdef __cplusplus
extern "C" {
#endif

#include <nds.h>

typedef unsigned int uint;
#define BIT_MASK(len)       ( (1<<(len))-1 )
static inline u32 quad8(u8 x)   {   x |= x<<8; return x | x<<16;    }


//# Declarations and inlines.

void tonccpy(void *dst, const void *src, uint size);

void __toncset(void *dst, u32 fill, uint size);
static inline void toncset(void *dst, u8 src, uint size);
static inline void toncset16(void *dst, u16 src, uint size);
static inline void toncset32(void *dst, u32 src, uint size);


//! VRAM-safe memset, byte version. Size in bytes.
static inline void toncset(void *dst, u8 src, uint size)
{   __toncset(dst, quad8(src), size);               }

//! VRAM-safe memset, halfword version. Size in hwords.
static inline void toncset16(void *dst, u16 src, uint size)
{   __toncset(dst, src|src<<16, size*2);            }

//! VRAM-safe memset, word version. Size in words.
static inline void toncset32(void *dst, u32 src, uint size)
{   __toncset(dst, src, size*4);                    }

#ifdef __cplusplus
}
#endif
#endif


================================================
FILE: bootloader/Makefile
================================================
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM)
endif

-include $(DEVKITARM)/ds_rules

#---------------------------------------------------------------------------------
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# INCLUDES is a list of directories containing extra header files
#---------------------------------------------------------------------------------
TARGET		:=	load
BUILD		:=	build
SOURCES		:=	source
INCLUDES	:=	build
SPECS		:=	specs

#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH	:=	-mthumb -mthumb-interwork

CFLAGS	:=	-g -Wall -Os\
			-mcpu=arm7tdmi -mtune=arm7tdmi -fomit-frame-pointer\
			-ffast-math \
			$(ARCH)

CFLAGS	+=	$(INCLUDE) $(EXTRA_CFLAGS) -DARM7

ASFLAGS	:=	-g $(ARCH) $(EXTRA_CFLAGS) $(INCLUDE)
LDFLAGS	=	-nostartfiles -T $(TOPDIR)/load.ld -g $(ARCH) -Wl,-Map,$(TARGET).map

LIBS	:=

#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS	:=	$(LIBNDS)


#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------

export TOPDIR	:=	$(CURDIR)
export LOADBIN	?=	$(CURDIR)/../data/$(TARGET).bin
export LOADELF	:=	$(CURDIR)/$(TARGET).elf
export DEPSDIR	:=	$(CURDIR)/$(BUILD)

export VPATH	:=	$(foreach dir,$(SOURCES),$(CURDIR)/$(dir))

export CC		:=	$(PREFIX)gcc
export CXX		:=	$(PREFIX)g++
export AR		:=	$(PREFIX)ar
export OBJCOPY	:=	$(PREFIX)objcopy

CFILES		:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES	:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES		:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))

export OFILES	:=	$(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)

export INCLUDE	:=	$(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
					$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
					-I$(CURDIR)/$(BUILD)

export LIBPATHS	:=	$(foreach dir,$(LIBDIRS),-L$(dir)/lib)

#---------------------------------------------------------------------------------
# use CC for linking standard C
#---------------------------------------------------------------------------------
export LD	:=	$(CC)
#---------------------------------------------------------------------------------

.PHONY: $(BUILD) clean

#---------------------------------------------------------------------------------
$(BUILD):
	@[ -d $@ ] || mkdir -p $@
	@$(MAKE) -C $(BUILD) -f $(CURDIR)/Makefile

#---------------------------------------------------------------------------------
clean:
	@echo clean ...
	@rm -fr $(BUILD) *.elf *.bin

#---------------------------------------------------------------------------------
else

DEPENDS	:=	$(OFILES:.o=.d)

#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
$(LOADBIN)	:	$(LOADELF)
	@mkdir -p ../../data
	@$(OBJCOPY) -O binary $< $@
	@echo built ... $(notdir $@)

$(LOADELF)	: $(OFILES)
	@echo linking $(notdir $@)
	@$(LD)  $(LDFLAGS) $(OFILES) $(LIBPATHS) $(LIBS) -o $@

arm9mpu_reset.o: mpu_reset.bin

mpu_reset.bin: mpu_reset.elf
	$(OBJCOPY) -O binary $< $@

mpu_reset.elf: $(TOPDIR)/arm9code/mpu_reset.s
	$(CC) $(ASFLAGS) -Ttext=0 -x assembler-with-cpp -nostartfiles -nostdlib $< -o $@

-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------


================================================
FILE: bootloader/arm9code/mpu_reset.s
================================================
/*
	Copyright 2006 - 2015 Dave Murphy (WinterMute)

	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 2 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/>.

*/

#include <nds/arm9/cache_asm.h>

	.text
	.align 4

	.arm

	.arch	armv5te
	.cpu	arm946e-s

@---------------------------------------------------------------------------------
	.global _start
	.type	_start STT_FUNC
@---------------------------------------------------------------------------------
_start:
@---------------------------------------------------------------------------------
	@ Switch off MPU
	mrc	p15, 0, r0, c1, c0, 0
	bic	r0, r0, #PROTECT_ENABLE
	mcr	p15, 0, r0, c1, c0, 0


	adr	r12, mpu_initial_data
	ldmia	r12, {r0-r10}

	mcr	p15, 0, r0, c2, c0, 0
	mcr	p15, 0, r0, c2, c0, 1
	mcr	p15, 0, r1, c3, c0, 0
	mcr	p15, 0, r2, c5, c0, 2
	mcr	p15, 0, r3, c5, c0, 3
	mcr	p15, 0, r4, c6, c0, 0
	mcr	p15, 0, r5, c6, c1, 0
	mcr	p15, 0, r6, c6, c3, 0
	mcr	p15, 0, r7, c6, c4, 0
	mcr	p15, 0, r8, c6, c6, 0
	mcr	p15, 0, r9, c6, c7, 0
	mcr	p15, 0, r10, c9, c1, 0

	mov	r0, #0
	mcr	p15, 0, r0, c6, c2, 0   @ PU Protection Unit Data/Unified Region 2
	mcr	p15, 0, r0, c6, c5, 0   @ PU Protection Unit Data/Unified Region 5

	mrc	p15, 0, r0, c9, c1, 0   @ DTCM
	mov	r0, r0, lsr #12         @ base
	mov	r0, r0, lsl #12         @ size
	add	r0, r0, #0x4000         @ dtcm top

	sub	r0, r0, #4              @ irq vector
	mov	r1, #0
	str 	r1, [r0]
	sub	r0, r0, #4              @ IRQ1 Check Bits
	str 	r1, [r0]

	sub	r0, r0, #128
	bic	r0, r0, #7

	msr	cpsr_c, #0xd3      @ svc mode
	mov	sp, r0
	sub	r0, r0, #128
	msr	cpsr_c, #0xd2      @ irq mode
	mov	sp, r0
	sub	r0, r0, #128
	msr	cpsr_c, #0xdf      @ system mode
	mov	sp, r0

	@ enable cache & tcm
	mrc	p15, 0, r0, c1, c0, 0
	ldr	r1,= ITCM_ENABLE | DTCM_ENABLE | ICACHE_ENABLE | DCACHE_ENABLE
	orr	r0,r0,r1
	mcr	p15, 0, r0, c1, c0, 0

	ldr	r10, =0x2FFFE04
	ldr	r0, =0xE59FF018
	str	r0, [r10]
	add	r1, r10, #0x20
	str	r10, [r1]
	bx	r10

	.pool

mpu_initial_data:
	.word 0x00000042  @ p15,0,c2,c0,0..1,r0 ;PU Cachability Bits for Data/Unified+Instruction Protection Region
	.word 0x00000002  @ p15,0,c3,c0,0,r1    ;PU Write-Bufferability Bits for Data Protection Regions
	.word 0x15111011  @ p15,0,c5,c0,2,r2    ;PU Extended Access Permission Data/Unified Protection Region
	.word 0x05100011  @ p15,0,c5,c0,3,r3    ;PU Extended Access Permission Instruction Protection Region
	.word 0x04000033  @ p15,0,c6,c0,0,r4    ;PU Protection Unit Data/Unified Region 0
	.word 0x0200002b  @ p15,0,c6,c1,0,r5    ;PU Protection Unit Data/Unified Region 1 4MB
	.word 0x08000035  @ p15,0,c6,c3,0,r6    ;PU Protection Unit Data/Unified Region 3
	.word 0x0300001b  @ p15,0,c6,c4,0,r7    ;PU Protection Unit Data/Unified Region 4
	.word 0xffff001d  @ p15,0,c6,c6,0,r8    ;PU Protection Unit Data/Unified Region 6
	.word 0x02fff017  @ p15,0,c6,c7,0,r9    ;PU Protection Unit Data/Unified Region 7 4KB
	.word 0x0300000a  @ p15,0,c9,c1,0,r10   ;TCM Data TCM Base and Virtual Size


================================================
FILE: bootloader/load.ld
================================================
OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")
OUTPUT_ARCH(arm)
ENTRY(_start)

MEMORY {

	vram	: ORIGIN = 0x06000000, LENGTH = 128K
}

__vram_start	=	ORIGIN(vram);
__vram_top	=	ORIGIN(vram)+ LENGTH(vram);
__sp_irq	=	__vram_top - 0x60;
__sp_svc	=	__sp_irq - 0x100;
__sp_usr	=	__sp_svc - 0x100;

__irq_flags	=	__vram_top - 8;
__irq_vector	=	__vram_top - 4;

SECTIONS
{
	.init	:
	{
		__text_start = . ;
		KEEP (*(.init))
		. = ALIGN(4);  /* REQUIRED. LD is flaky without it. */
	} >vram = 0xff
		
	.plt : 
	{ 
		*(.plt) 
	} >vram = 0xff

	.text :   /* ALIGN (4): */
	{

		*(.text*)
		*(.stub)
		/* .gnu.warning sections are handled specially by elf32.em.  */
		*(.gnu.warning)
		*(.gnu.linkonce.t*)
		*(.glue_7)
		*(.glue_7t)
		. = ALIGN(4);  /* REQUIRED. LD is flaky without it. */
	} >vram = 0xff

	.fini           :
	{
		KEEP (*(.fini))
	} >vram =0xff

	__text_end = . ;

	.rodata :
	{
		*(.rodata)
		*all.rodata*(*)
		*(.roda)
		*(.rodata.*)
		*(.gnu.linkonce.r*)
		SORT(CONSTRUCTORS)
		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */
	} >vram = 0xff

	.ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >vram
	__exidx_start = .;
	.ARM.exidx   : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } >vram
	__exidx_end = .;

/* Ensure the __preinit_array_start label is properly aligned.  We
   could instead move the label definition inside the section, but
   the linker would then create the section even if it turns out to
   be empty, which isn't pretty.  */
	. = ALIGN(32 / 8);
	PROVIDE (__preinit_array_start = .);
	.preinit_array     : { KEEP (*(.preinit_array)) } >vram = 0xff
	PROVIDE (__preinit_array_end = .);
	PROVIDE (__init_array_start = .);
	.init_array     : { KEEP (*(.init_array)) } >vram = 0xff
	PROVIDE (__init_array_end = .);
	PROVIDE (__fini_array_start = .);
	.fini_array     : { KEEP (*(.fini_array)) } >vram = 0xff
	PROVIDE (__fini_array_end = .);

	.ctors :
	{
	/* gcc uses crtbegin.o to find the start of the constructors, so
		we make sure it is first.  Because this is a wildcard, it
		doesn't matter if the user does not actually link against
		crtbegin.o; the linker won't look for a file to match a
		wildcard.  The wildcard also means that it doesn't matter which
		directory crtbegin.o is in.  */
		KEEP (*crtbegin.o(.ctors))
		KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors))
		KEEP (*(SORT(.ctors.*)))
		KEEP (*(.ctors))
		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */
	} >vram = 0xff

	.dtors :
	{
		KEEP (*crtbegin.o(.dtors))
		KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors))
		KEEP (*(SORT(.dtors.*)))
		KEEP (*(.dtors))
		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */
	} >vram = 0xff

	.eh_frame :
	{
		KEEP (*(.eh_frame))
		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */
	} >vram = 0xff

	.gcc_except_table :
	{
		*(.gcc_except_table)
		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */
	} >vram = 0xff
	.jcr            : { KEEP (*(.jcr)) } >vram = 0
	.got            : { *(.got.plt) *(.got) } >vram = 0

	
	.vram ALIGN(4) :
	{
		__vram_start = ABSOLUTE(.) ;
		*(.vram)
		*vram.*(.text)
		. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */
		__vram_end = ABSOLUTE(.) ;
	} >vram = 0xff


	.data ALIGN(4) : 	{
		__data_start = ABSOLUTE(.);
		*(.data)
		*(.data.*)
		*(.gnu.linkonce.d*)
		CONSTRUCTORS
		. = ALIGN(4);
		__data_end = ABSOLUTE(.) ;
	} >vram = 0xff



	.bss ALIGN(4) :
	{
		__bss_start = ABSOLUTE(.);
		__bss_start__ = ABSOLUTE(.);
		*(.dynbss)
		*(.gnu.linkonce.b*)
		*(.bss*)
		*(COMMON)
		. = ALIGN(4);    /* REQUIRED. LD is flaky without it. */
	} >vram

	__bss_end = . ;
	__bss_end__ = . ;

	_end = . ;
	__end__ = . ;
	PROVIDE (end = _end);

	/* Stabs debugging sections.  */
	.stab 0 : { *(.stab) }
	.stabstr 0 : { *(.stabstr) }
	.stab.excl 0 : { *(.stab.excl) }
	.stab.exclstr 0 : { *(.stab.exclstr) }
	.stab.index 0 : { *(.stab.index) }
	.stab.indexstr 0 : { *(.stab.indexstr) }
	.comment 0 : { *(.comment) }
	/*	DWARF debug sections.
		Symbols in the DWARF debugging sections are relative to the beginning
		of the section so we begin them at 0.  */
	/* DWARF 1 */
	.debug          0 : { *(.debug) }
	.line           0 : { *(.line) }
	/* GNU DWARF 1 extensions */
	.debug_srcinfo  0 : { *(.debug_srcinfo) }
	.debug_sfnames  0 : { *(.debug_sfnames) }
	/* DWARF 1.1 and DWARF 2 */
	.debug_aranges  0 : { *(.debug_aranges) }
	.debug_pubnames 0 : { *(.debug_pubnames) }
	/* DWARF 2 */
	.debug_info     0 : { *(.debug_info) }
	.debug_abbrev   0 : { *(.debug_abbrev) }
	.debug_line     0 : { *(.debug_line) }
	.debug_frame    0 : { *(.debug_frame) }
	.debug_str      0 : { *(.debug_str) }
	.debug_loc      0 : { *(.debug_loc) }
	.debug_macinfo  0 : { *(.debug_macinfo) }
	/* SGI/MIPS DWARF 2 extensions */
	.debug_weaknames 0 : { *(.debug_weaknames) }
	.debug_funcnames 0 : { *(.debug_funcnames) }
	.debug_typenames 0 : { *(.debug_typenames) }
	.debug_varnames  0 : { *(.debug_varnames) }
	.stack 0x80000 : { _stack = .; *(.stack) }
	/* These must appear regardless of  .  */
}


================================================
FILE: bootloader/source/arm7clear.s
================================================
/*-----------------------------------------------------------------

 Copyright (C) 2005  Michael "Chishm" Chisholm

 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 2
 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, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

 If you use this code, please give due credit and email me about your
 project at chishm@hotmail.com
------------------------------------------------------------------*/

	.arm
	.global arm7clearRAM
	.type	arm7clearRAM STT_FUNC
arm7clearRAM:

	push	{r0-r9}
	// clear exclusive IWRAM
	// 0380:0000 to 0380:FFFF, total 64KiB
	mov	r0, #0
	mov	r1, #0
	mov	r2, #0
	mov	r3, #0
	mov	r4, #0
	mov	r5, #0
	mov	r6, #0
	mov	r7, #0
	mov	r8, #0x03800000
	sub	r8, #0x00008000
	mov	r9, #0x03800000
	orr	r9, r9, #0x10000
clear_IWRAM_loop:
	stmia	r8!, {r0, r1, r2, r3, r4, r5, r6, r7}
	cmp	r8, r9
	blt	clear_IWRAM_loop

	// clear most of EWRAM - except after RAM end - 0xc000, which has the bootstub
	mov	r8, #0x02000000
	add	r8, #0x00000800
	
	ldr	r9,=0x4004008
	ldr	r9,[r9]
	ands	r9,r9,#0x8000
	bne	dsi_mode

	mov	r9, #0x02400000
	b	ds_mode
dsi_mode:
	mov	r9, #0x03000000	
ds_mode:
	sub	r9, #0x0000c000
clear_EWRAM_loop:
	stmia	r8!, {r0, r1, r2, r3, r4, r5, r6, r7}
	cmp	r8, r9
	blt	clear_EWRAM_loop

	pop	{r0-r9}
	
	bx	lr
  


================================================
FILE: bootloader/source/arm9clear.arm.c
================================================
#define ARM9
#undef ARM7

#include <nds/ndstypes.h>
#include <nds/dma.h>
#include <nds/system.h>
#include <nds/interrupts.h>
#include <nds/timers.h>

#include <nds/memory.h>
#include <nds/arm9/video.h>
#include <nds/arm9/input.h>

#include "boot.h"

/*-------------------------------------------------------------------------
resetMemory2_ARM9
Clears the ARM9's DMA channels and resets video memory
Written by Darkain.
Modified by Chishm:
 * Changed MultiNDS specific stuff
--------------------------------------------------------------------------*/
void __attribute__ ((long_call)) __attribute__((naked)) __attribute__((noreturn)) resetMemory2_ARM9 (void) 
{
 	register int i;
	// int reg;
  
	//clear out ARM9 DMA channels
	for (i=0; i<4; i++) {
		DMA_CR(i) = 0;
		DMA_SRC(i) = 0;
		DMA_DEST(i) = 0;
		TIMER_CR(i) = 0;
		TIMER_DATA(i) = 0;
		// for(reg=0; reg<0x1c; reg+=4)*((u32*)(0x04004104 + ((i*0x1c)+reg))) = 0;//Reset NDMA.
	}

	VRAM_CR = (VRAM_CR & 0xffff0000) | 0x00008080 ;
	
	vu16 *mainregs = (vu16*)0x04000000;
	vu16 *subregs = (vu16*)0x04001000;
	
	for (i=0; i<43; i++) {
		mainregs[i] = 0;
		subregs[i] = 0;
	}
	
	REG_DISPSTAT = 0;

	VRAM_A_CR = 0;
	VRAM_B_CR = 0;
	VRAM_D_CR = 0;
	VRAM_E_CR = 0;
	VRAM_F_CR = 0;
	VRAM_G_CR = 0;
	VRAM_H_CR = 0;
	VRAM_I_CR = 0;
	REG_POWERCNT  = 0x820F;
	//set shared ram to ARM7
	WRAM_CR = 0x03;
	// REG_EXMEMCNT = 0xE880;

	// Return to passme loop
	*((vu32*)0x02FFFE04) = (u32)0xE59FF018;		// ldr pc, 0x02FFFE24
	*((vu32*)0x02FFFE24) = (u32)0x02FFFE04;		// Set ARM9 Loop address

	asm volatile(
		"\tbx %0\n"
		: : "r" (0x02FFFE04)
	);
	while(1);
}

/*
void __attribute__ ((long_call)) __attribute__((naked)) __attribute__((noreturn)) initMBK_ARM9 (void) 
{

	*((vu32*)REG_MBK1)=0x8C888480;
	*((vu32*)REG_MBK2)=0x8D898581;
	*((vu32*)REG_MBK3)=0x9C999591;
	*((vu32*)REG_MBK4)=0x8D898581;
	*((vu32*)REG_MBK5)=0x9D999591;

	REG_MBK6=0x080037C0;
	REG_MBK7=0x07C03000;
	REG_MBK8=0x00003000;
	REG_MBK9=0xFF000000;

	// Return to passme loop
	*((vu32*)0x02FFFE04) = (u32)0xE59FF018;		// ldr pc, 0x02FFFE24
	*((vu32*)0x02FFFE24) = (u32)0x02FFFE04;		// Set ARM9 Loop address

	asm volatile(
		"\tbx %0\n"
		: : "r" (0x02FFFE04)
	);
	while(1);
}
*/

/*-------------------------------------------------------------------------
startBinary_ARM9
Jumps to the ARM9 NDS binary in sync with the display and ARM7
Written by Darkain.
Modified by Chishm:
 * Removed MultiNDS specific stuff
--------------------------------------------------------------------------*/
void __attribute__ ((long_call)) __attribute__((noreturn)) __attribute__((naked)) startBinary_ARM9 (void)
{
	// REG_SCFG_CLK = 0x87;
	// REG_SCFG_RST = 0x0001;
	// REG_SCFG_MC = 0x0018;

	REG_IME=0;
	REG_EXMEMCNT = 0xE880;
	// set ARM9 load address to 0 and wait for it to change again
	ARM9_START_FLAG = 0;
	while(REG_VCOUNT!=191);
	while(REG_VCOUNT==191);
	while ( ARM9_START_FLAG != 1 );
	VoidFn arm9code = *(VoidFn*)(0x2FFFE24);
	arm9code();
	while(1);
}



================================================
FILE: bootloader/source/arm9mpu_reset.s
================================================
	.arm
	.global mpu_reset, mpu_reset_end

mpu_reset:
	.incbin "mpu_reset.bin"
mpu_reset_end:


================================================
FILE: bootloader/source/bios.s
================================================
	.text
	.align 4

	.thumb

@---------------------------------------------------------------------------------
	.global swiDelay
	.thumb_func
@---------------------------------------------------------------------------------
swiDelay:
@---------------------------------------------------------------------------------
	swi	0x03
	bx	lr


================================================
FILE: bootloader/source/boot.c
================================================
/*-----------------------------------------------------------------
 boot.c
 
 BootLoader
 Loads a file into memory and runs it

 All resetMemory and startBinary functions are based 
 on the MultiNDS loader by Darkain.
 Original source available at:
 http://cvs.sourceforge.net/viewcvs.py/ndslib/ndslib/examples/loader/boot/main.cpp

License:
 Copyright (C) 2005  Michael "Chishm" Chisholm

 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 2
 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, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

 If you use this code, please give due credit and email me about your
 project at chishm@hotmail.com
 
Helpful information:
 This code runs from VRAM bank C on ARM7
------------------------------------------------------------------*/

#include <nds/ndstypes.h>
#include <nds/dma.h>
#include <nds/system.h>
#include <nds/interrupts.h>
#include <nds/timers.h>
#define ARM9
#undef ARM7
#include <nds/memory.h>
#include <nds/arm9/video.h>
#include <nds/arm9/input.h>
#undef ARM9
#define ARM7
#include <nds/arm7/audio.h>
#include <string.h>

#include "sdmmc.h"
#include "fat.h"
#include "card.h"
#include "boot.h"

void mpu_reset();
void mpu_reset_end();
void arm7clearRAM();

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Important things
#define TEMP_MEM 0x02FFD000
#define NDS_HEAD 0x02FFFE00
#define TEMP_ARM9_START_ADDRESS (*(vu32*)0x02FFFFF4)

const char* bootName = "BOOTLOADER.NDS";

extern unsigned long _start;
extern unsigned long storedFileCluster;
extern unsigned long initDisc;
extern unsigned long wantToPatchDLDI;
extern unsigned long argStart;
extern unsigned long argSize;
extern unsigned long dsiSD;
extern unsigned long dsiMode;

/*-------------------------------------------------------------------------
resetMemory_ARM7
Clears all of the NDS's RAM that is visible to the ARM7
Written by Darkain.
Modified by Chishm:
 * Added STMIA clear mem loop
--------------------------------------------------------------------------*/
void resetMemory_ARM7 (void)
{
	int i;
	
	REG_IME = 0;

	for (i=0; i<16; i++) {
		SCHANNEL_CR(i) = 0;
		SCHANNEL_TIMER(i) = 0;
		SCHANNEL_SOURCE(i) = 0;
		SCHANNEL_LENGTH(i) = 0;
	}

	REG_SOUNDCNT = 0;

	//clear out ARM7 DMA channels and timers
	for (i=0; i<4; i++) {
		DMA_CR(i) = 0;
		DMA_SRC(i) = 0;
		DMA_DEST(i) = 0;
		TIMER_CR(i) = 0;
		TIMER_DATA(i) = 0;
	}
	
	arm7clearRAM();

	REG_IE = 0;
	REG_IF = ~0;
	(*(vu32*)(0x04000000-4)) = 0;  //IRQ_HANDLER ARM7 version
	(*(vu32*)(0x04000000-8)) = ~0; //VBLANK_INTR_WAIT_FLAGS, ARM7 version
	REG_POWERCNT = 1;  //turn off power to stuff

}


void loadBinary_ARM7 (u32 fileCluster)
{
	u32 ndsHeader[0x170>>2];

	// read NDS header
	fileRead ((char*)ndsHeader, fileCluster, 0, 0x170);
	// read ARM9 info from NDS header
	u32 ARM9_SRC = ndsHeader[0x020>>2];
	char* ARM9_DST = (char*)ndsHeader[0x028>>2];
	u32 ARM9_LEN = ndsHeader[0x02C>>2];
	// read ARM7 info from NDS header
	u32 ARM7_SRC = ndsHeader[0x030>>2];
	char* ARM7_DST = (char*)ndsHeader[0x038>>2];
	u32 ARM7_LEN = ndsHeader[0x03C>>2];
	
	// Load binaries into memory
	fileRead(ARM9_DST, fileCluster, ARM9_SRC, ARM9_LEN);
	fileRead(ARM7_DST, fileCluster, ARM7_SRC, ARM7_LEN);

	// first copy the header to its proper location, excluding
	// the ARM9 start address, so as not to start it
	TEMP_ARM9_START_ADDRESS = ndsHeader[0x024>>2];		// Store for later
	ndsHeader[0x024>>2] = 0;
	dmaCopyWords(3, (void*)ndsHeader, (void*)NDS_HEAD, 0x170);

}

/*-------------------------------------------------------------------------
startBinary_ARM7
Jumps to the ARM7 NDS binary in sync with the display and ARM9
Written by Darkain.
Modified by Chishm:
 * Removed MultiNDS specific stuff
--------------------------------------------------------------------------*/
void startBinary_ARM7 (void) {	

	REG_IME=0;
	while(REG_VCOUNT!=191);
	while(REG_VCOUNT==191);
	// copy NDS ARM9 start address into the header, starting ARM9
	*((vu32*)0x02FFFE24) = TEMP_ARM9_START_ADDRESS;
	ARM9_START_FLAG = 1;

	// Start ARM7
	VoidFn arm7code = *(VoidFn*)(0x2FFFE34);
	arm7code();
}
#ifndef NO_SDMMC
int sdmmc_sd_readsectors(u32 sector_no, u32 numsectors, void *out);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Main function
bool sdmmc_inserted() {
	return true;
}

bool sdmmc_startup() {
	sdmmc_controller_init();
	return sdmmc_sdcard_init() == 0;
}

bool sdmmc_readsectors(u32 sector_no, u32 numsectors, void *out) {
	return sdmmc_sdcard_readsectors(sector_no, numsectors, out) == 0;
}
#endif

int main (void) {
#ifndef NO_SDMMC
	if (dsiSD) {
		_io_dldi.fn_readSectors = sdmmc_readsectors;
		_io_dldi.fn_isInserted = sdmmc_inserted;
		_io_dldi.fn_startup = sdmmc_startup;
	}
#endif
	u32 fileCluster = storedFileCluster;
	// Init card
	if(!FAT_InitFiles(initDisc))
	{
		return -1;
	}
	if (fileCluster == CLUSTER_FREE)
	{
		return -1;
	}
	
	// ARM9 clears its memory part 2
	// copy ARM9 function to RAM, and make the ARM9 jump to it
	memcpy((u32*)TEMP_MEM, (u32*)resetMemory2_ARM9, resetMemory2_ARM9_size);
	(*(vu32*)0x02FFFE24) = (u32)TEMP_MEM;	// Make ARM9 jump to the function
	// Wait until the ARM9 has completed its task
	while ((*(vu32*)0x02FFFE24) == (u32)TEMP_MEM);

	// ARM9 sets up mpu
	// copy ARM9 function to RAM, and make the ARM9 jump to it
	memcpy((u32*)TEMP_MEM, (u32*)mpu_reset, mpu_reset_end - mpu_reset);
	(*(vu32*)0x02FFFE24) = (u32)TEMP_MEM;	// Make ARM9 jump to the function
	// Wait until the ARM9 has completed its task
	while ((*(vu32*)0x02FFFE24) == (u32)TEMP_MEM);

	// ARM9 enters a wait loop
	// copy ARM9 function to RAM, and make the ARM9 jump to it
	memcpy((u32*)TEMP_MEM, (u32*)startBinary_ARM9, startBinary_ARM9_size);
	(*(vu32*)0x02FFFE24) = (u32)TEMP_MEM;	// Make ARM9 jump to the function

	// Load the NDS file
	loadBinary_ARM7(fileCluster);

	// Reset SDMC. Required to get bootloader to init things correctly.
	sdmmc_controller_init();
	*(vu16*)(SDMMC_BASE + REG_SDDATACTL32) &= 0xFFFDu;
	*(vu16*)(SDMMC_BASE + REG_SDDATACTL) &= 0xFFDDu;
	*(vu16*)(SDMMC_BASE + REG_SDBLKLEN32) = 0;

	startBinary_ARM7();

	return 0;
}



================================================
FILE: bootloader/source/boot.h
================================================
#ifndef _BOOT_H_
#define _BOOT_H_

#define initMBK_ARM9_size 0x400
void __attribute__ ((long_call)) __attribute__((noreturn)) __attribute__((naked)) initMBK_ARM9 ();
#define resetMemory2_ARM9_size 0x400
void __attribute__ ((long_call)) __attribute__((naked)) __attribute__((noreturn)) resetMemory2_ARM9();
#define startBinary_ARM9_size 0x100
void __attribute__ ((long_call)) __attribute__((noreturn)) __attribute__((naked)) startBinary_ARM9 ();
#define ARM9_START_FLAG (*(vu8*)0x02FFFDFB)

#endif // _BOOT_H_


================================================
FILE: bootloader/source/card.h
================================================
/*-----------------------------------------------------------------

 Copyright (C) 2005  Michael "Chishm" Chisholm

 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 2
 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, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

 If you use this code, please give due credit and email me about your
 project at chishm@hotmail.com
------------------------------------------------------------------*/

#ifndef CARD_H
#define CARD_H

#include "disc_io.h"
#include "io_dldi.h"

static inline bool CARD_StartUp (void) {
	return _io_dldi.fn_startup();
}

static inline bool CARD_IsInserted (void) {
	return _io_dldi.fn_isInserted();
}

static inline bool CARD_ReadSector (u32 sector, void *buffer) {
	return _io_dldi.fn_readSectors(sector, 1, buffer);
}

static inline bool CARD_ReadSectors (u32 sector, int count, void *buffer) {
	return _io_dldi.fn_readSectors(sector, count, buffer);
}

#endif // CARD_H


================================================
FILE: bootloader/source/disc_io.h
================================================
/*
 disc_io.h
 Interface template for low level disc functions.

 Copyright (c) 2006 Michael "Chishm" Chisholm
	
 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. The name of the author may not be used to endorse or promote products derived
     from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.

	2006-07-11 - Chishm
		* Original release
		
	2006-07-16 - Chishm
		* Renamed _CF_USE_DMA to _IO_USE_DMA
		* Renamed _CF_ALLOW_UNALIGNED to _IO_ALLOW_UNALIGNED
*/

#ifndef _DISC_IO_H
#define _DISC_IO_H

#include <nds/ndstypes.h>
#define BYTES_PER_SECTOR 512

//----------------------------------------------------------------------
// Customisable features

// Use DMA to read the card, remove this line to use normal reads/writes
// #define _IO_USE_DMA

// Allow buffers not alligned to 16 bits when reading files. 
// Note that this will slow down access speed, so only use if you have to.
// It is also incompatible with DMA
#define _IO_ALLOW_UNALIGNED

#if defined _IO_USE_DMA && defined _IO_ALLOW_UNALIGNED
 #error "You can't use both DMA and unaligned memory"
#endif

#define FEATURE_MEDIUM_CANREAD		0x00000001
#define FEATURE_MEDIUM_CANWRITE		0x00000002
#define FEATURE_SLOT_GBA			0x00000010
#define FEATURE_SLOT_NDS			0x00000020

typedef bool (* FN_MEDIUM_STARTUP)(void) ;
typedef bool (* FN_MEDIUM_ISINSERTED)(void) ;
typedef bool (* FN_MEDIUM_READSECTORS)(u32 sector, u32 numSectors, void* buffer) ;
typedef bool (* FN_MEDIUM_WRITESECTORS)(u32 sector, u32 numSectors, const void* buffer) ;
typedef bool (* FN_MEDIUM_CLEARSTATUS)(void) ;
typedef bool (* FN_MEDIUM_SHUTDOWN)(void) ;

struct IO_INTERFACE_STRUCT {
	unsigned long			ioType ;
	unsigned long			features ;
	FN_MEDIUM_STARTUP		fn_startup ;
	FN_MEDIUM_ISINSERTED	fn_isInserted ;
	FN_MEDIUM_READSECTORS	fn_readSectors ;
	FN_MEDIUM_WRITESECTORS	fn_writeSectors ;
	FN_MEDIUM_CLEARSTATUS	fn_clearStatus ;
	FN_MEDIUM_SHUTDOWN		fn_shutdown ;
} ;

typedef struct IO_INTERFACE_STRUCT IO_INTERFACE ;

#endif	// define _DISC_IO_H


================================================
FILE: bootloader/source/fat.c
================================================
/*-----------------------------------------------------------------
 fat.c
 
 NDS MP
 GBAMP NDS Firmware Hack Version 2.12
 An NDS aware firmware patch for the GBA Movie Player.
 By Michael Chisholm (Chishm)
 
 Filesystem code based on GBAMP_CF.c by Chishm (me).
 
License:
 Copyright (C) 2005  Michael "Chishm" Chisholm

 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 2
 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, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

 If you use this code, please give due credit and email me about your
 project at chishm@hotmail.com
------------------------------------------------------------------*/

#include "fat.h"
#include "card.h"


//---------------------------------------------------------------
// FAT constants

#define FILE_LAST 0x00
#define FILE_FREE 0xE5

#define ATTRIB_ARCH	0x20
#define ATTRIB_DIR	0x10
#define ATTRIB_LFN	0x0F
#define ATTRIB_VOL	0x08
#define ATTRIB_HID	0x02
#define ATTRIB_SYS	0x04
#define ATTRIB_RO	0x01

#define FAT16_ROOT_DIR_CLUSTER 0x00

// File Constants
#ifndef EOF
#define EOF -1
#define SEEK_SET	0
#define SEEK_CUR	1
#define SEEK_END	2
#endif


//-----------------------------------------------------------------
// FAT constants
#define CLUSTER_EOF_16	0xFFFF

#define ATTRIB_ARCH	0x20
#define ATTRIB_DIR	0x10
#define ATTRIB_LFN	0x0F
#define ATTRIB_VOL	0x08
#define ATTRIB_HID	0x02
#define ATTRIB_SYS	0x04
#define ATTRIB_RO	0x01

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Data Structures

#define __PACKED __attribute__ ((__packed__))

// Boot Sector - must be packed
typedef struct
{
	u8	jmpBoot[3];
	u8	OEMName[8];
	// BIOS Parameter Block
	u16	bytesPerSector;
	u8	sectorsPerCluster;
	u16	reservedSectors;
	u8	numFATs;
	u16	rootEntries;
	u16	numSectorsSmall;
	u8	mediaDesc;
	u16	sectorsPerFAT;
	u16	sectorsPerTrk;
	u16	numHeads;
	u32	numHiddenSectors;
	u32	numSectors;
	union	// Different types of extended BIOS Parameter Block for FAT16 and FAT32
	{
		struct  
		{
			// Ext BIOS Parameter Block for FAT16
			u8	driveNumber;
			u8	reserved1;
			u8	extBootSig;
			u32	volumeID;
			u8	volumeLabel[11];
			u8	fileSysType[8];
			// Bootcode
			u8	bootCode[448];
		} __PACKED fat16;
		struct  
		{
			// FAT32 extended block
			u32	sectorsPerFAT32;
			u16	extFlags;
			u16	fsVer;
			u32	rootClus;
			u16	fsInfo;
			u16	bkBootSec;
			u8	reserved[12];
			// Ext BIOS Parameter Block for FAT16
			u8	driveNumber;
			u8	reserved1;
			u8	extBootSig;
			u32	volumeID;
			u8	volumeLabel[11];
			u8	fileSysType[8];
			// Bootcode
			u8	bootCode[420];
		} __PACKED fat32;
	}	extBlock;

	__PACKED	u16	bootSig;

}	__PACKED BOOT_SEC;

// Directory entry - must be packed
typedef struct
{
	u8	name[8];
	u8	ext[3];
	u8	attrib;
	u8	reserved;
	u8	cTime_ms;
	u16	cTime;
	u16	cDate;
	u16	aDate;
	u16	startClusterHigh;
	u16	mTime;
	u16	mDate;
	u16	startCluster;
	u32	fileSize;
}	__PACKED DIR_ENT;

// File information - no need to pack
typedef struct
{
	u32 firstCluster;
	u32 length;
	u32 curPos;
	u32 curClus;			// Current cluster to read from
	int curSect;			// Current sector within cluster
	int curByte;			// Current byte within sector
	char readBuffer[512];	// Buffer used for unaligned reads
	u32 appClus;			// Cluster to append to
	int appSect;			// Sector within cluster for appending
	int appByte;			// Byte within sector for appending
	bool read;	// Can read from file
	bool write;	// Can write to file
	bool append;// Can append to file
	bool inUse;	// This file is open
	u32 dirEntSector;	// The sector where the directory entry is stored
	int dirEntOffset;	// The offset within the directory sector
}	FAT_FILE;


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Global Variables

// _VARS_IN_RAM variables are stored in the largest section of WRAM 
// available: IWRAM on NDS ARM7, EWRAM on NDS ARM9 and GBA

// Locations on card
int discRootDir;
int discRootDirClus;
int discFAT;
int discSecPerFAT;
int discNumSec;
int discData;
int discBytePerSec;
int discSecPerClus;
int discBytePerClus;

enum {FS_UNKNOWN, FS_FAT12, FS_FAT16, FS_FAT32} discFileSystem;

// Global sector buffer to save on stack space
unsigned char globalBuffer[BYTES_PER_SECTOR];


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//FAT routines

u32 FAT_ClustToSect (u32 cluster) {
	return (((cluster-2) * discSecPerClus) + discData);
}

/*-----------------------------------------------------------------
FAT_NextCluster
Internal function - gets the cluster linked from input cluster
-----------------------------------------------------------------*/
u32 FAT_NextCluster(u32 cluster)
{
	u32 nextCluster = CLUSTER_FREE;
	u32 sector;
	int offset;
	
	
	switch (discFileSystem) 
	{
		case FS_UNKNOWN:
			nextCluster = CLUSTER_FREE;
			break;
			
		case FS_FAT12:
			sector = discFAT + (((cluster * 3) / 2) / BYTES_PER_SECTOR);
			offset = ((cluster * 3) / 2) % BYTES_PER_SECTOR;
			CARD_ReadSector(sector, globalBuffer);
			nextCluster = ((u8*) globalBuffer)[offset];
			offset++;
			
			if (offset >= BYTES_PER_SECTOR) {
				offset = 0;
				sector++;
			}
			
			CARD_ReadSector(sector, globalBuffer);
			nextCluster |= (((u8*) globalBuffer)[offset]) << 8;
			
			if (cluster & 0x01) {
				nextCluster = nextCluster >> 4;
			} else 	{
				nextCluster &= 0x0FFF;
			}
			
			break;
			
		case FS_FAT16:
			sector = discFAT + ((cluster << 1) / BYTES_PER_SECTOR);
			offset = cluster % (BYTES_PER_SECTOR >> 1);
			
			CARD_ReadSector(sector, globalBuffer);
			// read the nextCluster value
			nextCluster = ((u16*)globalBuffer)[offset];
			
			if (nextCluster >= 0xFFF7)
			{
				nextCluster = CLUSTER_EOF;
			}
			break;
			
		case FS_FAT32:
			sector = discFAT + ((cluster << 2) / BYTES_PER_SECTOR);
			offset = cluster % (BYTES_PER_SECTOR >> 2);
			
			CARD_ReadSector(sector, globalBuffer);
			// read the nextCluster value
			nextCluster = (((u32*)globalBuffer)[offset]) & 0x0FFFFFFF;
			
			if (nextCluster >= 0x0FFFFFF7)
			{
				nextCluster = CLUSTER_EOF;
			}
			break;
			
		default:
			nextCluster = CLUSTER_FREE;
			break;
	}
	
	return nextCluster;
}

/*-----------------------------------------------------------------
ucase
Returns the uppercase version of the given char
char IN: a character
char return OUT: uppercase version of character
-----------------------------------------------------------------*/
char ucase (char character)
{
	if ((character > 0x60) && (character < 0x7B))
		character = character - 0x20;
	return (character);
}

/*-----------------------------------------------------------------
FAT_InitFiles
Reads the FAT information from the CF card.
You need to call this before reading any files.
bool return OUT: true if successful.
-----------------------------------------------------------------*/
bool FAT_InitFiles (bool initCard)
{
	int i;
	int bootSector;
	BOOT_SEC* bootSec;
	
	if (initCard && !CARD_StartUp())
	{
		return (false);
	}
	
	// Read first sector of card
	if (!CARD_ReadSector (0, globalBuffer)) 
	{
		return false;
	}
	// Check if there is a FAT string, which indicates this is a boot sector
	if ((globalBuffer[0x36] == 'F') && (globalBuffer[0x37] == 'A') && (globalBuffer[0x38] == 'T'))
	{
		bootSector = 0;
	}
	// Check for FAT32
	else if ((globalBuffer[0x52] == 'F') && (globalBuffer[0x53] == 'A') && (globalBuffer[0x54] == 'T'))
	{
		bootSector = 0;
	}
	else	// This is an MBR
	{
		// Find first valid partition from MBR
		// First check for an active partition
		for (i=0x1BE; (i < 0x1FE) && (globalBuffer[i] != 0x80); i+= 0x10);
		// If it didn't find an active partition, search for any valid partition
		if (i == 0x1FE) 
			for (i=0x1BE; (i < 0x1FE) && (globalBuffer[i+0x04] == 0x00); i+= 0x10);
		
		// Go to first valid partition
		if ( i != 0x1FE)	// Make sure it found a partition
		{
			bootSector = globalBuffer[0x8 + i] + (globalBuffer[0x9 + i] << 8) + (globalBuffer[0xA + i] << 16) + ((globalBuffer[0xB + i] << 24) & 0x0F);
		} else {
			bootSector = 0;	// No partition found, assume this is a MBR free disk
		}
	}

	// Read in boot sector
	bootSec = (BOOT_SEC*) globalBuffer;
	CARD_ReadSector (bootSector,  bootSec);

	// Store required information about the file system
	if (bootSec->sectorsPerFAT != 0)
	{
		discSecPerFAT = bootSec->sectorsPerFAT;
	}
	else
	{
		discSecPerFAT = bootSec->extBlock.fat32.sectorsPerFAT32;
	}
	
	if (bootSec->numSectorsSmall != 0)
	{
		discNumSec = bootSec->numSectorsSmall;
	}
	else
	{
		discNumSec = bootSec->numSectors;
	}

	discBytePerSec = BYTES_PER_SECTOR;	// Sector size is redefined to be 512 bytes
	discSecPerClus = bootSec->sectorsPerCluster * bootSec->bytesPerSector / BYTES_PER_SECTOR;
	discBytePerClus = discBytePerSec * discSecPerClus;
	discFAT = bootSector + bootSec->reservedSectors;

	discRootDir = discFAT + (bootSec->numFATs * discSecPerFAT);
	discData = discRootDir + ((bootSec->rootEntries * sizeof(DIR_ENT)) / BYTES_PER_SECTOR);

	if ((discNumSec - discData) / bootSec->sectorsPerCluster < 4085)
	{
		discFileSystem = FS_FAT12;
	}
	else if ((discNumSec - discData) / bootSec->sectorsPerCluster < 65525)
	{
		discFileSystem = FS_FAT16;
	}
	else
	{
		discFileSystem = FS_FAT32;
	}

	if (discFileSystem != FS_FAT32)
	{
		discRootDirClus = FAT16_ROOT_DIR_CLUSTER;
	}
	else	// Set up for the FAT32 way
	{
		discRootDirClus = bootSec->extBlock.fat32.rootClus;
		// Check if FAT mirroring is enabled
		if (!(bootSec->extBlock.fat32.extFlags & 0x80))
		{
			// Use the active FAT
			discFAT = discFAT + ( discSecPerFAT * (bootSec->extBlock.fat32.extFlags & 0x0F));
		}
	}

	return (true);
}


/*-----------------------------------------------------------------
fileRead(buffer, cluster, startOffset, length)
-----------------------------------------------------------------*/
u32 fileRead (char* buffer, u32 cluster, u32 startOffset, u32 length)
{
	int curByte;
	int curSect;
	
	int dataPos = 0;
	int chunks;
	int beginBytes;

	if (cluster == CLUSTER_FREE || cluster == CLUSTER_EOF) 
	{
		return 0;
	}
	
	// Follow cluster list until desired one is found
	for (chunks = startOffset / discBytePerClus; chunks > 0; chunks--)
	{
		cluster = FAT_NextCluster (cluster);
	}
	
	// Calculate the sector and byte of the current position,
	// and store them
	curSect = (startOffset % discBytePerClus) / BYTES_PER_SECTOR;
	curByte = startOffset % BYTES_PER_SECTOR;

	// Load sector buffer for new position in file
	CARD_ReadSector( curSect + FAT_ClustToSect(cluster), globalBuffer);
	curSect++;

	// Number of bytes needed to read to align with a sector
	beginBytes = (BYTES_PER_SECTOR < length + curByte ? (BYTES_PER_SECTOR - curByte) : length);

	// Read first part from buffer, to align with sector boundary
	for (dataPos = 0 ; dataPos < beginBytes; dataPos++)
	{
		buffer[dataPos] = globalBuffer[curByte++];
	}

	// Read in all the 512 byte chunks of the file directly, saving time
	for ( chunks = ((int)length - beginBytes) / BYTES_PER_SECTOR; chunks > 0;)
	{
		int sectorsToRead;

		// Move to the next cluster if necessary
		if (curSect >= discSecPerClus)
		{
			curSect = 0;
			cluster = FAT_NextCluster (cluster);
		}

		// Calculate how many sectors to read (read a maximum of discSecPerClus at a time)
		sectorsToRead = discSecPerClus - curSect;
		if(chunks < sectorsToRead)
			sectorsToRead = chunks;

		// Read the sectors
		CARD_ReadSectors(curSect + FAT_ClustToSect(cluster), sectorsToRead, buffer + dataPos);
		chunks  -= sectorsToRead;
		curSect += sectorsToRead;
		dataPos += BYTES_PER_SECTOR * sectorsToRead;
	}

	// Take care of any bytes left over before end of read
	if (dataPos < length)
	{

		// Update the read buffer
		curByte = 0;
		if (curSect >= discSecPerClus)
		{
			curSect = 0;
			cluster = FAT_NextCluster (cluster);
		}
		CARD_ReadSector( curSect + FAT_ClustToSect( cluster), globalBuffer);
		
		// Read in last partial chunk
		for (; dataPos < length; dataPos++)
		{
			buffer[dataPos] = globalBuffer[curByte];
			curByte++;
		}
	}
	
	return dataPos;
}


================================================
FILE: bootloader/source/fat.h
================================================
/*-----------------------------------------------------------------
 fat.h
 
 NDS MP
 GBAMP NDS Firmware Hack Version 2.12
 An NDS aware firmware patch for the GBA Movie Player.
 By Michael Chisholm (Chishm)
 
 Filesystem code based on GBAMP_CF.c by Chishm (me).
 
License:
 Copyright (C) 2005  Michael "Chishm" Chisholm

 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 2
 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, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

 If you use this code, please give due credit and email me about your
 project at chishm@hotmail.com
------------------------------------------------------------------*/

#ifndef FAT_H
#define FAT_H

#include <nds/ndstypes.h>

#define CLUSTER_FREE	0x00000000
#define	CLUSTER_EOF		0x0FFFFFFF
#define CLUSTER_FIRST	0x00000002

bool FAT_InitFiles (bool initCard);
u32 getBootFileCluster (const char* bootName);
u32 fileRead (char* buffer, u32 cluster, u32 startOffset, u32 length);
u32 FAT_ClustToSect (u32 cluster);

#endif // FAT_H


================================================
FILE: bootloader/source/io_dldi.h
================================================
/*
 io_dldi.h 

 Reserved space for post-compilation adding of an extra driver

 Copyright (c) 2006 Michael "Chishm" Chisholm
	
 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. The name of the author may not be used to endorse or promote products derived
     from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.

	2006-12-22 - Chishm
		* Original release
*/

#ifndef IO_DLDI_H
#define IO_DLDI_H

// 'DLDD'
#define DEVICE_TYPE_DLDD 0x49444C44

#include "disc_io.h"

// export interface
extern IO_INTERFACE _io_dldi ;

#endif	// define IO_DLDI_H


================================================
FILE: bootloader/source/io_dldi.s
================================================
/*-----------------------------------------------------------------

 Copyright (C) 2005  Michael "Chishm" Chisholm

 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 2
 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, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

 If you use this code, please give due credit and email me about your
 project at chishm@hotmail.com
------------------------------------------------------------------*/
@---------------------------------------------------------------------------------
	.align	4
	.arm
	.global _dldi_start
	.global _io_dldi
@---------------------------------------------------------------------------------
.equ FEATURE_MEDIUM_CANREAD,		0x00000001
.equ FEATURE_MEDIUM_CANWRITE,		0x00000002
.equ FEATURE_SLOT_GBA,			0x00000010
.equ FEATURE_SLOT_NDS,			0x00000020


_dldi_start:
#ifndef NO_DLDI

@---------------------------------------------------------------------------------
@ Driver patch file standard header -- 16 bytes
#ifdef STANDARD_DLDI
	.word	0xBF8DA5ED		@ Magic number to identify this region
#else
	.word	0xBF8DA5EE		@ Magic number to identify this region
#endif
	.asciz	" Chishm"		@ Identifying Magic string (8 bytes with null terminator)
	.byte	0x01			@ Version number
	.byte	0x0e		@ 16KiB	@ Log [base-2] of the size of this driver in bytes.
	.byte	0x00			@ Sections to fix
	.byte 	0x0e		@ 16KiB	@ Log [base-2] of the allocated space in bytes.
	
@---------------------------------------------------------------------------------
@ Text identifier - can be anything up to 47 chars + terminating null -- 16 bytes
	.align	4
	.asciz "Loader (No interface)"

@---------------------------------------------------------------------------------
@ Offsets to important sections within the data	-- 32 bytes
	.align	6
	.word   _dldi_start		@ data start
	.word   _dldi_end		@ data end
	.word	0x00000000		@ Interworking glue start	-- Needs address fixing
	.word	0x00000000		@ Interworking glue end
	.word   0x00000000		@ GOT start			-- Needs address fixing
	.word   0x00000000		@ GOT end
	.word   0x00000000		@ bss start			-- Needs setting to zero
	.word   0x00000000		@ bss end
@---------------------------------------------------------------------------------
@ IO_INTERFACE data -- 32 bytes
_io_dldi:
	.ascii	"DLDI"				@ ioType
	.word	0x00000000			@ Features
	.word	_DLDI_startup			@ 
	.word	_DLDI_isInserted		@ 
	.word	_DLDI_readSectors		@   Function pointers to standard device driver functions
	.word	_DLDI_writeSectors		@ 
	.word	_DLDI_clearStatus		@ 
	.word	_DLDI_shutdown			@ 

	
@---------------------------------------------------------------------------------

_DLDI_startup:
_DLDI_isInserted:
_DLDI_readSectors:
_DLDI_writeSectors:
_DLDI_clearStatus:
_DLDI_shutdown:
	mov		r0, #0x00		@ Return false for every function
	bx		lr



@---------------------------------------------------------------------------------
	.align
	.pool

	.space (_dldi_start + 16384) - .	@ Fill to 16KiB

_dldi_end:
	.end
@---------------------------------------------------------------------------------
#else
@---------------------------------------------------------------------------------
@ IO_INTERFACE data -- 32 bytes
_io_dldi:
	.ascii	"DLDI"				@ ioType
	.word	0x00000000			@ Features
	.word	_DLDI_startup			@
	.word	_DLDI_isInserted		@
	.word	_DLDI_readSectors		@   Function pointers to standard device driver functions
	.word	_DLDI_writeSectors		@
	.word	_DLDI_clearStatus		@
	.word	_DLDI_shutdown			@

	_DLDI_startup:
_DLDI_isInserted:
_DLDI_readSectors:
_DLDI_writeSectors:
_DLDI_clearStatus:
_DLDI_shutdown:
	mov		r0, #0x00		@ Return false for every function
	bx		lr


#endif


================================================
FILE: bootloader/source/load_crt0.s
================================================
/*-----------------------------------------------------------------

 Copyright (C) 2005  Michael "Chishm" Chisholm

 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 2
 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, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

 If you use this code, please give due credit and email me about your
 project at chishm@hotmail.com
------------------------------------------------------------------*/

@---------------------------------------------------------------------------------
	.section ".init"
	.global _start
	.global storedFileCluster
	.global initDisc
	.global wantToPatchDLDI
	.global argStart
	.global argSize
	.global dsiSD
	.global dsiMode
@---------------------------------------------------------------------------------
	.align	4
	.arm
@---------------------------------------------------------------------------------
_start:
@---------------------------------------------------------------------------------
	b	startUp

storedFileCluster:
	.word	0x0FFFFFFF		@ default BOOT.NDS
initDisc:
	.word	0x00000001		@ init the disc by default
wantToPatchDLDI:
	.word	0x00000001		@ by default patch the DLDI section of the loaded NDS
@ Used for passing arguments to the loaded app
argStart:
	.word	_end - _start
argSize:
	.word	0x00000000
dldiOffset:
	.word	_dldi_start - _start
dsiSD:
	.word	0
dsiMode:
	.word	0

startUp:
	mov	r0, #0x04000000
	mov	r1, #0
	str	r1, [r0,#0x208]		@ REG_IME
	str	r1, [r0,#0x210]		@ REG_IE
	str	r1, [r0,#0x218]		@ REG_AUXIE

	mov	r0, #0x12		@ Switch to IRQ Mode
	msr	cpsr, r0
	ldr	sp, =__sp_irq		@ Set IRQ stack

	mov	r0, #0x13		@ Switch to SVC Mode
	msr	cpsr, r0
	ldr	sp, =__sp_svc		@ Set SVC stack

	mov	r0, #0x1F		@ Switch to System Mode
	msr	cpsr, r0
	ldr	sp, =__sp_usr		@ Set user stack

	ldr	r0, =__bss_start	@ Clear BSS section to 0x00
	ldr	r1, =__bss_end
	sub	r1, r1, r0
	bl	ClearMem

	mov	r0, #0			@ int argc
	mov	r1, #0			@ char *argv[]
	ldr	r3, =main
	bl	_blx_r3_stub		@ jump to user code

	@ If the user ever returns, restart
	b	_start

@---------------------------------------------------------------------------------
_blx_r3_stub:
@---------------------------------------------------------------------------------
	bx	r3

@---------------------------------------------------------------------------------
@ Clear memory to 0x00 if length != 0
@  r0 = Start Address
@  r1 = Length
@---------------------------------------------------------------------------------
ClearMem:
@---------------------------------------------------------------------------------
	mov	r2, #3			@ Round down to nearest word boundary
	add	r1, r1, r2		@ Shouldn't be needed
	bics	r1, r1, r2		@ Clear 2 LSB (and set Z)
	bxeq	lr			@ Quit if copy size is 0

	mov	r2, #0
ClrLoop:
	stmia	r0!, {r2}
	subs	r1, r1, #4
	bne	ClrLoop
	bx	lr

@---------------------------------------------------------------------------------
@ Copy memory if length	!= 0
@  r1 = Source Address
@  r2 = Dest Address
@  r4 = Dest Address + Length
@---------------------------------------------------------------------------------
CopyMemCheck:
@---------------------------------------------------------------------------------
	sub	r3, r4, r2		@ Is there any data to copy?
@---------------------------------------------------------------------------------
@ Copy memory
@  r1 = Source Address
@  r2 = Dest Address
@  r3 = Length
@---------------------------------------------------------------------------------
CopyMem:
@---------------------------------------------------------------------------------
	mov	r0, #3			@ These commands are used in cases where
	add	r3, r3, r0		@ the length is not a multiple of 4,
	bics	r3, r3, r0		@ even though it should be.
	bxeq	lr			@ Length is zero, so exit
CIDLoop:
	ldmia	r1!, {r0}
	stmia	r2!, {r0}
	subs	r3, r3, #4
	bne	CIDLoop
	bx	lr

@---------------------------------------------------------------------------------
	.align
	.pool
	.end
@---------------------------------------------------------------------------------


================================================
FILE: bootloader/source/sdmmc.c
================================================
#ifndef NO_SDMMC
#include <nds/bios.h>
#include "sdmmc.h"
#include <stddef.h>

static struct mmcdevice deviceSD;

//---------------------------------------------------------------------------------
int geterror(struct mmcdevice *ctx) {
//---------------------------------------------------------------------------------
    //if(ctx->error == 0x4) return -1;
    //else return 0;
    return (ctx->error << 29) >> 31;
}


//---------------------------------------------------------------------------------
void setTarget(struct mmcdevice *ctx) {
//---------------------------------------------------------------------------------
    sdmmc_mask16(REG_SDPORTSEL,0x3,(u16)ctx->devicenumber);
    setckl(ctx->clk);
    if (ctx->SDOPT == 0) {
        sdmmc_mask16(REG_SDOPT, 0, 0x8000);
    } else {
        sdmmc_mask16(REG_SDOPT, 0x8000, 0);
    }

}


//---------------------------------------------------------------------------------
void sdmmc_send_command(struct mmcdevice *ctx, uint32_t cmd, uint32_t args) {
//---------------------------------------------------------------------------------
	const bool getSDRESP = (cmd << 15) >> 31;
	u16 flags = (cmd << 15) >> 31;
	const bool readdata = cmd & 0x20000;
	const bool writedata = cmd & 0x40000;

	if(readdata || writedata)
	{
		flags |= TMIO_STAT0_DATAEND;
	}

	ctx->error = 0;
	while((sdmmc_read16(REG_SDSTATUS1) & TMIO_STAT1_CMD_BUSY)); //mmc working?
	sdmmc_write16(REG_SDIRMASK0,0);
	sdmmc_write16(REG_SDIRMASK1,0);
	sdmmc_write16(REG_SDSTATUS0,0);
	sdmmc_write16(REG_SDSTATUS1,0);
	sdmmc_mask16(REG_SDDATACTL32,0x1800,0x400); // Disable TX32RQ and RX32RDY IRQ. Clear fifo.
	sdmmc_write16(REG_SDCMDARG0,args &0xFFFF);
	sdmmc_write16(REG_SDCMDARG1,args >> 16);
	sdmmc_write16(REG_SDCMD,cmd &0xFFFF);

	u32 size = ctx->size;
	const u16 blkSize = sdmmc_read16(REG_SDBLKLEN32);
	u32 *rDataPtr32 = (u32*)ctx->rData;
	u8  *rDataPtr8  = ctx->rData;
	const u32 *tDataPtr32 = (u32*)ctx->tData;
	const u8  *tDataPtr8  = ctx->tData;

	bool rUseBuf = ( NULL != rDataPtr32 );
	bool tUseBuf = ( NULL != tDataPtr32 );

	u16 status0 = 0;
	while(1)
	{
		volatile u16 status1 = sdmmc_read16(REG_SDSTATUS1);
#ifdef DATA32_SUPPORT
		volatile u16 ctl32 = sdmmc_read16(REG_SDDATACTL32);
		if((ctl32 & 0x100))
#else
		if((status1 & TMIO_STAT1_RXRDY))
#endif
		{
			if(readdata)
			{
				if(rUseBuf)
				{
					sdmmc_mask16(REG_SDSTATUS1, TMIO_STAT1_RXRDY, 0);
					if(size >= blkSize)
					{
						#ifdef DATA32_SUPPORT
						if(!((u32)rDataPtr32 & 3))
						{
							for(u32 i = 0; i < blkSize; i += 4)
							{
								*rDataPtr32++ = sdmmc_read32(REG_SDFIFO32);
							}
						}
						else
						{
							for(u32 i = 0; i < blkSize; i += 4)
							{
								u32 data = sdmmc_read32(REG_SDFIFO32);
								*rDataPtr8++ = data;
								*rDataPtr8++ = data >> 8;
								*rDataPtr8++ = data >> 16;
								*rDataPtr8++ = data >> 24;
							}
						}
						#else
						if(!((u32)rDataPtr16 & 1))
						{
							for(u32 i = 0; i < blkSize; i += 4)
							{
								*rDataPtr16++ = sdmmc_read16(REG_SDFIFO);
							}
						}
						else
						{
							for(u32 i = 0; i < blkSize; i += 4)
							{
								u16 data = sdmmc_read16(REG_SDFIFO);
								*rDataPtr8++ = data;
								*rDataPtr8++ = data >> 8;
							}
						}
						#endif
						size -= blkSize;
					}
				}

				sdmmc_mask16(REG_SDDATACTL32, 0x800, 0);
			}
		}
#ifdef DATA32_SUPPORT
		if(!(ctl32 & 0x200))
#else
		if((status1 & TMIO_STAT1_TXRQ))
#endif
		{
			if(writedata)
			{
				if(tUseBuf)
				{
					sdmmc_mask16(REG_SDSTATUS1, TMIO_STAT1_TXRQ, 0);
					if(size >= blkSize)
					{
						#ifdef DATA32_SUPPORT
						if(!((u32)tDataPtr32 & 3))
						{
							for(u32 i = 0; i < blkSize; i += 4)
							{
								sdmmc_write32(REG_SDFIFO32, *tDataPtr32++);
							}
						}
						else
						{
							for(u32 i = 0; i < blkSize; i += 4)
							{
								u32 data = *tDataPtr8++;
								data |= (u32)*tDataPtr8++ << 8;
								data |= (u32)*tDataPtr8++ << 16;
								data |= (u32)*tDataPtr8++ << 24;
								sdmmc_write32(REG_SDFIFO32, data);
							}
						}
						#else
						if(!((u32)tDataPtr16 & 1))
						{
							for(u32 i = 0; i < blkSize; i += 2)
							{
								sdmmc_write16(REG_SDFIFO, *tDataPtr16++);
							}
						}
						else
						{
							for(u32 i = 0; i < blkSize; i += 2)
							{
								u16 data = *tDataPtr8++;
								data |= (u16)(*tDataPtr8++ << 8);
								sdmmc_write16(REG_SDFIFO, data);
							}
						}
						#endif
						size -= blkSize;
					}
				}

				sdmmc_mask16(REG_SDDATACTL32, 0x1000, 0);
			}
		}
		if(status1 & TMIO_MASK_GW)
		{
			ctx->error |= 4;
			break;
		}

		if(!(status1 & TMIO_STAT1_CMD_BUSY))
		{
			status0 = sdmmc_read16(REG_SDSTATUS0);
			if(sdmmc_read16(REG_SDSTATUS0) & TMIO_STAT0_CMDRESPEND)
			{
				ctx->error |= 0x1;
			}
			if(status0 & TMIO_STAT0_DATAEND)
			{
				ctx->error |= 0x2;
			}

			if((status0 & flags) == flags)
				break;
		}
	}
	ctx->stat0 = sdmmc_read16(REG_SDSTATUS0);
	ctx->stat1 = sdmmc_read16(REG_SDSTATUS1);
	sdmmc_write16(REG_SDSTATUS0,0);
	sdmmc_write16(REG_SDSTATUS1,0);

	if(getSDRESP != 0)
	{
		ctx->ret[0] = (u32)(sdmmc_read16(REG_SDRESP0) | (sdmmc_read16(REG_SDRESP1) << 16));
		ctx->ret[1] = (u32)(sdmmc_read16(REG_SDRESP2) | (sdmmc_read16(REG_SDRESP3) << 16));
		ctx->ret[2] = (u32)(sdmmc_read16(REG_SDRESP4) | (sdmmc_read16(REG_SDRESP5) << 16));
		ctx->ret[3] = (u32)(sdmmc_read16(REG_SDRESP6) | (sdmmc_read16(REG_SDRESP7) << 16));
	}
}

//---------------------------------------------------------------------------------
static u32 calcSDSize(u8* csd, int type) {
//---------------------------------------------------------------------------------
    u32 result = 0;
    if (type == -1) type = csd[14] >> 6;
    switch (type) {
        case 0:
            {
                u32 block_len = csd[9] & 0xf;
                block_len = 1 << block_len;
                u32 mult = (csd[4] >> 7) | ((csd[5] & 3) << 1);
                mult = 1 << (mult + 2);
                result = csd[8] & 3;
                result = (result << 8) | csd[7];
                result = (result << 2) | (csd[6] >> 6);
                result = (result + 1) * mult * block_len / 512;
            }
            break;
        case 1:
            result = csd[7] & 0x3f;
            result = (result << 8) | csd[6];
            result = (result << 8) | csd[5];
            result = (result + 1) * 1024;
            break;
    }
    return result;
}

//---------------------------------------------------------------------------------
void sdmmc_controller_init() {
//---------------------------------------------------------------------------------
    deviceSD.isSDHC = 0;
    deviceSD.SDOPT = 0;
    deviceSD.res = 0;
    deviceSD.initarg = 0;
    deviceSD.clk = 0x80;
    deviceSD.devicenumber = 0;

    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) &= 0xF7FFu;
    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) &= 0xEFFFu;
#ifdef DATA32_SUPPORT
    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) |= 0x402u;
#else
    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) |= 0x402u;
#endif
    *(vu16*)(SDMMC_BASE + REG_SDDATACTL) = (*(vu16*)(SDMMC_BASE + REG_SDDATACTL) & 0xFFDD) | 2;
#ifdef DATA32_SUPPORT
    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) &= 0xFFFFu;
    *(vu16*)(SDMMC_BASE + REG_SDDATACTL) &= 0xFFDFu;
    *(vu16*)(SDMMC_BASE + REG_SDBLKLEN32) = 512;
#else
    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) &= 0xFFFDu;
    *(vu16*)(SDMMC_BASE + REG_SDDATACTL) &= 0xFFDDu;
    *(vu16*)(SDMMC_BASE + REG_SDBLKLEN32) = 0;
#endif
    *(vu16*)(SDMMC_BASE + REG_SDBLKCOUNT32) = 1;
    *(vu16*)(SDMMC_BASE + REG_SDRESET) &= 0xFFFEu;
    *(vu16*)(SDMMC_BASE + REG_SDRESET) |= 1u;
    *(vu16*)(SDMMC_BASE + REG_SDIRMASK0) |= TMIO_MASK_ALL;
    *(vu16*)(SDMMC_BASE + REG_SDIRMASK1) |= TMIO_MASK_ALL>>16;
    *(vu16*)(SDMMC_BASE + 0x0fc) |= 0xDBu; //SDCTL_RESERVED7
    *(vu16*)(SDMMC_BASE + 0x0fe) |= 0xDBu; //SDCTL_RESERVED8
    *(vu16*)(SDMMC_BASE + REG_SDPORTSEL) &= 0xFFFCu;
#ifdef DATA32_SUPPORT
    *(vu16*)(SDMMC_BASE + REG_SDCLKCTL) = 0x20;
    *(vu16*)(SDMMC_BASE + REG_SDOPT) = 0x40EE;
#else
    *(vu16*)(SDMMC_BASE + REG_SDCLKCTL) = 0x40; //Nintendo sets this to 0x20
    *(vu16*)(SDMMC_BASE + REG_SDOPT) = 0x40EB; //Nintendo sets this to 0x40EE
#endif
    *(vu16*)(SDMMC_BASE + REG_SDPORTSEL) &= 0xFFFCu;
    *(vu16*)(SDMMC_BASE + REG_SDBLKLEN) = 512;
    *(vu16*)(SDMMC_BASE + REG_SDSTOP) = 0;

    setTarget(&deviceSD);
}

//---------------------------------------------------------------------------------
int sdmmc_sdcard_init() {
//---------------------------------------------------------------------------------
	// We need to send at least 74 clock pulses.
    setTarget(&deviceSD);
	swiDelay(0x1980); // ~75-76 clocks

    // card reset
    sdmmc_send_command(&deviceSD,0,0);

    // CMD8 0x1AA
    sdmmc_send_command(&deviceSD,0x10408,0x1AA);
    u32 temp = (deviceSD.error & 0x1) << 0x1E;

    u32 temp2 = 0;
    do {
        do {
            // CMD55
            sdmmc_send_command(&deviceSD,0x10437,deviceSD.initarg << 0x10);
            // ACMD41
            sdmmc_send_command(&deviceSD,0x10769,0x00FF8000 | temp);
            temp2 = 1;
        } while ( !(deviceSD.error & 1) );

    } while((deviceSD.ret[0] & 0x80000000) == 0);

    if(!((deviceSD.ret[0] >> 30) & 1) || !temp)
        temp2 = 0;

    deviceSD.isSDHC = temp2;

    sdmmc_send_command(&deviceSD,0x10602,0);
    if (deviceSD.error & 0x4) return -1;

    sdmmc_send_command(&deviceSD,0x10403,0);
    if (deviceSD.error & 0x4) return -2;
    deviceSD.initarg = deviceSD.ret[0] >> 0x10;

    sdmmc_send_command(&deviceSD,0x10609,deviceSD.initarg << 0x10);
    if (deviceSD.error & 0x4) return -3;

	// Command Class 10 support
	const bool cmd6Supported = ((u8*)deviceSD.ret)[10] & 0x40;
    deviceSD.total_size = calcSDSize((u8*)&deviceSD.ret[0],-1);
    setckl(0x201); // 16.756991 MHz

    sdmmc_send_command(&deviceSD,0x10507,deviceSD.initarg << 0x10);
    if (deviceSD.error & 0x4) return -4;

    // CMD55
    sdmmc_send_command(&deviceSD,0x10437,deviceSD.initarg << 0x10);
    if (deviceSD.error & 0x4) return -5;

    // ACMD42
    sdmmc_send_command(&deviceSD,0x1076A,0x0);
    if (deviceSD.error & 0x4) return -6;

    // CMD55
    sdmmc_send_command(&deviceSD,0x10437,deviceSD.initarg << 0x10);
    if (deviceSD.error & 0x4) return -7;

    deviceSD.SDOPT = 1;
    sdmmc_send_command(&deviceSD,0x10446,0x2);
    if (deviceSD.error & 0x4) return -8;
	sdmmc_mask16(REG_SDOPT, 0x8000, 0); // Switch to 4 bit mode.

	// TODO: CMD6 to switch to high speed mode.
	if(cmd6Supported)
	{
		sdmmc_write16(REG_SDSTOP,0);
		sdmmc_write16(REG_SDBLKLEN32,64);
		sdmmc_write16(REG_SDBLKLEN,64);
		deviceSD.rData = NULL;
		deviceSD.size = 64;
		sdmmc_send_command(&deviceSD,0x31C06,0x80FFFFF1);
		sdmmc_write16(REG_SDBLKLEN,512);
		if(deviceSD.error & 0x4) return -9;

		deviceSD.clk = 0x200; // 33.513982 MHz
		setckl(0x200);
	}
	else deviceSD.clk = 0x201; // 16.756991 MHz

    sdmmc_send_command(&deviceSD,0x1040D,deviceSD.initarg << 0x10);
    if (deviceSD.error & 0x4) return -9;

    sdmmc_send_command(&deviceSD,0x10410,0x200);
    if (deviceSD.error & 0x4) return -10;

    return 0;

}

//---------------------------------------------------------------------------------
int sdmmc_sdcard_readsectors(u32 sector_no, u32 numsectors, void *out) {
//---------------------------------------------------------------------------------
    if (deviceSD.isSDHC == 0)
        sector_no <<= 9;
    setTarget(&deviceSD);
    sdmmc_write16(REG_SDSTOP,0x100);

#ifdef DATA32_SUPPORT
    sdmmc_write16(REG_SDBLKCOUNT32,numsectors);
    sdmmc_write16(REG_SDBLKLEN32,0x200);
#endif

    sdmmc_write16(REG_SDBLKCOUNT,numsectors);
    deviceSD.rData = out;
    deviceSD.size = numsectors << 9;
    sdmmc_send_command(&deviceSD,0x33C12,sector_no);
    return geterror(&deviceSD);
}
#endif

================================================
FILE: bootloader/source/sdmmc.h
================================================
#ifndef __SDMMC_H__
#define __SDMMC_H__

#include <nds/ndstypes.h>

#define DATA32_SUPPORT

#define SDMMC_BASE	0x04004800


#define REG_SDCMD       0x00
#define REG_SDPORTSEL   0x02
#define REG_SDCMDARG    0x04
#define REG_SDCMDARG0   0x04
#define REG_SDCMDARG1  	0x06
#define REG_SDSTOP      0x08
#define REG_SDRESP      0x0c
#define REG_SDBLKCOUNT  0x0a

#define REG_SDRESP0     0x0c
#define REG_SDRESP1     0x0e
#define REG_SDRESP2     0x10
#define REG_SDRESP3     0x12
#define REG_SDRESP4     0x14
#define REG_SDRESP5     0x16
#define REG_SDRESP6     0x18
#define REG_SDRESP7     0x1a

#define REG_SDSTATUS0   0x1c
#define REG_SDSTATUS1   0x1e

#define REG_SDIRMASK0   0x20
#define REG_SDIRMASK1   0x22
#define REG_SDCLKCTL    0x24

#define REG_SDBLKLEN    0x26
#define REG_SDOPT       0x28
#define REG_SDFIFO      0x30

#define REG_SDDATACTL   0xd8
#define REG_SDRESET     0xe0
#define REG_SDPROTECTED 0xf6 //bit 0 determines if sd is protected or not?

#define REG_SDDATACTL32         0x100
#define REG_SDBLKLEN32          0x104
#define REG_SDBLKCOUNT32        0x108
#define REG_SDFIFO32            0x10C

#define REG_CLK_AND_WAIT_CTL    0x138
#define REG_RESET_SDIO          0x1e0
//The below defines are from linux kernel drivers/mmc tmio_mmc.h.
/* Definitions for values the CTRL_STATUS register can take. */
#define TMIO_STAT0_CMDRESPEND    0x0001
#define TMIO_STAT0_DATAEND       0x0004
#define TMIO_STAT0_CARD_REMOVE   0x0008
#define TMIO_STAT0_CARD_INSERT   0x0010
#define TMIO_STAT0_SIGSTATE      0x0020
#define TMIO_STAT0_WRPROTECT     0x0080
#define TMIO_STAT0_CARD_REMOVE_A 0x0100
#define TMIO_STAT0_CARD_INSERT_A 0x0200
#define TMIO_STAT0_SIGSTATE_A    0x0400

#define TMIO_STAT1_CMD_IDX_ERR   0x0001
#define TMIO_STAT1_CRCFAIL       0x0002
#define TMIO_STAT1_STOPBIT_ERR   0x0004
#define TMIO_STAT1_DATATIMEOUT   0x0008
#define TMIO_STAT1_RXOVERFLOW    0x0010
#define TMIO_STAT1_TXUNDERRUN    0x0020
#define TMIO_STAT1_CMDTIMEOUT    0x0040
#define TMIO_STAT1_RXRDY         0x0100
#define TMIO_STAT1_TXRQ          0x0200
#define TMIO_STAT1_ILL_FUNC      0x2000
#define TMIO_STAT1_CMD_BUSY      0x4000
#define TMIO_STAT1_ILL_ACCESS    0x8000

#define SDMC_NORMAL              0x00000000
#define SDMC_ERR_COMMAND         0x00000001
#define SDMC_ERR_CRC             0x00000002
#define SDMC_ERR_END             0x00000004
#define SDMC_ERR_TIMEOUT         0x00000008
#define SDMC_ERR_FIFO_OVF        0x00000010
#define SDMC_ERR_FIFO_UDF        0x00000020
#define SDMC_ERR_WP              0x00000040
#define SDMC_ERR_ABORT           0x00000080
#define SDMC_ERR_FPGA_TIMEOUT    0x00000100
#define SDMC_ERR_PARAM           0x00000200
#define SDMC_ERR_R1_STATUS       0x00000800
#define SDMC_ERR_NUM_WR_SECTORS  0x00001000
#define SDMC_ERR_RESET           0x00002000
#define SDMC_ERR_ILA             0x00004000
#define SDMC_ERR_INFO_DETECT     0x00008000

#define SDMC_STAT_ERR_UNKNOWN    0x00080000
#define SDMC_STAT_ERR_CC         0x00100000
#define SDMC_STAT_ERR_ECC_FAILED 0x00200000
#define SDMC_STAT_ERR_CRC        0x00800000
#define SDMC_STAT_ERR_OTHER      0xf9c70008

#define TMIO_MASK_ALL           0x837f031d

#define TMIO_MASK_GW      (TMIO_STAT1_ILL_ACCESS | TMIO_STAT1_CMDTIMEOUT | TMIO_STAT1_TXUNDERRUN | TMIO_STAT1_RXOVERFLOW | \
                           TMIO_STAT1_DATATIMEOUT | TMIO_STAT1_STOPBIT_ERR | TMIO_STAT1_CRCFAIL | TMIO_STAT1_CMD_IDX_ERR)

#define TMIO_MASK_READOP  (TMIO_STAT1_RXRDY | TMIO_STAT1_DATAEND)
#define TMIO_MASK_WRITEOP (TMIO_STAT1_TXRQ | TMIO_STAT1_DATAEND)

typedef struct mmcdevice {
	u8* rData;
	const u8* tData;
    u32 size;
    u32 startOffset;
    u32 endOffset;
    u32 error;
    u16 stat0;
    u16 stat1;
    u32 ret[4];
    u32 initarg;
    u32 isSDHC;
    u32 clk;
    u32 SDOPT;
    u32 devicenumber;
    u32 total_size; //size in sectors of the device
    u32 res;
} mmcdevice;

enum {
    MMC_DEVICE_SDCARD,
    MMC_DEVICE_NAND,
};

void sdmmc_controller_init();
void sdmmc_initirq();
int sdmmc_cardinserted();

int sdmmc_sdcard_init();
int sdmmc_nand_init();
void sdmmc_get_cid(int devicenumber, u32 *cid);

static inline void sdmmc_nand_cid( u32 *cid) {
    sdmmc_get_cid(MMC_DEVICE_NAND,cid);
}

static inline void sdmmc_sdcard_cid( u32 *cid) {
    sdmmc_get_cid(MMC_DEVICE_SDCARD,cid);
}

int sdmmc_sdcard_readsectors(u32 sector_no, u32 numsectors, void *out);
int sdmmc_sdcard_writesectors(u32 sector_no, u32 numsectors, void *in);
int sdmmc_nand_readsectors(u32 sector_no, u32 numsectors, void *out);
int sdmmc_nand_writesectors(u32 sector_no, u32 numsectors, void *in);

extern u32 sdmmc_cid[];
extern int sdmmc_curdevice;

//---------------------------------------------------------------------------------
static inline u16 sdmmc_read16(u16 reg) {
//---------------------------------------------------------------------------------
	return *(vu16*)(SDMMC_BASE + reg);
}

//---------------------------------------------------------------------------------
static inline void sdmmc_write16(u16 reg, u16 val) {
//---------------------------------------------------------------------------------
	*(vu16*)(SDMMC_BASE + reg) = val;
}

//---------------------------------------------------------------------------------
static inline u32 sdmmc_read32(u16 reg) {
//---------------------------------------------------------------------------------
    return *(vu32*)(SDMMC_BASE + reg);
}

//---------------------------------------------------------------------------------
static inline void sdmmc_write32(u16 reg, u32 val) {
//---------------------------------------------------------------------------------
    *(vu32*)(SDMMC_BASE + reg) = val;
}

//---------------------------------------------------------------------------------
static inline void sdmmc_mask16(u16 reg, u16 clear, u16 set) {
//---------------------------------------------------------------------------------
	u16 val = sdmmc_read16(reg);
	val &= ~clear;
	val |= set;
	sdmmc_write16(reg, val);
}


//---------------------------------------------------------------------------------
static inline void setckl(u32 data) {
//---------------------------------------------------------------------------------
    sdmmc_mask16(REG_SDCLKCTL, 0x100, 0);
    sdmmc_mask16(REG_SDCLKCTL, 0x2FF, data & 0x2FF);
    sdmmc_mask16(REG_SDCLKCTL, 0x0, 0x100);
}

#endif


================================================
FILE: fix_ndsheader.py
================================================
# -*- coding: utf8 -*-
# Patch an .nds (works with homebrew and ds demo only) to make it ready for make_cia
#
# 2016-02-28, Ahezard 
#
# inspired by 
# Apache Thunder .nds edited files and comments
# https://github.com/Relys/Project_CTR/blob/master/makerom/srl.h
# https://dsibrew.org/wiki/DSi_Cartridge_Header
# if the header size of the input nds file is 0x200 (homebrew)
# the header size of the output nds file will be patched to 0x4000 (normal ds/dsi header), 0x3E00 offset

from struct import *
from collections import namedtuple
# from collections import OrderedDict
from pprint import pprint
import os  # , sys
# import binascii
import argparse
from ctypes import c_ushort


parser = argparse.ArgumentParser(description='Patch an nds in order to be ready cia conversion via make_cia --srl=.')
parser.add_argument('file', metavar='file.nds', type=argparse.FileType('rb'), help='nds file to patch')
parser.add_argument('--verbose', help='verbose mode', action="store_true")
parser.add_argument('--out', help='output file [optionnal]')
parser.add_argument('--read', help='print only the header content, do not patch', action="store_true")
parser.add_argument('--extract', help='extract the content of the rom : header.bin,arm9.bin,arm7.bin,icon.bin,arm9i.bin,arm7i.bin, do not patch', action="store_true")  # Not yet implemented
parser.add_argument('--title', help='Game title')
parser.add_argument('--code', help='Game code')
parser.add_argument('--maker', help='Maker code')
parser.add_argument('--mode', help='target mode, default mode is ds [ds|dsi|dsinogba|nitrohax]')
parser.add_argument('--arm9', type=argparse.FileType('rb'), help='swap the ds arm9 binary by the one provided')
parser.add_argument('--arm7', type=argparse.FileType('rb'), help='swap the ds arm7 binary by the one provided')
parser.add_argument('--arm9EntryAddress', help='arm9 ram address of the binary provided')
parser.add_argument('--arm7EntryAddress', help='arm7 ram address of the binary provided')
parser.add_argument('--arm9i', type=argparse.FileType('rb'), help='add a dsi arm9i binary to the file')
parser.add_argument
Download .txt
gitextract_sb4kvjyr/

├── .gitattributes
├── .github/
│   └── workflows/
│       └── build.yml
├── .gitignore
├── .gitmodules
├── LICENSE
├── Makefile
├── README.md
├── arm7/
│   ├── Makefile
│   └── source/
│       └── main.c
├── arm9/
│   ├── Makefile
│   ├── ds_arm9_hiya.mem
│   ├── ds_arm9_hiya.specs
│   ├── graphics_xcf/
│   │   ├── credits.xcf
│   │   └── topSplash.xcf
│   └── source/
│       ├── bios_decompress_callback.c
│       ├── bios_decompress_callback.h
│       ├── dsi_only.cpp
│       ├── fileOperations.cpp
│       ├── fileOperations.h
│       ├── gif.cpp
│       ├── gif.hpp
│       ├── inifile.cpp
│       ├── inifile.h
│       ├── lzw.cpp
│       ├── lzw.hpp
│       ├── main.cpp
│       ├── nds_loader_arm9.c
│       ├── nds_loader_arm9.h
│       ├── stringtool.cpp
│       ├── stringtool.h
│       ├── tonccpy.c
│       └── tonccpy.h
├── bootloader/
│   ├── Makefile
│   ├── arm9code/
│   │   └── mpu_reset.s
│   ├── load.ld
│   └── source/
│       ├── arm7clear.s
│       ├── arm9clear.arm.c
│       ├── arm9mpu_reset.s
│       ├── bios.s
│       ├── boot.c
│       ├── boot.h
│       ├── card.h
│       ├── disc_io.h
│       ├── fat.c
│       ├── fat.h
│       ├── io_dldi.h
│       ├── io_dldi.s
│       ├── load_crt0.s
│       ├── sdmmc.c
│       └── sdmmc.h
├── fix_ndsheader.py
├── hiyaCFW.pnproj
├── hiyaCFW.pnps
├── hiyacfw_helper.py
└── logo/
    └── logo.xcf
Download .txt
SYMBOL INDEX (103 symbols across 23 files)

FILE: arm7/source/main.c
  function VcountHandler (line 34) | void VcountHandler() { inputGetAndSend(); }
  function main (line 36) | int main(void) {

FILE: arm9/source/bios_decompress_callback.c
  function getSizeBiosCallback (line 21) | static int getSizeBiosCallback (uint8 * source, uint16 * dest, uint32 r2)
  function uint8 (line 28) | static uint8 readByteBiosCallback (uint8 * source)

FILE: arm9/source/dsi_only.cpp
  function dsiOnly_setBrightness (line 5) | static void dsiOnly_setBrightness(u8 screen, s8 bright) {
  function dsiOnly (line 18) | void dsiOnly(void) {

FILE: arm9/source/fileOperations.cpp
  function off_t (line 10) | off_t getFileSize(const char *fileName)

FILE: arm9/source/gif.hpp
  class Gif (line 10) | class Gif {
    type Header (line 11) | struct Header {
    type Frame (line 24) | struct Frame {
      type GraphicsControlExtension (line 25) | struct GraphicsControlExtension {
      type Descriptor (line 48) | struct Descriptor {
      type Image (line 61) | struct Image {
    method Gif (line 97) | Gif() {}
    method Gif (line 98) | Gif(const char *path, bool top, bool animate, bool forceDecompress) { ...
    method Frame (line 103) | Frame &frame(int frame) { return _frames[frame]; }
      type GraphicsControlExtension (line 25) | struct GraphicsControlExtension {
      type Descriptor (line 48) | struct Descriptor {
      type Image (line 61) | struct Image {
    method gct (line 104) | std::vector<u16> gct() { return _gct; }
    method paused (line 106) | bool paused() { return _paused; }
    method pause (line 107) | void pause() { _paused = true; }
    method unpause (line 108) | void unpause() { _paused = false; }
    method toggle (line 109) | void toggle() { _paused = !_paused; }
    method loopForever (line 111) | bool loopForever(void) { return _loopCount == 0xFFFF; }
    method waitingForInput (line 112) | bool waitingForInput(void) { return _waitingForInput; }
    method resume (line 113) | void resume(void) { _waitingForInput = false; _currentDelayProgress = ...
    method finished (line 114) | bool finished(void) { return _finished; }
    method currentFrame (line 116) | int currentFrame(void) { return _currentFrame; }

FILE: arm9/source/inifile.cpp
  function freadLine (line 26) | static bool freadLine(FILE* f,std::string& str)
  function trimString (line 58) | static void trimString(std::string& str)

FILE: arm9/source/inifile.h
  function class (line 28) | class CIniFile

FILE: arm9/source/lzw.cpp
  function u16 (line 3) | u16 LZWReader::readLSB(std::vector<u8>::iterator &begin, const std::vect...

FILE: arm9/source/lzw.hpp
  class LZWReader (line 11) | class LZWReader {

FILE: arm9/source/main.cpp
  function hBlankHandler (line 41) | void hBlankHandler() {
  function loadBMP (line 63) | bool loadBMP(bool top) {
  function bootSplashInit (line 150) | void bootSplashInit() {
  function loadScreen (line 177) | void loadScreen() {
  function loadSettings (line 204) | void loadSettings(void) {
  function saveSettings (line 214) | void saveSettings(void) {
  function setupConsole (line 224) | void setupConsole() {
  function main (line 232) | int main( int argc, char **argv) {

FILE: arm9/source/nds_loader_arm9.c
  type addr_t (line 43) | typedef signed int addr_t;
  type data_t (line 44) | typedef unsigned char data_t;
  function addr_t (line 51) | static addr_t readAddr (data_t *mem, addr_t offset) {
  function writeAddr (line 55) | static void writeAddr (data_t *mem, addr_t offset, addr_t value) {
  function vramcpy (line 59) | static void vramcpy (void* dst, const void* src, int len)
  function runNds (line 69) | int runNds (const void* loader, u32 loaderSize, u32 cluster, bool initDi...
  function runNdsFile (line 146) | int runNdsFile (const char* filename, int argc, const char** argv)  {

FILE: arm9/source/stringtool.cpp
  function formatString (line 40) | std::string formatString( const char* fmt, ... )

FILE: arm9/source/tonccpy.c
  function tonccpy (line 14) | void tonccpy(void *dst, const void *src, uint size)
  function __toncset (line 90) | void __toncset(void *dst, u32 fill, uint size)

FILE: arm9/source/tonccpy.h
  type uint (line 13) | typedef unsigned int uint;
  function u32 (line 15) | static inline u32 quad8(u8 x)   {   x |= x<<8; return x | x<<16;    }
  function toncset (line 29) | static inline void toncset(void *dst, u8 src, uint size)
  function toncset16 (line 33) | static inline void toncset16(void *dst, u16 src, uint size)
  function toncset32 (line 37) | static inline void toncset32(void *dst, u32 src, uint size)

FILE: bootloader/source/arm9clear.arm.c
  function resetMemory2_ARM9 (line 23) | void __attribute__ ((long_call)) __attribute__((naked)) __attribute__((n...
  function startBinary_ARM9 (line 108) | void __attribute__ ((long_call)) __attribute__((noreturn)) __attribute__...

FILE: bootloader/source/boot.c
  function resetMemory_ARM7 (line 84) | void resetMemory_ARM7 (void)
  function loadBinary_ARM7 (line 119) | void loadBinary_ARM7 (u32 fileCluster)
  function startBinary_ARM7 (line 153) | void startBinary_ARM7 (void) {
  function sdmmc_inserted (line 170) | bool sdmmc_inserted() {
  function sdmmc_startup (line 174) | bool sdmmc_startup() {
  function sdmmc_readsectors (line 179) | bool sdmmc_readsectors(u32 sector_no, u32 numsectors, void *out) {
  function main (line 184) | int main (void) {

FILE: bootloader/source/card.h
  function CARD_StartUp (line 29) | static inline bool CARD_StartUp (void) {
  function CARD_IsInserted (line 33) | static inline bool CARD_IsInserted (void) {
  function CARD_ReadSector (line 37) | static inline bool CARD_ReadSector (u32 sector, void *buffer) {
  function CARD_ReadSectors (line 41) | static inline bool CARD_ReadSectors (u32 sector, int count, void *buffer) {

FILE: bootloader/source/disc_io.h
  type IO_INTERFACE_STRUCT (line 69) | struct IO_INTERFACE_STRUCT {
  type IO_INTERFACE (line 80) | typedef struct IO_INTERFACE_STRUCT IO_INTERFACE ;

FILE: bootloader/source/fat.c
  type __PACKED (line 79) | typedef struct
  type __PACKED (line 137) | typedef struct
  type FAT_FILE (line 155) | typedef struct
  function u32 (line 202) | u32 FAT_ClustToSect (u32 cluster) {
  function u32 (line 210) | u32 FAT_NextCluster(u32 cluster)
  function ucase (line 288) | char ucase (char character)
  function FAT_InitFiles (line 301) | bool FAT_InitFiles (bool initCard)
  function u32 (line 411) | u32 fileRead (char* buffer, u32 cluster, u32 startOffset, u32 length)

FILE: bootloader/source/sdmmc.c
  type mmcdevice (line 6) | struct mmcdevice
  function geterror (line 9) | int geterror(struct mmcdevice *ctx) {
  function setTarget (line 18) | void setTarget(struct mmcdevice *ctx) {
  type mmcdevice (line 32) | struct mmcdevice
  function u32 (line 221) | static u32 calcSDSize(u8* csd, int type) {
  function sdmmc_controller_init (line 249) | void sdmmc_controller_init() {
  function sdmmc_sdcard_init (line 298) | int sdmmc_sdcard_init() {
  function sdmmc_sdcard_readsectors (line 391) | int sdmmc_sdcard_readsectors(u32 sector_no, u32 numsectors, void *out) {

FILE: bootloader/source/sdmmc.h
  type mmcdevice (line 107) | typedef struct mmcdevice {
  function sdmmc_nand_cid (line 139) | static inline void sdmmc_nand_cid( u32 *cid) {
  function sdmmc_sdcard_cid (line 143) | static inline void sdmmc_sdcard_cid( u32 *cid) {
  function u16 (line 156) | static inline u16 sdmmc_read16(u16 reg) {
  function sdmmc_write16 (line 162) | static inline void sdmmc_write16(u16 reg, u16 val) {
  function u32 (line 168) | static inline u32 sdmmc_read32(u16 reg) {
  function sdmmc_write32 (line 174) | static inline void sdmmc_write32(u16 reg, u32 val) {
  function sdmmc_mask16 (line 180) | static inline void sdmmc_mask16(u16 reg, u16 clear, u16 set) {
  function setckl (line 190) | static inline void setckl(u32 data) {

FILE: fix_ndsheader.py
  class CRC16 (line 45) | class CRC16(object):
    method __init__ (line 54) | def __init__(self, modbus_flag=False):
    method calculate (line 60) | def calculate(self, input_data=None):
    method init_crc16 (line 81) | def init_crc16(self):
  function getSize (line 93) | def getSize(fileobject):
  function skipUntilAddress (line 100) | def skipUntilAddress(f_in, f_out, caddr, taddr):
  function writeBlankuntilAddress (line 104) | def writeBlankuntilAddress(f_out, caddr, taddr):

FILE: hiyacfw_helper.py
  function unpack_int (line 14) | def unpack_int(string):
  function apply (line 19) | def apply(patchpath, filepath):
Condensed preview — 55 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (227K chars).
[
  {
    "path": ".gitattributes",
    "chars": 378,
    "preview": "# Auto detect text files and perform LF normalization\n* text=auto\n\n# Custom for Visual Studio\n*.cs     diff=csharp\n\n# St"
  },
  {
    "path": ".github/workflows/build.yml",
    "chars": 2504,
    "preview": "name: Build hiyaCFW\n\non:\n  push:\n    branches: [\"*\"]\n    paths-ignore:\n      - 'README.md'\n  pull_request:\n    branches:"
  },
  {
    "path": ".gitignore",
    "chars": 81,
    "preview": "*/build\n*.nds\n*.dsi\n*.cia\n*.elf\ndata/*\n*.DS_Store\n.vscode\narm9/include/version.h\n"
  },
  {
    "path": ".gitmodules",
    "chars": 98,
    "preview": "[submodule \"libs/libslim\"]\n\tpath = libs/libslim\n\turl = https://github.com/DS-Homebrew/libslim.git\n"
  },
  {
    "path": "LICENSE",
    "chars": 35141,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "Makefile",
    "chars": 2591,
    "preview": "#---------------------------------------------------------------------------------\n.SUFFIXES:\n#-------------------------"
  },
  {
    "path": "README.md",
    "chars": 2036,
    "preview": "<p align=\"center\">\n  <img src=\"https://github.com/RocketRobz/hiyaCFW/blob/master/logo/logo.png\"><br>\n  <a href=\"https://"
  },
  {
    "path": "arm7/Makefile",
    "chars": 4899,
    "preview": "#---------------------------------------------------------------------------------\n.SUFFIXES:\n#-------------------------"
  },
  {
    "path": "arm7/source/main.c",
    "chars": 2010,
    "preview": "/*---------------------------------------------------------------------------------\n\ndefault ARM7 core\n\nCopyright (C) 20"
  },
  {
    "path": "arm9/Makefile",
    "chars": 6440,
    "preview": "#---------------------------------------------------------------------------------\n.SUFFIXES:\n#-------------------------"
  },
  {
    "path": "arm9/ds_arm9_hiya.mem",
    "chars": 567,
    "preview": "/*--------------------------------------------------------------------------------\n\tThis Source Code Form is subject to "
  },
  {
    "path": "arm9/ds_arm9_hiya.specs",
    "chars": 165,
    "preview": "%rename link                old_link\n\n*link:\n%(old_link) -T ../ds_arm9_hiya.mem%s -T ds_arm9.ld%s --gc-sections\n\n*startf"
  },
  {
    "path": "arm9/source/bios_decompress_callback.c",
    "chars": 1109,
    "preview": "/*\n    NitroHax -- Cheat tool for the Nintendo DS\n    Copyright (C) 2008  Michael \"Chishm\" Chisholm\n\n    This program is"
  },
  {
    "path": "arm9/source/bios_decompress_callback.h",
    "chars": 1039,
    "preview": "/*\n    NitroHax -- Cheat tool for the Nintendo DS\n    Copyright (C) 2008  Michael \"Chishm\" Chisholm\n\n    This program is"
  },
  {
    "path": "arm9/source/dsi_only.cpp",
    "chars": 1148,
    "preview": "#include <nds.h>\n#include \"dsiOnly_top.h\"\n#include \"dsiOnly_bot.h\"\n\nstatic void dsiOnly_setBrightness(u8 screen, s8 brig"
  },
  {
    "path": "arm9/source/fileOperations.cpp",
    "chars": 385,
    "preview": "#include \"fileOperations.h\"\n#include <nds.h>\n#include <slim.h>\n#include <stdio.h>\n#include <dirent.h>\n#include <vector>\n"
  },
  {
    "path": "arm9/source/fileOperations.h",
    "chars": 123,
    "preview": "#include <nds.h>\n\n#ifndef FILE_COPY\n#define FILE_COPY\n\nextern off_t getFileSize(const char *fileName);\n\n#endif // FILE_C"
  },
  {
    "path": "arm9/source/gif.cpp",
    "chars": 7376,
    "preview": "#include \"gif.hpp\"\n#include \"lzw.hpp\"\n#include \"tonccpy.h\"\n\n#include <stdio.h>\n\nstd::vector<Gif *> Gif::_animating;\n\nvoi"
  },
  {
    "path": "arm9/source/gif.hpp",
    "chars": 2745,
    "preview": "#ifndef GIF_HPP\n#define GIF_HPP\n\n#include <nds/ndstypes.h>\n#include <vector>\n#include <cstddef>\n\ntypedef unsigned int ui"
  },
  {
    "path": "arm9/source/inifile.cpp",
    "chars": 8999,
    "preview": "/*\n    inifile.cpp\n    Copyright (C) 2007 Acekard, www.acekard.com\n    Copyright (C) 2007-2009 somebody\n    Copyright (C"
  },
  {
    "path": "arm9/source/inifile.h",
    "chars": 2568,
    "preview": "/*\n    inifile.h\n    Copyright (C) 2007 Acekard, www.acekard.com\n    Copyright (C) 2007-2009 somebody\n    Copyright (C) "
  },
  {
    "path": "arm9/source/lzw.cpp",
    "chars": 2957,
    "preview": "#include \"lzw.hpp\"\n\nu16 LZWReader::readLSB(std::vector<u8>::iterator &begin, const std::vector<u8>::iterator &end) {\n\twh"
  },
  {
    "path": "arm9/source/lzw.hpp",
    "chars": 931,
    "preview": "#ifndef LZW_HPP\n#define LZW_HPP\n\n#include <nds.h>\n#include <functional>\n#include <vector>\n\ntypedef unsigned int uint;\nty"
  },
  {
    "path": "arm9/source/main.cpp",
    "chars": 19728,
    "preview": "#include <dirent.h>\n#include <nds.h>\n#include <slim.h>\n#include <stdarg.h>\n#include <stdio.h>\n\n#include \"bios_decompress"
  },
  {
    "path": "arm9/source/nds_loader_arm9.c",
    "chars": 4400,
    "preview": "/*-----------------------------------------------------------------\n Copyright (C) 2005 - 2010\n\tMichael \"Chishm\" Chishol"
  },
  {
    "path": "arm9/source/nds_loader_arm9.h",
    "chars": 1268,
    "preview": "/*-----------------------------------------------------------------\n Copyright (C) 2005 - 2010\n\tMichael \"Chishm\" Chishol"
  },
  {
    "path": "arm9/source/stringtool.cpp",
    "chars": 1663,
    "preview": "/*---------------------------------------------------------------------------------\n\n\nCopyright (C) 2007 Acekard, www.ac"
  },
  {
    "path": "arm9/source/stringtool.h",
    "chars": 1391,
    "preview": "/*---------------------------------------------------------------------------------\n\n\nCopyright (C) 2007 Acekard, www.ac"
  },
  {
    "path": "arm9/source/tonccpy.c",
    "chars": 3311,
    "preview": "#include \"tonccpy.h\"\n//# tonccpy.c\n\n//! VRAM-safe cpy.\n/*! This version mimics memcpy in functionality, with \n    the be"
  },
  {
    "path": "arm9/source/tonccpy.h",
    "chars": 1123,
    "preview": "//# Stuff you may not have yet.\n\n#ifndef TONCCPY_H\n#define TONCCPY_H\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include "
  },
  {
    "path": "bootloader/Makefile",
    "chars": 4392,
    "preview": "#---------------------------------------------------------------------------------\n.SUFFIXES:\n#-------------------------"
  },
  {
    "path": "bootloader/arm9code/mpu_reset.s",
    "chars": 3478,
    "preview": "/*\n\tCopyright 2006 - 2015 Dave Murphy (WinterMute)\n\n\tThis program is free software: you can redistribute it and/or modif"
  },
  {
    "path": "bootloader/load.ld",
    "chars": 4989,
    "preview": "OUTPUT_FORMAT(\"elf32-littlearm\", \"elf32-bigarm\", \"elf32-littlearm\")\nOUTPUT_ARCH(arm)\nENTRY(_start)\n\nMEMORY {\n\n\tvram\t: OR"
  },
  {
    "path": "bootloader/source/arm7clear.s",
    "chars": 1821,
    "preview": "/*-----------------------------------------------------------------\n\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n Th"
  },
  {
    "path": "bootloader/source/arm9clear.arm.c",
    "chars": 2959,
    "preview": "#define ARM9\n#undef ARM7\n\n#include <nds/ndstypes.h>\n#include <nds/dma.h>\n#include <nds/system.h>\n#include <nds/interrupt"
  },
  {
    "path": "bootloader/source/arm9mpu_reset.s",
    "chars": 92,
    "preview": "\t.arm\n\t.global mpu_reset, mpu_reset_end\n\nmpu_reset:\n\t.incbin \"mpu_reset.bin\"\nmpu_reset_end:\n"
  },
  {
    "path": "bootloader/source/bios.s",
    "chars": 334,
    "preview": "\t.text\n\t.align 4\n\n\t.thumb\n\n@---------------------------------------------------------------------------------\n\t.global s"
  },
  {
    "path": "bootloader/source/boot.c",
    "chars": 6622,
    "preview": "/*-----------------------------------------------------------------\n boot.c\n \n BootLoader\n Loads a file into memory and "
  },
  {
    "path": "bootloader/source/boot.h",
    "chars": 509,
    "preview": "#ifndef _BOOT_H_\n#define _BOOT_H_\n\n#define initMBK_ARM9_size 0x400\nvoid __attribute__ ((long_call)) __attribute__((noret"
  },
  {
    "path": "bootloader/source/card.h",
    "chars": 1483,
    "preview": "/*-----------------------------------------------------------------\n\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n Th"
  },
  {
    "path": "bootloader/source/disc_io.h",
    "chars": 3164,
    "preview": "/*\n disc_io.h\n Interface template for low level disc functions.\n\n Copyright (c) 2006 Michael \"Chishm\" Chisholm\n\t\n Redist"
  },
  {
    "path": "bootloader/source/fat.c",
    "chars": 12461,
    "preview": "/*-----------------------------------------------------------------\n fat.c\n \n NDS MP\n GBAMP NDS Firmware Hack Version 2."
  },
  {
    "path": "bootloader/source/fat.h",
    "chars": 1547,
    "preview": "/*-----------------------------------------------------------------\n fat.h\n \n NDS MP\n GBAMP NDS Firmware Hack Version 2."
  },
  {
    "path": "bootloader/source/io_dldi.h",
    "chars": 1723,
    "preview": "/*\n io_dldi.h \n\n Reserved space for post-compilation adding of an extra driver\n\n Copyright (c) 2006 Michael \"Chishm\" Chi"
  },
  {
    "path": "bootloader/source/io_dldi.s",
    "chars": 4173,
    "preview": "/*-----------------------------------------------------------------\n\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n Th"
  },
  {
    "path": "bootloader/source/load_crt0.s",
    "chars": 4541,
    "preview": "/*-----------------------------------------------------------------\n\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n Th"
  },
  {
    "path": "bootloader/source/sdmmc.c",
    "chars": 11794,
    "preview": "#ifndef NO_SDMMC\n#include <nds/bios.h>\n#include \"sdmmc.h\"\n#include <stddef.h>\n\nstatic struct mmcdevice deviceSD;\n\n//----"
  },
  {
    "path": "bootloader/source/sdmmc.h",
    "chars": 6294,
    "preview": "#ifndef __SDMMC_H__\n#define __SDMMC_H__\n\n#include <nds/ndstypes.h>\n\n#define DATA32_SUPPORT\n\n#define SDMMC_BASE\t0x0400480"
  },
  {
    "path": "fix_ndsheader.py",
    "chars": 11086,
    "preview": "# -*- coding: utf8 -*-\n# Patch an .nds (works with homebrew and ds demo only) to make it ready for make_cia\n#\n# 2016-02-"
  },
  {
    "path": "hiyaCFW.pnproj",
    "chars": 972,
    "preview": "<Project name=\"hiyaCFW\"><MagicFolder excludeFolders=\"CVS;.svn\" filter=\"*\" name=\"arm9\" path=\"arm9\\\"><MagicFolder excludeF"
  },
  {
    "path": "hiyaCFW.pnps",
    "chars": 223,
    "preview": "<pd><ViewState><e p=\"hiyaCFW\\arm9\" x=\"true\"></e><e p=\"hiyaCFW\\arm9\\graphics_xcf\" x=\"false\"></e><e p=\"hiyaCFW\\arm9\\source"
  },
  {
    "path": "hiyacfw_helper.py",
    "chars": 5745,
    "preview": "import hashlib\nimport os\nimport sys\nimport subprocess\n\n# use apply ips function for https://github.com/meunierd/python-i"
  }
]

// ... and 3 more files (download for full content)

About this extraction

This page contains the full source code of the RocketRobz/hiyaCFW GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 55 files (204.7 KB), approximately 60.6k tokens, and a symbol index with 103 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!