<commit_before>#ifndef BYTECODES_H
#define BYTECODES_H
#include "processes.hpp"
#include"types.hpp"
#include<boost/shared_ptr.hpp>

/*
By defining the actual bytecode implementation
here, we can (?) possibly make it easier to
change the interpreter system (for example,
direct threading, maybe even dynamic inlining
some day)
*/
/*
RULE: Implementations here are concerned only with
allocating stuff and manipulating stack.  Control
flow and closure creation may very well be coupled
to the interpreter system, so we don't define them
here.
*/

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

template<Object::ref (*MF)(void)>
inline void bytecode_(ProcessStack& stack){
	stack.push( (*MF)() );
}

template<Object::ref (*MF)(Object::ref)>
inline void bytecode_(ProcessStack& stack){
	stack.top() = (*MF)(stack.top());
}

template<Object::ref (*MF)(Process&)>
inline void bytecode_(Process& proc, ProcessStack& stack){
	stack.push( (*MF)(proc) );
}

template<Object::ref const& (*MF)(Object::ref const&)>
inline void bytecode_(ProcessStack& stack){
	stack.top() = (*MF)(stack.top());
}

template<Object::ref (*MF)(Process& proc, Object::ref, Object::ref)>
inline void bytecode2_(Process& proc, ProcessStack& stack) {
  Object::ref v2 = stack.top(); stack.pop();
  stack.top() = (*MF)(proc, stack.top(), v2);
}

template<Object::ref (*MF)(Object::ref, Object::ref)>
inline void bytecode2_(ProcessStack& stack){
  Object::ref v2 = stack.top(); stack.pop();
  stack.top() = (*MF)(stack.top(), v2);
}

template<Object::ref (*MF)(Process& proc, Object::ref, Object::ref)>
inline void bytecode3_(Process& proc, ProcessStack& stack) {
  Object::ref v3 = stack.top(); stack.pop();
  Object::ref v2 = stack.top(); stack.pop();
  stack.top() = (*MF)(proc, stack.top(), v2, v3);
}

template<Object::ref (*MF)(Object::ref)>
inline void bytecode_local_push_(ProcessStack& stack, int N){
	stack.push((*MF)(stack[N]));
}

template<Object::ref const& (*MF)(Object::ref const&)>
inline void bytecode_local_push_(ProcessStack& stack, int N){
	stack.push((*MF)(stack[N]));
}

template<Object::ref (*MF)(Object::ref)>
inline void bytecode_clos_push_(ProcessStack& stack, Closure& clos, int N){
	stack.push((*MF)(clos[N]));
}

template<Object::ref const& (*MF)(Object::ref const&)>
inline void bytecode_clos_push_(ProcessStack& stack, Closure& clos, int N){
	stack.push((*MF)(clos[N]));
}

template<Object::ref (*MF)(Object::ref, Process&)>
inline void bytecode_(Process& proc, ProcessStack& stack){
	stack.top() = (*MF)(stack.top(), proc);
}

template<Object::ref (*MF)(Object::ref, Process&)>
inline void bytecode_local_push_(Process& proc, ProcessStack& stack, int N) {
	stack.push((*MF)(stack[N], proc));
}

template<Object::ref (*MF)(Object::ref, Process&)>
inline void bytecode_clos_push_(Process& proc, ProcessStack& stack,
		Closure& clos, int N){
	stack.push((*MF)(clos[N], proc));
}

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

/*parameters are on-stack*/
inline void bytecode_cons(Process& proc, ProcessStack& stack){
	Cons* cp = proc.create<Cons>();
	cp->scar(stack.top(2));
	cp->scdr(stack.top(1));
	stack.top(2) = Object::to_ref(cp);
	stack.pop();
}

inline void bytecode_check_vars(ProcessStack& stack, int N){
  if(stack.size() != N)
    throw_HlError("apply: function called with incorrect number of parameters");
}
inline void bytecode_closure_ref(ProcessStack& stack, Closure& clos, int N){
	stack.push(clos[N]);
}
inline void bytecode_global(Process& proc, ProcessStack& stack,
		Symbol *S){
  stack.push(proc.global_read(S));
}
inline void bytecode_int(Process& proc, ProcessStack& stack, int N){
  stack.push(Object::to_ref(N));
}
inline void bytecode_lit_nil(Process&proc, ProcessStack& stack){
	stack.push(Object::nil());
}
inline void bytecode_lit_t(Process&proc, ProcessStack& stack){
	stack.push(Object::t());
}
inline void bytecode_local(ProcessStack& stack, int N){
	stack.push(stack[N]);
}
inline void bytecode_global_set(Process& proc, ProcessStack& stack,
		Symbol *S){
	/*global-set has to retain the stack top! This is because
	<axiom>set has to return the value that was assigned.
	The hl-to-bytecode compiler always assumes bytecodes replace
	all their arguments with a single value; since global-set
	has a single argument, it must be replaced with a single
	value, viz. itself.
	*/
	proc.global_write(S, stack.top());
}
/*
inline void bytecode_sv_set(ProcessStack& stack){
	SharedVar* sp = dynamic_cast<SharedVar*>(stack.top(2));
	if(sp == NULL){
          throw_HlError("container: expected an object of type 'container");
	}
	sp->val = stack.top(1);
	stack.top(2) = stack.top(1);
	stack.pop();
}
*/
inline void bytecode_sym(Process& proc, ProcessStack& stack, Symbol *S) {
  stack.push(Object::to_ref(S));
}
inline void bytecode_symeval(Process& proc, ProcessStack& stack) {
  if(!is_a<Symbol*>(stack.top())) {
    throw_HlError("symeval expects a symbol");
  }
  Symbol* sp = as_a<Symbol*>(stack.top());
  stack.top() = proc.global_read(sp);
}
/*TODO: consider factoring these*/
inline void bytecode_table_create(Process& proc, ProcessStack& stack) {
  stack.push(Object::to_ref(proc.heap().create<HlTable>()));
}
inline void bytecode_table_ref(Process& proc, ProcessStack& stack) {
  HlTable& T = *expect_type<HlTable>(stack.top(2), "table-ref expects a table");
  stack.top(2) = T.lookup(stack.top(1));
  stack.pop();
}
inline void bytecode_table_sref(Process& proc, ProcessStack& stack) {
  HlTable& T = *expect_type<HlTable>(stack.top(3), "table-sref expects a table");
  HlTable::insert(proc.heap(), stack);
}
inline void bytecode_table_keys(Process& proc, ProcessStack& stack) {
  HlTable& T = *expect_type<HlTable>(stack.top(), "table-keys expects a table");
  HlTable::keys(proc.heap(), stack);
}

inline void bytecode_tag(Process& proc, ProcessStack& stack){
	/*unlike Arc, we allow the user to tag anything she or he wants.*/
	HlTagged* tp = proc.heap().create<HlTagged>();
	tp->o_type = stack.top(2);
	tp->o_rep = stack.top(1);
	stack.pop();
	stack.top() = Object::to_ref<Generic*>(tp);
}

inline void bytecode_variadic(Process& proc, ProcessStack& stack, int N){
  int i = stack.size();
  stack.push(Object::nil());
  while(i > N){
    bytecode_cons(proc, stack);
    --i;
  }
  if(i != N)
    throw_HlError("apply: insufficient number of parameters to variadic function");
}

// Math

/*integer math*/
inline void bytecode_iplus(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      stack.top() =
        Object::from_a_scaled_int(Object::to_a_scaled_int(a) +
                                  Object::to_a_scaled_int(b));
      return;
    }
  }
  throw_HlError("'i+ expected two integers");
}

inline void bytecode_iminus(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      stack.top() =
        Object::from_a_scaled_int(Object::to_a_scaled_int(a) -
                                  Object::to_a_scaled_int(b));
      return;
    }
  }
  throw_HlError("'i- expected two integers");
}

inline void bytecode_imul(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      stack.top() = Object::to_ref(as_a<int>(a) * as_a<int>(b));
      return;
    }
  }
  throw_HlError("'i* expected two integers");
}

inline void bytecode_idiv(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      int x = as_a<int>(b);
      if (x == 0)
        throw_HlError("division by zero");
      stack.top() = Object::to_ref(as_a<int>(a) / x);
      return;
    }
  }
  throw_HlError("'i/ expected two integers");
}

inline void bytecode_imod(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      int x = as_a<int>(b);
      if (x == 0)
        throw_HlError("division by zero");
      stack.top() = Object::to_ref(as_a<int>(a) % x);
      return;
    }
  }
  throw_HlError("'imod expects two integers");
}

inline void bytecode_iless(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      stack.top() =
        as_a<int>(a) < as_a<int>(b) ?          Object::t() :
        /*otherwise*/                          Object::nil() ;
      return;
    }
  }
  throw_HlError("'i< expects two integers");
}

/*float math*/
inline void bytecode_fplus(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (maybe_type<Float>(a)) {
    if (maybe_type<Float>(b)) {
      Float* fa = known_type<Float>(a);
      Float* fb = known_type<Float>(b);
      stack.top() =
        Object::to_ref(Float::mk(p, fa->get() + fb->get()));;
      return;
    }
  }
  throw_HlError("'f+ expected two floats");
}

inline void bytecode_fminus(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (maybe_type<Float>(a)) {
    if (maybe_type<Float>(b)) {
      Float* fa = known_type<Float>(a);
      Float* fb = known_type<Float>(b);
      stack.top() =
        Object::to_ref(Float::mk(p, fa->get() - fb->get()));;
      return;
    }
  }
  throw_HlError("'f- expected two floats");
}

inline void bytecode_fmul(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (maybe_type<Float>(a)) {
    if (maybe_type<Float>(b)) {
      Float* fa = known_type<Float>(a);
      Float* fb = known_type<Float>(b);
      stack.top() =
        Object::to_ref(Float::mk(p, fa->get() * fb->get()));;
      return;
    }
  }
  throw_HlError("'f* expected two floats");
}

inline void bytecode_fdiv(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (maybe_type<Float>(a)) {
    if (maybe_type<Float>(b)) {
      Float* fa = known_type<Float>(a);
      Float* fb = known_type<Float>(b);
      if(fb->get() == 0.0)
        throw_HlError("division by zero");
      stack.top() =
        Object::to_ref(Float::mk(p, fa->get() / fb->get()));;
      return;
    }
  }
  throw_HlError("'f/ expected two floats");
}

inline void bytecode_fless(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (maybe_type<Float>(a)) {
    if (maybe_type<Float>(b)) {
      Float* fa = known_type<Float>(a);
      Float* fb = known_type<Float>(b);
      stack.top() =
        fa->get() < fb->get() ?                Object::t() :
        /*otherwise*/                          Object::nil() ;
      return;
    }
  }
  throw_HlError("'f< expects two floats");
}

/*consider whether this can be factored out*/
inline void bytecode_string_create(Heap& hp, ProcessStack& stack, int N) {
	HlString::stack_create( hp, stack, N );
}
inline void bytecode_string_sref( Heap& hp, ProcessStack& stack ) {
	HlString::sref(hp, stack );
}

inline void bytecode_char(ProcessStack& stack, int N) {
	stack.push( Object::to_ref(UnicodeChar((uint32_t)N)) );
}

#endif //BYTECODES_H
<commit_msg>inc/bytecodes.hpp: Corrected number of arguments in template signature<commit_after>#ifndef BYTECODES_H
#define BYTECODES_H
#include "processes.hpp"
#include"types.hpp"
#include<boost/shared_ptr.hpp>

/*
By defining the actual bytecode implementation
here, we can (?) possibly make it easier to
change the interpreter system (for example,
direct threading, maybe even dynamic inlining
some day)
*/
/*
RULE: Implementations here are concerned only with
allocating stuff and manipulating stack.  Control
flow and closure creation may very well be coupled
to the interpreter system, so we don't define them
here.
*/

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

template<Object::ref (*MF)(void)>
inline void bytecode_(ProcessStack& stack){
	stack.push( (*MF)() );
}

template<Object::ref (*MF)(Object::ref)>
inline void bytecode_(ProcessStack& stack){
	stack.top() = (*MF)(stack.top());
}

template<Object::ref (*MF)(Process&)>
inline void bytecode_(Process& proc, ProcessStack& stack){
	stack.push( (*MF)(proc) );
}

template<Object::ref const& (*MF)(Object::ref const&)>
inline void bytecode_(ProcessStack& stack){
	stack.top() = (*MF)(stack.top());
}

template<Object::ref (*MF)(Process& proc, Object::ref, Object::ref)>
inline void bytecode2_(Process& proc, ProcessStack& stack) {
  Object::ref v2 = stack.top(); stack.pop();
  stack.top() = (*MF)(proc, stack.top(), v2);
}

template<Object::ref (*MF)(Object::ref, Object::ref)>
inline void bytecode2_(ProcessStack& stack){
  Object::ref v2 = stack.top(); stack.pop();
  stack.top() = (*MF)(stack.top(), v2);
}

template<Object::ref (*MF)(Process& proc, Object::ref, Object::ref, Object::ref)>
inline void bytecode3_(Process& proc, ProcessStack& stack) {
  Object::ref v3 = stack.top(); stack.pop();
  Object::ref v2 = stack.top(); stack.pop();
  stack.top() = (*MF)(proc, stack.top(), v2, v3);
}

template<Object::ref (*MF)(Object::ref)>
inline void bytecode_local_push_(ProcessStack& stack, int N){
	stack.push((*MF)(stack[N]));
}

template<Object::ref const& (*MF)(Object::ref const&)>
inline void bytecode_local_push_(ProcessStack& stack, int N){
	stack.push((*MF)(stack[N]));
}

template<Object::ref (*MF)(Object::ref)>
inline void bytecode_clos_push_(ProcessStack& stack, Closure& clos, int N){
	stack.push((*MF)(clos[N]));
}

template<Object::ref const& (*MF)(Object::ref const&)>
inline void bytecode_clos_push_(ProcessStack& stack, Closure& clos, int N){
	stack.push((*MF)(clos[N]));
}

template<Object::ref (*MF)(Object::ref, Process&)>
inline void bytecode_(Process& proc, ProcessStack& stack){
	stack.top() = (*MF)(stack.top(), proc);
}

template<Object::ref (*MF)(Object::ref, Process&)>
inline void bytecode_local_push_(Process& proc, ProcessStack& stack, int N) {
	stack.push((*MF)(stack[N], proc));
}

template<Object::ref (*MF)(Object::ref, Process&)>
inline void bytecode_clos_push_(Process& proc, ProcessStack& stack,
		Closure& clos, int N){
	stack.push((*MF)(clos[N], proc));
}

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

/*parameters are on-stack*/
inline void bytecode_cons(Process& proc, ProcessStack& stack){
	Cons* cp = proc.create<Cons>();
	cp->scar(stack.top(2));
	cp->scdr(stack.top(1));
	stack.top(2) = Object::to_ref(cp);
	stack.pop();
}

inline void bytecode_check_vars(ProcessStack& stack, int N){
  if(stack.size() != N)
    throw_HlError("apply: function called with incorrect number of parameters");
}
inline void bytecode_closure_ref(ProcessStack& stack, Closure& clos, int N){
	stack.push(clos[N]);
}
inline void bytecode_global(Process& proc, ProcessStack& stack,
		Symbol *S){
  stack.push(proc.global_read(S));
}
inline void bytecode_int(Process& proc, ProcessStack& stack, int N){
  stack.push(Object::to_ref(N));
}
inline void bytecode_lit_nil(Process&proc, ProcessStack& stack){
	stack.push(Object::nil());
}
inline void bytecode_lit_t(Process&proc, ProcessStack& stack){
	stack.push(Object::t());
}
inline void bytecode_local(ProcessStack& stack, int N){
	stack.push(stack[N]);
}
inline void bytecode_global_set(Process& proc, ProcessStack& stack,
		Symbol *S){
	/*global-set has to retain the stack top! This is because
	<axiom>set has to return the value that was assigned.
	The hl-to-bytecode compiler always assumes bytecodes replace
	all their arguments with a single value; since global-set
	has a single argument, it must be replaced with a single
	value, viz. itself.
	*/
	proc.global_write(S, stack.top());
}
/*
inline void bytecode_sv_set(ProcessStack& stack){
	SharedVar* sp = dynamic_cast<SharedVar*>(stack.top(2));
	if(sp == NULL){
          throw_HlError("container: expected an object of type 'container");
	}
	sp->val = stack.top(1);
	stack.top(2) = stack.top(1);
	stack.pop();
}
*/
inline void bytecode_sym(Process& proc, ProcessStack& stack, Symbol *S) {
  stack.push(Object::to_ref(S));
}
inline void bytecode_symeval(Process& proc, ProcessStack& stack) {
  if(!is_a<Symbol*>(stack.top())) {
    throw_HlError("symeval expects a symbol");
  }
  Symbol* sp = as_a<Symbol*>(stack.top());
  stack.top() = proc.global_read(sp);
}
/*TODO: consider factoring these*/
inline void bytecode_table_create(Process& proc, ProcessStack& stack) {
  stack.push(Object::to_ref(proc.heap().create<HlTable>()));
}
inline void bytecode_table_ref(Process& proc, ProcessStack& stack) {
  HlTable& T = *expect_type<HlTable>(stack.top(2), "table-ref expects a table");
  stack.top(2) = T.lookup(stack.top(1));
  stack.pop();
}
inline void bytecode_table_sref(Process& proc, ProcessStack& stack) {
  HlTable& T = *expect_type<HlTable>(stack.top(3), "table-sref expects a table");
  HlTable::insert(proc.heap(), stack);
}
inline void bytecode_table_keys(Process& proc, ProcessStack& stack) {
  HlTable& T = *expect_type<HlTable>(stack.top(), "table-keys expects a table");
  HlTable::keys(proc.heap(), stack);
}

inline void bytecode_tag(Process& proc, ProcessStack& stack){
	/*unlike Arc, we allow the user to tag anything she or he wants.*/
	HlTagged* tp = proc.heap().create<HlTagged>();
	tp->o_type = stack.top(2);
	tp->o_rep = stack.top(1);
	stack.pop();
	stack.top() = Object::to_ref<Generic*>(tp);
}

inline void bytecode_variadic(Process& proc, ProcessStack& stack, int N){
  int i = stack.size();
  stack.push(Object::nil());
  while(i > N){
    bytecode_cons(proc, stack);
    --i;
  }
  if(i != N)
    throw_HlError("apply: insufficient number of parameters to variadic function");
}

// Math

/*integer math*/
inline void bytecode_iplus(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      stack.top() =
        Object::from_a_scaled_int(Object::to_a_scaled_int(a) +
                                  Object::to_a_scaled_int(b));
      return;
    }
  }
  throw_HlError("'i+ expected two integers");
}

inline void bytecode_iminus(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      stack.top() =
        Object::from_a_scaled_int(Object::to_a_scaled_int(a) -
                                  Object::to_a_scaled_int(b));
      return;
    }
  }
  throw_HlError("'i- expected two integers");
}

inline void bytecode_imul(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      stack.top() = Object::to_ref(as_a<int>(a) * as_a<int>(b));
      return;
    }
  }
  throw_HlError("'i* expected two integers");
}

inline void bytecode_idiv(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      int x = as_a<int>(b);
      if (x == 0)
        throw_HlError("division by zero");
      stack.top() = Object::to_ref(as_a<int>(a) / x);
      return;
    }
  }
  throw_HlError("'i/ expected two integers");
}

inline void bytecode_imod(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      int x = as_a<int>(b);
      if (x == 0)
        throw_HlError("division by zero");
      stack.top() = Object::to_ref(as_a<int>(a) % x);
      return;
    }
  }
  throw_HlError("'imod expects two integers");
}

inline void bytecode_iless(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (is_a<int>(a)) {
    if (is_a<int>(b)) {
      stack.top() =
        as_a<int>(a) < as_a<int>(b) ?          Object::t() :
        /*otherwise*/                          Object::nil() ;
      return;
    }
  }
  throw_HlError("'i< expects two integers");
}

/*float math*/
inline void bytecode_fplus(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (maybe_type<Float>(a)) {
    if (maybe_type<Float>(b)) {
      Float* fa = known_type<Float>(a);
      Float* fb = known_type<Float>(b);
      stack.top() =
        Object::to_ref(Float::mk(p, fa->get() + fb->get()));;
      return;
    }
  }
  throw_HlError("'f+ expected two floats");
}

inline void bytecode_fminus(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (maybe_type<Float>(a)) {
    if (maybe_type<Float>(b)) {
      Float* fa = known_type<Float>(a);
      Float* fb = known_type<Float>(b);
      stack.top() =
        Object::to_ref(Float::mk(p, fa->get() - fb->get()));;
      return;
    }
  }
  throw_HlError("'f- expected two floats");
}

inline void bytecode_fmul(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (maybe_type<Float>(a)) {
    if (maybe_type<Float>(b)) {
      Float* fa = known_type<Float>(a);
      Float* fb = known_type<Float>(b);
      stack.top() =
        Object::to_ref(Float::mk(p, fa->get() * fb->get()));;
      return;
    }
  }
  throw_HlError("'f* expected two floats");
}

inline void bytecode_fdiv(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (maybe_type<Float>(a)) {
    if (maybe_type<Float>(b)) {
      Float* fa = known_type<Float>(a);
      Float* fb = known_type<Float>(b);
      if(fb->get() == 0.0)
        throw_HlError("division by zero");
      stack.top() =
        Object::to_ref(Float::mk(p, fa->get() / fb->get()));;
      return;
    }
  }
  throw_HlError("'f/ expected two floats");
}

inline void bytecode_fless(Process & p, ProcessStack & stack) {
  Object::ref a = stack.top(2);
  Object::ref b = stack.top(); stack.pop();
  if (maybe_type<Float>(a)) {
    if (maybe_type<Float>(b)) {
      Float* fa = known_type<Float>(a);
      Float* fb = known_type<Float>(b);
      stack.top() =
        fa->get() < fb->get() ?                Object::t() :
        /*otherwise*/                          Object::nil() ;
      return;
    }
  }
  throw_HlError("'f< expects two floats");
}

/*consider whether this can be factored out*/
inline void bytecode_string_create(Heap& hp, ProcessStack& stack, int N) {
	HlString::stack_create( hp, stack, N );
}
inline void bytecode_string_sref( Heap& hp, ProcessStack& stack ) {
	HlString::sref(hp, stack );
}

inline void bytecode_char(ProcessStack& stack, int N) {
	stack.push( Object::to_ref(UnicodeChar((uint32_t)N)) );
}

#endif //BYTECODES_H
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: unxmgr.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-15 16:18:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <cstdarg>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <osl/thread.h>

#include <vcl/svapp.hxx>
#include <plugin/impl.hxx>

using namespace std;
using namespace com::sun::star::uno;
using namespace com::sun::star::plugin;

// Unix specific implementation
static PluginDescription** CheckPlugin( const ByteString& rPath, int& rDescriptions )
{
    rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
    PluginDescription** pRet = NULL;
    rDescriptions = 0;

    ByteString aCommand( "pluginapp.bin \"" );
    aCommand.Append( rPath );
    aCommand.Append( '"' );

    FILE* pResult = popen( aCommand.GetBuffer(), "r" );
    if( pResult )
    {
        ByteString aMIME;
        char buf[256];
        while( fgets( buf, sizeof( buf ), pResult ) )
            aMIME += buf;
        pclose( pResult );
        if( aMIME.Len() > 0 )
        {
            if( aMIME.GetChar( aMIME.Len()-1 ) == '\n' )
                aMIME.Erase( aMIME.Len()-1 );
            char cTok = ';';
            if( aMIME.GetTokenCount( ';' ) > 2 )
                cTok = ';';
            if( aMIME.GetTokenCount( ':' ) > 2 )
                cTok = ':';
            ByteString aExtension = aMIME.GetToken( 1, cTok );
            int nExtensions = aExtension.GetTokenCount( ',' );
            pRet = new PluginDescription*[ nExtensions ];
            for( int i = 0; i < nExtensions; i++ )
            {
                pRet[i] = new PluginDescription;
                pRet[i]->PluginName = String( rPath, aEncoding );
                pRet[i]->Mimetype   = String( aMIME.GetToken( 0, cTok ), aEncoding );
                ByteString aExt( "*." );
                aExt += aExtension.GetToken( i, ',' ).EraseLeadingChars().EraseTrailingChars();
                pRet[i]->Extension  = String( aExt, aEncoding );
                pRet[i]->Description= String( aMIME.GetToken( 2, cTok ), aEncoding );
            }
            rDescriptions = nExtensions;
        }
    }
    return pRet;
}

Sequence<PluginDescription> XPluginManager_Impl::getPluginDescriptions() throw()
{
    static Sequence<PluginDescription> aDescriptions;
    static BOOL bHavePlugins = FALSE;
    if( ! bHavePlugins )
    {
        rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
        list<PluginDescription*> aPlugins;
        int i;

        // unix: search for plugins in /usr/lib/netscape/plugins,
        //       ~/.netscape/plugins und NPX_PLUGIN_PATH
        // additionally: search in PluginsPath
        static const char* pHome = getenv( "HOME" );
        static const char* pNPXPluginPath = getenv( "NPX_PLUGIN_PATH" );

        ByteString aSearchPath( "/usr/lib/netscape/plugins" );
        if( pHome )
        {
            aSearchPath.Append( ':' );
            aSearchPath.Append( pHome );
            aSearchPath += "/.netscape/plugins";
        }
        if( pNPXPluginPath )
        {
            aSearchPath.Append( ':' );
            aSearchPath += pNPXPluginPath;
        }

        const Sequence< ::rtl::OUString >& rPaths( PluginManager::getAdditionalSearchPaths() );
        for( i = 0; i < rPaths.getLength(); i++ )
        {
            aSearchPath += ":";
            aSearchPath += ByteString( String( rPaths.getConstArray()[i] ), aEncoding );
        }

        long aBuffer[ sizeof( struct dirent ) + _PC_NAME_MAX +1 ];
        int nPaths = aSearchPath.GetTokenCount( ':' );
        for( i = 0; i < nPaths; i++ )
        {
            ByteString aPath( aSearchPath.GetToken( i, ':' ) );
            if( aPath.Len() )
            {
                DIR* pDIR = opendir( aPath.GetBuffer() );
                struct dirent* pDirEnt = NULL;
                while( pDIR && ! readdir_r( pDIR, (struct dirent*)aBuffer, &pDirEnt ) && pDirEnt )
                {
                    struct stat aStat;
                    ByteString aFileName( aPath );
                    aFileName += "/";
                    aFileName += ((struct dirent*)aBuffer)->d_name;
                    if( ! stat( aFileName.GetBuffer(), &aStat )
                        && S_ISREG( aStat.st_mode )
                        && strncmp( ((struct dirent*)aBuffer)->d_name, "libnullplugin", 13 )
                        // cannot use flash since it needs a java runtime
                        && strncmp( ((struct dirent*)aBuffer)->d_name, "libflashplayer.so", 17 )
                        )
                    {
#if OSL_DEBUG_LEVEL > 1
                        fprintf( stderr, "Trying plugin %s ... ", aFileName.GetBuffer() );
#endif
                        int nStructs;
                        PluginDescription** pStructs =
                            CheckPlugin( aFileName, nStructs );
                        if( pStructs )
                        {
#if OSL_DEBUG_LEVEL > 1
                            fprintf( stderr, "success: %d\n", nStructs );
#endif
                            for( int i = 0; i < nStructs; i++ )
                            {
                                aPlugins.push_back( pStructs[i] );
#if OSL_DEBUG_LEVEL > 1
                                fprintf( stderr, "Mimetype: %s\nExtension: %s\n"
                                         "Description: %s\n",
                                         ::rtl::OUStringToOString( pStructs[i]->Mimetype, aEncoding ).getStr(),
                                         ::rtl::OUStringToOString( pStructs[i]->Extension, aEncoding ).getStr(),
                                         ::rtl::OUStringToOString( pStructs[i]->Description, aEncoding ).getStr()
                                         );
#endif
                            }
                            delete pStructs;
                        }
#if OSL_DEBUG_LEVEL > 1
                        else
                            fprintf(stderr, "failed\n" );
#endif
                    }
                }
                if( pDIR )
                    closedir( pDIR );
            }
        }
        aDescriptions = Sequence<PluginDescription>( aPlugins.size() );
#if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "found %d plugins\n", aPlugins.size() );
#endif
        list<PluginDescription*>::iterator iter;
        for( iter = aPlugins.begin(), i=0; iter != aPlugins.end(); ++iter ,i++ )
        {
            aDescriptions.getArray()[ i ] = **iter;
            delete *iter;
        }
        aPlugins.clear();
        bHavePlugins = TRUE;
    }
    return aDescriptions;
}

<commit_msg>INTEGRATION: CWS vcl09 (1.7.10); FILE MERGED 2003/05/08 18:46:11 pl 1.7.10.1: #109426# make rpnp.so work on Linux<commit_after>/*************************************************************************
 *
 *  $RCSfile: unxmgr.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: vg $ $Date: 2003-05-28 12:39:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <cstdarg>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <osl/thread.h>

#include <vcl/svapp.hxx>
#include <plugin/impl.hxx>

using namespace rtl;
using namespace std;
using namespace com::sun::star::uno;
using namespace com::sun::star::plugin;

// Unix specific implementation
static bool CheckPlugin( const ByteString& rPath, list< PluginDescription* >& rDescriptions )
{
#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr, "Trying plugin %s ... ", rPath.GetBuffer() );
#endif

    xub_StrLen nPos = rPath.SearchBackward( '/' );
    if( nPos == STRING_NOTFOUND )
    {
#if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "no absolute path to plugin\n" );
#endif
        return false;
    }

    ByteString aBaseName = rPath.Copy( nPos+1 );
    if( aBaseName.Equals( "libnullplugin.so" ) )
    {
#if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "don't like %s\n", aBaseName.GetBuffer() );
#endif
        return false;
    }

    struct stat aStat;
    if( stat( rPath.GetBuffer(), &aStat ) || ! S_ISREG( aStat.st_mode ) )
    {
#if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "%s is not a regular file\n", rPath.GetBuffer() );
#endif
        return false;
    }

    rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();

    ByteString aCommand( "pluginapp.bin \"" );
    aCommand.Append( rPath );
    aCommand.Append( '"' );

    FILE* pResult = popen( aCommand.GetBuffer(), "r" );
    int nDescriptions = 0;
    if( pResult )
    {
        ByteString aMIME;
        char buf[256];
        while( fgets( buf, sizeof( buf ), pResult ) )
            aMIME += buf;
        pclose( pResult );
        if( aMIME.Len() > 0 )
        {
            if( aMIME.GetChar( aMIME.Len()-1 ) == '\n' )
                aMIME.Erase( aMIME.Len()-1 );
            xub_StrLen nIndex = 0;
            while( nIndex != STRING_NOTFOUND )
            {
                ByteString aType = aMIME.GetToken( 0, ';', nIndex );

                PluginDescription* pNew = new PluginDescription;
                pNew->PluginName    = String( rPath, aEncoding );
                pNew->Mimetype  = String( aType.GetToken( 0, ':' ), aEncoding );
                ByteString aExt( "*." );
                aExt += aType.GetToken( 1, ':' ).EraseLeadingChars().EraseTrailingChars();
                pNew->Extension = String( aExt, aEncoding );
                pNew->Description= String( aType.GetToken( 2, ':' ), aEncoding );
                rDescriptions.push_back( pNew );
#if OSL_DEBUG_LEVEL > 1
                fprintf( stderr, "Mimetype: %s\nExtension: %s\n"
                         "Description: %s\n",
                         OUStringToOString( pNew->Mimetype, aEncoding ).getStr(),
                         OUStringToOString( pNew->Extension, aEncoding ).getStr(),
                         OUStringToOString( pNew->Description, aEncoding ).getStr()
                         );
#endif
            }
        }
#if OSL_DEBUG_LEVEL > 1
        else
            fprintf( stderr, "result of \"%s\" contains no mimtype:\n%s\n",
                     aCommand.GetBuffer(),
                     aMIME.GetBuffer() );
#endif
    }
#if OSL_DEBUG_LEVEL > 1
    else
        fprintf( stderr, "command \"%s\" failed\n", aCommand.GetBuffer() );
#endif
    return nDescriptions > 0;
}

Sequence<PluginDescription> XPluginManager_Impl::getPluginDescriptions() throw()
{
    static Sequence<PluginDescription> aDescriptions;
    static BOOL bHavePlugins = FALSE;
    if( ! bHavePlugins )
    {
        rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
        list<PluginDescription*> aPlugins;
        int i;

        // unix: search for plugins in /usr/lib/netscape/plugins,
        //       ~/.netscape/plugins und NPX_PLUGIN_PATH
        // additionally: search in PluginsPath
        static const char* pHome = getenv( "HOME" );
        static const char* pNPXPluginPath = getenv( "NPX_PLUGIN_PATH" );

        ByteString aSearchPath( "/usr/lib/netscape/plugins" );
        if( pHome )
        {
            aSearchPath.Append( ':' );
            aSearchPath.Append( pHome );
            aSearchPath += "/.netscape/plugins";
        }
        if( pNPXPluginPath )
        {
            aSearchPath.Append( ':' );
            aSearchPath += pNPXPluginPath;
        }

        const Sequence< ::rtl::OUString >& rPaths( PluginManager::getAdditionalSearchPaths() );
        for( i = 0; i < rPaths.getLength(); i++ )
        {
            aSearchPath += ":";
            aSearchPath += ByteString( String( rPaths.getConstArray()[i] ), aEncoding );
        }

        long aBuffer[ sizeof( struct dirent ) + _PC_NAME_MAX +1 ];
        int nPaths = aSearchPath.GetTokenCount( ':' );
        for( i = 0; i < nPaths; i++ )
        {
            ByteString aPath( aSearchPath.GetToken( i, ':' ) );
            if( aPath.Len() )
            {
                DIR* pDIR = opendir( aPath.GetBuffer() );
                struct dirent* pDirEnt = NULL;
                while( pDIR && ! readdir_r( pDIR, (struct dirent*)aBuffer, &pDirEnt ) && pDirEnt )
                {
                    char* pBaseName = ((struct dirent*)aBuffer)->d_name;
                    if( pBaseName[0] != '.' ||
                        pBaseName[1] != '.' ||
                        pBaseName[2] != 0 )
                    {
                        ByteString aFileName( aPath );
                        aFileName += "/";
                        aFileName += pBaseName;
                        CheckPlugin( aFileName, aPlugins );
                    }
                }
                if( pDIR )
                    closedir( pDIR );
            }
        }

        // try ~/.mozilla/pluginreg.dat
        ByteString aMozPluginreg( pHome );
        aMozPluginreg.Append( "/.mozilla/pluginreg.dat" );
        FILE* fp = fopen( aMozPluginreg.GetBuffer(), "r" );
        if( fp )
        {
#if OSL_DEBUG_LEVEL > 1
            fprintf( stderr, "parsing %s\n", aMozPluginreg.GetBuffer() );
#endif
            char aLine[1024];
            while( fgets( aLine, sizeof( aLine ), fp ) )
            {
                int nLineLen = strlen( aLine );
                int nDotPos;
                for( nDotPos = nLineLen-1; nDotPos > 0 && aLine[nDotPos] != ':'; nDotPos-- )
                    ;
                if( aLine[0] == '/' && aLine[nDotPos] == ':' && aLine[nDotPos+1] == '$' )
                    CheckPlugin( ByteString( aLine, nDotPos ), aPlugins );
            }
            fclose( fp );
        }

        // create return value
        aDescriptions = Sequence<PluginDescription>( aPlugins.size() );
#if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "found %d plugins\n", aPlugins.size() );
#endif
        list<PluginDescription*>::iterator iter;
        for( iter = aPlugins.begin(), i=0; iter != aPlugins.end(); ++iter ,i++ )
        {
            aDescriptions.getArray()[ i ] = **iter;
            delete *iter;
        }
        aPlugins.clear();
        bHavePlugins = TRUE;
    }
    return aDescriptions;
}

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkFastNumericConversion.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
// .NAME vtkFastNumericConversion - Enables fast conversion of floating point to fixed point
// .SECTION Description
// vtkFastNumericConversion uses a portable (assuming IEEE format) method for converting single and
// double precision floating point values to a fixed point representation. This allows fast
// integer flooring on platforms, such as Intel X86, in which CPU floating point flooring
// algorithms are very slow. It is based on the techniques described in Chris Hecker's article,
// "Let's Get to the (Floating) Point", in Game Developer Magazine, Feb/Mar 1996, and the
// techniques described in Michael Herf's website, http://www.stereopsis.com/FPU.html.
// The Hecker article can be found at http://www.d6.com/users/checker/pdfs/gdmfp.pdf.
// Unfortunately, each of these techniques is incomplete, and doesn't floor properly,
// in a way that depends on how many bits are reserved for fixed point fractional use, due to
// failing to properly account for the default round-towards-even rounding mode of the X86. Thus,
// my implementation incorporates some rounding correction that undoes the rounding that the
// FPU performs during denormalization of the floating point value. Note that
// the rounding affect I'm talking about here is not the effect on the fistp instruction,
// but rather the effect that occurs during the denormalization of a value that occurs when
// adding it to a much larger value. The bits must be shifted to the right, and when a "1" bit
// falls off the edge, the rounding mode determines what happens next, in order
// to avoid completely "losing" the 1-bit. Furthermore, my implementation works on Linux, where the
// default precision mode is 64-bit extended precision.

// This class is contributed to VTK by Chris Volpe of Applied Research Associates, Inc.
// (My employer requires me to say that -- CRV)

#include "vtkFastNumericConversion.h"
#include "vtkObjectFactory.h"
#include "vtkTimerLog.h"

vtkStandardNewMacro(vtkFastNumericConversion);

void vtkFastNumericConversion::InternalRebuild()
{
  int i;
  this->fixRound=.5;
  for (i=this->internalReservedFracBits; i; i--)
    {
    this->fixRound *= .5;
    }
  this->fracMask = (1<<this->internalReservedFracBits)-1;
  this->fpDenormalizer = (static_cast<unsigned long>(1) << (52-30-this->internalReservedFracBits)) *
    this->two30() * this->BorrowBit();
  this->epTempDenormalizer = this->fpDenormalizer * (static_cast<unsigned long>(1) << (63-52));
}

void vtkFastNumericConversion::PrintSelf(ostream &os, vtkIndent indent)
{
  os << indent << "ReservedFracBits: " << this->internalReservedFracBits << endl;
}
<commit_msg>Remove unused vtkTimerlog.h.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkFastNumericConversion.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
// .NAME vtkFastNumericConversion - Enables fast conversion of floating point to fixed point
// .SECTION Description
// vtkFastNumericConversion uses a portable (assuming IEEE format) method for converting single and
// double precision floating point values to a fixed point representation. This allows fast
// integer flooring on platforms, such as Intel X86, in which CPU floating point flooring
// algorithms are very slow. It is based on the techniques described in Chris Hecker's article,
// "Let's Get to the (Floating) Point", in Game Developer Magazine, Feb/Mar 1996, and the
// techniques described in Michael Herf's website, http://www.stereopsis.com/FPU.html.
// The Hecker article can be found at http://www.d6.com/users/checker/pdfs/gdmfp.pdf.
// Unfortunately, each of these techniques is incomplete, and doesn't floor properly,
// in a way that depends on how many bits are reserved for fixed point fractional use, due to
// failing to properly account for the default round-towards-even rounding mode of the X86. Thus,
// my implementation incorporates some rounding correction that undoes the rounding that the
// FPU performs during denormalization of the floating point value. Note that
// the rounding affect I'm talking about here is not the effect on the fistp instruction,
// but rather the effect that occurs during the denormalization of a value that occurs when
// adding it to a much larger value. The bits must be shifted to the right, and when a "1" bit
// falls off the edge, the rounding mode determines what happens next, in order
// to avoid completely "losing" the 1-bit. Furthermore, my implementation works on Linux, where the
// default precision mode is 64-bit extended precision.

// This class is contributed to VTK by Chris Volpe of Applied Research Associates, Inc.
// (My employer requires me to say that -- CRV)

#include "vtkFastNumericConversion.h"
#include "vtkObjectFactory.h"

vtkStandardNewMacro(vtkFastNumericConversion);

void vtkFastNumericConversion::InternalRebuild()
{
  int i;
  this->fixRound=.5;
  for (i=this->internalReservedFracBits; i; i--)
    {
    this->fixRound *= .5;
    }
  this->fracMask = (1<<this->internalReservedFracBits)-1;
  this->fpDenormalizer = (static_cast<unsigned long>(1) << (52-30-this->internalReservedFracBits)) *
    this->two30() * this->BorrowBit();
  this->epTempDenormalizer = this->fpDenormalizer * (static_cast<unsigned long>(1) << (63-52));
}

void vtkFastNumericConversion::PrintSelf(ostream &os, vtkIndent indent)
{
  os << indent << "ReservedFracBits: " << this->internalReservedFracBits << endl;
}
<|endoftext|>


<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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
//
// 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 <string>

#include <utils.hpp>

#ifndef FLOPS_HPP
#define FLOPS_HPP

namespace isa {
namespace Benchmarks {

  std::string  * getFlopsOpenCL(const unsigned int iterations, const unsigned int vector, const std::string & dataType);

// Implementations
std::string * getFlopsOpenCL(const unsigned int iterations, const unsigned int vector, const std::string & dataType) {
  std::string * code = new std::string();

  if ( vector == 1 ) {
    *code = "__kernel void flops(__global const " + dataType + " * restrict const A, __global const " + dataType + " * restrict const B, __global " + dataType + " * C) {\n"
      + dataType + " a;\n"
      + dataType + " b;\n"
      + dataType + " c;\n"
      // Load
      "a = A[get_global_id(0)];\n"
      "b = B[get_global_id(0)];\n"
      // Compute
      "<%COMPUTE%>"
      // Store
      "C[get_global_id(0)] = c;\n"
      "}\n";
  } else {
    *code = "__kernel void flops(__global const " + dataType + " * restrict const A, __global const " + dataType + " * restrict const B, __global " + dataType + " * C) {\n"
      + dataType + isa::utils::toString(vector) + " a;\n"
      + dataType + isa::utils::toString(vector) + " b;\n"
      + dataType + isa::utils::toString(vector) + " c;\n"
      // Load
      "a = vload" + isa::utils::toString(vector) + "(0, &(A[get_global_id(0) * " + isa::utils::toString(vector) + "]));\n"
      "b = vload" + isa::utils::toString(vector) + "(0, &(B[get_global_id(0) * " + isa::utils::toString(vector) + "]));\n"
      // Compute
      "<%COMPUTE%>"
      // Store
      "vstore" + isa::utils::toString(vector) + "(c, 0, &(C[get_global_id(0) * " + isa::utils::toString(vector) + "]));\n"
      "}\n";
  }
  std::string computeTemplate = "c = (a + b) * get_local_id(0);\n";

  std::string * compute_s = new std::string();

  for ( unsigned int i = 0; i < iterations; i++ ) {
    compute_s->append(computeTemplate);
  }

  code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);

  return code;
}

} // Benchmarks
} // isa

#endif

<commit_msg>Style.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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
//
// 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 <string>

#include <utils.hpp>

#ifndef FLOPS_HPP
#define FLOPS_HPP

namespace isa {
namespace Benchmarks {

std::string  * getFlopsOpenCL(const unsigned int iterations, const unsigned int vector, const std::string & dataType);

// Implementations
std::string * getFlopsOpenCL(const unsigned int iterations, const unsigned int vector, const std::string & dataType) {
  std::string * code = new std::string();

  if ( vector == 1 ) {
    *code = "__kernel void flops(__global const " + dataType + " * restrict const A, __global const " + dataType + " * restrict const B, __global " + dataType + " * C) {\n"
      + dataType + " a;\n"
      + dataType + " b;\n"
      + dataType + " c;\n"
      // Load
      "a = A[get_global_id(0)];\n"
      "b = B[get_global_id(0)];\n"
      // Compute
      "<%COMPUTE%>"
      // Store
      "C[get_global_id(0)] = c;\n"
      "}\n";
  } else {
    *code = "__kernel void flops(__global const " + dataType + " * restrict const A, __global const " + dataType + " * restrict const B, __global " + dataType + " * C) {\n"
      + dataType + isa::utils::toString(vector) + " a;\n"
      + dataType + isa::utils::toString(vector) + " b;\n"
      + dataType + isa::utils::toString(vector) + " c;\n"
      // Load
      "a = vload" + isa::utils::toString(vector) + "(0, &(A[get_global_id(0) * " + isa::utils::toString(vector) + "]));\n"
      "b = vload" + isa::utils::toString(vector) + "(0, &(B[get_global_id(0) * " + isa::utils::toString(vector) + "]));\n"
      // Compute
      "<%COMPUTE%>"
      // Store
      "vstore" + isa::utils::toString(vector) + "(c, 0, &(C[get_global_id(0) * " + isa::utils::toString(vector) + "]));\n"
      "}\n";
  }
  std::string computeTemplate = "c = (a + b) * get_local_id(0);\n";

  std::string * compute_s = new std::string();

  for ( unsigned int i = 0; i < iterations; i++ ) {
    compute_s->append(computeTemplate);
  }

  code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);

  return code;
}

} // Benchmarks
} // isa

#endif

<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkPointSetWriter.h"
#include <iostream>
#include <fstream>
#include <locale>

//
// Initialization of the xml tags.
//

const char* mitk::PointSetWriter::XML_POINT_SET_FILE = "point_set_file" ;

const char* mitk::PointSetWriter::XML_FILE_VERSION = "file_version" ;

const char* mitk::PointSetWriter::XML_POINT_SET = "point_set" ;

const char* mitk::PointSetWriter::XML_TIME_SERIES = "time_series";

const char* mitk::PointSetWriter::XML_TIME_SERIES_ID = "time_series_id";

const char* mitk::PointSetWriter::XML_POINT = "point" ;

const char* mitk::PointSetWriter::XML_ID = "id" ;

const char* mitk::PointSetWriter::XML_SPEC = "specification" ;

const char* mitk::PointSetWriter::XML_X = "x" ;

const char* mitk::PointSetWriter::XML_Y = "y" ;

const char* mitk::PointSetWriter::XML_Z = "z" ;

const char* mitk::PointSetWriter::VERSION_STRING = "0.1" ;

mitk::PointSetWriter::PointSetWriter()
    : m_FileName(""), m_FilePrefix(""), m_FilePattern("")
{
    this->SetNumberOfRequiredInputs( 1 );
    this->SetNumberOfOutputs( 1 );
    this->SetNthOutput( 0, mitk::PointSet::New().GetPointer() );
    m_Indent = 2;
    m_IndentDepth = 0;
    m_Success = false;
}

mitk::PointSetWriter::~PointSetWriter()
{}

void mitk::PointSetWriter::GenerateData()
{
    m_Success = false;
    m_IndentDepth = 0;

    //
    // Opening the file to write to
    //
    if ( m_FileName == "" )
    {
        itkWarningMacro( << "Sorry, filename has not been set!" );
        return ;
    }
    std::ofstream out( m_FileName.c_str() );
    if ( !out.good() )
    {
      itkExceptionMacro(<< "File " << m_FileName << " could not be opened!");
      itkWarningMacro( << "Sorry, file " << m_FileName << " could not be opened!" );
      out.close();
        return ;
    }

    std::locale previousLocale(out.getloc());
    std::locale I("C");
    out.imbue(I);

    //
    // Here the actual xml writing begins
    //
    WriteXMLHeader( out );
    WriteStartElement( XML_POINT_SET_FILE, out );
    WriteStartElement( XML_FILE_VERSION, out );
    WriteCharacterData( VERSION_STRING, out );
    WriteEndElement( XML_FILE_VERSION, out, false );

    //
    // for each input object write its xml representation to
    // the stream
    //
    for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i )
    {
        InputType::Pointer pointSet = this->GetInput( i );
        assert( pointSet.IsNotNull() );
        WriteXML( pointSet.GetPointer(), out );
    }

   WriteEndElement( XML_POINT_SET_FILE, out );
   out.imbue(previousLocale);
    if ( !out.good() ) // some error during output
    {
      out.close();
      throw std::ios_base::failure("Some error during point set writing.");
    }

    out.close();
    m_Success = true;
    m_MimeType = "application/MITK.PointSet";
}

void mitk::PointSetWriter::WriteXML( mitk::PointSet* pointSet, std::ofstream& out )
{
    WriteStartElement( XML_POINT_SET, out );
    mitk::PointSet::PointsContainer* pointsContainer = pointSet->GetPointSet()->GetPoints();
    mitk::PointSet::PointsContainer::Iterator it;

    unsigned int timecount = pointSet->GetTimeSteps();

    for(unsigned int i=0; i< timecount; i++)
    {
      WriteStartElement( XML_TIME_SERIES, out );

      WriteStartElement( XML_TIME_SERIES_ID, out );
      WriteCharacterData( ConvertToString( i ).c_str() , out );
      WriteEndElement( XML_TIME_SERIES_ID, out, false );

      for ( it = pointsContainer->Begin(); it != pointsContainer->End(); ++it )
      {
          WriteStartElement( XML_POINT, out );

          WriteStartElement( XML_ID, out );
          WriteCharacterData( ConvertToString( it->Index() ).c_str() , out );
          WriteEndElement( XML_ID, out, false );

          mitk::PointSet::PointType point = it->Value();

          WriteStartElement( XML_SPEC, out );
          WriteCharacterData( ConvertToString( pointSet->GetSpecificationTypeInfo(it->Index(), i) ).c_str() , out );
          WriteEndElement( XML_SPEC, out, false );

          WriteStartElement( XML_X, out );
          WriteCharacterData( ConvertToString( point[ 0 ] ).c_str(), out );
          WriteEndElement( XML_X, out, false );

          WriteStartElement( XML_Y, out );
          WriteCharacterData( ConvertToString( point[ 1 ] ).c_str(), out );
          WriteEndElement( XML_Y, out, false );

          WriteStartElement( XML_Z, out );
          WriteCharacterData( ConvertToString( point[ 2 ] ).c_str(), out );
          WriteEndElement( XML_Z, out, false );

          WriteEndElement( XML_POINT, out );
      }
    WriteEndElement( XML_TIME_SERIES, out );
    }

    WriteEndElement( XML_POINT_SET, out );
}

void mitk::PointSetWriter::ResizeInputs( const unsigned int& num )
{
    unsigned int prevNum = this->GetNumberOfInputs();
    this->SetNumberOfInputs( num );
    for ( unsigned int i = prevNum; i < num; ++i )
    {
        this->SetNthInput( i, mitk::PointSet::New().GetPointer() );
    }
}

void mitk::PointSetWriter::SetInput( InputType* pointSet )
{
    this->ProcessObject::SetNthInput( 0, pointSet );
}

void mitk::PointSetWriter::SetInput( const unsigned int& id, InputType* pointSet )
{
    if ( id >= this->GetNumberOfInputs() )
        this->ResizeInputs( id + 1 );
    this->ProcessObject::SetNthInput( id, pointSet );
}

mitk::PointSet* mitk::PointSetWriter::GetInput()
{
    if ( this->GetNumberOfInputs() < 1 )
    {
        return 0;
    }
    else
    {
        return dynamic_cast<InputType*> ( this->GetInput( 0 ) );
    }
}

mitk::PointSet* mitk::PointSetWriter::GetInput( const unsigned int& num )
{
    return dynamic_cast<InputType*> ( this->ProcessObject::GetInput( num ) );
}

template < typename T>
std::string mitk::PointSetWriter::ConvertToString( T value )
{
    std::ostringstream o;
    std::locale I("C");
    o.imbue(I);

    if ( o << value )
    {
        return o.str();
     }
    else
        return "conversion error";
}

void mitk::PointSetWriter::WriteXMLHeader( std::ofstream &file )
{
    file << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
}

void mitk::PointSetWriter::WriteStartElement( const char *const tag, std::ofstream &file )
{
    file << std::endl;
    WriteIndent( file );
    file << '<' << tag << '>';
    m_IndentDepth++;
}

void mitk::PointSetWriter::WriteEndElement( const char *const tag, std::ofstream &file, const bool& indent )
{
    m_IndentDepth--;
    if ( indent )
    {
        file << std::endl;
        WriteIndent( file );
    }
    file << '<' << '/' << tag << '>';
}

void mitk::PointSetWriter::WriteCharacterData( const char *const data, std::ofstream &file )
{
    file << data;
}

void mitk::PointSetWriter::WriteStartElement( std::string &tag, std::ofstream &file )
{
    WriteStartElement( tag.c_str(), file );
}

void mitk::PointSetWriter::WriteEndElement( std::string &tag, std::ofstream &file, const bool& indent )
{
    WriteEndElement( tag.c_str(), file, indent );
}

void mitk::PointSetWriter::WriteCharacterData( std::string &data, std::ofstream &file )
{
    WriteCharacterData( data.c_str(), file );
}

void mitk::PointSetWriter::WriteIndent( std::ofstream& file )
{
    std::string spaces( m_IndentDepth * m_Indent, ' ' );
    file << spaces.c_str();
}

bool mitk::PointSetWriter::GetSuccess() const
{
    return m_Success;
}

bool mitk::PointSetWriter::CanWriteDataType( DataNode* input )
{
  if ( input )
  {
    mitk::BaseData* data = input->GetData();
    if ( data )
    {
       mitk::PointSet::Pointer pointSet = dynamic_cast<mitk::PointSet*>( data );
       if( pointSet.IsNotNull() )
       {
         //this writer has no "SetDefaultExtension()" - function
         m_Extension = ".mps";
         return true;
       }
    }
  }
  return false;
}

void mitk::PointSetWriter::SetInput( DataNode* input )
{
  if( input && CanWriteDataType( input ) )
    this->ProcessObject::SetNthInput( 0, dynamic_cast<mitk::PointSet*>( input->GetData() ) );
}

std::string mitk::PointSetWriter::GetWritenMIMEType()
{
  return m_MimeType;
}

std::vector<std::string> mitk::PointSetWriter::GetPossibleFileExtensions()
{
  std::vector<std::string> possibleFileExtensions;
  possibleFileExtensions.push_back(".mps");
  return possibleFileExtensions;
}

std::string mitk::PointSetWriter::GetFileExtension()
{
  return m_Extension;
}
<commit_msg>Support 4D point set<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkPointSetWriter.h"
#include <iostream>
#include <fstream>
#include <locale>

//
// Initialization of the xml tags.
//

const char* mitk::PointSetWriter::XML_POINT_SET_FILE = "point_set_file" ;

const char* mitk::PointSetWriter::XML_FILE_VERSION = "file_version" ;

const char* mitk::PointSetWriter::XML_POINT_SET = "point_set" ;

const char* mitk::PointSetWriter::XML_TIME_SERIES = "time_series";

const char* mitk::PointSetWriter::XML_TIME_SERIES_ID = "time_series_id";

const char* mitk::PointSetWriter::XML_POINT = "point" ;

const char* mitk::PointSetWriter::XML_ID = "id" ;

const char* mitk::PointSetWriter::XML_SPEC = "specification" ;

const char* mitk::PointSetWriter::XML_X = "x" ;

const char* mitk::PointSetWriter::XML_Y = "y" ;

const char* mitk::PointSetWriter::XML_Z = "z" ;

const char* mitk::PointSetWriter::VERSION_STRING = "0.1" ;

mitk::PointSetWriter::PointSetWriter()
    : m_FileName(""), m_FilePrefix(""), m_FilePattern("")
{
    this->SetNumberOfRequiredInputs( 1 );
    this->SetNumberOfOutputs( 1 );
    this->SetNthOutput( 0, mitk::PointSet::New().GetPointer() );
    m_Indent = 2;
    m_IndentDepth = 0;
    m_Success = false;
}

mitk::PointSetWriter::~PointSetWriter()
{}

void mitk::PointSetWriter::GenerateData()
{
    m_Success = false;
    m_IndentDepth = 0;

    //
    // Opening the file to write to
    //
    if ( m_FileName == "" )
    {
        itkWarningMacro( << "Sorry, filename has not been set!" );
        return ;
    }
    std::ofstream out( m_FileName.c_str() );
    if ( !out.good() )
    {
      itkExceptionMacro(<< "File " << m_FileName << " could not be opened!");
      itkWarningMacro( << "Sorry, file " << m_FileName << " could not be opened!" );
      out.close();
        return ;
    }

    std::locale previousLocale(out.getloc());
    std::locale I("C");
    out.imbue(I);

    //
    // Here the actual xml writing begins
    //
    WriteXMLHeader( out );
    WriteStartElement( XML_POINT_SET_FILE, out );
    WriteStartElement( XML_FILE_VERSION, out );
    WriteCharacterData( VERSION_STRING, out );
    WriteEndElement( XML_FILE_VERSION, out, false );

    //
    // for each input object write its xml representation to
    // the stream
    //
    for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i )
    {
        InputType::Pointer pointSet = this->GetInput( i );
        assert( pointSet.IsNotNull() );
        WriteXML( pointSet.GetPointer(), out );
    }

   WriteEndElement( XML_POINT_SET_FILE, out );
   out.imbue(previousLocale);
    if ( !out.good() ) // some error during output
    {
      out.close();
      throw std::ios_base::failure("Some error during point set writing.");
    }

    out.close();
    m_Success = true;
    m_MimeType = "application/MITK.PointSet";
}

void mitk::PointSetWriter::WriteXML( mitk::PointSet* pointSet, std::ofstream& out )
{
    WriteStartElement( XML_POINT_SET, out );
    unsigned int timecount = pointSet->GetTimeSteps();

    for(unsigned int i=0; i< timecount; i++)
    {
      WriteStartElement( XML_TIME_SERIES, out );

      WriteStartElement( XML_TIME_SERIES_ID, out );
      WriteCharacterData( ConvertToString( i ).c_str() , out );
      WriteEndElement( XML_TIME_SERIES_ID, out, false );

      mitk::PointSet::PointsContainer* pointsContainer = pointSet->GetPointSet(i)->GetPoints();
      mitk::PointSet::PointsContainer::Iterator it;

      for ( it = pointsContainer->Begin(); it != pointsContainer->End(); ++it )
      {
          WriteStartElement( XML_POINT, out );

          WriteStartElement( XML_ID, out );
          WriteCharacterData( ConvertToString( it->Index() ).c_str() , out );
          WriteEndElement( XML_ID, out, false );

          mitk::PointSet::PointType point = it->Value();

          WriteStartElement( XML_SPEC, out );
          WriteCharacterData( ConvertToString( pointSet->GetSpecificationTypeInfo(it->Index(), i) ).c_str() , out );
          WriteEndElement( XML_SPEC, out, false );

          WriteStartElement( XML_X, out );
          WriteCharacterData( ConvertToString( point[ 0 ] ).c_str(), out );
          WriteEndElement( XML_X, out, false );

          WriteStartElement( XML_Y, out );
          WriteCharacterData( ConvertToString( point[ 1 ] ).c_str(), out );
          WriteEndElement( XML_Y, out, false );

          WriteStartElement( XML_Z, out );
          WriteCharacterData( ConvertToString( point[ 2 ] ).c_str(), out );
          WriteEndElement( XML_Z, out, false );

          WriteEndElement( XML_POINT, out );
      }
    WriteEndElement( XML_TIME_SERIES, out );
    }

    WriteEndElement( XML_POINT_SET, out );
}

void mitk::PointSetWriter::ResizeInputs( const unsigned int& num )
{
    unsigned int prevNum = this->GetNumberOfInputs();
    this->SetNumberOfInputs( num );
    for ( unsigned int i = prevNum; i < num; ++i )
    {
        this->SetNthInput( i, mitk::PointSet::New().GetPointer() );
    }
}

void mitk::PointSetWriter::SetInput( InputType* pointSet )
{
    this->ProcessObject::SetNthInput( 0, pointSet );
}

void mitk::PointSetWriter::SetInput( const unsigned int& id, InputType* pointSet )
{
    if ( id >= this->GetNumberOfInputs() )
        this->ResizeInputs( id + 1 );
    this->ProcessObject::SetNthInput( id, pointSet );
}

mitk::PointSet* mitk::PointSetWriter::GetInput()
{
    if ( this->GetNumberOfInputs() < 1 )
    {
        return 0;
    }
    else
    {
        return dynamic_cast<InputType*> ( this->GetInput( 0 ) );
    }
}

mitk::PointSet* mitk::PointSetWriter::GetInput( const unsigned int& num )
{
    return dynamic_cast<InputType*> ( this->ProcessObject::GetInput( num ) );
}

template < typename T>
std::string mitk::PointSetWriter::ConvertToString( T value )
{
    std::ostringstream o;
    std::locale I("C");
    o.imbue(I);

    if ( o << value )
    {
        return o.str();
     }
    else
        return "conversion error";
}

void mitk::PointSetWriter::WriteXMLHeader( std::ofstream &file )
{
    file << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
}

void mitk::PointSetWriter::WriteStartElement( const char *const tag, std::ofstream &file )
{
    file << std::endl;
    WriteIndent( file );
    file << '<' << tag << '>';
    m_IndentDepth++;
}

void mitk::PointSetWriter::WriteEndElement( const char *const tag, std::ofstream &file, const bool& indent )
{
    m_IndentDepth--;
    if ( indent )
    {
        file << std::endl;
        WriteIndent( file );
    }
    file << '<' << '/' << tag << '>';
}

void mitk::PointSetWriter::WriteCharacterData( const char *const data, std::ofstream &file )
{
    file << data;
}

void mitk::PointSetWriter::WriteStartElement( std::string &tag, std::ofstream &file )
{
    WriteStartElement( tag.c_str(), file );
}

void mitk::PointSetWriter::WriteEndElement( std::string &tag, std::ofstream &file, const bool& indent )
{
    WriteEndElement( tag.c_str(), file, indent );
}

void mitk::PointSetWriter::WriteCharacterData( std::string &data, std::ofstream &file )
{
    WriteCharacterData( data.c_str(), file );
}

void mitk::PointSetWriter::WriteIndent( std::ofstream& file )
{
    std::string spaces( m_IndentDepth * m_Indent, ' ' );
    file << spaces.c_str();
}

bool mitk::PointSetWriter::GetSuccess() const
{
    return m_Success;
}

bool mitk::PointSetWriter::CanWriteDataType( DataNode* input )
{
  if ( input )
  {
    mitk::BaseData* data = input->GetData();
    if ( data )
    {
       mitk::PointSet::Pointer pointSet = dynamic_cast<mitk::PointSet*>( data );
       if( pointSet.IsNotNull() )
       {
         //this writer has no "SetDefaultExtension()" - function
         m_Extension = ".mps";
         return true;
       }
    }
  }
  return false;
}

void mitk::PointSetWriter::SetInput( DataNode* input )
{
  if( input && CanWriteDataType( input ) )
    this->ProcessObject::SetNthInput( 0, dynamic_cast<mitk::PointSet*>( input->GetData() ) );
}

std::string mitk::PointSetWriter::GetWritenMIMEType()
{
  return m_MimeType;
}

std::vector<std::string> mitk::PointSetWriter::GetPossibleFileExtensions()
{
  std::vector<std::string> possibleFileExtensions;
  possibleFileExtensions.push_back(".mps");
  return possibleFileExtensions;
}

std::string mitk::PointSetWriter::GetFileExtension()
{
  return m_Extension;
}
<|endoftext|>


<commit_before>/*Copyright 2010 George Karagoulis

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

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 "ireadonlyobject.h"
using namespace GUtil::Core;

Interfaces::IReadOnlyObject::IReadOnlyObject(bool readonly)
{
    _init(readonly);
}

Interfaces::IReadOnlyObject::~IReadOnlyObject(){}

Interfaces::IReadOnlyObject::IReadOnlyObject(const Interfaces::IReadOnlyObject &other)
{
    _init(other._my_readonly_bool);
}

void Interfaces::IReadOnlyObject::_init(bool readonly)
{
    _my_readonly_bool = readonly;
    SetReadonlyBooleanReference(_my_readonly_bool);
}

std::string Interfaces::IReadOnlyObject::ReadonlyMessageIdentifier() const
{
    // This string is not too useful.  Derived classes should override to give more information
    return "IReadonlyObject";
}

void Interfaces::IReadOnlyObject::SetReadonlyBooleanReference(bool &readonlybool)
{
    _readonly_bool_reference = &readonlybool;
}

void Interfaces::IReadOnlyObject::ClearReadonlyBooleanReference()
{
    SetReadonlyBooleanReference(_my_readonly_bool);
}

void Interfaces::IReadOnlyObject::TrackReadonlyObject(const Interfaces::IReadOnlyObject &other)
{
    SetReadonlyBooleanReference(*other._readonly_bool_reference);
}

bool Interfaces::IReadOnlyObject::IsReadOnly() const
{
    return *_readonly_bool_reference;
}

void Interfaces::IReadOnlyObject::SetReadOnly(bool readonly)
{
    *_readonly_bool_reference = readonly;
}

void Interfaces::IReadOnlyObject::FailIfReadOnly() const throw(ReadOnlyException)
{
    if(IsReadOnly())
        throw ReadOnlyException(ReadonlyMessageIdentifier());
}
<commit_msg>Fixed the build<commit_after>/*Copyright 2010 George Karagoulis

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

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 "ireadonlyobject.h"
using namespace GUtil::Core;

Interfaces::IReadOnlyObject::IReadOnlyObject(bool readonly)
{
    _init_readonly_interface(readonly);
}

Interfaces::IReadOnlyObject::~IReadOnlyObject(){}

Interfaces::IReadOnlyObject::IReadOnlyObject(const Interfaces::IReadOnlyObject &other)
{
    _init_readonly_interface(other._my_readonly_bool);
}

void Interfaces::IReadOnlyObject::_init_readonly_interface(bool readonly)
{
    _my_readonly_bool = readonly;
    SetReadonlyBooleanReference(_my_readonly_bool);
}

std::string Interfaces::IReadOnlyObject::ReadonlyMessageIdentifier() const
{
    // This string is not too useful.  Derived classes should override to give more information
    return "IReadonlyObject";
}

void Interfaces::IReadOnlyObject::SetReadonlyBooleanReference(bool &readonlybool)
{
    _readonly_bool_reference = &readonlybool;
}

void Interfaces::IReadOnlyObject::ClearReadonlyBooleanReference()
{
    SetReadonlyBooleanReference(_my_readonly_bool);
}

void Interfaces::IReadOnlyObject::TrackReadonlyObject(const Interfaces::IReadOnlyObject &other)
{
    SetReadonlyBooleanReference(*other._readonly_bool_reference);
}

bool Interfaces::IReadOnlyObject::IsReadOnly() const
{
    return *_readonly_bool_reference;
}

void Interfaces::IReadOnlyObject::SetReadOnly(bool readonly)
{
    *_readonly_bool_reference = readonly;
}

void Interfaces::IReadOnlyObject::FailIfReadOnly() const throw(ReadOnlyException)
{
    if(IsReadOnly())
        throw ReadOnlyException(ReadonlyMessageIdentifier());
}
<|endoftext|>


<commit_before>// $Id$

//____________________________________________________________________
//////////////////////////////////////////////////////////////////////
//                                                                  //
// class AliHBTReaderESD                                            //
//                                                                  //
// Reader for ALICE Event Summary Data (ESD).                       //
//                                                                  //
// Piotr.Skowronski@cern.ch                                         //
//                                                                  //
//////////////////////////////////////////////////////////////////////

#include <Riostream.h>
#include <TMath.h>
#include <TPDGCode.h>
#include <TString.h>
#include <TObjString.h>
#include <TTree.h>
#include <TFile.h>
#include <TKey.h>
#include <TH1.h>
#include <AliESD.h>
#include <AliESDtrack.h>
#include <AliKalmanTrack.h>
#include <AliJetEventParticles.h>
#include "AliJetParticlesReaderESD.h"

ClassImp(AliJetParticlesReaderESD)

AliJetParticlesReaderESD::AliJetParticlesReaderESD(Bool_t constrained,
						   const Char_t* esdfilename) :
  AliJetParticlesReader(),
  fConstrained(constrained),
  fESDFileName(esdfilename),
  fESD(0),
  fFile(0),
  fTree(0),
  fKeyIterator(0),
  fPassFlag(AliESDtrack::kTPCrefit)
{
  //constructor
}

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

AliJetParticlesReaderESD::AliJetParticlesReaderESD(
                                      Bool_t constrained,
                                      TObjArray* dirs,
                                      const Char_t* esdfilename) :
  AliJetParticlesReader(dirs),
  fConstrained(constrained),
  fESDFileName(esdfilename),
  fESD(0),
  fFile(0),
  fTree(0),
  fKeyIterator(0),
  fPassFlag(AliESDtrack::kTPCrefit)
{
  //constructor
}

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

AliJetParticlesReaderESD::~AliJetParticlesReaderESD()
{
  //desctructor
  if(fESD) delete fESD;
  if(fTree) delete fTree;
  if(fKeyIterator) delete fKeyIterator;
  if(fFile) delete fFile;
}

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

Int_t AliJetParticlesReaderESD::ReadESD(AliESD* esd)
{
  //Reads one ESD

  if (esd == 0)
   {
     Error("ReadESD","ESD is NULL");
     return kFALSE;
   }

  //TDatabasePDG* pdgdb = TDatabasePDG::Instance();
  //if (pdgdb == 0)
  //{
  //   Error("ReadESD","Can not get PDG Database Instance.");
  //   return kFALSE;
  // }

  Float_t mf = esd->GetMagneticField();
  if (mf <= 0.0)
  {
     Error("ReadESD","Magnetic Field is 0. Skipping to next event.");
     return kFALSE;
  }
  AliKalmanTrack::SetMagneticField(mf/10.);

  Info("ReadESD","Reading Event %d",fCurrentEvent);
  if((!fOwner) || (fEventParticles==0))
    fEventParticles = new AliJetEventParticles();

  const Int_t kntr = esd->GetNumberOfTracks();
  Info("ReadESD","Found %d tracks.",kntr);
  fEventParticles->Reset(kntr);

  TString headdesc="";
  headdesc+="Run ";
  headdesc+=esd->GetRunNumber();
  headdesc+=": Ev ";
  headdesc+=esd->GetEventNumber();
  fEventParticles->SetHeader(headdesc);

  Double_t vertexpos[3];//vertex position
  const AliESDVertex* kvertex = esd->GetVertex();
  if (kvertex == 0)
   {
     Info("ReadESD","ESD returned NULL pointer to vertex - assuming (0.0,0.0,0.0)");
     vertexpos[0] = 0.0;
     vertexpos[1] = 0.0;
     vertexpos[2] = 0.0;
   }
  else
   {
     kvertex->GetXYZ(vertexpos);
   }
  fEventParticles->SetVertex(vertexpos[0],vertexpos[1],vertexpos[2]);

  //loop over tracks
  for (Int_t i = 0;i<kntr; i++)
   {

     const AliESDtrack *kesdtrack = esd->GetTrack(i);
     if (kesdtrack == 0)
      {
        Error("ReadESD","Can't get track %d", i);
        continue;
      }

     ULong_t cmptest=(kesdtrack->GetStatus() & fPassFlag);
     if (cmptest!=fPassFlag)
      {
	cout << i << " "; PrintESDtrack(kesdtrack); cout << endl;
	Info("ReadNext","Particle %d skipped: %u.",i,kesdtrack->GetStatus());
        continue;
      }

     Double_t mom[3];  //momentum
     Double_t xyz[3];  //position
     if (fConstrained) {
       if (kesdtrack->GetConstrainedChi2() > 25) continue;
       kesdtrack->GetConstrainedPxPyPz(mom);
       kesdtrack->GetConstrainedXYZ(xyz);
     } else {
       kesdtrack->GetPxPyPz(mom);
       kesdtrack->GetXYZ(xyz);
     }
     const Float_t kmass=kesdtrack->GetMass();
     const Float_t kp2=mom[0]*mom[0]+mom[1]*mom[1]+mom[2]*mom[2];
     const Float_t ketot=TMath::Sqrt(kmass*kmass+kp2);
     const Float_t kpt=TMath::Sqrt(mom[0]*mom[0]+mom[1]*mom[1]);
     const Float_t kp=TMath::Sqrt(kp2);
     const Float_t keta=0.5*TMath::Log((kp+mom[2]+1e-30)/(kp-mom[2]+1e-30));
     const Float_t kphi=TMath::Pi()+TMath::ATan2(-mom[1],-mom[0]);
     //Double_t dx = xyz[0]-vertexpos[0];
     //Double_t dy = xyz[1]-vertexpos[1];
     //Float_t dca = TMath::Sqrt(dx*dx + dy*dy);
     //Float_t dz = xyz[2]-vertexpos[2];
     UInt_t index[6];
     const Int_t kncl=kesdtrack->GetITSclusters(index)
                      +kesdtrack->GetTPCclusters(NULL)
                      +kesdtrack->GetTRDclusters(NULL);
     if(IsAcceptedParticle(kpt,kphi,keta))
       fEventParticles->AddParticle(mom[0],mom[1],mom[2],ketot,i,kesdtrack->GetLabel(),kncl,kpt,kphi,keta);

   } // loop over tracks

  return kTRUE;
}

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

void AliJetParticlesReaderESD::Rewind()
{
  //rewinds reading

  if(fFile) delete fFile;
  if(fKeyIterator) delete fKeyIterator;
  fKeyIterator = 0;
  fFile = 0;
  fCurrentDir = 0;
  fNEventsRead = 0;
}

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

Int_t AliJetParticlesReaderESD::ReadNext()
{
  //reads next event from fFile

  do   // is OK even if 0 dirs specified,
    {  // in that case we try to read from "./"
      if (fFile == 0)
	{
	  fFile = OpenFile(fCurrentDir);
	  if (fFile == 0)
	    {
	      Error("ReadNext","Can't get fFile for dir no. %d",fCurrentDir);
	      fCurrentDir++;
	      continue;
	    }

	  fCurrentEvent = 0;
	  //fFile->GetListOfKeys()->Print();

	  if(fTree) delete fTree;
	  fTree = dynamic_cast<TTree*>(fFile->Get("esdTree"));
	  if(fTree)
	    fTree->SetBranchAddress("ESD",&fESD);
	  else
	    fKeyIterator = new TIter(fFile->GetListOfKeys());
	}

      if(fTree)
	{
	  if(AliKalmanTrack::GetConvConst()<=0.)
	    AliKalmanTrack::SetMagneticField(0.5);
	  if(fCurrentEvent>=fTree->GetEntries())
	    {
	      fCurrentDir++;
	      delete fTree;
	      fTree = 0;
	      delete fFile;
	      fFile = 0;
	      continue;
	    }
	  fTree->GetEvent(fCurrentEvent);
	}
      else
	{ // "old" way via ESD objects stored in root file
	  TKey* key = (TKey*)fKeyIterator->Next();
	  if (key == 0)
	    {
	      fCurrentDir++;
	      delete fKeyIterator;
	      fKeyIterator = 0;
	      delete fFile; //we have to assume there are no more ESD objects in the fFile
	      fFile = 0;
	      continue;
	    }
	  TString esdname = "ESD";
	  esdname+=fCurrentEvent;
	  if(fESD) delete fESD;
	  fESD = dynamic_cast<AliESD*>(fFile->Get(esdname));
	  if (fESD == 0)
	    {
	      Info("ReadNext","Can't find AliESD object named %s",esdname.Data());
	      fCurrentDir++;
	      delete fKeyIterator;
	      fKeyIterator = 0;
	      delete fFile;//we have to assume there is no more ESD objects in the fFile
	      fFile = 0;
	      continue;
	    }
	}
      ReadESD(fESD);
      fCurrentEvent++;
      fNEventsRead++;
      return kTRUE;//success -> read one event
    }  while(fCurrentDir < GetNumberOfDirs());
      //end of loop over directories specified in fDirs Obj Array
  return kFALSE; //no more directories to read
}

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

TFile* AliJetParticlesReaderESD::OpenFile(Int_t n)
{
  //opens fFile with kine tree

 const TString& dirname = GetDirName(n);
 if (dirname == "")
  {
   Error("OpenFiles","Can't get directory name");
   return 0;
  }
 TString filename = dirname +"/"+ fESDFileName;
 TFile *ret = TFile::Open(filename.Data());
 if (ret == 0)
  {
    Error("OpenFiles","Can't open fFile %s",filename.Data());
    return 0;
  }
 if (!ret->IsOpen())
  {
    Error("OpenFiles","Can't open fFile  %s",filename.Data());
    return 0;
  }

 return ret;
}

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

void AliJetParticlesReaderESD::PrintESDtrack(const AliESDtrack *kesdtrack) const
{
  ULong_t status=kesdtrack->GetStatus();
  cout << hex << status << dec << ": ";
  if((status & AliESDtrack::kITSin) == AliESDtrack::kITSin) cout << "ITSin ";
  if((status & AliESDtrack::kITSout) == AliESDtrack::kITSout) cout << "ITSout ";
  if((status & AliESDtrack::kITSrefit) == AliESDtrack::kITSrefit) cout << "ITSrefit ";
  if((status & AliESDtrack::kITSpid) == AliESDtrack::kITSpid) cout << "ITSpid ";

  if((status & AliESDtrack::kTPCin)  == AliESDtrack::kTPCin) cout << "TPCin ";
  if((status & AliESDtrack::kTPCout) == AliESDtrack::kTPCout) cout << "TPCout ";
  if((status & AliESDtrack::kTPCrefit) == AliESDtrack::kTPCrefit) cout << "TPCrefit ";
  if((status & AliESDtrack::kTPCpid) == AliESDtrack::kTPCpid) cout << "TPCpid ";

  if((status & AliESDtrack::kTRDin) == AliESDtrack::kTRDin) cout << "TRDin ";
  if((status & AliESDtrack::kTRDout) == AliESDtrack::kTRDout) cout << "TRDout ";
  if((status & AliESDtrack::kTRDrefit) == AliESDtrack::kTRDrefit) cout << "TRDrefit ";
  if((status & AliESDtrack::kTRDpid) == AliESDtrack::kTRDpid) cout << "TRDpid ";
  if((status & AliESDtrack::kTRDbackup) == AliESDtrack::kTRDbackup) cout << "TRDbackup ";
  if((status & AliESDtrack::kTRDStop) == AliESDtrack::kTRDStop) cout << "TRDstop ";

  if((status & AliESDtrack::kTOFin) == AliESDtrack::kTOFin) cout << "TOFin ";
  if((status & AliESDtrack::kTOFout) == AliESDtrack::kTOFout) cout << "TOFout ";
  if((status & AliESDtrack::kTOFrefit) == AliESDtrack::kTOFrefit) cout << "TOFrefit ";
  if((status & AliESDtrack::kTOFpid) == AliESDtrack::kTOFpid) cout << "TOFpid ";

  if((status & AliESDtrack::kPHOSpid) == AliESDtrack::kPHOSpid) cout << "PHOSpid ";
  if((status & AliESDtrack::kRICHpid) == AliESDtrack::kRICHpid) cout << "RICHpid ";
  if((status & AliESDtrack::kEMCALpid) == AliESDtrack::kEMCALpid) cout << "EMCALpid ";
  if((status & AliESDtrack::kESDpid) == AliESDtrack::kESDpid) cout << "ESDpid ";
  if((status & AliESDtrack::kTIME) == AliESDtrack::kTIME) cout << "TIME ";
  cout << endl;
  /*
  cout << kesdtrack->GetConstrainedChi2()
       << " " << kesdtrack->GetITSchi2()
       << " " << kesdtrack->GetTPCchi2()
       << " " << kesdtrack->GetTRDchi2()<< endl;
  */
}
<commit_msg>Removed unnecessary output.<commit_after>// $Id$

//____________________________________________________________________
//////////////////////////////////////////////////////////////////////
//                                                                  //
// class AliHBTReaderESD                                            //
//                                                                  //
// Reader for ALICE Event Summary Data (ESD).                       //
//                                                                  //
// Piotr.Skowronski@cern.ch                                         //
//                                                                  //
//////////////////////////////////////////////////////////////////////

#include <Riostream.h>
#include <TMath.h>
#include <TPDGCode.h>
#include <TString.h>
#include <TObjString.h>
#include <TTree.h>
#include <TFile.h>
#include <TKey.h>
#include <TH1.h>
#include <AliESD.h>
#include <AliESDtrack.h>
#include <AliKalmanTrack.h>
#include <AliJetEventParticles.h>
#include "AliJetParticlesReaderESD.h"

ClassImp(AliJetParticlesReaderESD)

AliJetParticlesReaderESD::AliJetParticlesReaderESD(Bool_t constrained,
						   const Char_t* esdfilename) :
  AliJetParticlesReader(),
  fConstrained(constrained),
  fESDFileName(esdfilename),
  fESD(0),
  fFile(0),
  fTree(0),
  fKeyIterator(0),
  fPassFlag(AliESDtrack::kTPCrefit)
{
  //constructor
}

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

AliJetParticlesReaderESD::AliJetParticlesReaderESD(
                                      Bool_t constrained,
                                      TObjArray* dirs,
                                      const Char_t* esdfilename) :
  AliJetParticlesReader(dirs),
  fConstrained(constrained),
  fESDFileName(esdfilename),
  fESD(0),
  fFile(0),
  fTree(0),
  fKeyIterator(0),
  fPassFlag(AliESDtrack::kTPCrefit)
{
  //constructor
}

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

AliJetParticlesReaderESD::~AliJetParticlesReaderESD()
{
  //desctructor
  if(fESD) delete fESD;
  if(fTree) delete fTree;
  if(fKeyIterator) delete fKeyIterator;
  if(fFile) delete fFile;
}

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

Int_t AliJetParticlesReaderESD::ReadESD(AliESD* esd)
{
  //Reads one ESD

  if (esd == 0)
   {
     Error("ReadESD","ESD is NULL");
     return kFALSE;
   }

  //TDatabasePDG* pdgdb = TDatabasePDG::Instance();
  //if (pdgdb == 0)
  //{
  //   Error("ReadESD","Can not get PDG Database Instance.");
  //   return kFALSE;
  // }

  Float_t mf = esd->GetMagneticField();
  if (mf <= 0.0)
  {
     Error("ReadESD","Magnetic Field is 0. Skipping to next event.");
     return kFALSE;
  }
  AliKalmanTrack::SetMagneticField(mf/10.);

  Info("ReadESD","Reading Event %d",fCurrentEvent);
  if((!fOwner) || (fEventParticles==0))
    fEventParticles = new AliJetEventParticles();

  const Int_t kntr = esd->GetNumberOfTracks();
  Info("ReadESD","Found %d tracks.",kntr);
  fEventParticles->Reset(kntr);

  TString headdesc="";
  headdesc+="Run ";
  headdesc+=esd->GetRunNumber();
  headdesc+=": Ev ";
  headdesc+=esd->GetEventNumber();
  fEventParticles->SetHeader(headdesc);

  Double_t vertexpos[3];//vertex position
  const AliESDVertex* kvertex = esd->GetVertex();
  if (kvertex == 0)
   {
     Info("ReadESD","ESD returned NULL pointer to vertex - assuming (0.0,0.0,0.0)");
     vertexpos[0] = 0.0;
     vertexpos[1] = 0.0;
     vertexpos[2] = 0.0;
   }
  else
   {
     kvertex->GetXYZ(vertexpos);
   }
  fEventParticles->SetVertex(vertexpos[0],vertexpos[1],vertexpos[2]);

  //loop over tracks
  for (Int_t i = 0;i<kntr; i++)
   {

     const AliESDtrack *kesdtrack = esd->GetTrack(i);
     if (kesdtrack == 0)
      {
        Error("ReadESD","Can't get track %d", i);
        continue;
      }

     ULong_t cmptest=(kesdtrack->GetStatus() & fPassFlag);
     if (cmptest!=fPassFlag)
      {
	//cout << i << " "; PrintESDtrack(kesdtrack); cout << endl;
	Info("ReadNext","Particle %d skipped: %u.",i,kesdtrack->GetStatus());
        continue;
      }

     Double_t mom[3];  //momentum
     Double_t xyz[3];  //position
     if (fConstrained) {
       if (kesdtrack->GetConstrainedChi2() > 25) continue;
       kesdtrack->GetConstrainedPxPyPz(mom);
       kesdtrack->GetConstrainedXYZ(xyz);
     } else {
       kesdtrack->GetPxPyPz(mom);
       kesdtrack->GetXYZ(xyz);
     }
     const Float_t kmass=kesdtrack->GetMass();
     const Float_t kp2=mom[0]*mom[0]+mom[1]*mom[1]+mom[2]*mom[2];
     const Float_t ketot=TMath::Sqrt(kmass*kmass+kp2);
     const Float_t kpt=TMath::Sqrt(mom[0]*mom[0]+mom[1]*mom[1]);
     const Float_t kp=TMath::Sqrt(kp2);
     const Float_t keta=0.5*TMath::Log((kp+mom[2]+1e-30)/(kp-mom[2]+1e-30));
     const Float_t kphi=TMath::Pi()+TMath::ATan2(-mom[1],-mom[0]);
     //Double_t dx = xyz[0]-vertexpos[0];
     //Double_t dy = xyz[1]-vertexpos[1];
     //Float_t dca = TMath::Sqrt(dx*dx + dy*dy);
     //Float_t dz = xyz[2]-vertexpos[2];
     UInt_t index[6];
     const Int_t kncl=kesdtrack->GetITSclusters(index)
                      +kesdtrack->GetTPCclusters(NULL)
                      +kesdtrack->GetTRDclusters(NULL);
     if(IsAcceptedParticle(kpt,kphi,keta))
       fEventParticles->AddParticle(mom[0],mom[1],mom[2],ketot,i,kesdtrack->GetLabel(),kncl,kpt,kphi,keta);

   } // loop over tracks

  return kTRUE;
}

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

void AliJetParticlesReaderESD::Rewind()
{
  //rewinds reading

  if(fFile) delete fFile;
  if(fKeyIterator) delete fKeyIterator;
  fKeyIterator = 0;
  fFile = 0;
  fCurrentDir = 0;
  fNEventsRead = 0;
}

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

Int_t AliJetParticlesReaderESD::ReadNext()
{
  //reads next event from fFile

  do   // is OK even if 0 dirs specified,
    {  // in that case we try to read from "./"
      if (fFile == 0)
	{
	  fFile = OpenFile(fCurrentDir);
	  if (fFile == 0)
	    {
	      Error("ReadNext","Can't get fFile for dir no. %d",fCurrentDir);
	      fCurrentDir++;
	      continue;
	    }

	  fCurrentEvent = 0;
	  //fFile->GetListOfKeys()->Print();

	  if(fTree) delete fTree;
	  fTree = dynamic_cast<TTree*>(fFile->Get("esdTree"));
	  if(fTree)
	    fTree->SetBranchAddress("ESD",&fESD);
	  else
	    fKeyIterator = new TIter(fFile->GetListOfKeys());
	}

      if(fTree)
	{
	  if(AliKalmanTrack::GetConvConst()<=0.)
	    AliKalmanTrack::SetMagneticField(0.5);
	  if(fCurrentEvent>=fTree->GetEntries())
	    {
	      fCurrentDir++;
	      delete fTree;
	      fTree = 0;
	      delete fFile;
	      fFile = 0;
	      continue;
	    }
	  fTree->GetEvent(fCurrentEvent);
	}
      else
	{ // "old" way via ESD objects stored in root file
	  TKey* key = (TKey*)fKeyIterator->Next();
	  if (key == 0)
	    {
	      fCurrentDir++;
	      delete fKeyIterator;
	      fKeyIterator = 0;
	      delete fFile; //we have to assume there are no more ESD objects in the fFile
	      fFile = 0;
	      continue;
	    }
	  TString esdname = "ESD";
	  esdname+=fCurrentEvent;
	  if(fESD) delete fESD;
	  fESD = dynamic_cast<AliESD*>(fFile->Get(esdname));
	  if (fESD == 0)
	    {
	      Info("ReadNext","Can't find AliESD object named %s",esdname.Data());
	      fCurrentDir++;
	      delete fKeyIterator;
	      fKeyIterator = 0;
	      delete fFile;//we have to assume there is no more ESD objects in the fFile
	      fFile = 0;
	      continue;
	    }
	}
      ReadESD(fESD);
      fCurrentEvent++;
      fNEventsRead++;
      return kTRUE;//success -> read one event
    }  while(fCurrentDir < GetNumberOfDirs());
      //end of loop over directories specified in fDirs Obj Array
  return kFALSE; //no more directories to read
}

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

TFile* AliJetParticlesReaderESD::OpenFile(Int_t n)
{
  //opens fFile with kine tree

 const TString& dirname = GetDirName(n);
 if (dirname == "")
  {
   Error("OpenFiles","Can't get directory name");
   return 0;
  }
 TString filename = dirname +"/"+ fESDFileName;
 TFile *ret = TFile::Open(filename.Data());
 if (ret == 0)
  {
    Error("OpenFiles","Can't open fFile %s",filename.Data());
    return 0;
  }
 if (!ret->IsOpen())
  {
    Error("OpenFiles","Can't open fFile  %s",filename.Data());
    return 0;
  }

 return ret;
}

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

void AliJetParticlesReaderESD::PrintESDtrack(const AliESDtrack *kesdtrack) const
{
  ULong_t status=kesdtrack->GetStatus();
  cout << hex << status << dec << ": ";
  if((status & AliESDtrack::kITSin) == AliESDtrack::kITSin) cout << "ITSin ";
  if((status & AliESDtrack::kITSout) == AliESDtrack::kITSout) cout << "ITSout ";
  if((status & AliESDtrack::kITSrefit) == AliESDtrack::kITSrefit) cout << "ITSrefit ";
  if((status & AliESDtrack::kITSpid) == AliESDtrack::kITSpid) cout << "ITSpid ";

  if((status & AliESDtrack::kTPCin)  == AliESDtrack::kTPCin) cout << "TPCin ";
  if((status & AliESDtrack::kTPCout) == AliESDtrack::kTPCout) cout << "TPCout ";
  if((status & AliESDtrack::kTPCrefit) == AliESDtrack::kTPCrefit) cout << "TPCrefit ";
  if((status & AliESDtrack::kTPCpid) == AliESDtrack::kTPCpid) cout << "TPCpid ";

  if((status & AliESDtrack::kTRDin) == AliESDtrack::kTRDin) cout << "TRDin ";
  if((status & AliESDtrack::kTRDout) == AliESDtrack::kTRDout) cout << "TRDout ";
  if((status & AliESDtrack::kTRDrefit) == AliESDtrack::kTRDrefit) cout << "TRDrefit ";
  if((status & AliESDtrack::kTRDpid) == AliESDtrack::kTRDpid) cout << "TRDpid ";
  if((status & AliESDtrack::kTRDbackup) == AliESDtrack::kTRDbackup) cout << "TRDbackup ";
  if((status & AliESDtrack::kTRDStop) == AliESDtrack::kTRDStop) cout << "TRDstop ";

  if((status & AliESDtrack::kTOFin) == AliESDtrack::kTOFin) cout << "TOFin ";
  if((status & AliESDtrack::kTOFout) == AliESDtrack::kTOFout) cout << "TOFout ";
  if((status & AliESDtrack::kTOFrefit) == AliESDtrack::kTOFrefit) cout << "TOFrefit ";
  if((status & AliESDtrack::kTOFpid) == AliESDtrack::kTOFpid) cout << "TOFpid ";

  if((status & AliESDtrack::kPHOSpid) == AliESDtrack::kPHOSpid) cout << "PHOSpid ";
  if((status & AliESDtrack::kRICHpid) == AliESDtrack::kRICHpid) cout << "RICHpid ";
  if((status & AliESDtrack::kEMCALpid) == AliESDtrack::kEMCALpid) cout << "EMCALpid ";
  if((status & AliESDtrack::kESDpid) == AliESDtrack::kESDpid) cout << "ESDpid ";
  if((status & AliESDtrack::kTIME) == AliESDtrack::kTIME) cout << "TIME ";
  cout << endl;
  /*
  cout << kesdtrack->GetConstrainedChi2()
       << " " << kesdtrack->GetITSchi2()
       << " " << kesdtrack->GetTPCchi2()
       << " " << kesdtrack->GetTRDchi2()<< endl;
  */
}
<|endoftext|>