<commit_before>/*****************************************************************************

YASK: Yet Another Stencil Kernel
Copyright (c) 2014-2018, Intel Corporation

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.

*****************************************************************************/

/////////////// Main vector-folding code-generation code. /////////////

// YASK compiler-solution code.
#include "Soln.hpp"
#include "CppIntrin.hpp"
#include "Parse.hpp"

using namespace yask;

// output streams.
map<string, string> outfiles;

// other vars set via cmd-line options.
CompilerSettings settings;
int vlenForStats = 0;
StencilBase* stencilSoln = NULL;
string solutionName;
int radius = 1;

void usage(const string& cmd) {

    cout << "Options:\n"
        " -h\n"
        "     Print this help message.\n"
        "\n"
        " -stencil <name>\n"
        "     Select stencil solution (required)\n";
    for (bool show_test : { false, true }) {
        if (show_test)
            cout << "       Built-in test solutions:\n";
        else
            cout << "       Built-in example solutions:\n";
        for (auto si : stencils) {
            auto name = si.first;
            if ((name.rfind("test_", 0) == 0) == show_test) {
                auto sp = si.second;
                cout << "           " << name;
                if (sp->usesRadius())
                    cout << " *";
                cout << endl;
            }
        }
    }
    cout <<
        " -radius <radius>\n"
        "     Set radius for stencils marked with '*' above (default=" << radius << ").\n"
        "\n"
        " -elem-bytes <n>"
        "    Set number of bytes in each FP element (default=" << settings._elem_bytes << ").\n"
        " -fold <dim>=<size>,...\n"
        "    Set number of elements in each given dimension in a vector block.\n"
        "    Default depends on -elem-bytes setting and print format (below).\n"
        "    If product of fold lengths does not equal SIMD vector length for print\n"
        "      formats with explicit lengths, lengths will adjusted as needed.\n"
        " -cluster <dim>=<size>,...\n"
        "    Set number of vectors to evaluate in each dimension.\n"
        " -grids <regex>\n"
        "    Only process updates to grids whose names match <regex>.\n"
        "      This can be used to generate code for a subset of the stencil equations.\n"
        " -eq-bundles <name>=<regex>,...\n"
        "    Put updates to grids matching <regex> in equation-bundle with base-name <name>.\n"
        "      By default, eq-bundles are created as needed based on dependencies between equations:\n"
        "        equations that do not depend on each other are bundled together into bundles with the\n"
        "        base-name '" << settings._eq_bundle_basename_default << "'.\n"
        "      Each eq-bundle base-name is appended with a unique index number, so the default bundle\n"
        "        names are '" << settings._eq_bundle_basename_default << "_0', " <<
        settings._eq_bundle_basename_default << "_1', etc.\n"
        "      This option allows more control over this bundling.\n"
        "      Example: \"-eq-bundles a=foo,b=b[aeiou]r\" creates one or more eq-bundles named 'a_0', 'a_1', etc.\n"
        "        containing updates to each grid whose name contains 'foo' and one or more eq-bundles\n"
        "        named 'b_0', 'b_1', etc. containing updates to each grid whose name matches 'b[aeiou]r'.\n"
        "      Standard regex-format tokens in <name> will be replaced based on matches to <regex>.\n"
        "      Example: \"-eq-bundles 'g_$&=b[aeiou]r'\" with grids 'bar_x', 'bar_y', 'ber_x', and 'ber_y'\n"
        "        would create eq-bundle 'g_bar_0' for grids 'bar_x' and 'bar_y' and eq-bundle 'g_ber_0' for\n"
        "        grids 'ber_x' and 'ber_y' because '$&' is substituted by the string that matches the regex.\n"
        " [-no]-bundle-scratch\n"
        "    Bundle scratch equations even if the sizes of their scratch grids must be increased\n"
        "      to do so (default=" << settings._bundleScratch << ").\n"
        " -step-alloc <size>\n"
        "    Specify the size of the step-dimension memory allocation.\n"
        "      By default, allocations are calculated automatically for each grid.\n"
        " -halo <size>\n"
        "    Specify the sizes of the halos.\n"
        "      By default, halos are calculated automatically for each grid.\n"
        " -fus\n"
        "    Make first dimension of fold unit stride (default=" << settings._firstInner << ").\n"
        "      This controls the intra-vector memory layout.\n"
        " -lus\n"
        "    Make last dimension of fold unit stride (default=" << (!settings._firstInner) << ").\n"
        "      This controls the intra-vector memory layout.\n"
        " [-no]-ul\n"
        "    Do [not] generate simple unaligned loads (default=" <<
        settings._allowUnalignedLoads << ").\n"
        "      [Advanced] To use this correctly, only 1D folds are allowed, and\n"
        "        the memory layout used by YASK must have that same dimension in unit stride.\n"
        " [-no]-opt-comb\n"
        "    Do [not] combine commutative operations (default=" << settings._doComb << ").\n"
        " [-no]-opt-cse\n"
        "    Do [not] eliminate common subexpressions (default=" << settings._doCse << ").\n"
        " [-no]-opt-cluster\n"
        "    Do [not] apply optimizations across the cluster (default=" << settings._doOptCluster << ").\n"
        " -max-es <num-nodes>\n"
        "    Set heuristic for max single expression-size (default=" << settings._maxExprSize << ").\n"
        " -min-es <num-nodes>\n"
        "    Set heuristic for min expression-size for reuse (default=" << settings._minExprSize << ").\n"
        " [-no]-find-deps\n"
        "    Find dependencies between stencil equations (default=" << settings._findDeps << ").\n"
        " [-no]-print-eqs\n"
        "    Print each equation when defined (default=" << settings._printEqs << ").\n"
        "\n"
        " -p <format-type> <filename>\n"
        "    Format output per <format-type> and write to <filename>.\n"
        "    Supported format-types:\n"
        "      cpp       YASK stencil classes for generic C++ (no explicit HW SIMD vectors).\n"
        "      avx       YASK stencil classes for CORE AVX ISA (256-bit HW SIMD vectors).\n"
        "      avx2      YASK stencil classes for CORE AVX2 ISA (256-bit HW SIMD vectors).\n"
        "      avx512    YASK stencil classes for CORE AVX-512 & MIC AVX-512 ISAs (512-bit HW SIMD vectors).\n"
        "      knc       YASK stencil classes for KNC ISA (512-bit HW SIMD vectors).\n"
        "      pseudo    Human-readable scalar pseudo-code for one point.\n"
        "      dot       DOT-language description.\n"
        "      dot-lite  DOT-language description of grid accesses only.\n"
        //"      pov-ray    POV-Ray code.\n"
        //" -ps <vec-len>         Print stats for all folding options for given vector length.\n"
        "\n"
        "Examples:\n"
        " " << cmd << " -stencil 3axis -radius 2 -fold x=4,y=4 -p pseudo -  # '-' for stdout\n"
        " " << cmd << " -stencil awp -elem-bytes 8 -fold x=4,y=2 -p avx2 stencil_code.hpp\n"
        " " << cmd << " -stencil iso3dfd -radius 8 -cluster y=2 -p avx512 stencil_code.hpp\n";
    exit(1);
}

// Parse command-line and set global cmd-line option vars.
// Exits on error.
void parseOpts(int argc, const char* argv[])
{
    if (argc <= 1)
        usage(argv[0]);

    int argi;               // current arg index.
    for (argi = 1; argi < argc; argi++) {
        if ( argv[argi][0] == '-' && argv[argi][1] ) {
            string opt = argv[argi];

            // options w/o values.
            if (opt == "-h" || opt == "-help" || opt == "--help")
                usage(argv[0]);

            else if (opt == "-fus")
                settings._firstInner = true;
            else if (opt == "-lus")
                settings._firstInner = false;
            else if (opt == "-ul")
                settings._allowUnalignedLoads = true;
            else if (opt == "-no-ul")
                settings._allowUnalignedLoads = false;
            else if (opt == "-opt-comb")
                settings._doComb = true;
            else if (opt == "-no-opt-comb")
                settings._doComb = false;
            else if (opt == "-opt-cse")
                settings._doCse = true;
            else if (opt == "-no-opt-cse")
                settings._doCse = false;
            else if (opt == "-opt-cluster")
                settings._doOptCluster = true;
            else if (opt == "-no-opt-cluster")
                settings._doOptCluster = false;
            else if (opt == "-find-deps")
                settings._findDeps = true;
            else if (opt == "-no-find-deps")
                settings._findDeps = false;
            else if (opt == "-bundle-scratch")
                settings._bundleScratch = true;
            else if (opt == "-no-bundle-scratch")
                settings._bundleScratch = false;
            else if (opt == "-print-eqs")
                settings._printEqs = true;
            else if (opt == "-no-print-eqs")
                settings._printEqs = false;

            // add any more options w/o values above.

            // options w/a value.
            else {

                // at least one value needed.
                if (argi + 1 >= argc) {
                    cerr << "Error: value missing or bad option '" << opt << "'." << endl;
                    usage(argv[0]);
                }
                string argop = argv[++argi];

                // options w/a string value.
                if (opt == "-stencil")
                    solutionName = argop;
                else if (opt == "-grids")
                    settings._gridRegex = argop;
                else if (opt == "-eq-bundles")
                    settings._eqBundleTargets = argop;
                else if (opt == "-fold" || opt == "-cluster") {

                    // example: x=4,y=2
                    ArgParser ap;
                    ap.parseKeyValuePairs
                        (argop, [&](const string& key, const string& value) {
                            int size = atoi(value.c_str());

                            // set dim in tuple.
                            if (opt == "-fold")
                                settings._foldOptions.addDimBack(key, size);
                            else
                                settings._clusterOptions.addDimBack(key, size);
                        });
                }

                // Print options w/format & filename args.
                else if (opt == "-p") {

                    // another arg needed.
                    if (argi + 1 >= argc) {
                        cerr << "Error: filename missing after '" << opt <<
                            " " << argop << "'." << endl;
                        usage(argv[0]);
                    }
                    string argop2 = argv[++argi];
                    outfiles[argop] = argop2;
                }

                // add any more options w/a string value above.

                else {

                    // options w/an int value.
                    int val = atoi(argop.c_str());

                    if (opt == "-max-es")
                        settings._maxExprSize = val;
                    else if (opt == "-min-es")
                        settings._minExprSize = val;

                    else if (opt == "-radius")
                        radius = val;
                    else if (opt == "-elem-bytes")
                        settings._elem_bytes = val;

                    else if (opt == "-ps")
                        vlenForStats = val;

                    else if (opt == "-halo")
                        settings._haloSize = val;
                    else if (opt == "-step-alloc")
                        settings._stepAlloc = val;

                    // add any more options w/int values here.

                    else {
                        cerr << "Error: option '" << opt << "' not recognized." << endl;
                        usage(argv[0]);
                    }
                }
            }
        }
        else break;
    }
    if (argi < argc) {
        cerr << "Error: unrecognized parameter '" << argv[argi] << "'." << endl;
        usage(argv[0]);
    }
    if (solutionName.length() == 0) {
        cerr << "Error: solution not specified." << endl;
        usage(argv[0]);
    }

    // Find the stencil in the registry.
    auto stencilIter = stencils.find(solutionName);
    if (stencilIter == stencils.end()) {
        cerr << "Error: unknown stencil solution '" << solutionName << "'." << endl;
        usage(argv[0]);
    }
    stencilSoln = stencilIter->second;
    assert(stencilSoln);

    cout << "Stencil-solution name: " << solutionName << endl;
    if (stencilSoln->usesRadius()) {
        bool rOk = stencilSoln->setRadius(radius);
        if (!rOk) {
            cerr << "Error: invalid radius=" << radius << " for stencil type '" <<
                solutionName << "'." << endl;
            usage(argv[0]);
        }
        cout << "Stencil radius: " << radius << endl;
    }

    // Copy cmd-line settings into solution.
    stencilSoln->getSettings() = settings;
}

// Main program.
int main(int argc, const char* argv[]) {

    cout << "YASK -- Yet Another Stencil Kernel\n"
        "YASK Stencil Compiler\n"
        "Copyright (c) 2014-2018, Intel Corporation.\n"
        "Version: " << yask_get_version_string() << endl;

    try {
		// Parse options and create the stencil-solution object.
		parseOpts(argc, argv);

		// Create the requested output...
		for (auto i : outfiles) {
			auto& type = i.first;
			auto& fname = i.second;

			yask_output_factory ofac;
			yask_output_ptr os;
			if (fname == "-")
				os = ofac.new_stdout_output();
			else
				os = ofac.new_file_output(fname);
			stencilSoln->format(type, os);
		}
    } catch (yask_exception e) {
        cerr << "YASK Stencil Compiler: " << e.get_message() << ".\n";
        exit(1);
    }

    cout << "YASK Stencil Compiler: done.\n";
    return 0;
}
<commit_msg>Cleanup indentation.<commit_after>/*****************************************************************************

YASK: Yet Another Stencil Kernel
Copyright (c) 2014-2018, Intel Corporation

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.

*****************************************************************************/

/////////////// Main vector-folding code-generation code. /////////////

// YASK compiler-solution code.
#include "Soln.hpp"
#include "CppIntrin.hpp"
#include "Parse.hpp"

using namespace yask;

// output streams.
map<string, string> outfiles;

// other vars set via cmd-line options.
CompilerSettings settings;
int vlenForStats = 0;
StencilBase* stencilSoln = NULL;
string solutionName;
int radius = 1;

void usage(const string& cmd) {

    cout << "Options:\n"
        " -h\n"
        "     Print this help message.\n"
        "\n"
        " -stencil <name>\n"
        "     Select stencil solution (required)\n";
    for (bool show_test : { false, true }) {
        if (show_test)
            cout << "       Built-in test solutions:\n";
        else
            cout << "       Built-in example solutions:\n";
        for (auto si : stencils) {
            auto name = si.first;
            if ((name.rfind("test_", 0) == 0) == show_test) {
                auto sp = si.second;
                cout << "           " << name;
                if (sp->usesRadius())
                    cout << " *";
                cout << endl;
            }
        }
    }
    cout <<
        " -radius <radius>\n"
        "     Set radius for stencils marked with '*' above (default=" << radius << ").\n"
        "\n"
        " -elem-bytes <n>"
        "    Set number of bytes in each FP element (default=" << settings._elem_bytes << ").\n"
        " -fold <dim>=<size>,...\n"
        "    Set number of elements in each given dimension in a vector block.\n"
        "    Default depends on -elem-bytes setting and print format (below).\n"
        "    If product of fold lengths does not equal SIMD vector length for print\n"
        "      formats with explicit lengths, lengths will adjusted as needed.\n"
        " -cluster <dim>=<size>,...\n"
        "    Set number of vectors to evaluate in each dimension.\n"
        " -grids <regex>\n"
        "    Only process updates to grids whose names match <regex>.\n"
        "      This can be used to generate code for a subset of the stencil equations.\n"
        " -eq-bundles <name>=<regex>,...\n"
        "    Put updates to grids matching <regex> in equation-bundle with base-name <name>.\n"
        "      By default, eq-bundles are created as needed based on dependencies between equations:\n"
        "        equations that do not depend on each other are bundled together into bundles with the\n"
        "        base-name '" << settings._eq_bundle_basename_default << "'.\n"
        "      Each eq-bundle base-name is appended with a unique index number, so the default bundle\n"
        "        names are '" << settings._eq_bundle_basename_default << "_0', " <<
        settings._eq_bundle_basename_default << "_1', etc.\n"
        "      This option allows more control over this bundling.\n"
        "      Example: \"-eq-bundles a=foo,b=b[aeiou]r\" creates one or more eq-bundles named 'a_0', 'a_1', etc.\n"
        "        containing updates to each grid whose name contains 'foo' and one or more eq-bundles\n"
        "        named 'b_0', 'b_1', etc. containing updates to each grid whose name matches 'b[aeiou]r'.\n"
        "      Standard regex-format tokens in <name> will be replaced based on matches to <regex>.\n"
        "      Example: \"-eq-bundles 'g_$&=b[aeiou]r'\" with grids 'bar_x', 'bar_y', 'ber_x', and 'ber_y'\n"
        "        would create eq-bundle 'g_bar_0' for grids 'bar_x' and 'bar_y' and eq-bundle 'g_ber_0' for\n"
        "        grids 'ber_x' and 'ber_y' because '$&' is substituted by the string that matches the regex.\n"
        " [-no]-bundle-scratch\n"
        "    Bundle scratch equations even if the sizes of their scratch grids must be increased\n"
        "      to do so (default=" << settings._bundleScratch << ").\n"
        " -step-alloc <size>\n"
        "    Specify the size of the step-dimension memory allocation.\n"
        "      By default, allocations are calculated automatically for each grid.\n"
        " -halo <size>\n"
        "    Specify the sizes of the halos.\n"
        "      By default, halos are calculated automatically for each grid.\n"
        " -fus\n"
        "    Make first dimension of fold unit stride (default=" << settings._firstInner << ").\n"
        "      This controls the intra-vector memory layout.\n"
        " -lus\n"
        "    Make last dimension of fold unit stride (default=" << (!settings._firstInner) << ").\n"
        "      This controls the intra-vector memory layout.\n"
        " [-no]-ul\n"
        "    Do [not] generate simple unaligned loads (default=" <<
        settings._allowUnalignedLoads << ").\n"
        "      [Advanced] To use this correctly, only 1D folds are allowed, and\n"
        "        the memory layout used by YASK must have that same dimension in unit stride.\n"
        " [-no]-opt-comb\n"
        "    Do [not] combine commutative operations (default=" << settings._doComb << ").\n"
        " [-no]-opt-cse\n"
        "    Do [not] eliminate common subexpressions (default=" << settings._doCse << ").\n"
        " [-no]-opt-cluster\n"
        "    Do [not] apply optimizations across the cluster (default=" << settings._doOptCluster << ").\n"
        " -max-es <num-nodes>\n"
        "    Set heuristic for max single expression-size (default=" << settings._maxExprSize << ").\n"
        " -min-es <num-nodes>\n"
        "    Set heuristic for min expression-size for reuse (default=" << settings._minExprSize << ").\n"
        " [-no]-find-deps\n"
        "    Find dependencies between stencil equations (default=" << settings._findDeps << ").\n"
        " [-no]-print-eqs\n"
        "    Print each equation when defined (default=" << settings._printEqs << ").\n"
        "\n"
        " -p <format-type> <filename>\n"
        "    Format output per <format-type> and write to <filename>.\n"
        "    Supported format-types:\n"
        "      cpp       YASK stencil classes for generic C++ (no explicit HW SIMD vectors).\n"
        "      avx       YASK stencil classes for CORE AVX ISA (256-bit HW SIMD vectors).\n"
        "      avx2      YASK stencil classes for CORE AVX2 ISA (256-bit HW SIMD vectors).\n"
        "      avx512    YASK stencil classes for CORE AVX-512 & MIC AVX-512 ISAs (512-bit HW SIMD vectors).\n"
        "      knc       YASK stencil classes for KNC ISA (512-bit HW SIMD vectors).\n"
        "      pseudo    Human-readable scalar pseudo-code for one point.\n"
        "      dot       DOT-language description.\n"
        "      dot-lite  DOT-language description of grid accesses only.\n"
        //"      pov-ray    POV-Ray code.\n"
        //" -ps <vec-len>         Print stats for all folding options for given vector length.\n"
        "\n"
        "Examples:\n"
        " " << cmd << " -stencil 3axis -radius 2 -fold x=4,y=4 -p pseudo -  # '-' for stdout\n"
        " " << cmd << " -stencil awp -elem-bytes 8 -fold x=4,y=2 -p avx2 stencil_code.hpp\n"
        " " << cmd << " -stencil iso3dfd -radius 8 -cluster y=2 -p avx512 stencil_code.hpp\n";
    exit(1);
}

// Parse command-line and set global cmd-line option vars.
// Exits on error.
void parseOpts(int argc, const char* argv[])
{
    if (argc <= 1)
        usage(argv[0]);

    int argi;               // current arg index.
    for (argi = 1; argi < argc; argi++) {
        if ( argv[argi][0] == '-' && argv[argi][1] ) {
            string opt = argv[argi];

            // options w/o values.
            if (opt == "-h" || opt == "-help" || opt == "--help")
                usage(argv[0]);

            else if (opt == "-fus")
                settings._firstInner = true;
            else if (opt == "-lus")
                settings._firstInner = false;
            else if (opt == "-ul")
                settings._allowUnalignedLoads = true;
            else if (opt == "-no-ul")
                settings._allowUnalignedLoads = false;
            else if (opt == "-opt-comb")
                settings._doComb = true;
            else if (opt == "-no-opt-comb")
                settings._doComb = false;
            else if (opt == "-opt-cse")
                settings._doCse = true;
            else if (opt == "-no-opt-cse")
                settings._doCse = false;
            else if (opt == "-opt-cluster")
                settings._doOptCluster = true;
            else if (opt == "-no-opt-cluster")
                settings._doOptCluster = false;
            else if (opt == "-find-deps")
                settings._findDeps = true;
            else if (opt == "-no-find-deps")
                settings._findDeps = false;
            else if (opt == "-bundle-scratch")
                settings._bundleScratch = true;
            else if (opt == "-no-bundle-scratch")
                settings._bundleScratch = false;
            else if (opt == "-print-eqs")
                settings._printEqs = true;
            else if (opt == "-no-print-eqs")
                settings._printEqs = false;

            // add any more options w/o values above.

            // options w/a value.
            else {

                // at least one value needed.
                if (argi + 1 >= argc) {
                    cerr << "Error: value missing or bad option '" << opt << "'." << endl;
                    usage(argv[0]);
                }
                string argop = argv[++argi];

                // options w/a string value.
                if (opt == "-stencil")
                    solutionName = argop;
                else if (opt == "-grids")
                    settings._gridRegex = argop;
                else if (opt == "-eq-bundles")
                    settings._eqBundleTargets = argop;
                else if (opt == "-fold" || opt == "-cluster") {

                    // example: x=4,y=2
                    ArgParser ap;
                    ap.parseKeyValuePairs
                        (argop, [&](const string& key, const string& value) {
                            int size = atoi(value.c_str());

                            // set dim in tuple.
                            if (opt == "-fold")
                                settings._foldOptions.addDimBack(key, size);
                            else
                                settings._clusterOptions.addDimBack(key, size);
                        });
                }

                // Print options w/format & filename args.
                else if (opt == "-p") {

                    // another arg needed.
                    if (argi + 1 >= argc) {
                        cerr << "Error: filename missing after '" << opt <<
                            " " << argop << "'." << endl;
                        usage(argv[0]);
                    }
                    string argop2 = argv[++argi];
                    outfiles[argop] = argop2;
                }

                // add any more options w/a string value above.

                else {

                    // options w/an int value.
                    int val = atoi(argop.c_str());

                    if (opt == "-max-es")
                        settings._maxExprSize = val;
                    else if (opt == "-min-es")
                        settings._minExprSize = val;

                    else if (opt == "-radius")
                        radius = val;
                    else if (opt == "-elem-bytes")
                        settings._elem_bytes = val;

                    else if (opt == "-ps")
                        vlenForStats = val;

                    else if (opt == "-halo")
                        settings._haloSize = val;
                    else if (opt == "-step-alloc")
                        settings._stepAlloc = val;

                    // add any more options w/int values here.

                    else {
                        cerr << "Error: option '" << opt << "' not recognized." << endl;
                        usage(argv[0]);
                    }
                }
            }
        }
        else break;
    }
    if (argi < argc) {
        cerr << "Error: unrecognized parameter '" << argv[argi] << "'." << endl;
        usage(argv[0]);
    }
    if (solutionName.length() == 0) {
        cerr << "Error: solution not specified." << endl;
        usage(argv[0]);
    }

    // Find the stencil in the registry.
    auto stencilIter = stencils.find(solutionName);
    if (stencilIter == stencils.end()) {
        cerr << "Error: unknown stencil solution '" << solutionName << "'." << endl;
        usage(argv[0]);
    }
    stencilSoln = stencilIter->second;
    assert(stencilSoln);

    cout << "Stencil-solution name: " << solutionName << endl;
    if (stencilSoln->usesRadius()) {
        bool rOk = stencilSoln->setRadius(radius);
        if (!rOk) {
            cerr << "Error: invalid radius=" << radius << " for stencil type '" <<
                solutionName << "'." << endl;
            usage(argv[0]);
        }
        cout << "Stencil radius: " << radius << endl;
    }

    // Copy cmd-line settings into solution.
    stencilSoln->getSettings() = settings;
}

// Main program.
int main(int argc, const char* argv[]) {

    cout << "YASK -- Yet Another Stencil Kernel\n"
        "YASK Stencil Compiler\n"
        "Copyright (c) 2014-2018, Intel Corporation.\n"
        "Version: " << yask_get_version_string() << endl;

    try {
        // Parse options and create the stencil-solution object.
        parseOpts(argc, argv);

        // Create the requested output...
        for (auto i : outfiles) {
            auto& type = i.first;
            auto& fname = i.second;

            yask_output_factory ofac;
            yask_output_ptr os;
            if (fname == "-")
                os = ofac.new_stdout_output();
            else
                os = ofac.new_file_output(fname);
            stencilSoln->format(type, os);
        }
    } catch (yask_exception e) {
        cerr << "YASK Stencil Compiler: " << e.get_message() << ".\n";
        exit(1);
    }

    cout << "YASK Stencil Compiler: done.\n";
    return 0;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <iostream>

#include <cxxopts.hpp>

#include "ast.h"
#include "gen.h"

using namespace std;

extern FILE *yyin, *yyout;

extern int yyparse();

extern NBlock *programBlock;

int main(int argc, char **argv) {
  cxxopts::Options options("The xy Language Compiler",
                           "A toy complier based on LLVM JIT.");
  options.add_options()("d,debug", "Enable debugging")(
      "f,file", "Input file name", cxxopts::value<std::string>())(
      "o,output", "Output file name", cxxopts::value<std::string>())(
      "v,verbose", "Verbose output",
      cxxopts::value<bool>()->default_value("false"))("h,help", "Print usage");

  auto result = options.parse(argc, argv);

  if (result.count("help")) {
    std::cout << options.help() << std::endl;
    exit(0);
  }
  if (result.count("file")) {
    auto inputFilePath = result["f,file"].as<std::string>();
    fopen_s(&yyin, inputFilePath.c_str(), "r");
  }
  if (result.count("output")) {
    auto outputFilePath = result["o,output"].as<std::string>();
    fopen_s(&yyout, outputFilePath.c_str(), "w");
  }

  yyparse();
  std::cout << programBlock << endl;
  InitializeNativeTarget();
  InitializeNativeTargetAsmPrinter();
  InitializeNativeTargetAsmParser();
  CodeGenContext context;
  context.generateCode(*programBlock);
  context.runCode();

  std::cout << "Exiting...\n";

  return 0;
}
<commit_msg>update<commit_after>#if defined(__STDC_LIB_EXT1__)
#define __STDC_WANT_LIB_EXT1__ 1
#endif

#include <cstdio>
#include <cstdlib>
#include <iostream>

#include <cxxopts.hpp>

#include "ast.h"
#include "gen.h"

using namespace std;

extern FILE *yyin, *yyout;

extern int yyparse();

extern NBlock *programBlock;

int main(int argc, char **argv) {
  cxxopts::Options options("The xy Language Compiler",
                           "A toy complier based on LLVM JIT.");
  options.add_options()("d,debug", "Enable debugging")(
      "f,file", "Input file name", cxxopts::value<std::string>())(
      "o,output", "Output file name", cxxopts::value<std::string>())(
      "v,verbose", "Verbose output",
      cxxopts::value<bool>()->default_value("false"))("h,help", "Print usage");

  auto result = options.parse(argc, argv);

  if (result.count("help")) {
    std::cout << options.help() << std::endl;
    exit(0);
  }
  if (result.count("file")) {
    auto inputFilePath = result["f,file"].as<std::string>();
#if defined(__STDC_LIB_EXT1__)
    fopen_s(&yyin, inputFilePath.c_str(), "r");
#else
    yyin = fopen(inputFilePath.c_str(), "r");
#endif
  }
  if (result.count("output")) {
    auto outputFilePath = result["o,output"].as<std::string>();
#if defined(__STDC_LIB_EXT1__)
    fopen_s(&yyout, outputFilePath.c_str(), "w");
#else
    yyout = fopen(outputFilePath.c_str(), "w");
#endif
  }

  yyparse();
  std::cout << programBlock << endl;
  InitializeNativeTarget();
  InitializeNativeTargetAsmPrinter();
  InitializeNativeTargetAsmParser();
  CodeGenContext context;
  context.generateCode(*programBlock);
  context.runCode();

  std::cout << "Exiting...\n";

  return 0;
}
<|endoftext|>


<commit_before>/*
 *
 * bitcoin_transaction_tests.cpp
 * ledger-core
 *
 * Created by Pierre Pollastri on 28/03/2018.
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Ledger
 *
 * 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 "BaseFixture.h"
#include "../fixtures/medium_xpub_fixtures.h"
#include <wallet/bitcoin/transaction_builders/BitcoinLikeTransactionBuilder.h>

struct BitcoinMakeTransaction : public BaseFixture {

    void SetUp() override {
        BaseFixture::SetUp();
        recreate();
    }

    void recreate() {
        pool = newDefaultPool();
        wallet = wait(pool->createWallet("my_wallet", "bitcoin", DynamicObject::newInstance()));
        p2pkh_account = ledger::testing::medium_xpub::inflate(pool, wallet);
        currency = wallet->getCurrency();
    }

    void TearDown() override {
        BaseFixture::TearDown();
        pool = nullptr;
        wallet = nullptr;
        p2pkh_account = nullptr;
    }

    std::shared_ptr<BitcoinLikeTransactionBuilder> p2pkh_tx_builder() {
        return std::dynamic_pointer_cast<BitcoinLikeTransactionBuilder>(p2pkh_account->buildTransaction());
    }

    std::shared_ptr<WalletPool> pool;
    std::shared_ptr<AbstractWallet> wallet;
    std::shared_ptr<BitcoinLikeAccount> p2pkh_account;
    api::Currency currency;
};

TEST_F(BitcoinMakeTransaction, CreateStandardP2PKHWithOneOutput) {
    auto builder = p2pkh_tx_builder();
    builder->sendToAddress(api::Amount::fromLong(currency, 10000), "14GH47aGFWSjvdrEiYTEfwjgsphNtbkWzP");
    builder->pickInputs(api::BitcoinLikePickingStrategy::DEEP_OUTPUTS_FIRST, 0xFFFFFFFF);
    builder->setFeesPerByte(api::Amount::fromLong(currency, 10));
    auto f = builder->build();
    auto tx = ::wait(f);
    std::cout << hex::toString(tx->serialize()) << std::endl;
    EXPECT_EQ(
            "0100000001f6390f2600568e3dd28af5d53e821219751d6cb7a03ec9476f96f5695f2807a2000000001976a914bfe0a15bbed6211262d3a8d8a891e738bab36ffb88acffffffff0210270000000000001976a91423cc0488e5832d8f796b88948b8af1dd186057b488ac10580100000000001976a914d642b9c546d114dc634e65f72283e3458032a3d488ac41eb0700",
            hex::toString(tx->serialize())
    );
}

TEST_F(BitcoinMakeTransaction, CreateStandardP2PKHWithOneOutputAndFakeSignature) {
    auto builder = p2pkh_tx_builder();
    builder->sendToAddress(api::Amount::fromLong(currency, 10000), "14GH47aGFWSjvdrEiYTEfwjgsphNtbkWzP");
    builder->pickInputs(api::BitcoinLikePickingStrategy::DEEP_OUTPUTS_FIRST, 0xFFFFFFFF);
    builder->setFeesPerByte(api::Amount::fromLong(currency, 10));
    auto f = builder->build();
    auto tx = ::wait(f);
    tx->getInputs()[0]->pushToScriptSig({5, 'h', 'e', 'l', 'l', 'o'});
    std::cout << hex::toString(tx->serialize()) << std::endl;
    EXPECT_EQ(
            "0100000001f6390f2600568e3dd28af5d53e821219751d6cb7a03ec9476f96f5695f2807a200000000060568656c6c6fffffffff0210270000000000001976a91423cc0488e5832d8f796b88948b8af1dd186057b488ac10580100000000001976a914d642b9c546d114dc634e65f72283e3458032a3d488ac41eb0700",
            hex::toString(tx->serialize())
    );
}<commit_msg>Add test for multiple inputs coin selection<commit_after>/*
 *
 * bitcoin_transaction_tests.cpp
 * ledger-core
 *
 * Created by Pierre Pollastri on 28/03/2018.
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Ledger
 *
 * 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 "BaseFixture.h"
#include "../fixtures/medium_xpub_fixtures.h"
#include <wallet/bitcoin/transaction_builders/BitcoinLikeTransactionBuilder.h>

struct BitcoinMakeTransaction : public BaseFixture {

    void SetUp() override {
        BaseFixture::SetUp();
        recreate();
    }

    void recreate() {
        pool = newDefaultPool();
        wallet = wait(pool->createWallet("my_wallet", "bitcoin", DynamicObject::newInstance()));
        p2pkh_account = ledger::testing::medium_xpub::inflate(pool, wallet);
        currency = wallet->getCurrency();
    }

    void TearDown() override {
        BaseFixture::TearDown();
        pool = nullptr;
        wallet = nullptr;
        p2pkh_account = nullptr;
    }

    std::shared_ptr<BitcoinLikeTransactionBuilder> p2pkh_tx_builder() {
        return std::dynamic_pointer_cast<BitcoinLikeTransactionBuilder>(p2pkh_account->buildTransaction());
    }

    std::shared_ptr<WalletPool> pool;
    std::shared_ptr<AbstractWallet> wallet;
    std::shared_ptr<BitcoinLikeAccount> p2pkh_account;
    api::Currency currency;
};

TEST_F(BitcoinMakeTransaction, CreateStandardP2PKHWithOneOutput) {
    auto builder = p2pkh_tx_builder();
    builder->sendToAddress(api::Amount::fromLong(currency, 10000), "14GH47aGFWSjvdrEiYTEfwjgsphNtbkWzP");
    builder->pickInputs(api::BitcoinLikePickingStrategy::DEEP_OUTPUTS_FIRST, 0xFFFFFFFF);
    builder->setFeesPerByte(api::Amount::fromLong(currency, 10));
    auto f = builder->build();
    auto tx = ::wait(f);
    std::cout << hex::toString(tx->serialize()) << std::endl;
    EXPECT_EQ(
            "0100000001f6390f2600568e3dd28af5d53e821219751d6cb7a03ec9476f96f5695f2807a2000000001976a914bfe0a15bbed6211262d3a8d8a891e738bab36ffb88acffffffff0210270000000000001976a91423cc0488e5832d8f796b88948b8af1dd186057b488ac10580100000000001976a914d642b9c546d114dc634e65f72283e3458032a3d488ac41eb0700",
            hex::toString(tx->serialize())
    );
}

TEST_F(BitcoinMakeTransaction, CreateStandardP2PKHWithOneOutputAndFakeSignature) {
    auto builder = p2pkh_tx_builder();
    builder->sendToAddress(api::Amount::fromLong(currency, 10000), "14GH47aGFWSjvdrEiYTEfwjgsphNtbkWzP");
    builder->pickInputs(api::BitcoinLikePickingStrategy::DEEP_OUTPUTS_FIRST, 0xFFFFFFFF);
    builder->setFeesPerByte(api::Amount::fromLong(currency, 10));
    auto f = builder->build();
    auto tx = ::wait(f);
    tx->getInputs()[0]->pushToScriptSig({5, 'h', 'e', 'l', 'l', 'o'});
    std::cout << hex::toString(tx->serialize()) << std::endl;
    EXPECT_EQ(
            "0100000001f6390f2600568e3dd28af5d53e821219751d6cb7a03ec9476f96f5695f2807a200000000060568656c6c6fffffffff0210270000000000001976a91423cc0488e5832d8f796b88948b8af1dd186057b488ac10580100000000001976a914d642b9c546d114dc634e65f72283e3458032a3d488ac41eb0700",
            hex::toString(tx->serialize())
    );
}

TEST_F(BitcoinMakeTransaction, CreateStandardP2PKHWithMultipleInputs) {
    auto builder = p2pkh_tx_builder();
    builder->sendToAddress(api::Amount::fromLong(currency, 10000000), "14GH47aGFWSjvdrEiYTEfwjgsphNtbkWzP");
    builder->pickInputs(api::BitcoinLikePickingStrategy::DEEP_OUTPUTS_FIRST, 0xFFFFFFFF);
    builder->setFeesPerByte(api::Amount::fromLong(currency, 10));
    auto f = builder->build();
    auto tx = ::wait(f);
    std::cout << hex::toString(tx->serialize()) << std::endl;
    EXPECT_EQ(
            "0100000003f6390f2600568e3dd28af5d53e821219751d6cb7a03ec9476f96f5695f2807a2000000001976a914bfe0a15bbed6211262d3a8d8a891e738bab36ffb88acffffffff02e32c49a32937f38fc25d28b8bcd90baaea7b592649af465792cac7b6a9e484000000001976a9148229692a444f0c3f75faafcfd465540a7c2f954988acffffffff1de6319dc1176cc26ee2ed80578dfdbd85a1147dcf9e10eebb5d416f33919f51000000001976a91415a3065a3c32b2d4de4dcceafca0fbd674bdcf7988acffffffff0280969800000000001976a91423cc0488e5832d8f796b88948b8af1dd186057b488acd0b51000000000001976a914d642b9c546d114dc634e65f72283e3458032a3d488ac41eb0700",
            hex::toString(tx->serialize())
    );
}<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "platformWin32/platformWin32.h"
#include "console/console.h"
#include "core/stringTable.h"
#include "platform/platformCPUCount.h"
#include <math.h>
#include <intrin.h>

Platform::SystemInfo_struct Platform::SystemInfo;
extern void PlatformBlitInit();

static void getBrand(char* brand)
{
   S32 extendedInfo[4];
   __cpuid(extendedInfo, 0x80000000);
   S32 numberExtendedIds = extendedInfo[0];

   // Sets brand
   if (numberExtendedIds >= 0x80000004)
   {
      int offset = 0;
      for (int i = 0; i < 3; ++i)
      {
         S32 brandInfo[4];
         __cpuidex(brandInfo, 0x80000002 + i, 0);

         *reinterpret_cast<int*>(brand + offset + 0) = brandInfo[0];
         *reinterpret_cast<int*>(brand + offset + 4) = brandInfo[1];
         *reinterpret_cast<int*>(brand + offset + 8) = brandInfo[2];
         *reinterpret_cast<int*>(brand + offset + 12) = brandInfo[3];

         offset += sizeof(S32) * 4;
      }
   }
}

enum CpuFlags
{
   // EDX Register flags
   BIT_MMX = BIT(23),
   BIT_SSE = BIT(25),
   BIT_SSE2 = BIT(26),
   BIT_3DNOW = BIT(31), // only available for amd cpus in x86

   // These use a different value for comparison than the above flags (ECX Register)
   BIT_SSE3 = BIT(0),
   BIT_SSE3ex = BIT(9),
   BIT_SSE4_1 = BIT(19),
   BIT_SSE4_2 = BIT(20),

   BIT_XSAVE_RESTORE = BIT(27),
   BIT_AVX = BIT(28),
};

static void detectCpuFeatures(Platform::SystemInfo_struct::Processor &processor)
{
   S32 cpuInfo[4];
   __cpuid(cpuInfo, 1);
   U32 eax = cpuInfo[0];   // eax
   U32 edx = cpuInfo[3];  // edx
   U32 ecx = cpuInfo[2]; // ecx

   if (processor.type == ProcessorType::CPU_AMD)
      processor.properties |= (edx & BIT_3DNOW) ? CPU_PROP_3DNOW : 0;

   processor.properties |= (edx & BIT_MMX) ? CPU_PROP_MMX : 0;
   processor.properties |= (edx & BIT_SSE) ? CPU_PROP_SSE : 0;
   processor.properties |= (edx & BIT_SSE2) ? CPU_PROP_SSE2 : 0;
   processor.properties |= (ecx & BIT_SSE3) ? CPU_PROP_SSE3 : 0;
   processor.properties |= (ecx & BIT_SSE3ex) ? CPU_PROP_SSE3ex : 0;
   processor.properties |= (ecx & BIT_SSE4_1) ? CPU_PROP_SSE4_1 : 0;
   processor.properties |= (ecx & BIT_SSE4_2) ? CPU_PROP_SSE4_2 : 0;

   // AVX detection requires that xsaverestore is supported
   if (ecx & BIT_XSAVE_RESTORE && ecx & BIT_AVX)
   {
      bool supportsAVX = _xgetbv(_XCR_XFEATURE_ENABLED_MASK) & 0x6;
      if (supportsAVX)
      {
         processor.properties |= CPU_PROP_AVX;
      }
   }

   if (processor.isMultiCore)
      processor.properties |= CPU_PROP_MP;

#ifdef TORQUE_CPU_X64
   processor.properties |= CPU_PROP_64bit;
#endif
}

void Processor::init()
{
   // Reference:
   //    www.cyrix.com
   //    www.amd.com
   //    www.intel.com
   //       http://developer.intel.com/design/PentiumII/manuals/24512701.pdf

   Platform::SystemInfo.processor.type = CPU_X86Compatible;
   Platform::SystemInfo.processor.name = StringTable->insert("Unknown x86 Compatible");
   Platform::SystemInfo.processor.mhz  = 0;
   Platform::SystemInfo.processor.properties = CPU_PROP_C | CPU_PROP_FPU | CPU_PROP_LE;

   char  vendor[0x20];
   dMemset(vendor, 0, sizeof(vendor));

   S32 vendorInfo[4];
   __cpuid(vendorInfo, 0);
   *reinterpret_cast<int*>(vendor) = vendorInfo[1];     // ebx
   *reinterpret_cast<int*>(vendor + 4) = vendorInfo[3]; // edx
   *reinterpret_cast<int*>(vendor + 8) = vendorInfo[2]; // ecx

   char brand[0x40];
   dMemset(brand, 0, sizeof(brand));
   getBrand(brand);

   SetProcessorInfo(Platform::SystemInfo.processor, vendor, brand);
   detectCpuFeatures(Platform::SystemInfo.processor);

   U32 mhz = 1000; // default if it can't be found

   LONG result;
   DWORD data = 0;
   DWORD dataSize = 4;
   HKEY hKey;

   result = ::RegOpenKeyExA (HKEY_LOCAL_MACHINE,"Hardware\\Description\\System\\CentralProcessor\\0", 0, KEY_QUERY_VALUE, &hKey);

   if (result == ERROR_SUCCESS)
   {
      result = ::RegQueryValueExA (hKey, "~MHz",NULL, NULL,(LPBYTE)&data, &dataSize);

      if (result == ERROR_SUCCESS)
         mhz = data;

      ::RegCloseKey(hKey);
   }

   Platform::SystemInfo.processor.mhz = mhz;

   Con::printf("Processor Init:");
   Con::printf("   Processor: %s", Platform::SystemInfo.processor.name);
   if (Platform::SystemInfo.processor.properties & CPU_PROP_MMX)
      Con::printf("      MMX detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_3DNOW)
      Con::printf("      3DNow detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE)
      Con::printf("      SSE detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE2)
      Con::printf("      SSE2 detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE3)
      Con::printf("      SSE3 detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE3ex)
      Con::printf("      SSE3ex detected ");
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE4_1)
      Con::printf("      SSE4.1 detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE4_2)
      Con::printf("      SSE4.2 detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_AVX)
      Con::printf("      AVX detected");

   if (Platform::SystemInfo.processor.properties & CPU_PROP_MP)
      Con::printf("   MultiCore CPU detected [%i cores, %i logical]", Platform::SystemInfo.processor.numPhysicalProcessors, Platform::SystemInfo.processor.numLogicalProcessors);

   Con::printf(" ");

   PlatformBlitInit();
}
<commit_msg>* BugFix: Remove the last remnant of 3DNow! Extensions.<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "platformWin32/platformWin32.h"
#include "console/console.h"
#include "core/stringTable.h"
#include "platform/platformCPUCount.h"
#include <math.h>
#include <intrin.h>

Platform::SystemInfo_struct Platform::SystemInfo;
extern void PlatformBlitInit();

static void getBrand(char* brand)
{
   S32 extendedInfo[4];
   __cpuid(extendedInfo, 0x80000000);
   S32 numberExtendedIds = extendedInfo[0];

   // Sets brand
   if (numberExtendedIds >= 0x80000004)
   {
      int offset = 0;
      for (int i = 0; i < 3; ++i)
      {
         S32 brandInfo[4];
         __cpuidex(brandInfo, 0x80000002 + i, 0);

         *reinterpret_cast<int*>(brand + offset + 0) = brandInfo[0];
         *reinterpret_cast<int*>(brand + offset + 4) = brandInfo[1];
         *reinterpret_cast<int*>(brand + offset + 8) = brandInfo[2];
         *reinterpret_cast<int*>(brand + offset + 12) = brandInfo[3];

         offset += sizeof(S32) * 4;
      }
   }
}

enum CpuFlags
{
   // EDX Register flags
   BIT_MMX = BIT(23),
   BIT_SSE = BIT(25),
   BIT_SSE2 = BIT(26),
   BIT_3DNOW = BIT(31), // only available for amd cpus in x86

   // These use a different value for comparison than the above flags (ECX Register)
   BIT_SSE3 = BIT(0),
   BIT_SSE3ex = BIT(9),
   BIT_SSE4_1 = BIT(19),
   BIT_SSE4_2 = BIT(20),

   BIT_XSAVE_RESTORE = BIT(27),
   BIT_AVX = BIT(28),
};

static void detectCpuFeatures(Platform::SystemInfo_struct::Processor &processor)
{
   S32 cpuInfo[4];
   __cpuid(cpuInfo, 1);
   U32 eax = cpuInfo[0];   // eax
   U32 edx = cpuInfo[3];  // edx
   U32 ecx = cpuInfo[2]; // ecx

   processor.properties |= (edx & BIT_MMX) ? CPU_PROP_MMX : 0;
   processor.properties |= (edx & BIT_SSE) ? CPU_PROP_SSE : 0;
   processor.properties |= (edx & BIT_SSE2) ? CPU_PROP_SSE2 : 0;
   processor.properties |= (ecx & BIT_SSE3) ? CPU_PROP_SSE3 : 0;
   processor.properties |= (ecx & BIT_SSE3ex) ? CPU_PROP_SSE3ex : 0;
   processor.properties |= (ecx & BIT_SSE4_1) ? CPU_PROP_SSE4_1 : 0;
   processor.properties |= (ecx & BIT_SSE4_2) ? CPU_PROP_SSE4_2 : 0;

   // AVX detection requires that xsaverestore is supported
   if (ecx & BIT_XSAVE_RESTORE && ecx & BIT_AVX)
   {
      bool supportsAVX = _xgetbv(_XCR_XFEATURE_ENABLED_MASK) & 0x6;
      if (supportsAVX)
      {
         processor.properties |= CPU_PROP_AVX;
      }
   }

   if (processor.isMultiCore)
      processor.properties |= CPU_PROP_MP;

#ifdef TORQUE_CPU_X64
   processor.properties |= CPU_PROP_64bit;
#endif
}

void Processor::init()
{
   // Reference:
   //    www.cyrix.com
   //    www.amd.com
   //    www.intel.com
   //       http://developer.intel.com/design/PentiumII/manuals/24512701.pdf

   Platform::SystemInfo.processor.type = CPU_X86Compatible;
   Platform::SystemInfo.processor.name = StringTable->insert("Unknown x86 Compatible");
   Platform::SystemInfo.processor.mhz  = 0;
   Platform::SystemInfo.processor.properties = CPU_PROP_C | CPU_PROP_FPU | CPU_PROP_LE;

   char  vendor[0x20];
   dMemset(vendor, 0, sizeof(vendor));

   S32 vendorInfo[4];
   __cpuid(vendorInfo, 0);
   *reinterpret_cast<int*>(vendor) = vendorInfo[1];     // ebx
   *reinterpret_cast<int*>(vendor + 4) = vendorInfo[3]; // edx
   *reinterpret_cast<int*>(vendor + 8) = vendorInfo[2]; // ecx

   char brand[0x40];
   dMemset(brand, 0, sizeof(brand));
   getBrand(brand);

   SetProcessorInfo(Platform::SystemInfo.processor, vendor, brand);
   detectCpuFeatures(Platform::SystemInfo.processor);

   U32 mhz = 1000; // default if it can't be found

   LONG result;
   DWORD data = 0;
   DWORD dataSize = 4;
   HKEY hKey;

   result = ::RegOpenKeyExA (HKEY_LOCAL_MACHINE,"Hardware\\Description\\System\\CentralProcessor\\0", 0, KEY_QUERY_VALUE, &hKey);

   if (result == ERROR_SUCCESS)
   {
      result = ::RegQueryValueExA (hKey, "~MHz",NULL, NULL,(LPBYTE)&data, &dataSize);

      if (result == ERROR_SUCCESS)
         mhz = data;

      ::RegCloseKey(hKey);
   }

   Platform::SystemInfo.processor.mhz = mhz;

   Con::printf("Processor Init:");
   Con::printf("   Processor: %s", Platform::SystemInfo.processor.name);
   if (Platform::SystemInfo.processor.properties & CPU_PROP_MMX)
      Con::printf("      MMX detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE)
      Con::printf("      SSE detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE2)
      Con::printf("      SSE2 detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE3)
      Con::printf("      SSE3 detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE3ex)
      Con::printf("      SSE3ex detected ");
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE4_1)
      Con::printf("      SSE4.1 detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE4_2)
      Con::printf("      SSE4.2 detected" );
   if (Platform::SystemInfo.processor.properties & CPU_PROP_AVX)
      Con::printf("      AVX detected");

   if (Platform::SystemInfo.processor.properties & CPU_PROP_MP)
      Con::printf("   MultiCore CPU detected [%i cores, %i logical]", Platform::SystemInfo.processor.numPhysicalProcessors, Platform::SystemInfo.processor.numLogicalProcessors);

   Con::printf(" ");

   PlatformBlitInit();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <tuple>

#include "unicode.h"
#include "utf8.h"
#include "utf16.h"

using namespace ufal::unilib;
using namespace std;

int passed = 0, failed = 0;

template<class Test, class I, class O>
void test(Test test, I input, O output) {
  O result = test(input);
  if (result != output) {
    cerr << "Failed, expected"; for (auto&& chr : output) cerr << ' ' << chr; cerr << ", but got"; for (auto&& chr : result) cerr << ' ' << chr; cerr << "." << endl;
    failed++;
  } else
    passed++;
}

struct udata {
  string u8;
  u16string u16;
  u32string u32;

  udata(string u8, u16string u16, u32string u32) : u8(u8), u16(u16), u32(u32) {}
};
#define U(str) udata(u8"" str, u"" str, U"" str)

int main(void) {
  auto u8_to_u32 = [](string str){ u32string res; utf8::decode(str, res); return res; };
  auto u16_to_u32 = [](u16string str){ u32string res; utf16::decode(str, res); return res; };
  auto u32_to_u16 = [](u32string str){ u16string res; utf16::encode(str, res); return res; };
  auto u32_to_u8 = [](u32string str){ string res; utf8::encode(str, res); return res; };

  for (auto&& data : {
    U("Příliš žluťoučký kůň úpěl ďábelské ódy"),
    U("あめ つち ほし そら / やま かは みね たに / くも きり むろ こけ / ひと いぬ うへ すゑ / ゆわ さる おふ せよ / えのえを なれ ゐて"),
    U("В чащах юга жил бы цитрус? Да, но фальшивый экземпляръ!"),
    U("صِف خَلقَ خَودِ كَمِثلِ الشَمسِ إِذ بَزَغَت — يَحظى الضَجيعُ بِها نَجلاءَ مِعطارِ"),
    U("דג סקרן שט בים מאוכזב ולפתע מצא חברה")})
  {
    test(u8_to_u32, data.u8, data.u32);
    test(u16_to_u32, data.u16, data.u32);
    test(u32_to_u16, data.u32, data.u16);
    test(u32_to_u8, data.u32, data.u8);
  }

  auto u32_uc = [](u32string str) { for (auto&& chr : str) chr = unicode::uppercase(chr); return str; };
  auto u32_lc = [](u32string str) { for (auto&& chr : str) chr = unicode::lowercase(chr); return str; };
  auto u16_uc = [](u16string str) { decltype(str) res; utf16::map(unicode::uppercase, str, res); return res; };
  auto u16_lc = [](u16string str) { decltype(str) res; utf16::map(unicode::lowercase, str, res); return res; };
  auto u8_uc = [](string str) { decltype(str) res; utf8::map(unicode::uppercase, str, res); return res; };
  auto u8_lc = [](string str) { decltype(str) res; utf8::map(unicode::lowercase, str, res); return res; };

  auto u16_uc_str_iter = [](u16string str) { decltype(str) res; for (auto&& chr : utf16::decoder(str)) utf16::append(res, unicode::uppercase(chr)); return res; };
  auto u16_uc_buffer_iter = [](u16string str) { decltype(str) res; for (auto&& chr : utf16::decoder(str.c_str(), str.size())) utf16::append(res, unicode::uppercase(chr)); return res; };
  auto u8_uc_str_iter = [](string str) { decltype(str) res; for (auto&& chr : utf8::decoder(str)) utf8::append(res, unicode::uppercase(chr)); return res; };
  auto u8_uc_buffer_iter = [](string str) { decltype(str) res; for (auto&& chr : utf8::decoder(str.c_str(), str.size())) utf8::append(res, unicode::uppercase(chr)); return res; };

  for (auto&& data : {
    make_tuple(U("PřÍlIš žLuŤoUčKý kŮň úPěL ĎáBeLsKé óDy"), U("PŘÍLIŠ ŽLUŤOUČKÝ KŮŇ ÚPĚL ĎÁBELSKÉ ÓDY"), U("příliš žluťoučký kůň úpěl ďábelské ódy")),
    make_tuple(U("В ЧаЩаХ ЮгА ЖиЛ Бы цИтРуС? ДА, нО ФаЛьШиВыЙ ЭкЗеМпЛяРъ!"), U("В ЧАЩАХ ЮГА ЖИЛ БЫ ЦИТРУС? ДА, НО ФАЛЬШИВЫЙ ЭКЗЕМПЛЯРЪ!"), U("в чащах юга жил бы цитрус? да, но фальшивый экземпляръ!"))})
  {
    test(u32_uc, get<0>(data).u32, get<1>(data).u32);
    test(u32_lc, get<0>(data).u32, get<2>(data).u32);
    test(u16_uc, get<0>(data).u16, get<1>(data).u16);
    test(u16_lc, get<0>(data).u16, get<2>(data).u16);
    test(u8_uc, get<0>(data).u8, get<1>(data).u8);
    test(u8_lc, get<0>(data).u8, get<2>(data).u8);

    test(u16_uc_str_iter, get<0>(data).u16, get<1>(data).u16);
    test(u16_uc_buffer_iter, get<0>(data).u16, get<1>(data).u16);
    test(u8_uc_str_iter, get<0>(data).u8, get<1>(data).u8);
    test(u8_uc_buffer_iter, get<0>(data).u8, get<1>(data).u8);
  }

  cerr << "Passed: " << passed << ", failed: " << failed << endl;

  return 0;
}
<commit_msg>Add case-sensitive non-BMP Unicode-6.3-introduced test.<commit_after>#include <iostream>
#include <string>
#include <tuple>

#include "unicode.h"
#include "utf8.h"
#include "utf16.h"

using namespace ufal::unilib;
using namespace std;

int passed = 0, failed = 0;

template<class Test, class I, class O>
void test(Test test, I input, O output) {
  O result = test(input);
  if (result != output) {
    cerr << "Failed, expected"; for (auto&& chr : output) cerr << ' ' << chr; cerr << ", but got"; for (auto&& chr : result) cerr << ' ' << chr; cerr << "." << endl;
    failed++;
  } else
    passed++;
}

struct udata {
  string u8;
  u16string u16;
  u32string u32;

  udata(string u8, u16string u16, u32string u32) : u8(u8), u16(u16), u32(u32) {}
};
#define U(str) udata(u8"" str, u"" str, U"" str)

int main(void) {
  auto u8_to_u32 = [](string str){ u32string res; utf8::decode(str, res); return res; };
  auto u16_to_u32 = [](u16string str){ u32string res; utf16::decode(str, res); return res; };
  auto u32_to_u16 = [](u32string str){ u16string res; utf16::encode(str, res); return res; };
  auto u32_to_u8 = [](u32string str){ string res; utf8::encode(str, res); return res; };

  for (auto&& data : {
    U("Příliš žluťoučký kůň úpěl ďábelské ódy"),
    U("あめ つち ほし そら / やま かは みね たに / くも きり むろ こけ / ひと いぬ うへ すゑ / ゆわ さる おふ せよ / えのえを なれ ゐて"),
    U("В чащах юга жил бы цитрус? Да, но фальшивый экземпляръ!"),
    U("صِف خَلقَ خَودِ كَمِثلِ الشَمسِ إِذ بَزَغَت — يَحظى الضَجيعُ بِها نَجلاءَ مِعطارِ"),
    U("דג סקרן שט בים מאוכזב ולפתע מצא חברה"),
    U("𐐀𐐁𐐂𐐃𐐄𐐅𐐆𐐇𐐈𐐉𐐊𐐋𐐌𐐍𐐎𐐏𐐐𐐑𐐒𐐓𐐔𐐕𐐖𐐗𐐘𐐙𐐚𐐛𐐜𐐝𐐞𐐟")}) //Deseret case sensitive Unicode 6.3 introduced alphabet
  {
    test(u8_to_u32, data.u8, data.u32);
    test(u16_to_u32, data.u16, data.u32);
    test(u32_to_u16, data.u32, data.u16);
    test(u32_to_u8, data.u32, data.u8);
  }

  auto u32_uc = [](u32string str) { for (auto&& chr : str) chr = unicode::uppercase(chr); return str; };
  auto u32_lc = [](u32string str) { for (auto&& chr : str) chr = unicode::lowercase(chr); return str; };
  auto u16_uc = [](u16string str) { decltype(str) res; utf16::map(unicode::uppercase, str, res); return res; };
  auto u16_lc = [](u16string str) { decltype(str) res; utf16::map(unicode::lowercase, str, res); return res; };
  auto u8_uc = [](string str) { decltype(str) res; utf8::map(unicode::uppercase, str, res); return res; };
  auto u8_lc = [](string str) { decltype(str) res; utf8::map(unicode::lowercase, str, res); return res; };

  auto u16_uc_str_iter = [](u16string str) { decltype(str) res; for (auto&& chr : utf16::decoder(str)) utf16::append(res, unicode::uppercase(chr)); return res; };
  auto u16_uc_buffer_iter = [](u16string str) { decltype(str) res; for (auto&& chr : utf16::decoder(str.c_str(), str.size())) utf16::append(res, unicode::uppercase(chr)); return res; };
  auto u8_uc_str_iter = [](string str) { decltype(str) res; for (auto&& chr : utf8::decoder(str)) utf8::append(res, unicode::uppercase(chr)); return res; };
  auto u8_uc_buffer_iter = [](string str) { decltype(str) res; for (auto&& chr : utf8::decoder(str.c_str(), str.size())) utf8::append(res, unicode::uppercase(chr)); return res; };

  for (auto&& data : {
    make_tuple(U("PřÍlIš žLuŤoUčKý kŮň úPěL ĎáBeLsKé óDy"), U("PŘÍLIŠ ŽLUŤOUČKÝ KŮŇ ÚPĚL ĎÁBELSKÉ ÓDY"), U("příliš žluťoučký kůň úpěl ďábelské ódy")),
    make_tuple(U("В ЧаЩаХ ЮгА ЖиЛ Бы цИтРуС? ДА, нО ФаЛьШиВыЙ ЭкЗеМпЛяРъ!"), U("В ЧАЩАХ ЮГА ЖИЛ БЫ ЦИТРУС? ДА, НО ФАЛЬШИВЫЙ ЭКЗЕМПЛЯРЪ!"), U("в чащах юга жил бы цитрус? да, но фальшивый экземпляръ!")),
    make_tuple(U("𐐨𐐁𐐪𐐃𐐬𐐅𐐮𐐇𐐰𐐉𐐲𐐋𐐴𐐍𐐶𐐏𐐸𐐑𐐺𐐓𐐼𐐕𐐾𐐗𐑀𐐙𐑂𐐛𐑄𐐝𐑆𐐟"), U("𐐀𐐁𐐂𐐃𐐄𐐅𐐆𐐇𐐈𐐉𐐊𐐋𐐌𐐍𐐎𐐏𐐐𐐑𐐒𐐓𐐔𐐕𐐖𐐗𐐘𐐙𐐚𐐛𐐜𐐝𐐞𐐟"), U("𐐨𐐩𐐪𐐫𐐬𐐭𐐮𐐯𐐰𐐱𐐲𐐳𐐴𐐵𐐶𐐷𐐸𐐹𐐺𐐻𐐼𐐽𐐾𐐿𐑀𐑁𐑂𐑃𐑄𐑅𐑆𐑇"))})
  {
    test(u32_uc, get<0>(data).u32, get<1>(data).u32);
    test(u32_lc, get<0>(data).u32, get<2>(data).u32);
    test(u16_uc, get<0>(data).u16, get<1>(data).u16);
    test(u16_lc, get<0>(data).u16, get<2>(data).u16);
    test(u8_uc, get<0>(data).u8, get<1>(data).u8);
    test(u8_lc, get<0>(data).u8, get<2>(data).u8);

    test(u16_uc_str_iter, get<0>(data).u16, get<1>(data).u16);
    test(u16_uc_buffer_iter, get<0>(data).u16, get<1>(data).u16);
    test(u8_uc_str_iter, get<0>(data).u8, get<1>(data).u8);
    test(u8_uc_buffer_iter, get<0>(data).u8, get<1>(data).u8);
  }

  cerr << "Passed: " << passed << ", failed: " << failed << endl;

  return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    ResampleImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//  Software Guide : BeginLatex
//
//  Resampling an image is a very important task in image analysis. It is
//  especially important in the frame of image registration. The
//  \doxygen{ResampleImageFilter} implements image resampling through the use
//  of \doxygen{Transform}s. The inputs expected by this filter are an image,
//  a transform and an interpolator. The space coordinates of the image are
//  mapped through the transform in order to generate a new image. The extent
//  and spacing of the resulting image are selected by the user. Resampling
//  is performed in space coordinates, not pixel/grid coordinates. It is
//  quite important to ensure that image spacing is properly set on the
//  images involved. The interpolator is required since the mapping from one
//  space to the other will often require evaluation of the intensity of the
//  image at non-grid positions.
//
//  \index{itk::ResampleImageFilter}
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

//  Software Guide : BeginLatex
//
//  The header file corresponding to this filter should be included first.
//
//  \index{itk::ResampleImageFilter!header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkResampleImageFilter.h"
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  The header files corresponding to the transform and interpolator must
//  also be included.
//
//  \index{itk::AffineTransform!header}
//  \index{itk::NearestNeighborInterpolateImageFunction!header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkAffineTransform.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
// Software Guide : EndCodeSnippet

int main( int argc, char * argv[] )
{
  if( argc < 4 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile  outputImageFile";
    std::cerr << "  [exampleAction={0,1,2,3}]" << std::endl;
    return 1;
    }

  int exampleAction = 0;

  if( argc >= 4 )
    {
    exampleAction = atoi( argv[3] );
    }

  //  Software Guide : BeginLatex
  //
  //  The dimension and pixel types for input and output image must be
  //  defined and with them the image types can be instantiated.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  const     unsigned int   Dimension = 2;
  typedef   unsigned char  InputPixelType;
  typedef   unsigned char  OutputPixelType;
  typedef itk::Image< InputPixelType,  Dimension >   InputImageType;
  typedef itk::Image< OutputPixelType, Dimension >   OutputImageType;
  // Software Guide : EndCodeSnippet

  typedef itk::ImageFileReader< InputImageType  >  ReaderType;
  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName( argv[1] );
  writer->SetFileName( argv[2] );

  //  Software Guide : BeginLatex
  //
  //  Using the image and transform types it is now possible to instantiate
  //  the filter type and create the filter object.
  //
  //  \index{itk::ResampleImageFilter!instantiation}
  //  \index{itk::ResampleImageFilter!New()}
  //  \index{itk::ResampleImageFilter!Pointer}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::ResampleImageFilter<
                  InputImageType, OutputImageType >  FilterType;
  FilterType::Pointer filter = FilterType::New();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The transform type is typically defined using the image dimension
  //  and the type used for representing space coordinates.
  //
  //  \index{itk::AffineTransform!instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::AffineTransform< double, Dimension >  TransformType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  An instance of the transform object is instantiated and passed to the
  //  resample filter. By default, the parameters of transform is set to
  //  represent the identity transform.
  //
  //  \index{itk::ResampleImageFilter!SetTransform()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  TransformType::Pointer transform = TransformType::New();
  filter->SetTransform( transform );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The interpolator type is defined using the full image type and the type
  //  used for representing space coordinates.
  //
  //  \index{itk::NearestNeighborInterpolateImageFunction!instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::NearestNeighborInterpolateImageFunction<
                       InputImageType, double >  InterpolatorType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  An instance of the interpolator object is instantiated and passed to
  //  the resample filter.
  //
  //  \index{itk::ResampleImageFilter!SetInterpolator()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  InterpolatorType::Pointer interpolator = InterpolatorType::New();
  filter->SetInterpolator( interpolator );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Given that some pixels of the output image may end up being mapped
  //  outside the extent of the input image it is necessary to decide what
  //  values to assign to them. This is done by invoking the
  //  \code{SetDefaultPixelValue()} method.
  //
  //  \index{itk::ResampleImageFilter!SetDefaultPixelValue()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetDefaultPixelValue( 0 );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The sampling grid of the output space is specified with the spacing along
  //  each dimension and the origin.
  //
  //  \index{itk::ResampleImageFilter!SetOutputOrigin()}
  //  \index{itk::ResampleImageFilter!SetOutputSpacing()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  double spacing[ Dimension ];
  spacing[0] = 1.0; // pixel spacing in millimeters along X
  spacing[1] = 1.0; // pixel spacing in millimeters along Y

  filter->SetOutputSpacing( spacing );

  double origin[ Dimension ];
  origin[0] = 0.0;  // X space coordinate of origin
  origin[1] = 0.0;  // Y space coordinate of origin

  filter->SetOutputOrigin( origin );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The extent of the sampling grid on the output image is defined by a
  //  \code{SizeType} and is set using the \code{SetSize()} method.
  //
  //  \index{itk::ResampleImageFilter!SetSize()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  InputImageType::SizeType   size;

  size[0] = 300;  // number of pixels along X
  size[1] = 300;  // number of pixels along Y

  filter->SetSize( size );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The input to the filter can be taken from any other filter, for example
  //  a reader. The output can be passed down the pipeline to other filters,
  //  for example a writer. An update call on any downstream filter will
  //  trigger the execution of the resampling filter.
  //
  //  \index{itk::ResampleImageFilter!SetInput()}
  //  \index{itk::ResampleImageFilter!GetOutput()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetInput( reader->GetOutput() );
  writer->SetInput( filter->GetOutput() );
  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice.eps}
  // \includegraphics[width=0.44\textwidth]{ResampleImageFilterOutput1.eps}
  // \itkcaption[Effect of the Resample filter]{Effect of the resample filter.}
  // \label{fig:ResampleImageFilterOutput1}
  // \end{figure}
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=\textwidth]{ResampleImageFilterOutput1Analysis.eps}
  // \itkcaption[Analysis of resampling in common coordinate system]{Analysis of
  // the resample image done in a common coordinate system.}
  // \label{fig:ResampleImageFilterOutput1Analysis}
  // \end{figure}
  //
  //  Figure \ref{fig:ResampleImageFilterOutput1} illustrates the effect of
  //  this filter on a slice of MRI brain image using an affine transform
  //  containing an identity transform. Note that any analysis of the
  //  behavior of this filter must be done on the space coordinate system in
  //  millimeters, not with respect to the sampling grid in pixels. The
  //  figure shows the resulting image in the lower left quarter of the
  //  extent. This may seem odd if analyzed in terms of the image grid but is
  //  quite clear when seen with respect to space coordinates.  Figure
  //  \ref{fig:ResampleImageFilterOutput1} is particularly misleading
  //  because the images are rescaled to fit nicely on the text of this book.
  //  Figure \ref{fig:ResampleImageFilterOutput1Analysis} clarifies the
  //  situation. It shows the two same images placed on a equally scaled
  //  coordinate system.  It becomes clear here that an identity transform is
  //  being used to map the image data, and that simply, we has requested to
  //  resample additional empty space around the image. The input image is
  //  $181 \times 217$ pixels in size and we have requested an output of $300
  //  \times 300$ pixels. In this case, the input and output images both have
  //  spacing of $1mm \times 1mm$ and origin of $(0.0,0.0)$.
  //
  //  Software Guide : EndLatex

  //  Software Guide : BeginLatex
  //
  //  Let's now set values on the transform. Note that the supplied transform
  //  represents the mapping of points from the output space to the input
  //  space.  The following code sets up a translation.
  //
  //  \index{itk::AffineTransform!Translate()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  TransformType::OutputVectorType translation;
  translation[0] = -30;  // X translation in millimeters
  translation[1] = -50;  // Y translation in millimeters
  transform->Translate( translation );
  // Software Guide : EndCodeSnippet

  if( exampleAction == 1 )
    {
    writer->Update();
    }

  //  Software Guide : BeginLatex
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice.eps}
  // \includegraphics[width=0.44\textwidth]{ResampleImageFilterOutput2.eps}
  // \itkcaption[ResampleImageFilter with a translation by
  // $(-30,-50)$]{ResampleImageFilter with a translation by $(-30,-50)$.}
  // \label{fig:ResampleImageFilterOutput2}
  // \end{figure}
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=\textwidth]{ResampleImageFilterOutput2Analysis.eps}
  // \itkcaption[ResampleImageFilter. Analysis of a translation by
  // $(-30,-50)$]{ResampleImageFilter. Analysis of a translation by
  // $(-30,-50)$.}
  // \label{fig:ResampleImageFilterOutput2Analysis}
  // \end{figure}
  //
  // The output image resulting from the translation can be seen in Figure
  // \ref{fig:ResampleImageFilterOutput2}. Again, it is better to interpret
  // the result in a common coordinate system as illustrated in Figure
  // \ref{fig:ResampleImageFilterOutput2Analysis}.
  //
  // Probably the most important thing to keep in mind when resampling images
  // is that the transform is used to map points from the \textbf{output}
  // image space into the \textbf{input} image space. In this case, Figure
  // \ref{fig:ResampleImageFilterOutput2Analysis} shows that the translation
  // is applied to every point of the output image and the resulting position
  // is used to read the intensity from the input image. In this way, the
  // gray level of the point $P$ in the output image is taken from the point
  // $T(P)$ in the input image. Where $T$ is the transformation. In the
  // specific case of the Figure
  // \ref{fig:ResampleImageFilterOutput2Analysis}, the value of point
  // $(105,188)$ in the output image is taken from the point $(75,138)$ of
  // the input image because the transformation applied was a translation of
  // $(-30,-50)$.
  //
  //  Software Guide : EndLatex

  //  Software Guide : BeginLatex
  //
  //  It is sometimes useful to intentionally set the default output value to
  //  a distinct gray value in order to highlight the mapping of the image
  //  borders. For example, the following code sets the default external
  //  value of $100$.  The result is shown in the right side of Figure
  //  \ref{fig:ResampleImageFilterOutput3Analysis}
  //
  //  \index{itk::ResampleImageFilter!SetDefaultPixelValue()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetDefaultPixelValue( 100 );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=\textwidth]{ResampleImageFilterOutput3Analysis.eps}
  // \itkcaption[ResampleImageFilter highlighting image
  // borders]{ResampleImageFilter highlighting image borders with
  // SetDefaultPixelValue().}
  // \label{fig:ResampleImageFilterOutput3Analysis}
  // \end{figure}
  //
  //  With this change we can better appreciate the effect of the previous
  //  translation transform on the image resampling. Figure
  //  \ref{fig:ResampleImageFilterOutput3Analysis} illustrates how the point
  //  $(30,50)$ of the output image gets its gray value from the point $(0,0)$
  //  of the input image.
  //
  //  Software Guide : EndLatex

  if( exampleAction == 2 )
    {
    writer->Update();
    }

  return 0;
}

<commit_msg>DOC: ENH: index hyphenation.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    ResampleImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//  Software Guide : BeginLatex
//
//  Resampling an image is a very important task in image analysis. It is
//  especially important in the frame of image registration. The
//  \doxygen{ResampleImageFilter} implements image resampling through the use
//  of \doxygen{Transform}s. The inputs expected by this filter are an image,
//  a transform and an interpolator. The space coordinates of the image are
//  mapped through the transform in order to generate a new image. The extent
//  and spacing of the resulting image are selected by the user. Resampling
//  is performed in space coordinates, not pixel/grid coordinates. It is
//  quite important to ensure that image spacing is properly set on the
//  images involved. The interpolator is required since the mapping from one
//  space to the other will often require evaluation of the intensity of the
//  image at non-grid positions.
//
//  \index{itk::ResampleImageFilter}
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

//  Software Guide : BeginLatex
//
//  The header file corresponding to this filter should be included first.
//
//  \index{itk::ResampleImageFilter!header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkResampleImageFilter.h"
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  The header files corresponding to the transform and interpolator must
//  also be included.
//
//  \index{itk::AffineTransform!header}
//  \index{itk::Nearest\-Neighbor\-Interpolate\-Image\-Function!header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkAffineTransform.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
// Software Guide : EndCodeSnippet

int main( int argc, char * argv[] )
{
  if( argc < 4 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile  outputImageFile";
    std::cerr << "  [exampleAction={0,1,2,3}]" << std::endl;
    return 1;
    }

  int exampleAction = 0;

  if( argc >= 4 )
    {
    exampleAction = atoi( argv[3] );
    }

  //  Software Guide : BeginLatex
  //
  //  The dimension and pixel types for input and output image must be
  //  defined and with them the image types can be instantiated.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  const     unsigned int   Dimension = 2;
  typedef   unsigned char  InputPixelType;
  typedef   unsigned char  OutputPixelType;
  typedef itk::Image< InputPixelType,  Dimension >   InputImageType;
  typedef itk::Image< OutputPixelType, Dimension >   OutputImageType;
  // Software Guide : EndCodeSnippet

  typedef itk::ImageFileReader< InputImageType  >  ReaderType;
  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName( argv[1] );
  writer->SetFileName( argv[2] );

  //  Software Guide : BeginLatex
  //
  //  Using the image and transform types it is now possible to instantiate
  //  the filter type and create the filter object.
  //
  //  \index{itk::ResampleImageFilter!instantiation}
  //  \index{itk::ResampleImageFilter!New()}
  //  \index{itk::ResampleImageFilter!Pointer}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::ResampleImageFilter<
                  InputImageType, OutputImageType >  FilterType;
  FilterType::Pointer filter = FilterType::New();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The transform type is typically defined using the image dimension
  //  and the type used for representing space coordinates.
  //
  //  \index{itk::AffineTransform!instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::AffineTransform< double, Dimension >  TransformType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  An instance of the transform object is instantiated and passed to the
  //  resample filter. By default, the parameters of transform is set to
  //  represent the identity transform.
  //
  //  \index{itk::ResampleImageFilter!SetTransform()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  TransformType::Pointer transform = TransformType::New();
  filter->SetTransform( transform );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The interpolator type is defined using the full image type and the type
  //  used for representing space coordinates.
  //
  //  \index{itk::Nearest\-Neighbor\-Interpolate\-Image\-Function!instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::NearestNeighborInterpolateImageFunction<
                       InputImageType, double >  InterpolatorType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  An instance of the interpolator object is instantiated and passed to
  //  the resample filter.
  //
  //  \index{itk::ResampleImageFilter!SetInterpolator()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  InterpolatorType::Pointer interpolator = InterpolatorType::New();
  filter->SetInterpolator( interpolator );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Given that some pixels of the output image may end up being mapped
  //  outside the extent of the input image it is necessary to decide what
  //  values to assign to them. This is done by invoking the
  //  \code{SetDefaultPixelValue()} method.
  //
  //  \index{itk::ResampleImageFilter!SetDefaultPixelValue()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetDefaultPixelValue( 0 );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The sampling grid of the output space is specified with the spacing along
  //  each dimension and the origin.
  //
  //  \index{itk::ResampleImageFilter!SetOutputOrigin()}
  //  \index{itk::ResampleImageFilter!SetOutputSpacing()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  double spacing[ Dimension ];
  spacing[0] = 1.0; // pixel spacing in millimeters along X
  spacing[1] = 1.0; // pixel spacing in millimeters along Y

  filter->SetOutputSpacing( spacing );

  double origin[ Dimension ];
  origin[0] = 0.0;  // X space coordinate of origin
  origin[1] = 0.0;  // Y space coordinate of origin

  filter->SetOutputOrigin( origin );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The extent of the sampling grid on the output image is defined by a
  //  \code{SizeType} and is set using the \code{SetSize()} method.
  //
  //  \index{itk::ResampleImageFilter!SetSize()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  InputImageType::SizeType   size;

  size[0] = 300;  // number of pixels along X
  size[1] = 300;  // number of pixels along Y

  filter->SetSize( size );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The input to the filter can be taken from any other filter, for example
  //  a reader. The output can be passed down the pipeline to other filters,
  //  for example a writer. An update call on any downstream filter will
  //  trigger the execution of the resampling filter.
  //
  //  \index{itk::ResampleImageFilter!SetInput()}
  //  \index{itk::ResampleImageFilter!GetOutput()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetInput( reader->GetOutput() );
  writer->SetInput( filter->GetOutput() );
  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice.eps}
  // \includegraphics[width=0.44\textwidth]{ResampleImageFilterOutput1.eps}
  // \itkcaption[Effect of the Resample filter]{Effect of the resample filter.}
  // \label{fig:ResampleImageFilterOutput1}
  // \end{figure}
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=\textwidth]{ResampleImageFilterOutput1Analysis.eps}
  // \itkcaption[Analysis of resampling in common coordinate system]{Analysis of
  // the resample image done in a common coordinate system.}
  // \label{fig:ResampleImageFilterOutput1Analysis}
  // \end{figure}
  //
  //  Figure \ref{fig:ResampleImageFilterOutput1} illustrates the effect of
  //  this filter on a slice of MRI brain image using an affine transform
  //  containing an identity transform. Note that any analysis of the
  //  behavior of this filter must be done on the space coordinate system in
  //  millimeters, not with respect to the sampling grid in pixels. The
  //  figure shows the resulting image in the lower left quarter of the
  //  extent. This may seem odd if analyzed in terms of the image grid but is
  //  quite clear when seen with respect to space coordinates.  Figure
  //  \ref{fig:ResampleImageFilterOutput1} is particularly misleading
  //  because the images are rescaled to fit nicely on the text of this book.
  //  Figure \ref{fig:ResampleImageFilterOutput1Analysis} clarifies the
  //  situation. It shows the two same images placed on a equally scaled
  //  coordinate system.  It becomes clear here that an identity transform is
  //  being used to map the image data, and that simply, we has requested to
  //  resample additional empty space around the image. The input image is
  //  $181 \times 217$ pixels in size and we have requested an output of $300
  //  \times 300$ pixels. In this case, the input and output images both have
  //  spacing of $1mm \times 1mm$ and origin of $(0.0,0.0)$.
  //
  //  Software Guide : EndLatex

  //  Software Guide : BeginLatex
  //
  //  Let's now set values on the transform. Note that the supplied transform
  //  represents the mapping of points from the output space to the input
  //  space.  The following code sets up a translation.
  //
  //  \index{itk::AffineTransform!Translate()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  TransformType::OutputVectorType translation;
  translation[0] = -30;  // X translation in millimeters
  translation[1] = -50;  // Y translation in millimeters
  transform->Translate( translation );
  // Software Guide : EndCodeSnippet

  if( exampleAction == 1 )
    {
    writer->Update();
    }

  //  Software Guide : BeginLatex
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice.eps}
  // \includegraphics[width=0.44\textwidth]{ResampleImageFilterOutput2.eps}
  // \itkcaption[ResampleImageFilter with a translation by
  // $(-30,-50)$]{ResampleImageFilter with a translation by $(-30,-50)$.}
  // \label{fig:ResampleImageFilterOutput2}
  // \end{figure}
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=\textwidth]{ResampleImageFilterOutput2Analysis.eps}
  // \itkcaption[ResampleImageFilter. Analysis of a translation by
  // $(-30,-50)$]{ResampleImageFilter. Analysis of a translation by
  // $(-30,-50)$.}
  // \label{fig:ResampleImageFilterOutput2Analysis}
  // \end{figure}
  //
  // The output image resulting from the translation can be seen in Figure
  // \ref{fig:ResampleImageFilterOutput2}. Again, it is better to interpret
  // the result in a common coordinate system as illustrated in Figure
  // \ref{fig:ResampleImageFilterOutput2Analysis}.
  //
  // Probably the most important thing to keep in mind when resampling images
  // is that the transform is used to map points from the \textbf{output}
  // image space into the \textbf{input} image space. In this case, Figure
  // \ref{fig:ResampleImageFilterOutput2Analysis} shows that the translation
  // is applied to every point of the output image and the resulting position
  // is used to read the intensity from the input image. In this way, the
  // gray level of the point $P$ in the output image is taken from the point
  // $T(P)$ in the input image. Where $T$ is the transformation. In the
  // specific case of the Figure
  // \ref{fig:ResampleImageFilterOutput2Analysis}, the value of point
  // $(105,188)$ in the output image is taken from the point $(75,138)$ of
  // the input image because the transformation applied was a translation of
  // $(-30,-50)$.
  //
  //  Software Guide : EndLatex

  //  Software Guide : BeginLatex
  //
  //  It is sometimes useful to intentionally set the default output value to
  //  a distinct gray value in order to highlight the mapping of the image
  //  borders. For example, the following code sets the default external
  //  value of $100$.  The result is shown in the right side of Figure
  //  \ref{fig:ResampleImageFilterOutput3Analysis}
  //
  //  \index{itk::ResampleImageFilter!SetDefaultPixelValue()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetDefaultPixelValue( 100 );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=\textwidth]{ResampleImageFilterOutput3Analysis.eps}
  // \itkcaption[ResampleImageFilter highlighting image
  // borders]{ResampleImageFilter highlighting image borders with
  // SetDefaultPixelValue().}
  // \label{fig:ResampleImageFilterOutput3Analysis}
  // \end{figure}
  //
  //  With this change we can better appreciate the effect of the previous
  //  translation transform on the image resampling. Figure
  //  \ref{fig:ResampleImageFilterOutput3Analysis} illustrates how the point
  //  $(30,50)$ of the output image gets its gray value from the point $(0,0)$
  //  of the input image.
  //
  //  Software Guide : EndLatex

  if( exampleAction == 2 )
    {
    writer->Update();
    }

  return 0;
}

<|endoftext|>