<commit_before>/*ckwg +5
 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "read_video_gravl_process.h"

#include <processes/helpers/image/format.h>
#include <processes/helpers/image/read.h>

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

#include <gravl/core/api/data_block.h>
#include <gravl/core/api/frame_ptr.h>
#include <gravl/core/api/image.h>
#include <gravl/core/api/image_data.h>
#include <gravl/core/api/resource_ptr.h>

#include <gravl/raf/raf.h>

#include <vil/vil_image_view.h>

#include <string>

/**
 * \file read_video_gravl_process.cxx
 *
 * \brief Implementation of the read video gravl process.
 */

static size_t sabs(ptrdiff_t a);
static size_t compute_block_size(gravl::image::dimension dim,
                                 gravl::image::stride s);
static ptrdiff_t compute_offset(gravl::image::dimension dim,
                                gravl::image::stride s);
template <typename T> static T* compute_block_start(
  T* top_left, gravl::image::dimension dim, gravl::image::stride s);
template <typename T> static T* compute_top_left(
  T* top_left, gravl::image::dimension dim, gravl::image::stride s);

namespace vistk
{

class read_video_gravl_process::priv
{
  public:
    priv(std::string const& input_uri);
    ~priv();

    std::string const uri;

    gravl::resource_ptr resource;
    gravl::data_block* video;

    static config::key_t const config_pixtype;
    static config::key_t const config_pixfmt;
    static config::key_t const config_uri;
    static config::key_t const config_verify;
    static config::value_t const default_pixtype;
    static config::value_t const default_pixfmt;
    static config::value_t const default_verify;
    static port_t const port_output;
};

config::key_t const read_video_gravl_process::priv::config_pixtype = config::key_t("pixtype");
config::key_t const read_video_gravl_process::priv::config_pixfmt = config::key_t("pixfmt");
config::key_t const read_video_gravl_process::priv::config_uri = config::key_t("input");
config::value_t const read_video_gravl_process::priv::default_pixtype = config::value_t(pixtypes::pixtype_byte());
config::value_t const read_video_gravl_process::priv::default_pixfmt = config::value_t(pixfmts::pixfmt_rgb());
process::port_t const read_video_gravl_process::priv::port_output = port_t("image");

read_video_gravl_process
::read_video_gravl_process(config_t const& config)
  : process(config)
{
  declare_configuration_key(
    priv::config_pixtype,
    priv::default_pixtype,
    config::description_t("The pixel type of the input images."));
  declare_configuration_key(
    priv::config_pixfmt,
    priv::default_pixfmt,
    config::description_t("The pixel format of the input images."));
  declare_configuration_key(
    priv::config_uri,
    config::value_t(),
    config::description_t("The URI of the resource."));

  pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);
  pixfmt_t const pixfmt = config_value<pixfmt_t>(priv::config_pixfmt);

  port_type_t const port_type_output = port_type_for_pixtype(pixtype, pixfmt);

  port_flags_t required;

  required.insert(flag_required);

  declare_output_port(
    priv::port_output,
    port_type_output,
    required,
    port_description_t("The images that are read in."));
}

read_video_gravl_process
::~read_video_gravl_process()
{
}

void
read_video_gravl_process
::_configure()
{
  // Configure the process.
  {
    pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);
    std::string const uri = config_value<std::string>(priv::config_uri);

    d.reset(new priv(uri));
  }

  if (d->uri.empty())
  {
    static std::string const reason = "The URI given was empty";
    config::value_t const value = config::value_t(d->uri);

    throw invalid_configuration_value_exception(name(), priv::config_uri, value, reason);
  }

  d->resource = gravl::raf::get_resource(d->uri.c_str());
  if (!d->resource)
  {
    std::string const reason = "Failed to open the resource: " + d->uri;

    throw invalid_configuration_exception(name(), reason);
  }

  d->video = d->resource.get_data<gravl::data_block>();
  if (!d->video)
  {
    static std::string const reason = "Failed to obtain data_block from resource";

    throw invalid_configuration_exception(name(), reason);
  }

  process::_configure();
}

void
read_video_gravl_process
::_init()
{
  d->video->rewind();

  process::_init();
}

void
read_video_gravl_process
::_step()
{
  datum_t dat;

  if (d->video->at_end())
  {
    mark_process_as_complete();
    dat = datum::complete_datum();
  }
  else if (!d->video)
  {
    static datum::error_t const err_string = datum::error_t("Error with input file stream.");

    dat = datum::error_datum(err_string);
  }
  else
  {
    gravl::frame_ptr const frame = d->video->current_frame();
    gravl::image_data const* const image_data = frame.get_const_data<gravl::image_data>();
    gravl::image const image = (image_data ? image_data->pixels() : gravl::image());

    if (!image || image.format() != gravl::image::format_of<uint8_t>())
    {
      dat = datum::empty_datum();
    }
    else
    {
      gravl::image::dimension const dim = image.dimensions();
      gravl::image::stride const ps = image.strides();
      uint8_t const* const top_left = image.data<uint8_t>();
      size_t const size = compute_block_size(dim, ps);

      // Ugh, there is no way to create a vil_image_view from existing data
      // without arranging for said existing data to stick around, so stuck
      // having to copy the data (again) :-(
      vil_memory_chunk* const mem = new vil_memory_chunk(size, VIL_PIXEL_FORMAT_BYTE);
      uint8_t* const buffer = reinterpret_cast<uint8_t*>(mem->data());
      memcpy(buffer, compute_block_start(top_left, dim, ps), size);

      vil_image_view<vxl_byte> const vil(vil_memory_chunk_sptr(mem),
                                         compute_top_left(buffer, dim, ps),
                                         dim.width, dim.height, dim.planes,
                                         ps.width, ps.height, ps.planes);
      dat = datum::new_datum(vil);
    }

    d->video->advance();
  }

  push_datum_to_port(priv::port_output, dat);

  process::_step();
}

read_video_gravl_process::priv
::priv(std::string const& input_uri)
  : uri(input_uri)
{
}

read_video_gravl_process::priv
::~priv()
{
}

}

size_t
sabs(ptrdiff_t a)
{
  return static_cast<size_t>((a < 0 ? -a : a));
}

size_t
compute_block_size(gravl::image::dimension dim, gravl::image::stride s)
{
  return ((dim.width  - 1) * sabs(s.width)) +
         ((dim.height - 1) * sabs(s.height)) +
         ((dim.planes - 1) * sabs(s.planes)) + 1;
}

ptrdiff_t
compute_offset(gravl::image::dimension dim, gravl::image::stride s)
{
  ptrdiff_t result = 0;
  if (s.width < 0)
  {
    result -= s.width * (dim.width - 1);
  }
  if (s.height < 0)
  {
    result -= s.height * (dim.height - 1);
  }
  if (s.planes < 0)
  {
    result -= s.planes * (dim.planes - 1);
  }
  return result;
}

template <typename T>
T*
compute_block_start(
  T* top_left, gravl::image::dimension dim, gravl::image::stride s)
{
  return top_left - compute_offset(dim, s);
}

template <typename T>
T*
compute_top_left(
  T* top_left, gravl::image::dimension dim, gravl::image::stride s)
{
  return top_left + compute_offset(dim, s);
}
<commit_msg>Remove unneeded forward declarations<commit_after>/*ckwg +5
 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "read_video_gravl_process.h"

#include <processes/helpers/image/format.h>
#include <processes/helpers/image/read.h>

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

#include <gravl/core/api/data_block.h>
#include <gravl/core/api/frame_ptr.h>
#include <gravl/core/api/image.h>
#include <gravl/core/api/image_data.h>
#include <gravl/core/api/resource_ptr.h>

#include <gravl/raf/raf.h>

#include <vil/vil_image_view.h>

#include <string>

/**
 * \file read_video_gravl_process.cxx
 *
 * \brief Implementation of the read video gravl process.
 */

static size_t compute_block_size(gravl::image::dimension dim,
                                 gravl::image::stride s);
template <typename T> static T* compute_block_start(
  T* top_left, gravl::image::dimension dim, gravl::image::stride s);
template <typename T> static T* compute_top_left(
  T* top_left, gravl::image::dimension dim, gravl::image::stride s);

namespace vistk
{

class read_video_gravl_process::priv
{
  public:
    priv(std::string const& input_uri);
    ~priv();

    std::string const uri;

    gravl::resource_ptr resource;
    gravl::data_block* video;

    static config::key_t const config_pixtype;
    static config::key_t const config_pixfmt;
    static config::key_t const config_uri;
    static config::key_t const config_verify;
    static config::value_t const default_pixtype;
    static config::value_t const default_pixfmt;
    static config::value_t const default_verify;
    static port_t const port_output;
};

config::key_t const read_video_gravl_process::priv::config_pixtype = config::key_t("pixtype");
config::key_t const read_video_gravl_process::priv::config_pixfmt = config::key_t("pixfmt");
config::key_t const read_video_gravl_process::priv::config_uri = config::key_t("input");
config::value_t const read_video_gravl_process::priv::default_pixtype = config::value_t(pixtypes::pixtype_byte());
config::value_t const read_video_gravl_process::priv::default_pixfmt = config::value_t(pixfmts::pixfmt_rgb());
process::port_t const read_video_gravl_process::priv::port_output = port_t("image");

read_video_gravl_process
::read_video_gravl_process(config_t const& config)
  : process(config)
{
  declare_configuration_key(
    priv::config_pixtype,
    priv::default_pixtype,
    config::description_t("The pixel type of the input images."));
  declare_configuration_key(
    priv::config_pixfmt,
    priv::default_pixfmt,
    config::description_t("The pixel format of the input images."));
  declare_configuration_key(
    priv::config_uri,
    config::value_t(),
    config::description_t("The URI of the resource."));

  pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);
  pixfmt_t const pixfmt = config_value<pixfmt_t>(priv::config_pixfmt);

  port_type_t const port_type_output = port_type_for_pixtype(pixtype, pixfmt);

  port_flags_t required;

  required.insert(flag_required);

  declare_output_port(
    priv::port_output,
    port_type_output,
    required,
    port_description_t("The images that are read in."));
}

read_video_gravl_process
::~read_video_gravl_process()
{
}

void
read_video_gravl_process
::_configure()
{
  // Configure the process.
  {
    pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);
    std::string const uri = config_value<std::string>(priv::config_uri);

    d.reset(new priv(uri));
  }

  if (d->uri.empty())
  {
    static std::string const reason = "The URI given was empty";
    config::value_t const value = config::value_t(d->uri);

    throw invalid_configuration_value_exception(name(), priv::config_uri, value, reason);
  }

  d->resource = gravl::raf::get_resource(d->uri.c_str());
  if (!d->resource)
  {
    std::string const reason = "Failed to open the resource: " + d->uri;

    throw invalid_configuration_exception(name(), reason);
  }

  d->video = d->resource.get_data<gravl::data_block>();
  if (!d->video)
  {
    static std::string const reason = "Failed to obtain data_block from resource";

    throw invalid_configuration_exception(name(), reason);
  }

  process::_configure();
}

void
read_video_gravl_process
::_init()
{
  d->video->rewind();

  process::_init();
}

void
read_video_gravl_process
::_step()
{
  datum_t dat;

  if (d->video->at_end())
  {
    mark_process_as_complete();
    dat = datum::complete_datum();
  }
  else if (!d->video)
  {
    static datum::error_t const err_string = datum::error_t("Error with input file stream.");

    dat = datum::error_datum(err_string);
  }
  else
  {
    gravl::frame_ptr const frame = d->video->current_frame();
    gravl::image_data const* const image_data = frame.get_const_data<gravl::image_data>();
    gravl::image const image = (image_data ? image_data->pixels() : gravl::image());

    if (!image || image.format() != gravl::image::format_of<uint8_t>())
    {
      dat = datum::empty_datum();
    }
    else
    {
      gravl::image::dimension const dim = image.dimensions();
      gravl::image::stride const ps = image.strides();
      uint8_t const* const top_left = image.data<uint8_t>();
      size_t const size = compute_block_size(dim, ps);

      // Ugh, there is no way to create a vil_image_view from existing data
      // without arranging for said existing data to stick around, so stuck
      // having to copy the data (again) :-(
      vil_memory_chunk* const mem = new vil_memory_chunk(size, VIL_PIXEL_FORMAT_BYTE);
      uint8_t* const buffer = reinterpret_cast<uint8_t*>(mem->data());
      memcpy(buffer, compute_block_start(top_left, dim, ps), size);

      vil_image_view<vxl_byte> const vil(vil_memory_chunk_sptr(mem),
                                         compute_top_left(buffer, dim, ps),
                                         dim.width, dim.height, dim.planes,
                                         ps.width, ps.height, ps.planes);
      dat = datum::new_datum(vil);
    }

    d->video->advance();
  }

  push_datum_to_port(priv::port_output, dat);

  process::_step();
}

read_video_gravl_process::priv
::priv(std::string const& input_uri)
  : uri(input_uri)
{
}

read_video_gravl_process::priv
::~priv()
{
}

}

size_t
sabs(ptrdiff_t a)
{
  return static_cast<size_t>((a < 0 ? -a : a));
}

size_t
compute_block_size(gravl::image::dimension dim, gravl::image::stride s)
{
  return ((dim.width  - 1) * sabs(s.width)) +
         ((dim.height - 1) * sabs(s.height)) +
         ((dim.planes - 1) * sabs(s.planes)) + 1;
}

ptrdiff_t
compute_offset(gravl::image::dimension dim, gravl::image::stride s)
{
  ptrdiff_t result = 0;
  if (s.width < 0)
  {
    result -= s.width * (dim.width - 1);
  }
  if (s.height < 0)
  {
    result -= s.height * (dim.height - 1);
  }
  if (s.planes < 0)
  {
    result -= s.planes * (dim.planes - 1);
  }
  return result;
}

template <typename T>
T*
compute_block_start(
  T* top_left, gravl::image::dimension dim, gravl::image::stride s)
{
  return top_left - compute_offset(dim, s);
}

template <typename T>
T*
compute_top_left(
  T* top_left, gravl::image::dimension dim, gravl::image::stride s)
{
  return top_left + compute_offset(dim, s);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: collelem.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 14:27:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basic.hxx"

#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SBXCLASS_HXX //autogen
#include <basic/sbx.hxx>
#endif
#include "collelem.hxx"

// Das Sample-Element ist ein kleines Objekt, das die Properties
// Name und Value enthlt sowie die Methode Say, die den bergebenen
// Text mit dem eigenen Namen verkoppelt und ausgibt.

SampleElement::SampleElement( const String& r ) : SbxObject( r )
{
    // Methode Say mit einem String-Parameter
    SbxVariable* pMeth = Make( String( RTL_CONSTASCII_USTRINGPARAM("Say") ), SbxCLASS_METHOD, SbxEMPTY );
    pMeth->SetUserData( 0x12345678 );
    pMeth->ResetFlag( SBX_FIXED );
    SbxInfo* pInfo_ = new SbxInfo;
    pInfo_->AddParam( String( RTL_CONSTASCII_USTRINGPARAM("text") ), SbxSTRING, SBX_READ );
    pMeth->SetInfo( pInfo_ );
}

void SampleElement::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
                                const SfxHint& rHint, const TypeId& rHintType )
{
    const SbxHint* pHint = PTR_CAST(SbxHint,&rHint);
    if( pHint )
    {
        SbxVariable* pVar = pHint->GetVar();
        SbxArray* pPar_ = pVar->GetParameters();
        ULONG t = pHint->GetId();
        if( t == SBX_HINT_DATAWANTED && pVar->GetUserData() == 0x12345678 )
        {
            // Die Say-Methode:
            // 1 Parameter + Returnwert
            if( !pPar_ || pPar_->Count() != 2 )
                SetError( SbxERR_WRONG_ARGS );
            else
            {
                String s( GetName() );
                s.AppendAscii( " says: " );
                s += pPar_->Get( 1 )->GetString();
                pPar_->Get( 0 )->SetType(SbxSTRING);
                pPar_->Get( 0 )->PutString( s );
                InfoBox( NULL, s ).Execute();
            }
            return;
        }
        SbxObject::SFX_NOTIFY( rBC, rBCType, rHint, rHintType );
    }
}

<commit_msg>INTEGRATION: CWS changefileheader (1.6.88); FILE MERGED 2008/04/01 15:01:57 thb 1.6.88.3: #i85898# Stripping all external header guards 2008/04/01 10:48:43 thb 1.6.88.2: #i85898# Stripping all external header guards 2008/03/28 16:07:37 rt 1.6.88.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: collelem.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basic.hxx"
#include <tools/errcode.hxx>
#include <vcl/msgbox.hxx>
#include <basic/sbx.hxx>
#include "collelem.hxx"

// Das Sample-Element ist ein kleines Objekt, das die Properties
// Name und Value enthlt sowie die Methode Say, die den bergebenen
// Text mit dem eigenen Namen verkoppelt und ausgibt.

SampleElement::SampleElement( const String& r ) : SbxObject( r )
{
    // Methode Say mit einem String-Parameter
    SbxVariable* pMeth = Make( String( RTL_CONSTASCII_USTRINGPARAM("Say") ), SbxCLASS_METHOD, SbxEMPTY );
    pMeth->SetUserData( 0x12345678 );
    pMeth->ResetFlag( SBX_FIXED );
    SbxInfo* pInfo_ = new SbxInfo;
    pInfo_->AddParam( String( RTL_CONSTASCII_USTRINGPARAM("text") ), SbxSTRING, SBX_READ );
    pMeth->SetInfo( pInfo_ );
}

void SampleElement::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
                                const SfxHint& rHint, const TypeId& rHintType )
{
    const SbxHint* pHint = PTR_CAST(SbxHint,&rHint);
    if( pHint )
    {
        SbxVariable* pVar = pHint->GetVar();
        SbxArray* pPar_ = pVar->GetParameters();
        ULONG t = pHint->GetId();
        if( t == SBX_HINT_DATAWANTED && pVar->GetUserData() == 0x12345678 )
        {
            // Die Say-Methode:
            // 1 Parameter + Returnwert
            if( !pPar_ || pPar_->Count() != 2 )
                SetError( SbxERR_WRONG_ARGS );
            else
            {
                String s( GetName() );
                s.AppendAscii( " says: " );
                s += pPar_->Get( 1 )->GetString();
                pPar_->Get( 0 )->SetType(SbxSTRING);
                pPar_->Get( 0 )->PutString( s );
                InfoBox( NULL, s ).Execute();
            }
            return;
        }
        SbxObject::SFX_NOTIFY( rBC, rBCType, rHint, rHintType );
    }
}

<|endoftext|>


<commit_before>//===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class contains all of the shared state and information that is used by
// the BugPoint tool to track down errors in optimizations.  This class is the
// main driver class that invokes all sub-functionality.
//
//===----------------------------------------------------------------------===//

#include "BugDriver.h"
#include "llvm/Linker.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Support/ToolRunner.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileUtilities.h"
#include <iostream>
#include <memory>

using namespace llvm;

// Anonymous namespace to define command line options for debugging.
//
namespace {
  // Output - The user can specify a file containing the expected output of the
  // program.  If this filename is set, it is used as the reference diff source,
  // otherwise the raw input run through an interpreter is used as the reference
  // source.
  //
  cl::opt<std::string>
  OutputFile("output", cl::desc("Specify a reference program output "
                                "(for miscompilation detection)"));
}

/// setNewProgram - If we reduce or update the program somehow, call this method
/// to update bugdriver with it.  This deletes the old module and sets the
/// specified one as the current program.
void BugDriver::setNewProgram(Module *M) {
  delete Program;
  Program = M;
}

/// getPassesString - Turn a list of passes into a string which indicates the
/// command line options that must be passed to add the passes.
///
std::string llvm::getPassesString(const std::vector<const PassInfo*> &Passes) {
  std::string Result;
  for (unsigned i = 0, e = Passes.size(); i != e; ++i) {
    if (i) Result += " ";
    Result += "-";
    Result += Passes[i]->getPassArgument();
  }
  return Result;
}

BugDriver::BugDriver(const char *toolname, bool as_child)
  : ToolName(toolname), ReferenceOutputFile(OutputFile),
    Program(0), Interpreter(0), cbe(0), gcc(0), run_as_child(as_child) {}

/// ParseInputFile - Given a bytecode or assembly input filename, parse and
/// return it, or return null if not possible.
///
Module *llvm::ParseInputFile(const std::string &InputFilename) {
  Module *Result = 0;
  try {
    Result = ParseBytecodeFile(InputFilename);
    if (!Result && !(Result = ParseAssemblyFile(InputFilename))){
      std::cerr << "bugpoint: could not read input file '"
                << InputFilename << "'!\n";
    }
  } catch (const ParseException &E) {
    std::cerr << "bugpoint: " << E.getMessage() << '\n';
    Result = 0;
  }
  return Result;
}

// This method takes the specified list of LLVM input files, attempts to load
// them, either as assembly or bytecode, then link them together. It returns
// true on failure (if, for example, an input bytecode file could not be
// parsed), and false on success.
//
bool BugDriver::addSources(const std::vector<std::string> &Filenames) {
  assert(Program == 0 && "Cannot call addSources multiple times!");
  assert(!Filenames.empty() && "Must specify at least on input filename!");

  // Load the first input file...
  Program = ParseInputFile(Filenames[0]);
  if (Program == 0) return true;
  if (!run_as_child)
    std::cout << "Read input file      : '" << Filenames[0] << "'\n";

  for (unsigned i = 1, e = Filenames.size(); i != e; ++i) {
    std::auto_ptr<Module> M(ParseInputFile(Filenames[i]));
    if (M.get() == 0) return true;

    if (!run_as_child)
      std::cout << "Linking in input file: '" << Filenames[i] << "'\n";
    std::string ErrorMessage;
    if (Linker::LinkModules(Program, M.get(), &ErrorMessage)) {
      std::cerr << ToolName << ": error linking in '" << Filenames[i] << "': "
                << ErrorMessage << '\n';
      return true;
    }
  }

  if (!run_as_child)
    std::cout << "*** All input ok\n";

  // All input files read successfully!
  return false;
}

/// run - The top level method that is invoked after all of the instance
/// variables are set up from command line arguments.
///
bool BugDriver::run() {
  // The first thing to do is determine if we're running as a child. If we are,
  // then what to do is very narrow. This form of invocation is only called
  // from the runPasses method to actually run those passes in a child process.
  if (run_as_child) {
    // Execute the passes
    return runPassesAsChild(PassesToRun);
  }

  // If we're not running as a child, the first thing that we must do is
  // determine what the problem is. Does the optimization series crash the
  // compiler, or does it produce illegal code?  We make the top-level
  // decision by trying to run all of the passes on the the input program,
  // which should generate a bytecode file.  If it does generate a bytecode
  // file, then we know the compiler didn't crash, so try to diagnose a
  // miscompilation.
  if (!PassesToRun.empty()) {
    std::cout << "Running selected passes on program to test for crash: ";
    if (runPasses(PassesToRun))
      return debugOptimizerCrash();
  }

  // Set up the execution environment, selecting a method to run LLVM bytecode.
  if (initializeExecutionEnvironment()) return true;

  // Test to see if we have a code generator crash.
  std::cout << "Running the code generator to test for a crash: ";
  try {
    compileProgram(Program);
    std::cout << '\n';
  } catch (ToolExecutionError &TEE) {
    std::cout << TEE.what();
    return debugCodeGeneratorCrash();
  }

  // Run the raw input to see where we are coming from.  If a reference output
  // was specified, make sure that the raw output matches it.  If not, it's a
  // problem in the front-end or the code generator.
  //
  bool CreatedOutput = false;
  if (ReferenceOutputFile.empty()) {
    std::cout << "Generating reference output from raw program: ";
    try {
      ReferenceOutputFile = executeProgramWithCBE("bugpoint.reference.out");
      CreatedOutput = true;
      std::cout << "Reference output is: " << ReferenceOutputFile << '\n';
    } catch (ToolExecutionError &TEE) {
      std::cerr << TEE.what();
      if (Interpreter != cbe) {
        std::cerr << "*** There is a bug running the C backend.  Either debug"
                  << " it (use the -run-cbe bugpoint option), or fix the error"
                  << " some other way.\n";
        return 1;
      }
      return debugCodeGeneratorCrash();
    }
  }

  // Make sure the reference output file gets deleted on exit from this
  // function, if appropriate.
  sys::Path ROF(ReferenceOutputFile);
  FileRemover RemoverInstance(ROF, CreatedOutput);

  // Diff the output of the raw program against the reference output.  If it
  // matches, then we have a miscompilation bug.
  std::cout << "*** Checking the code generator...\n";
  try {
    if (!diffProgram()) {
      std::cout << "\n*** Debugging miscompilation!\n";
      return debugMiscompilation();
    }
  } catch (ToolExecutionError &TEE) {
    std::cerr << TEE.what();
    return debugCodeGeneratorCrash();
  }

  std::cout << "\n*** Input program does not match reference diff!\n";
  std::cout << "Debugging code generator problem!\n";
  try {
    return debugCodeGenerator();
  } catch (ToolExecutionError &TEE) {
    std::cerr << TEE.what();
    return debugCodeGeneratorCrash();
  }
}

void llvm::PrintFunctionList(const std::vector<Function*> &Funcs) {
  unsigned NumPrint = Funcs.size();
  if (NumPrint > 10) NumPrint = 10;
  for (unsigned i = 0; i != NumPrint; ++i)
    std::cout << " " << Funcs[i]->getName();
  if (NumPrint < Funcs.size())
    std::cout << "... <" << Funcs.size() << " total>";
  std::cout << std::flush;
}
<commit_msg>print a nice error if bugpoint gets an error reading inputs.  Bug identified by coverity.<commit_after>//===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class contains all of the shared state and information that is used by
// the BugPoint tool to track down errors in optimizations.  This class is the
// main driver class that invokes all sub-functionality.
//
//===----------------------------------------------------------------------===//

#include "BugDriver.h"
#include "llvm/Linker.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Support/ToolRunner.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileUtilities.h"
#include <iostream>
#include <memory>

using namespace llvm;

// Anonymous namespace to define command line options for debugging.
//
namespace {
  // Output - The user can specify a file containing the expected output of the
  // program.  If this filename is set, it is used as the reference diff source,
  // otherwise the raw input run through an interpreter is used as the reference
  // source.
  //
  cl::opt<std::string>
  OutputFile("output", cl::desc("Specify a reference program output "
                                "(for miscompilation detection)"));
}

/// setNewProgram - If we reduce or update the program somehow, call this method
/// to update bugdriver with it.  This deletes the old module and sets the
/// specified one as the current program.
void BugDriver::setNewProgram(Module *M) {
  delete Program;
  Program = M;
}

/// getPassesString - Turn a list of passes into a string which indicates the
/// command line options that must be passed to add the passes.
///
std::string llvm::getPassesString(const std::vector<const PassInfo*> &Passes) {
  std::string Result;
  for (unsigned i = 0, e = Passes.size(); i != e; ++i) {
    if (i) Result += " ";
    Result += "-";
    Result += Passes[i]->getPassArgument();
  }
  return Result;
}

BugDriver::BugDriver(const char *toolname, bool as_child)
  : ToolName(toolname), ReferenceOutputFile(OutputFile),
    Program(0), Interpreter(0), cbe(0), gcc(0), run_as_child(as_child) {}

/// ParseInputFile - Given a bytecode or assembly input filename, parse and
/// return it, or return null if not possible.
///
Module *llvm::ParseInputFile(const std::string &InputFilename) {
  Module *Result = 0;
  try {
    Result = ParseBytecodeFile(InputFilename);
    if (!Result && !(Result = ParseAssemblyFile(InputFilename))){
      std::cerr << "bugpoint: could not read input file '"
                << InputFilename << "'!\n";
    }
  } catch (const ParseException &E) {
    std::cerr << "bugpoint: " << E.getMessage() << '\n';
    Result = 0;
  }
  return Result;
}

// This method takes the specified list of LLVM input files, attempts to load
// them, either as assembly or bytecode, then link them together. It returns
// true on failure (if, for example, an input bytecode file could not be
// parsed), and false on success.
//
bool BugDriver::addSources(const std::vector<std::string> &Filenames) {
  assert(Program == 0 && "Cannot call addSources multiple times!");
  assert(!Filenames.empty() && "Must specify at least on input filename!");

  try {
    // Load the first input file.
    Program = ParseInputFile(Filenames[0]);
    if (Program == 0) return true;
    if (!run_as_child)
      std::cout << "Read input file      : '" << Filenames[0] << "'\n";

    for (unsigned i = 1, e = Filenames.size(); i != e; ++i) {
      std::auto_ptr<Module> M(ParseInputFile(Filenames[i]));
      if (M.get() == 0) return true;

      if (!run_as_child)
        std::cout << "Linking in input file: '" << Filenames[i] << "'\n";
      std::string ErrorMessage;
      if (Linker::LinkModules(Program, M.get(), &ErrorMessage)) {
        std::cerr << ToolName << ": error linking in '" << Filenames[i] << "': "
                  << ErrorMessage << '\n';
        return true;
      }
    }
  } catch (const std::string &Error) {
    std::cerr << ToolName << ": error reading input '" << Error << "'\n";
    return true;
  }

  if (!run_as_child)
    std::cout << "*** All input ok\n";

  // All input files read successfully!
  return false;
}

/// run - The top level method that is invoked after all of the instance
/// variables are set up from command line arguments.
///
bool BugDriver::run() {
  // The first thing to do is determine if we're running as a child. If we are,
  // then what to do is very narrow. This form of invocation is only called
  // from the runPasses method to actually run those passes in a child process.
  if (run_as_child) {
    // Execute the passes
    return runPassesAsChild(PassesToRun);
  }

  // If we're not running as a child, the first thing that we must do is
  // determine what the problem is. Does the optimization series crash the
  // compiler, or does it produce illegal code?  We make the top-level
  // decision by trying to run all of the passes on the the input program,
  // which should generate a bytecode file.  If it does generate a bytecode
  // file, then we know the compiler didn't crash, so try to diagnose a
  // miscompilation.
  if (!PassesToRun.empty()) {
    std::cout << "Running selected passes on program to test for crash: ";
    if (runPasses(PassesToRun))
      return debugOptimizerCrash();
  }

  // Set up the execution environment, selecting a method to run LLVM bytecode.
  if (initializeExecutionEnvironment()) return true;

  // Test to see if we have a code generator crash.
  std::cout << "Running the code generator to test for a crash: ";
  try {
    compileProgram(Program);
    std::cout << '\n';
  } catch (ToolExecutionError &TEE) {
    std::cout << TEE.what();
    return debugCodeGeneratorCrash();
  }

  // Run the raw input to see where we are coming from.  If a reference output
  // was specified, make sure that the raw output matches it.  If not, it's a
  // problem in the front-end or the code generator.
  //
  bool CreatedOutput = false;
  if (ReferenceOutputFile.empty()) {
    std::cout << "Generating reference output from raw program: ";
    try {
      ReferenceOutputFile = executeProgramWithCBE("bugpoint.reference.out");
      CreatedOutput = true;
      std::cout << "Reference output is: " << ReferenceOutputFile << '\n';
    } catch (ToolExecutionError &TEE) {
      std::cerr << TEE.what();
      if (Interpreter != cbe) {
        std::cerr << "*** There is a bug running the C backend.  Either debug"
                  << " it (use the -run-cbe bugpoint option), or fix the error"
                  << " some other way.\n";
        return 1;
      }
      return debugCodeGeneratorCrash();
    }
  }

  // Make sure the reference output file gets deleted on exit from this
  // function, if appropriate.
  sys::Path ROF(ReferenceOutputFile);
  FileRemover RemoverInstance(ROF, CreatedOutput);

  // Diff the output of the raw program against the reference output.  If it
  // matches, then we have a miscompilation bug.
  std::cout << "*** Checking the code generator...\n";
  try {
    if (!diffProgram()) {
      std::cout << "\n*** Debugging miscompilation!\n";
      return debugMiscompilation();
    }
  } catch (ToolExecutionError &TEE) {
    std::cerr << TEE.what();
    return debugCodeGeneratorCrash();
  }

  std::cout << "\n*** Input program does not match reference diff!\n";
  std::cout << "Debugging code generator problem!\n";
  try {
    return debugCodeGenerator();
  } catch (ToolExecutionError &TEE) {
    std::cerr << TEE.what();
    return debugCodeGeneratorCrash();
  }
}

void llvm::PrintFunctionList(const std::vector<Function*> &Funcs) {
  unsigned NumPrint = Funcs.size();
  if (NumPrint > 10) NumPrint = 10;
  for (unsigned i = 0; i != NumPrint; ++i)
    std::cout << " " << Funcs[i]->getName();
  if (NumPrint < Funcs.size())
    std::cout << "... <" << Funcs.size() << " total>";
  std::cout << std::flush;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <queue>
#include <vector>
#include <bitset>

using namespace std;

string inFileName;
int frequencyList[256];

struct huffNode
{
	int frequency;
	char character;
	huffNode* left;
	huffNode* right;
};

struct node_comparison
{
	bool operator () (const huffNode* A, const huffNode* B) const
	{
		return A->frequency > B->frequency;
	}
};

void generateEncodings(huffNode *root, vector<bool> & encoding, vector<vector<bool>> & encodingTable)
{
	if (root != NULL) {
		if (root->character != -1)
		{
			encodingTable[root->character] = encoding;
		}
		vector<bool> leftEncoding = encoding;
		leftEncoding.push_back(false);
		vector<bool> rightEncoding = encoding;
		rightEncoding.push_back(true);

		generateEncodings(root->left,leftEncoding,encodingTable);
		generateEncodings(root->right,rightEncoding,encodingTable);
	}
}

void generateInitialPQueue(int frequencyList[256], priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap)
{
	for (int i = 0; i < 256; i++)
	{
		if (frequencyList[i] != 0)
		{
			huffNode* tempNode;
			tempNode = new huffNode;
			tempNode->frequency=frequencyList[i];
			tempNode->character = (char)i;
			tempNode->left = NULL;
			tempNode->right = NULL;
			nodeHeap.push(tempNode);
		}
	}
}

void printPQueue(priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap)
{
	if (nodeHeap.empty())
	{
		cout << "There's nothing in the heap!" << endl;
	}
	while (!nodeHeap.empty())
	{
		huffNode* tempNode;
		tempNode = nodeHeap.top();
		cout << tempNode->character << endl;
		nodeHeap.pop();
	}
}

void initializeFrequencyList(int frequencyList[256])
{
	for (int i = 0; i < 256; i++)
		frequencyList[i] = 0;
}

void generateFrequencyList(ifstream& fin, int frequencyList[256])
{
	string line = "";
	while (!fin.eof())
	{
		getline(fin,line);
		for (int i = 0; i < line.length(); i++)
		{
			frequencyList[line[i]] += 1;
		}
		frequencyList[10] += 1;
		line = "";
	}
	frequencyList[26] = 1;
}

void printFrequencyList(int frequencyList[256])
{
	for (int i = 0; i < 256; i++)
	{
		if (frequencyList[i] != 0)
		{
			cout << "Character " << (char)i << ": " << frequencyList[i] << endl;
		}
	}
}

void getEncoding(vector<bool> bitString, string &encoding)
{
	for (int i = 0; i < bitString.size(); i++)
	{
		encoding += bitString[i];
	}
}

void printEncodings(vector<vector<bool>> encodingTable)
{
	string encoding = "";
	for (int i = 0; i < 256; i++)
	{
		if (!(encodingTable[i].empty()))
		{
			getEncoding(encodingTable[i], encoding);
			cout << "Character " << (char)i << " encoding: " << encoding << endl;
			encoding = "";
		}
	}
}

void generateHuffmanTree(priority_queue <huffNode*, vector<huffNode*>, node_comparison> &heap)
{
	if (heap.size() <= 1)
		return;
	else
	{
		huffNode *node1, *node2;
		node1 = new huffNode;
		node2 = new huffNode;

		node1 = heap.top();
		heap.pop();
		node2 = heap.top();
		heap.pop();
		int totalFreq = node1->frequency + node2->frequency;

		huffNode* newNode;
		newNode = new huffNode;
		newNode->frequency = totalFreq;
		newNode->character = (char)255;
		newNode->left = node1;
		newNode->right = node2;

		heap.push(newNode);
		totalFreq = 0;
		generateHuffmanTree(heap);
	}
}

void streamFrequencyList(ofstream &fout)
{
	for (int i = 0; i < 256; i++)
	{
		if (frequencyList[i] != 0)
		{
			fout << i << ':' << frequencyList[i] << '!';
		}
	}
}

void convertBuffer(vector<bool> & ogBuffer, bitset<8> &newBuffer)
{
	for (int i = 0; i < ogBuffer.size(); i++)
	{
		newBuffer[i] = ogBuffer[i];
	}
}

void checkBuffer(vector<bool> & bitBuffer, vector<bool> & encoding, ofstream &fout)
{
	while (encoding.size() != 0 )
	{
			int availableSpace = 8 - bitBuffer.size();
			for (int i = 0; i < availableSpace; i++)
			{
				if (!encoding.empty())
				{
					bitBuffer.push_back(encoding[0]);
					encoding.erase(encoding.begin());
				}
			}

			if (bitBuffer.size() == 8)
			{
				//convert vector<bool> to bitbuffer for output
				bitset<8> outputBuffer;
				convertBuffer(bitBuffer, outputBuffer);
				unsigned char n = outputBuffer.to_ulong();
				fout << n;
				bitBuffer.clear();
			}
	}
}

void streamEncoding(ifstream &fin, ofstream &fout, vector<bool> & bitBuffer, vector<vector<bool>> encodingTable)
{
	fout << "BIZCOMPRESS" << endl; //Printing "magic number
	fout << inFileName << endl;
	streamFrequencyList(fout); //need to output frequency list/table
	fout << endl;

	string line = "";
	vector<bool> currentEncoding;
	while (!fin.eof())
	{
		getline(fin, line);
		for (int i = 0; i < line.length(); i++)
		{
			currentEncoding = encodingTable[line[i]];
			checkBuffer(bitBuffer, currentEncoding, fout);
			while (!currentEncoding.empty())
			{
				bitBuffer.push_back(currentEncoding[0]);
				currentEncoding.erase(currentEncoding.begin());
			}
		}
		currentEncoding = encodingTable[10];
		checkBuffer(bitBuffer, currentEncoding, fout);
		while (!currentEncoding.empty())
		{
			bitBuffer.push_back(currentEncoding[0]);
			currentEncoding.erase(currentEncoding.begin());
		}

		line = "";
	}
	currentEncoding = encodingTable[26];
	checkBuffer(bitBuffer, currentEncoding, fout);
	checkBuffer(bitBuffer, currentEncoding, fout);

}

int main(int argc, char* argv[])
{
	if (argc != 2)
	{
		cout << "Please rerun the program and type a source file to be compressed." << endl;
	}

	else
	{
		//argv[1] contains the filename to be provided
		inFileName = argv[1];
		ifstream fin(inFileName);
		if (fin.fail())
			cout << "Could not open target file, please rerun the program with a valid text file (.txt)." << endl;
		else
		{
			string outFileName = inFileName.substr(0, inFileName.length() - 3) + "mcp"; //assumes a .txt file (changes output to a .mcp)
			ofstream fout(outFileName, ios::binary | ios::out);
			priority_queue<huffNode*, vector<huffNode*>, node_comparison> nodeHeap;
			vector<bool> startEncoding;
			vector<vector<bool>> encodingTable(256, vector<bool>(0));
			vector<bool> bitBuffer;

			initializeFrequencyList(frequencyList);
			generateFrequencyList(fin, frequencyList);
			fin.close();
			//printFrequencyList(frequencyList);
			generateInitialPQueue(frequencyList, nodeHeap);
			generateHuffmanTree(nodeHeap);

			huffNode *root;
			root = nodeHeap.top();
			nodeHeap.pop();

			//create the encoding for each leaf node (character)
			generateEncodings(root, startEncoding, encodingTable);

			fin.open(inFileName);
			streamEncoding(fin, fout, bitBuffer, encodingTable);

		}
	}

	cout << "Done." << endl;

	cin.get();
	cin.get();

	return 0;
}<commit_msg>Adjusted some of the output to make decompression easier.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <queue>
#include <vector>
#include <bitset>

using namespace std;

string inFileName;
int frequencyList[256];

struct huffNode
{
	int frequency;
	char character;
	huffNode* left;
	huffNode* right;
};

struct node_comparison
{
	bool operator () (const huffNode* A, const huffNode* B) const
	{
		return A->frequency > B->frequency;
	}
};

void generateEncodings(huffNode *root, vector<bool> & encoding, vector<vector<bool>> & encodingTable)
{
	if (root != NULL) {
		if (root->character != -1)
		{
			encodingTable[root->character] = encoding;
		}
		vector<bool> leftEncoding = encoding;
		leftEncoding.push_back(false);
		vector<bool> rightEncoding = encoding;
		rightEncoding.push_back(true);

		generateEncodings(root->left,leftEncoding,encodingTable);
		generateEncodings(root->right,rightEncoding,encodingTable);
	}
}

void generateInitialPQueue(int frequencyList[256], priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap)
{
	for (int i = 0; i < 256; i++)
	{
		if (frequencyList[i] != 0)
		{
			huffNode* tempNode;
			tempNode = new huffNode;
			tempNode->frequency=frequencyList[i];
			tempNode->character = (char)i;
			tempNode->left = NULL;
			tempNode->right = NULL;
			nodeHeap.push(tempNode);
		}
	}
}

void printPQueue(priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap)
{
	if (nodeHeap.empty())
	{
		cout << "There's nothing in the heap!" << endl;
	}
	while (!nodeHeap.empty())
	{
		huffNode* tempNode;
		tempNode = nodeHeap.top();
		cout << tempNode->character << endl;
		nodeHeap.pop();
	}
}

void initializeFrequencyList(int frequencyList[256])
{
	for (int i = 0; i < 256; i++)
		frequencyList[i] = 0;
}

void generateFrequencyList(ifstream& fin, int frequencyList[256])
{
	string line = "";
	while (!fin.eof())
	{
		getline(fin,line);
		for (int i = 0; i < line.length(); i++)
		{
			frequencyList[line[i]] += 1;
		}
		frequencyList[10] += 1;
		line = "";
	}
	frequencyList[26] = 1;
}

void printFrequencyList(int frequencyList[256])
{
	for (int i = 0; i < 256; i++)
	{
		if (frequencyList[i] != 0)
		{
			cout << "Character " << (char)i << ": " << frequencyList[i] << endl;
		}
	}
}

void getEncoding(vector<bool> bitString, string &encoding)
{
	for (int i = 0; i < bitString.size(); i++)
	{
		encoding += bitString[i];
	}
}

void printEncodings(vector<vector<bool>> encodingTable)
{
	string encoding = "";
	for (int i = 0; i < 256; i++)
	{
		if (!(encodingTable[i].empty()))
		{
			getEncoding(encodingTable[i], encoding);
			cout << "Character " << (char)i << " encoding: " << encoding << endl;
			encoding = "";
		}
	}
}

void generateHuffmanTree(priority_queue <huffNode*, vector<huffNode*>, node_comparison> &heap)
{
	if (heap.size() <= 1)
		return;
	else
	{
		huffNode *node1, *node2;
		node1 = new huffNode;
		node2 = new huffNode;

		node1 = heap.top();
		heap.pop();
		node2 = heap.top();
		heap.pop();
		int totalFreq = node1->frequency + node2->frequency;

		huffNode* newNode;
		newNode = new huffNode;
		newNode->frequency = totalFreq;
		newNode->character = (char)255;
		newNode->left = node1;
		newNode->right = node2;

		heap.push(newNode);
		totalFreq = 0;
		generateHuffmanTree(heap);
	}
}

void streamFrequencyList(ofstream &fout)
{
	for (int i = 0; i < 256; i++)
	{
			fout << i << endl << frequencyList[i] << endl;
	}
}

void convertBuffer(vector<bool> & ogBuffer, bitset<8> &newBuffer)
{
	for (int i = 0; i < ogBuffer.size(); i++)
	{
		newBuffer[i] = ogBuffer[i];
	}
}

void checkBuffer(vector<bool> & bitBuffer, vector<bool> & encoding, ofstream &fout)
{
	while (encoding.size() != 0 )
	{
			int availableSpace = 8 - bitBuffer.size();
			for (int i = 0; i < availableSpace; i++)
			{
				if (!encoding.empty())
				{
					bitBuffer.push_back(encoding[0]);
					encoding.erase(encoding.begin());
				}
			}

			if (bitBuffer.size() == 8)
			{
				//convert vector<bool> to bitbuffer for output
				bitset<8> outputBuffer;
				convertBuffer(bitBuffer, outputBuffer);
				unsigned char n = outputBuffer.to_ulong();
				fout << n;
				bitBuffer.clear();
			}
	}
}

void streamEncoding(ifstream &fin, ofstream &fout, vector<bool> & bitBuffer, vector<vector<bool>> encodingTable)
{
	fout << "BIZCOMPRESS" << endl; //Printing "magic number
	fout << inFileName << endl;
	streamFrequencyList(fout); //need to output frequency list/table
	fout << endl;

	string line = "";
	vector<bool> currentEncoding;
	while (!fin.eof())
	{
		getline(fin, line);
		for (int i = 0; i < line.length(); i++)
		{
			currentEncoding = encodingTable[line[i]];
			checkBuffer(bitBuffer, currentEncoding, fout);
			while (!currentEncoding.empty())
			{
				bitBuffer.push_back(currentEncoding[0]);
				currentEncoding.erase(currentEncoding.begin());
			}
		}
		currentEncoding = encodingTable[10];
		checkBuffer(bitBuffer, currentEncoding, fout);
		while (!currentEncoding.empty())
		{
			bitBuffer.push_back(currentEncoding[0]);
			currentEncoding.erase(currentEncoding.begin());
		}

		line = "";
	}
	currentEncoding = encodingTable[26];
	checkBuffer(bitBuffer, currentEncoding, fout);
	checkBuffer(bitBuffer, currentEncoding, fout);

}

int main(int argc, char* argv[])
{
	if (argc != 2)
	{
		cout << "Please rerun the program and type a source file to be compressed." << endl;
	}

	else
	{
		//argv[1] contains the filename to be provided
		inFileName = argv[1];
		ifstream fin(inFileName);
		if (fin.fail())
			cout << "Could not open target file, please rerun the program with a valid text file (.txt)." << endl;
		else
		{
			string outFileName = inFileName.substr(0, inFileName.length() - 3) + "mcp"; //assumes a .txt file (changes output to a .mcp)
			ofstream fout(outFileName, ios::binary | ios::out);
			priority_queue<huffNode*, vector<huffNode*>, node_comparison> nodeHeap;
			vector<bool> startEncoding;
			vector<vector<bool>> encodingTable(256, vector<bool>(0));
			vector<bool> bitBuffer;

			initializeFrequencyList(frequencyList);
			generateFrequencyList(fin, frequencyList);
			fin.close();
			//printFrequencyList(frequencyList);
			generateInitialPQueue(frequencyList, nodeHeap);
			generateHuffmanTree(nodeHeap);

			huffNode *root;
			root = nodeHeap.top();
			nodeHeap.pop();

			//create the encoding for each leaf node (character)
			generateEncodings(root, startEncoding, encodingTable);

			fin.open(inFileName);
			streamEncoding(fin, fout, bitBuffer, encodingTable);

		}
	}

	cout << "Done." << endl;

	cin.get();
	cin.get();

	return 0;
}<|endoftext|>


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

  Auto-generated KSenseJSAPI.cpp

\**********************************************************/

#include "JSObject.h"
#include "variant_list.h"
#include "DOM/Document.h"
#include "global/config.h"
#include <cmath>

#include "KSenseJSAPI.h"

///////////////////////////////////////////////////////////////////////////////
/// @fn KSenseJSPtr KSenseJSAPI::getPlugin()
///
/// @brief  Gets a reference to the plugin that was passed in when the object
///         was created.  If the plugin has already been released then this
///         will throw a FB::script_error that will be translated into a
///         javascript exception in the page.
///////////////////////////////////////////////////////////////////////////////
KSenseJSPtr KSenseJSAPI::getPlugin()
{
    KSenseJSPtr plugin(m_plugin.lock());
    if (!plugin) {
        throw FB::script_error("The plugin is invalid");
    }
    return plugin;
}

/*	Get the number of skeletons tracked by the Kinect. */
int KSenseJSAPI::get_tracked_skeletons_count()
{
	int tracked_skeleton_count = 0;
	KSenseJSPtr plugin = getPlugin();
	SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();

	if ( !skeleton_data ) {
		return 0;
	}

	for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {
		if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) {
			tracked_skeleton_count++;
		}
	}

	return tracked_skeleton_count;
}

/*	Get a list of tracking IDs for the currently tracked skeletons. */
FB::VariantList KSenseJSAPI::get_valid_tracking_ids()
{
	KSenseJSPtr plugin = getPlugin();
	SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();
	FB::VariantList tracking_ids;

	if ( !skeleton_data ) {
		return tracking_ids;
	}

	for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {
		if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) {
			tracking_ids.push_back(skeleton_data->SkeletonData[i].dwTrackingID);
		}
	}

	return tracking_ids;
}

/*	Get the skeleton data that corresponds to the given tracking ID.  If the tracking
	ID is invalid, throw an error. */
NUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id)
{
	KSenseJSPtr plugin = getPlugin();
	SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();
	FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);
	bool found_data = false;

	if ( !skeleton_data ) {
		throw FB::script_error("No skeleton data.");
	}

	for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {
		if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED &&
			 skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) {
			return &skeleton_data->SkeletonData[i];
		}
	}

	throw FB::script_error("Invalid tracking ID");
}

/*	Get the skeleton data that corresponds to the given tracking ID.  If the tracking
	ID is invalid, throw an error.  This version checks the given frame for data. */
NUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id, SkeletonDataPtr data)
{
	SkeletonDataPtr skeleton_data = data;
	FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);
	bool found_data = false;

	if ( !skeleton_data ) {
		throw FB::script_error("No skeleton data.");
	}

	for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {
		if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED &&
			 skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) {
			return &skeleton_data->SkeletonData[i];
		}
	}

	throw FB::script_error("Invalid tracking ID");
}

/*	Format the raw skeleton data and output using the JSAPI. */
FB::VariantList KSenseJSAPI::get_skeleton_data(const int tracking_id)
{
	FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);

	NUI_SKELETON_DATA const* skeleton_data = getDataByTrackingID(tracking_id);

	for ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) {
		FB::VariantList position (3,0);
		position[0] = skeleton_data->SkeletonPositions[j].x;
		position[1] = skeleton_data->SkeletonPositions[j].y;
		position[2] = skeleton_data->SkeletonPositions[j].z;
		skeleton_data_output[j] = position;
	}

	return skeleton_data_output;
}

inline float square(float x)
{
	return x*x;
}

FB::VariantList KSenseJSAPI::getJointVelocity(const int tracking_id)
{
	FB::VariantList joint_velocity (NUI_SKELETON_POSITION_COUNT, 0);
	KSenseJSPtr plugin = getPlugin();
	SkeletonDataPtr current_ptr = plugin->getCurrentSkeletonDataPtr();
	SkeletonDataPtr previous_ptr = plugin->getPreviousSkeletonDataPtr();

	NUI_SKELETON_DATA const* current = getDataByTrackingID(tracking_id, current_ptr);
	NUI_SKELETON_DATA const* previous = getDataByTrackingID(tracking_id, previous_ptr);
	float v_x, v_y, v_z;

	for ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) {
		FB::VariantList velocity (4,0);
		velocity[1] = v_x = current->SkeletonPositions[j].x - previous->SkeletonPositions[j].x;
		velocity[2] = v_y = current->SkeletonPositions[j].y - previous->SkeletonPositions[j].y;
		velocity[3] = v_z = current->SkeletonPositions[j].z - previous->SkeletonPositions[j].z;
		velocity[0] = sqrt(square(v_x)+square(v_y)+square(v_z));
		joint_velocity[j] = velocity;
	}

	return joint_velocity;
}

void KSenseJSAPI::new_skeleton_data_event()
{
	fire_newskeletondata();
}<commit_msg>Only get velocity if both previous and current pointers are valid.<commit_after>/**********************************************************\

  Auto-generated KSenseJSAPI.cpp

\**********************************************************/

#include "JSObject.h"
#include "variant_list.h"
#include "DOM/Document.h"
#include "global/config.h"
#include <cmath>

#include "KSenseJSAPI.h"

///////////////////////////////////////////////////////////////////////////////
/// @fn KSenseJSPtr KSenseJSAPI::getPlugin()
///
/// @brief  Gets a reference to the plugin that was passed in when the object
///         was created.  If the plugin has already been released then this
///         will throw a FB::script_error that will be translated into a
///         javascript exception in the page.
///////////////////////////////////////////////////////////////////////////////
KSenseJSPtr KSenseJSAPI::getPlugin()
{
    KSenseJSPtr plugin(m_plugin.lock());
    if (!plugin) {
        throw FB::script_error("The plugin is invalid");
    }
    return plugin;
}

/*	Get the number of skeletons tracked by the Kinect. */
int KSenseJSAPI::get_tracked_skeletons_count()
{
	int tracked_skeleton_count = 0;
	KSenseJSPtr plugin = getPlugin();
	SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();

	if ( !skeleton_data ) {
		return 0;
	}

	for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {
		if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) {
			tracked_skeleton_count++;
		}
	}

	return tracked_skeleton_count;
}

/*	Get a list of tracking IDs for the currently tracked skeletons. */
FB::VariantList KSenseJSAPI::get_valid_tracking_ids()
{
	KSenseJSPtr plugin = getPlugin();
	SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();
	FB::VariantList tracking_ids;

	if ( !skeleton_data ) {
		return tracking_ids;
	}

	for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {
		if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) {
			tracking_ids.push_back(skeleton_data->SkeletonData[i].dwTrackingID);
		}
	}

	return tracking_ids;
}

/*	Get the skeleton data that corresponds to the given tracking ID.  If the tracking
	ID is invalid, throw an error. */
NUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id)
{
	KSenseJSPtr plugin = getPlugin();
	SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();
	FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);
	bool found_data = false;

	if ( !skeleton_data ) {
		throw FB::script_error("No skeleton data.");
	}

	for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {
		if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED &&
			 skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) {
			return &skeleton_data->SkeletonData[i];
		}
	}

	throw FB::script_error("Invalid tracking ID");
}

/*	Get the skeleton data that corresponds to the given tracking ID.  If the tracking
	ID is invalid, throw an error.  This version checks the given frame for data. */
NUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id, SkeletonDataPtr data)
{
	SkeletonDataPtr skeleton_data = data;
	FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);
	bool found_data = false;

	if ( !skeleton_data ) {
		throw FB::script_error("No skeleton data.");
	}

	for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {
		if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED &&
			 skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) {
			return &skeleton_data->SkeletonData[i];
		}
	}

	throw FB::script_error("Invalid tracking ID");
}

/*	Format the raw skeleton data and output using the JSAPI. */
FB::VariantList KSenseJSAPI::get_skeleton_data(const int tracking_id)
{
	FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);

	NUI_SKELETON_DATA const* skeleton_data = getDataByTrackingID(tracking_id);

	for ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) {
		FB::VariantList position (3,0);
		position[0] = skeleton_data->SkeletonPositions[j].x;
		position[1] = skeleton_data->SkeletonPositions[j].y;
		position[2] = skeleton_data->SkeletonPositions[j].z;
		skeleton_data_output[j] = position;
	}

	return skeleton_data_output;
}

//FB::VariantList KSenseJSAPI::getBoneLengths(const int tracking_id)
//{
//	FB::VariantList bone_lengths_output (NUI_SKELETON_POSITION_COUNT, 0);
//	NUI_SKELETON_DATA const* skeleton_data = getDataByTrackingID(tracking_id);
//
//	for ( int i = 0; i < NUI_SKELETON_POSITION_COUNT; i++ ) {
//
//}

inline float square(float x)
{
	return x*x;
}

/*	Calculate the velocity since the last frame of skeleton data and send to the
	javascript. */
FB::VariantList KSenseJSAPI::getJointVelocity(const int tracking_id)
{
	FB::VariantList joint_velocity (NUI_SKELETON_POSITION_COUNT, 0);
	KSenseJSPtr plugin = getPlugin();
	SkeletonDataPtr current_ptr = plugin->getCurrentSkeletonDataPtr();
	SkeletonDataPtr previous_ptr = plugin->getPreviousSkeletonDataPtr();

	NUI_SKELETON_DATA const* current = getDataByTrackingID(tracking_id, current_ptr);
	NUI_SKELETON_DATA const* previous = getDataByTrackingID(tracking_id, previous_ptr);
	float v_x, v_y, v_z;

	for ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) {
		FB::VariantList velocity (4,0.0f);
		if (current && previous) {
			velocity[1] = v_x = current->SkeletonPositions[j].x - previous->SkeletonPositions[j].x;
			velocity[2] = v_y = current->SkeletonPositions[j].y - previous->SkeletonPositions[j].y;
			velocity[3] = v_z = current->SkeletonPositions[j].z - previous->SkeletonPositions[j].z;
			velocity[0] = sqrt(square(v_x)+square(v_y)+square(v_z));
		}
		joint_velocity[j] = velocity;
	}

	return joint_velocity;
}

void KSenseJSAPI::new_skeleton_data_event()
{
	fire_newskeletondata();
}<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved
 */
#ifndef _Stroika_Foundation_Containers_SortedCollection_inl_
#define _Stroika_Foundation_Containers_SortedCollection_inl_

#include "../Debug/Assertions.h"
#include "Factory/SortedCollection_Factory.h"

namespace Stroika {
    namespace Foundation {
        namespace Containers {

            /*
             ********************************************************************************
             ***************************** SortedCollection<T> ******************************
             ********************************************************************************
             */
            template <typename T>
            inline SortedCollection<T>::SortedCollection ()
                : SortedCollection (std::less<T>{})
            {
                _AssertRepValidType ();
            }
            template <typename T>
            template <typename INORDER_COMPARER, typename ENABLE_IF_IS_COMPARER>
            inline SortedCollection<T>::SortedCollection (const INORDER_COMPARER& inorderComparer, ENABLE_IF_IS_COMPARER*)
                : inherited (move (Factory::SortedCollection_Factory<T, INORDER_COMPARER> (inorderComparer) ()))
            {
                static_assert (Common::IsInOrderComparer<INORDER_COMPARER> (), "InOrder comparer required with SortedCollection");
                _AssertRepValidType ();
            }
            template <typename T>
            inline SortedCollection<T>::SortedCollection (const _SortedCollectionRepSharedPtr& src) noexcept
                : inherited (src)
            {
                RequireNotNull (src);
                _AssertRepValidType ();
            }
            template <typename T>
            inline SortedCollection<T>::SortedCollection (_SortedCollectionRepSharedPtr&& src) noexcept
                : inherited ((RequireNotNull (src), move (src)))
            {
                _AssertRepValidType ();
            }
			template <typename T>
			inline SortedCollection<T>::SortedCollection (const initializer_list<T>& src)
				: SortedCollection ()
			{
				this->AddAll (src);
				_AssertRepValidType ();
			}
			template <typename T>
			inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const initializer_list<T>& src)
				: SortedCollection (inOrderComparer)
			{
				this->AddAll (src);
				_AssertRepValidType ();
			}
			template <typename T>
            template <typename CONTAINER_OF_T, typename ENABLE_IF>
            inline SortedCollection<T>::SortedCollection (const CONTAINER_OF_T& src)
                : SortedCollection ()
            {
                this->AddAll (src);
                _AssertRepValidType ();
            }
            template <typename T>
            template <typename CONTAINER_OF_T, typename ENABLE_IF>
            inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const CONTAINER_OF_T& src)
                : SortedCollection (inOrderComparer)
            {
                this->AddAll (src);
                _AssertRepValidType ();
            }
			template <typename T>
			template <typename COPY_FROM_ITERATOR_OF_T>
			inline SortedCollection<T>::SortedCollection (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
				: SortedCollection ()
			{
				this->AddAll (start, end);
				_AssertRepValidType ();
			}
			template <typename T>
			template <typename COPY_FROM_ITERATOR_OF_T>
			inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
				: SortedCollection (inOrderComparer)
			{
				this->AddAll (start, end);
				_AssertRepValidType ();
			}
			template <typename T>
            inline void SortedCollection<T>::_AssertRepValidType () const
            {
#if qDebug
                _SafeReadRepAccessor<_IRep>{this};
#endif
            }
        }
    }
}

#endif /* _Stroika_Foundation_Containers_SortedCollection_inl_ */
<commit_msg>SortedCollection more overloads for inorder comparer<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved
 */
#ifndef _Stroika_Foundation_Containers_SortedCollection_inl_
#define _Stroika_Foundation_Containers_SortedCollection_inl_

#include "../Debug/Assertions.h"
#include "Factory/SortedCollection_Factory.h"

namespace Stroika {
    namespace Foundation {
        namespace Containers {

            /*
             ********************************************************************************
             ***************************** SortedCollection<T> ******************************
             ********************************************************************************
             */
            template <typename T>
            inline SortedCollection<T>::SortedCollection ()
                : SortedCollection (std::less<T>{})
            {
                _AssertRepValidType ();
            }
            template <typename T>
            template <typename INORDER_COMPARER, typename ENABLE_IF_IS_COMPARER>
            inline SortedCollection<T>::SortedCollection (const INORDER_COMPARER& inorderComparer, ENABLE_IF_IS_COMPARER*)
                : inherited (move (Factory::SortedCollection_Factory<T, INORDER_COMPARER> (inorderComparer) ()))
            {
                static_assert (Common::IsInOrderComparer<INORDER_COMPARER> (), "InOrder comparer required with SortedCollection");
                _AssertRepValidType ();
            }
            template <typename T>
            inline SortedCollection<T>::SortedCollection (const _SortedCollectionRepSharedPtr& src) noexcept
                : inherited (src)
            {
                RequireNotNull (src);
                _AssertRepValidType ();
            }
            template <typename T>
            inline SortedCollection<T>::SortedCollection (_SortedCollectionRepSharedPtr&& src) noexcept
                : inherited ((RequireNotNull (src), move (src)))
            {
                _AssertRepValidType ();
            }
            template <typename T>
            inline SortedCollection<T>::SortedCollection (const initializer_list<T>& src)
                : SortedCollection ()
            {
                this->AddAll (src);
                _AssertRepValidType ();
            }
            template <typename T>
            inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const initializer_list<T>& src)
                : SortedCollection (inOrderComparer)
            {
                this->AddAll (src);
                _AssertRepValidType ();
            }
            template <typename T>
            template <typename CONTAINER_OF_T, typename ENABLE_IF>
            inline SortedCollection<T>::SortedCollection (const CONTAINER_OF_T& src)
                : SortedCollection ()
            {
                this->AddAll (src);
                _AssertRepValidType ();
            }
            template <typename T>
            template <typename CONTAINER_OF_T, typename ENABLE_IF>
            inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const CONTAINER_OF_T& src)
                : SortedCollection (inOrderComparer)
            {
                this->AddAll (src);
                _AssertRepValidType ();
            }
            template <typename T>
            template <typename COPY_FROM_ITERATOR_OF_T>
            inline SortedCollection<T>::SortedCollection (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
                : SortedCollection ()
            {
                this->AddAll (start, end);
                _AssertRepValidType ();
            }
            template <typename T>
            template <typename COPY_FROM_ITERATOR_OF_T>
            inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
                : SortedCollection (inOrderComparer)
            {
                this->AddAll (start, end);
                _AssertRepValidType ();
            }
            template <typename T>
            inline void SortedCollection<T>::_AssertRepValidType () const
            {
#if qDebug
                _SafeReadRepAccessor<_IRep>{this};
#endif
            }
        }
    }
}

#endif /* _Stroika_Foundation_Containers_SortedCollection_inl_ */
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#ifndef _Stroika_Foundation_Traversal_DelegatedIterator_inl_
#define _Stroika_Foundation_Traversal_DelegatedIterator_inl_

#include    "../Debug/Assertions.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Traversal {

            /*
             ********************************************************************************
             *********************** DelegatedIterator<T, EXTRA_DATA>::Rep ******************
             ********************************************************************************
             */
            template    <typename T, typename EXTRA_DATA>
            DelegatedIterator<T, EXTRA_DATA>::Rep::Rep (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData)
                : fDelegateTo (delegateTo)
                , fExtraData (extraData)
            {
            }
            template    <typename T, typename EXTRA_DATA>
            typename    Iterator<T>::SharedIRepPtr   DelegatedIterator<T, EXTRA_DATA>::Rep::Clone () const
            {
                return SharedIRepPtr (new Rep (*this));
            }
            template    <typename T, typename EXTRA_DATA>
            void    DelegatedIterator<T, EXTRA_DATA>::Rep::More (Memory::Optional<T>* result, bool advance)
            {
                fDelegateTo.GetRep ().More (result, advance);
            }
            template    <typename T, typename EXTRA_DATA>
            bool    DelegatedIterator<T, EXTRA_DATA>::Rep::Equals (const IRep* rhs) const
            {
                return fDelegateTo.GetRep ().Equals (rhs);
            }
            template    <typename T>
            DelegatedIterator<T, void>::Rep::Rep (const Iterator<T>& delegateTo)
                : fDelegateTo (delegateTo)
            {
            }

            /*
             ********************************************************************************
             *********************** DelegatedIterator<T, EXTRA_DATA> ***********************
             ********************************************************************************
             */
            template    <typename T, typename EXTRA_DATA>
            DelegatedIterator<T, EXTRA_DATA>::DelegatedIterator (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData)
                : Iterator<T> (SharedIRepPtr (new Rep (delegateTo, extraData)))
            {
            }

        }
    }
}
#endif /* _Stroika_Foundation_Traversal_DelegatedIterator_inl_ */
<commit_msg>minor tweaks for DelegatedIterator/gcc<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#ifndef _Stroika_Foundation_Traversal_DelegatedIterator_inl_
#define _Stroika_Foundation_Traversal_DelegatedIterator_inl_

#include    "../Debug/Assertions.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Traversal {

            /*
             ********************************************************************************
             *********************** DelegatedIterator<T, EXTRA_DATA>::Rep ******************
             ********************************************************************************
             */
            template    <typename T, typename EXTRA_DATA>
            DelegatedIterator<T, EXTRA_DATA>::Rep::Rep (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData)
                : fDelegateTo (delegateTo)
                , fExtraData (extraData)
            {
            }
            template    <typename T, typename EXTRA_DATA>
            typename    Iterator<T>::SharedIRepPtr   DelegatedIterator<T, EXTRA_DATA>::Rep::Clone () const
            {
                return SharedIRepPtr (new Rep (*this));
            }
            template    <typename T, typename EXTRA_DATA>
            void    DelegatedIterator<T, EXTRA_DATA>::Rep::More (Memory::Optional<T>* result, bool advance)
            {
                fDelegateTo.GetRep ().More (result, advance);
            }
            template    <typename T, typename EXTRA_DATA>
            bool    DelegatedIterator<T, EXTRA_DATA>::Rep::Equals (const IRep* rhs) const
            {
                return fDelegateTo.GetRep ().Equals (rhs);
            }
            template    <typename T>
            DelegatedIterator<T, void>::Rep::Rep (const Iterator<T>& delegateTo)
                : fDelegateTo (delegateTo)
            {
            }

            /*
             ********************************************************************************
             *********************** DelegatedIterator<T, EXTRA_DATA> ***********************
             ********************************************************************************
             */
            template    <typename T, typename EXTRA_DATA>
            DelegatedIterator<T, EXTRA_DATA>::DelegatedIterator (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData)
                : Iterator<T> (typename Iterator<T>::SharedIRepPtr (new Rep (delegateTo, extraData)))
            {
            }

        }
    }
}
#endif /* _Stroika_Foundation_Traversal_DelegatedIterator_inl_ */
<|endoftext|>


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

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) CS Systemes d'information. All rights reserved.
 See CSCopyright.txt 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.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbBandMathImageFilter.h"
#include "itkComplexToPhaseImageFilter.h"
#include "itkComplexToModulusImageFilter.h"
#include <itkMacro.h>

namespace otb
{
//  Application class is defined in Wrapper namespace.
namespace Wrapper
{

//  ComputeModulusAndPhase class is derived from Application class.
class ComputeModulusAndPhase: public Application
{
public:
  // Class declaration is followed by ITK public types for the class, the superclass and smart pointers.
  typedef ComputeModulusAndPhase Self;
  typedef Application Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro (Self);
  itkTypeMacro(ComputeModulusAndPhase, otb::Application);

  //typedefs for the application
  typedef otb::BandMathImageFilter<FloatImageType>       BandMathType;
  typedef itk::ComplexToModulusImageFilter<ComplexFloatImageType, FloatImageType>   ModulusFilterType;
  typedef itk::ComplexToPhaseImageFilter<ComplexFloatImageType, FloatImageType>   PhaseFilterType;

private:
  void DoInit()
  {
    SetName("ComputeModulusAndPhase");
    SetDescription("This application computes the modulus and the phase of a complex SAR data.");

    SetDocName("Compute Modulus And Phase");
    SetDocLongDescription("This application computes the modulus and the phase of a complex SAR data. This complex SAR data could be provided as a monoband complex pixel type image or a 2 bands real pixel type image or two monobands (first one real part and second one imaginary part) real pixel type images.");
    SetDocLimitations("None");
    SetDocAuthors("Alexia Mondot (alexia.mondot@c-s.fr) and Mickael Savinaud (mickael.savinaud@c-s.fr)");
    SetDocSeeAlso(" ");
    AddDocTag(Tags::SAR);

    // Choice of number of entries
    AddParameter(ParameterType_Choice, "nbinput", "Number Of inputs");
    SetParameterDescription(
        "nbinput",
        "Choice about the number of input files used to store the real and imaginary part of the SAR image");

    AddChoice("nbinput.one", "One input");
    SetParameterDescription("nbinput.one", "One input: one band (complex pixel type) SAR image or two bands (real complex type) SAR image.");

    AddChoice("nbinput.two", "Two inputs");
    SetParameterDescription("nbinput.two", "Two inputs: the first one is considered as real part and the second one as the imaginary part of the SAR image.");

    // Inputs
    // Real part of a complex image
    AddParameter(ParameterType_InputImage, "nbinput.two.re", "Real part input");
    SetParameterDescription("nbinput.two.re", "Image file with real part of the SAR data.");
    // Imaginary part of a complex image
    AddParameter(ParameterType_InputImage, "nbinput.two.im", "Imaginary part input");
    SetParameterDescription("nbinput.two.im", "Image file with imaginary part of the SAR data.");
    // Complex image
    AddParameter(ParameterType_ComplexInputImage, "nbinput.one.in", "Input image");
    SetParameterDescription("nbinput.one.in", "Image file with SAR data.");

    // Outputs
    AddParameter(ParameterType_OutputImage, "mod", "Modulus");
    SetParameterDescription("mod", "Modulus of the input: sqrt(real*real + imag*imag).");

    AddParameter(ParameterType_OutputImage, "pha", "Phase");
    SetParameterDescription("pha", "Phase of the input: atan2(imag, real).");

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("nbinput.one.in", "monobandComplexFloat.tif");
    SetDocExampleParameterValue("mod", "modulus.tif");
    SetDocExampleParameterValue("pha", "phase.tif");
  }

  // DoUpdateParameters() is called as soon as a parameter value change.
  void DoUpdateParameters()
  {
    // If one entry is choosen, disabled the re and im part
    // else disable complex
    const std::string numberOfInputs = GetParameterString("nbinput");

    if (numberOfInputs == "one")
      {
      MandatoryOn("nbinput.one.in");

      MandatoryOff("nbinput.two.re");
      DisableParameter("nbinput.two.re");

      MandatoryOff("nbinput.two.im");
      DisableParameter("nbinput.two.im");

      EnableParameter("nbinput.one.in");
      }
    else
      {
      MandatoryOff("nbinput.one.in");
      DisableParameter("nbinput.one.in");

      MandatoryOn("nbinput.two.re");
      MandatoryOn("nbinput.two.im");

      EnableParameter("nbinput.two.re");
      EnableParameter("nbinput.two.im");
      }
  }

  // DoExecute() contains the application core.
  void DoExecute()
  {

    m_modulus2 = BandMathType::New();
    m_phase2 = BandMathType::New();

    m_modulus1 = ModulusFilterType::New();
    m_phase1 = PhaseFilterType::New();

    const std::string numberOfInputs = GetParameterString("nbinput");

    if (numberOfInputs == "one")
      {
      // Get the input image
      ComplexFloatImageType::Pointer inImage = this->GetParameterComplexFloatImage("nbinput.one.in");

      m_modulus1->SetInput(inImage);
      m_phase1->SetInput(inImage);

      SetParameterOutputImage("mod", m_modulus1->GetOutput() );
      SetParameterOutputImage("pha", m_phase1->GetOutput());

      }
    else if (numberOfInputs == "two")
      {

      // Get the input image re
      FloatImageType::Pointer inImageRe = this->GetParameterFloatImage("nbinput.two.re");

      // Get the input image im
      FloatImageType::Pointer inImageIm = this->GetParameterFloatImage("nbinput.two.im");

      m_modulus2->SetNthInput(0, inImageRe,"real");
      m_modulus2->SetNthInput(1, inImageIm,"imag");
      m_modulus2->SetExpression("sqrt(real * real + imag * imag)");

      m_phase2->SetNthInput(0, inImageRe,"real");
      m_phase2->SetNthInput(1, inImageIm,"imag");
      m_phase2->SetExpression("atan2( imag , real )");

      SetParameterOutputImage("mod", m_modulus2->GetOutput() );
      SetParameterOutputImage("pha", m_phase2->GetOutput());
      }
  }

BandMathType::Pointer m_modulus2;
BandMathType::Pointer m_phase2;
ModulusFilterType::Pointer m_modulus1;
PhaseFilterType::Pointer m_phase1;
}

;} // namespace Wrapper
} // namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::ComputeModulusAndPhase)
<commit_msg>DOC: Proof read ComputeModulusAndPhase doc<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) CS Systemes d'information. All rights reserved.
 See CSCopyright.txt 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.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbBandMathImageFilter.h"
#include "itkComplexToPhaseImageFilter.h"
#include "itkComplexToModulusImageFilter.h"
#include <itkMacro.h>

namespace otb
{
//  Application class is defined in Wrapper namespace.
namespace Wrapper
{

//  ComputeModulusAndPhase class is derived from Application class.
class ComputeModulusAndPhase: public Application
{
public:
  // Class declaration is followed by ITK public types for the class, the superclass and smart pointers.
  typedef ComputeModulusAndPhase Self;
  typedef Application Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro (Self);
  itkTypeMacro(ComputeModulusAndPhase, otb::Application);

  //typedefs for the application
  typedef otb::BandMathImageFilter<FloatImageType>       BandMathType;
  typedef itk::ComplexToModulusImageFilter<ComplexFloatImageType, FloatImageType>   ModulusFilterType;
  typedef itk::ComplexToPhaseImageFilter<ComplexFloatImageType, FloatImageType>   PhaseFilterType;

private:
  void DoInit()
  {
    SetName("ComputeModulusAndPhase");
    SetDescription("This application computes the modulus and the phase of a complex SAR image.");

    SetDocName("Compute Modulus And Phase");
    SetDocLongDescription("This application computes the modulus and the phase of a complex SAR image. This complex SAR image can be provided as either: a monoband image with complex pixels, a 2 bands image with real and imaginary channels, or 2 monoband images (first one real part and second one imaginary part)");
    SetDocLimitations("None");
    SetDocAuthors("Alexia Mondot (alexia.mondot@c-s.fr) and Mickael Savinaud (mickael.savinaud@c-s.fr)");
    SetDocSeeAlso(" ");
    AddDocTag(Tags::SAR);

    // Choice of number of entries
    AddParameter(ParameterType_Choice, "nbinput", "Number Of inputs");
    SetParameterDescription(
        "nbinput",
        "Choice about the number of input files used to store the real and imaginary part of the SAR image");

    AddChoice("nbinput.one", "One input");
    SetParameterDescription("nbinput.one", "One input: one band (complex pixel type) SAR image or two bands (real complex type) SAR image.");

    AddChoice("nbinput.two", "Two inputs");
    SetParameterDescription("nbinput.two", "Two inputs: the first one is considered as real part and the second one as the imaginary part of the SAR image.");

    // Inputs
    // Real part of a complex image
    AddParameter(ParameterType_InputImage, "nbinput.two.re", "Real part input");
    SetParameterDescription("nbinput.two.re", "Image file with real part of the SAR data.");
    // Imaginary part of a complex image
    AddParameter(ParameterType_InputImage, "nbinput.two.im", "Imaginary part input");
    SetParameterDescription("nbinput.two.im", "Image file with imaginary part of the SAR data.");
    // Complex image
    AddParameter(ParameterType_ComplexInputImage, "nbinput.one.in", "Input image");
    SetParameterDescription("nbinput.one.in", "Image file with SAR data.");

    // Outputs
    AddParameter(ParameterType_OutputImage, "mod", "Modulus");
    SetParameterDescription("mod", "Modulus of the input: sqrt(real*real + imag*imag).");

    AddParameter(ParameterType_OutputImage, "pha", "Phase");
    SetParameterDescription("pha", "Phase of the input: atan2(imag, real).");

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("nbinput.one.in", "monobandComplexFloat.tif");
    SetDocExampleParameterValue("mod", "modulus.tif");
    SetDocExampleParameterValue("pha", "phase.tif");
  }

  // DoUpdateParameters() is called as soon as a parameter value change.
  void DoUpdateParameters()
  {
    // If one entry is choosen, disabled the re and im part
    // else disable complex
    const std::string numberOfInputs = GetParameterString("nbinput");

    if (numberOfInputs == "one")
      {
      MandatoryOn("nbinput.one.in");

      MandatoryOff("nbinput.two.re");
      DisableParameter("nbinput.two.re");

      MandatoryOff("nbinput.two.im");
      DisableParameter("nbinput.two.im");

      EnableParameter("nbinput.one.in");
      }
    else
      {
      MandatoryOff("nbinput.one.in");
      DisableParameter("nbinput.one.in");

      MandatoryOn("nbinput.two.re");
      MandatoryOn("nbinput.two.im");

      EnableParameter("nbinput.two.re");
      EnableParameter("nbinput.two.im");
      }
  }

  // DoExecute() contains the application core.
  void DoExecute()
  {

    m_modulus2 = BandMathType::New();
    m_phase2 = BandMathType::New();

    m_modulus1 = ModulusFilterType::New();
    m_phase1 = PhaseFilterType::New();

    const std::string numberOfInputs = GetParameterString("nbinput");

    if (numberOfInputs == "one")
      {
      // Get the input image
      ComplexFloatImageType::Pointer inImage = this->GetParameterComplexFloatImage("nbinput.one.in");

      m_modulus1->SetInput(inImage);
      m_phase1->SetInput(inImage);

      SetParameterOutputImage("mod", m_modulus1->GetOutput() );
      SetParameterOutputImage("pha", m_phase1->GetOutput());

      }
    else if (numberOfInputs == "two")
      {

      // Get the input image re
      FloatImageType::Pointer inImageRe = this->GetParameterFloatImage("nbinput.two.re");

      // Get the input image im
      FloatImageType::Pointer inImageIm = this->GetParameterFloatImage("nbinput.two.im");

      m_modulus2->SetNthInput(0, inImageRe,"real");
      m_modulus2->SetNthInput(1, inImageIm,"imag");
      m_modulus2->SetExpression("sqrt(real * real + imag * imag)");

      m_phase2->SetNthInput(0, inImageRe,"real");
      m_phase2->SetNthInput(1, inImageIm,"imag");
      m_phase2->SetExpression("atan2( imag , real )");

      SetParameterOutputImage("mod", m_modulus2->GetOutput() );
      SetParameterOutputImage("pha", m_phase2->GetOutput());
      }
  }

BandMathType::Pointer m_modulus2;
BandMathType::Pointer m_phase2;
ModulusFilterType::Pointer m_modulus1;
PhaseFilterType::Pointer m_phase1;
}

;} // namespace Wrapper
} // namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::ComputeModulusAndPhase)
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "itkFilterWatcher.h"
#include "itkGaussianImageSource.h"

int itkGaussianImageSourceTest(int, char* [] )
{
  // This can be changed!
  const unsigned int dim = 3;

  // Image typedef
  typedef itk::Image< unsigned char, dim > ImageType;

  // Create a gaussian image source
  typedef itk::GaussianImageSource< ImageType > GaussianSourceType;
  GaussianSourceType::Pointer pSource = GaussianSourceType::New();
  FilterWatcher watcher(pSource, "pSource");

  ImageType::SpacingValueType   spacing[] = { 1.2f, 1.3f, 1.4f };
  ImageType::PointValueType     origin[] = { 1.0f, 4.0f, 2.0f };
  ImageType::SizeValueType      size[] = {  130,  150,  120 };

  GaussianSourceType::ArrayType mean;
  mean[0] = size[0]/2.0f + origin[0];
  mean[1] = size[1]/2.0f + origin[1];
  mean[2] = size[2]/2.0f + origin[2];

  GaussianSourceType::ArrayType sigma;
  sigma[0] = 25.0f;
  sigma[1] = 35.0f;
  sigma[2] = 55.0f;

  pSource->SetSize( size );
  pSource->SetOrigin( origin );
  pSource->SetSpacing( spacing );
  pSource->SetMean( mean );
  pSource->SetSigma( sigma );

  // Test the get macros as well (booorrring...)
  pSource->GetSize();
  pSource->GetSpacing();
  pSource->GetOrigin();
  pSource->GetDirection();
  pSource->GetScale();
  pSource->GetNormalized();
  pSource->GetSigma();
  pSource->GetMean();

  // Test the get/set parameters
  GaussianSourceType::ParametersType params = pSource->GetParameters();
  if ( params.GetSize() != 7 )
    {
    std::cerr << "Incorrect number of parameters. Expected 7, got "
              << params.GetSize() << "." << std::endl;
    return EXIT_FAILURE;
    }

  if ( params[0] != sigma[0] || params[1] != sigma[1] || params[2] != sigma[2] )
    {
    std::cerr << "Parameters have incorrect sigma value." << std::endl;
    return EXIT_FAILURE;
    }

  if ( params[3] != mean[0] || params[4] != mean[1] || params[5] != mean[2] )
    {
    std::cerr << "Parameters have incorrect mean value." << std::endl;
    return EXIT_FAILURE;
    }

  if ( params[6] != pSource->GetScale() )
    {
    std::cerr << "Parameters have incorrect scale value." << std::endl;
    return EXIT_FAILURE;
    }

  params[0] = 12.0;
  params[1] = 13.0;
  params[2] = 14.0;
  params[3] = 22.0;
  params[4] = 32.0;
  params[5] = 42.0;
  params[6] = 55.5;
  pSource->SetParameters( params );

  if ( pSource->GetSigma()[0] != params[0] ||
       pSource->GetSigma()[1] != params[1] ||
       pSource->GetSigma()[2] != params[2] )
    {
    std::cerr << "Sigma disagrees with parameters array." << std::endl;
    std::cerr << "Sigma: " << pSource->GetSigma() << ", parameters: ["
              << params[0] << ", " << params[1] << ", " << params[2]
              << "]" << std::endl;
    return EXIT_FAILURE;
    }

  if ( pSource->GetMean()[0] != params[3] ||
       pSource->GetMean()[1] != params[4] ||
       pSource->GetMean()[2] != params[5] )
    {
    std::cerr << "Mean disagrees with parameters array." << std::endl;
    std::cerr << "Mean: " << pSource->GetMean() << ", parameters: ["
             << params[3] << ", " << params[4] << ", " << params[5]
             << "]" << std::endl;
    return EXIT_FAILURE;
    }

  if ( pSource->GetScale() != params[6] )
    {
    std::cerr << "Scale disagrees with parameters array." << std::endl;
    std::cerr << "Scale: " << pSource->GetScale() << ", parameters: "
              << params[6] << std::endl;
    return EXIT_FAILURE;
    }

  // Get the output of the source
  ImageType::Pointer pImage = pSource->GetOutput();

  // Run the pipeline
  pSource->Update();

  std::cout << pImage << std::endl;

  return EXIT_SUCCESS;
}
<commit_msg>STYLE: Improve style in itkGaussianImageSourceTest.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "itkFilterWatcher.h"
#include "itkGaussianImageSource.h"
#include "itkTestingMacros.h"

int itkGaussianImageSourceTest(int, char* [] )
{
  // This can be changed!
  const unsigned int    Dimension = 3;
  typedef unsigned char PixelType;

  // Image typedef
  typedef itk::Image< PixelType, Dimension > ImageType;

  // Create a gaussian image source
  typedef itk::GaussianImageSource< ImageType > GaussianSourceType;
  GaussianSourceType::Pointer source = GaussianSourceType::New();
  FilterWatcher watcher(source, "source");

  ImageType::SpacingValueType   spacing[] = { 1.2f, 1.3f, 1.4f };
  ImageType::PointValueType     origin[] = { 1.0f, 4.0f, 2.0f };
  ImageType::SizeValueType      size[] = {  130,  150,  120 };

  GaussianSourceType::ArrayType mean;
  mean[0] = size[0]/2.0f + origin[0];
  mean[1] = size[1]/2.0f + origin[1];
  mean[2] = size[2]/2.0f + origin[2];

  GaussianSourceType::ArrayType sigma;
  sigma[0] = 25.0f;
  sigma[1] = 35.0f;
  sigma[2] = 55.0f;

  source->SetSize( size );
  source->SetOrigin( origin );
  source->SetSpacing( spacing );
  source->SetMean( mean );
  source->SetSigma( sigma );

  // Test the get macros as well (booorrring...)
  source->GetSize();
  source->GetSpacing();
  source->GetOrigin();
  source->GetDirection();
  source->GetScale();
  source->GetNormalized();
  source->GetSigma();
  source->GetMean();

  // Test the get/set parameters
  GaussianSourceType::ParametersType params = source->GetParameters();
  if ( params.GetSize() != 7 )
    {
    std::cerr << "Incorrect number of parameters. Expected 7, got "
              << params.GetSize() << "." << std::endl;
    return EXIT_FAILURE;
    }

  if ( params[0] != sigma[0] || params[1] != sigma[1] || params[2] != sigma[2] )
    {
    std::cerr << "Parameters have incorrect sigma value." << std::endl;
    return EXIT_FAILURE;
    }

  if ( params[3] != mean[0] || params[4] != mean[1] || params[5] != mean[2] )
    {
    std::cerr << "Parameters have incorrect mean value." << std::endl;
    return EXIT_FAILURE;
    }

  if ( params[6] != source->GetScale() )
    {
    std::cerr << "Parameters have incorrect scale value." << std::endl;
    return EXIT_FAILURE;
    }

  params[0] = 12.0;
  params[1] = 13.0;
  params[2] = 14.0;
  params[3] = 22.0;
  params[4] = 32.0;
  params[5] = 42.0;
  params[6] = 55.5;
  source->SetParameters( params );

  if ( source->GetSigma()[0] != params[0] ||
       source->GetSigma()[1] != params[1] ||
       source->GetSigma()[2] != params[2] )
    {
    std::cerr << "Sigma disagrees with parameters array." << std::endl;
    std::cerr << "Sigma: " << source->GetSigma() << ", parameters: ["
              << params[0] << ", " << params[1] << ", " << params[2]
              << "]" << std::endl;
    return EXIT_FAILURE;
    }

  if ( source->GetMean()[0] != params[3] ||
       source->GetMean()[1] != params[4] ||
       source->GetMean()[2] != params[5] )
    {
    std::cerr << "Mean disagrees with parameters array." << std::endl;
    std::cerr << "Mean: " << source->GetMean() << ", parameters: ["
             << params[3] << ", " << params[4] << ", " << params[5]
             << "]" << std::endl;
    return EXIT_FAILURE;
    }

  if ( source->GetScale() != params[6] )
    {
    std::cerr << "Scale disagrees with parameters array." << std::endl;
    std::cerr << "Scale: " << source->GetScale() << ", parameters: "
              << params[6] << std::endl;
    return EXIT_FAILURE;
    }

  // Get the output of the source
  ImageType::ConstPointer image = source->GetOutput();

  // Run the pipeline
  TRY_EXPECT_NO_EXCEPTION( source->Update() );

  // Exercise the print method
  std::cout << image << std::endl;

  return EXIT_SUCCESS;
}
<|endoftext|>