Exemple #1
0
lref_t run()
{
     if (DEBUG_FLAG(DF_NO_STARTUP))
          return NIL;

     return vmtrap(TRAP_RUN0, VMT_MANDATORY_TRAP, 0);
}
 void kinsol_errorHandler(int error_code, const char* module, const char* function, char* msg, void* user_data)
 {
   if(DEBUG_FLAG(LOG_INIT))
   {
     WARNING3("[module] %s | [function] %s | [error_code] %d", module, function, error_code);
     WARNING_AL1("%s", msg);
   }
 }
Exemple #3
0
void main() {
CubitMessage::instance()->output_debug_information(1, 10, 2);
CubitMessage::instance()->output_debug_information(12);
CubitMessage::instance()->set_debug_file(5, "Debug_Test.file");
DEBUG_FLAG(5, CUBIT_TRUE);
PRINT_DEBUG_5("This is a test\n");
CubitMessage::instance()->output_debug_information(5,5);
}
Exemple #4
0
int CubitMessage::is_debug_flag_set( int flag )
{
   if( DEBUG_FLAG( flag ))
   {
      currentDebugFlag = flag;
      return CUBIT_TRUE;
   }
   return CUBIT_FALSE;
}
Exemple #5
0
CABodies::CABodies(RefEntity* new_attrib_owner)
  : CubitAttrib(new_attrib_owner)
{
  if (DEBUG_FLAG(138))
  {
  PRINT_DEBUG_138( "Creating BODIES attribute for %s %d\n",
              (attribOwnerEntity ? attribOwnerEntity->class_name() : "(none)"),
              (attribOwnerEntity ? attribOwnerEntity->id() : 0));
  }
}
Exemple #6
0
CABodies::CABodies(RefEntity* new_attrib_owner,
		   CubitSimpleAttrib *csa_ptr)
  : CubitAttrib(new_attrib_owner)
{
  assert ( csa_ptr != NULL );
  if (DEBUG_FLAG(138))
  {
    PRINT_DEBUG_138( "Creating BODIES attribute from CSA for %s %d\n",
		     (attribOwnerEntity ? attribOwnerEntity->class_name() : "(none)"),
		     (attribOwnerEntity ? attribOwnerEntity->id() : 0));
  }

  std::vector<int> i_list = csa_ptr->int_data_list();

  // first, the ints
  if (i_list.size() > 0)
  {
    m_interface = i_list[0]; // is interface

    if (i_list.size() > 1)
    {
      m_uniqueID = i_list[1]; // unique ID

      if(i_list.size() > 2)
      {
        // shared bodies
        int num_list = i_list[2];
        for (int i = 0; i < num_list; i++) 
          m_sharedBodies.append(i_list[3+i]);

        // shared procs
        int new_start = 3 + num_list;
        if(i_list.size() > new_start + 1)
        {
          num_list = i_list[new_start];
          for (int i = 1; i <= num_list; i++) 
           m_sharedProcs.append(i_list[new_start + i]);

          // ghost procs
          new_start += num_list+1;
          if(i_list.size() > new_start + 1)
          {
           num_list = i_list[new_start];
           for (int i = 1; i <= num_list; i++) 
             m_ghostProcs.append(i_list[new_start + i]);
          } 
        }
      }
    }
  }
}
Exemple #7
0
CubitStatus CABodies::update()
{
  if (hasUpdated) return CUBIT_SUCCESS;
  
  if (DEBUG_FLAG(138))
  {
    PRINT_DEBUG_138( "Updating BODIES attribute for %s %d\n",
              attribOwnerEntity->class_name(), attribOwnerEntity->id());
  }

  // set the updated flag
  hasUpdated = CUBIT_TRUE;
  
  // if the owner has a body list, save it, otherwise delete this one
  TDParallel *td_par = (TDParallel *) attrib_owner()->get_TD(&TDParallel::is_parallel);
  
  if (td_par == NULL) {
    delete_attrib(CUBIT_TRUE);
  }
  else {
    m_interface = td_par->is_interface();
    m_uniqueID = td_par->get_unique_id();
    int size = td_par->get_shared_body_list()->size();
    td_par->get_shared_body_list()->reset();
    m_sharedBodies.clean_out();

    for (int i = 0; i < size; i++) {
      m_sharedBodies.append(td_par->get_shared_body_list()->get_and_step());
    }

    size = td_par->get_shared_proc_list()->size();
    td_par->get_shared_proc_list()->reset();
    m_sharedProcs.clean_out();

    for (int i = 0; i < size; i++) {
      m_sharedProcs.append(td_par->get_shared_proc_list()->get_and_step());
    }

    size = td_par->get_ghost_proc_list()->size();
    td_par->get_ghost_proc_list()->reset();
    m_ghostProcs.clean_out();

    for (int i = 0; i < size; i++) {
      m_ghostProcs.append(td_par->get_ghost_proc_list()->get_and_step());
    }
	
    if (delete_attrib() == CUBIT_TRUE) delete_attrib(CUBIT_FALSE);
  }

  return CUBIT_SUCCESS;
}
Exemple #8
0
int AppUtil::shutdown()
{
    // When the user is done, print out additional info if requested
   if (DEBUG_FLAG(3))
      report_resource_usage();

     // Return the number of errors in the session
   int ret_val = ( CubitMessage::instance()->error_count() );
   if ( ret_val > 0 )
   {
     PRINT_ERROR("Errors found during CUBIT session.\n");
   }

     // Delete the singletons
   CubitMessage::delete_instance();

   SettingHandler::delete_instance();

   mAppStarted = CUBIT_FALSE;

   return ret_val;
}
Exemple #9
0
size_t debug_port_write_chars(lref_t port, const _TCHAR *buf, size_t count)
{
     UNREFERENCED(port);
     assert(PORTP(port));

     _TCHAR block[DEBUG_PORT_BLOCK_SIZE + 1];

     size_t buf_loc = 0;
     size_t block_loc = 0;

     size_t len = count;

     /* Filter nulls out of the input string, and ensure that the
      * buffer we pass to OutputDebugString has as terminating
      * null. */
     while (len > 0)
     {
          for (block_loc = 0;
               (block_loc < DEBUG_PORT_BLOCK_SIZE) && (len > 0); block_loc++, buf_loc++, len--)
          {
               if (buf[buf_loc] == '\0')
                    block[block_loc] = '~';
               else
                    block[block_loc] = buf[buf_loc];
          }

          block[block_loc] = '\0';

          if (DEBUG_FLAG(DF_DEBUGGER_TO_ODS))
               sys_output_debug_string(block);
          else
               fputs(block, stderr);
     }

     return len;
}
Exemple #10
0
static void fast_read(lref_t reader, lref_t * retval, bool allow_loader_ops /* = false */ )
{
    lref_t *fasl_table_entry = NULL;

    *retval = NIL;

    if (!FASL_READER_P(reader))
        vmerror_wrong_type_n(1, reader);

    assert(NULLP(FASL_READER_STREAM(reader)->table) || VECTORP(FASL_READER_STREAM(reader)->table));

    /* The core of this function is wrapped in a giant while loop to remove
     * tail recursive calls. Some opcodes don't directly return anything:
     * they just tail recursively read the next opcode after performing their
     * action via side effect. */
    bool current_read_complete = false;
    while (!current_read_complete)
    {
        /*  Assume we're going to complete the read unless we find out otherwise.. */
        current_read_complete = true;

        size_t opcode_location = PORT_BYTES_READ(FASL_READER_PORT(reader));

        enum fasl_opcode_t opcode = fast_read_opcode(reader);
        fixnum_t index = 0;
        lref_t name;

        if (DEBUG_FLAG(DF_FASL_SHOW_OPCODES))
        {
            const _TCHAR *opcode_name = fasl_opcode_name(opcode);

            dscwritef(DF_FASL_SHOW_OPCODES,
                      (_T("; DEBUG: fasl-opcode@~cx :~cS\n"),
                       opcode_location, opcode_name ? opcode_name : _T("<INVALID>")));
        }

        switch (opcode)
        {
        case FASL_OP_NIL:
            *retval = NIL;
            break;

        case FASL_OP_TRUE:
            *retval = boolcons(true);
            break;

        case FASL_OP_FALSE:
            *retval = boolcons(false);
            break;

        case FASL_OP_CHARACTER:
            fast_read_character(reader, retval);
            break;

        case FASL_OP_LIST:
            fast_read_list(reader, false, retval);
            break;

        case FASL_OP_LISTD:
            fast_read_list(reader, true, retval);
            break;

        case FASL_OP_FIX8:
            fast_read_fixnum_int8(reader, retval);
            break;

        case FASL_OP_FIX16:
            fast_read_fixnum_int16(reader, retval);
            break;

        case FASL_OP_FIX32:
            fast_read_fixnum_int32(reader, retval);
            break;

        case FASL_OP_FIX64:
            fast_read_fixnum_int64(reader, retval);
            break;

        case FASL_OP_FLOAT:
            fast_read_flonum(reader, false, retval);
            break;

        case FASL_OP_COMPLEX:
            fast_read_flonum(reader, true, retval);
            break;

        case FASL_OP_STRING:
            fast_read_string(reader, retval);
            break;

        case FASL_OP_PACKAGE:
            fast_read_package(reader, retval);
            break;

        case FASL_OP_VECTOR:
            fast_read_vector(reader, retval);
            break;

        case FASL_OP_HASH:
            fast_read_hash(reader, retval);
            break;

        case FASL_OP_CLOSURE:
            fast_read_closure(reader, retval);
            break;

        case FASL_OP_MACRO:
            fast_read_macro(reader, retval);
            break;

        case FASL_OP_SYMBOL:
            fast_read_symbol(reader, retval);
            break;

        case FASL_OP_SUBR:
            fast_read_subr(reader, retval);
            break;

        case FASL_OP_STRUCTURE:
            fast_read_structure(reader, retval);
            break;

        case FASL_OP_STRUCTURE_LAYOUT:
            fast_read_structure_layout(reader, retval);
            break;

        case FASL_OP_FAST_OP_0:
            fast_read_fast_op(0, false, reader, retval);
            break;

        case FASL_OP_FAST_OP_1:
            fast_read_fast_op(1, false, reader, retval);
            break;

        case FASL_OP_FAST_OP_2:
            fast_read_fast_op(2, false, reader, retval);
            break;

        case FASL_OP_FAST_OP_0N:
            fast_read_fast_op(0, true, reader, retval);
            break;

        case FASL_OP_FAST_OP_1N:
            fast_read_fast_op(1, true, reader, retval);
            break;

        case FASL_OP_FAST_OP_2N:
            fast_read_fast_op(2, true, reader, retval);
            break;

        case FASL_OP_NOP_1:
        case FASL_OP_NOP_2:
        case FASL_OP_NOP_3:
            current_read_complete = false;
            break;

        case FASL_OP_COMMENT_1:
        case FASL_OP_COMMENT_2:
            fast_read_to_newline(reader);
            current_read_complete = false;
            break;

        case FASL_OP_RESET_READER_DEFS:
            FASL_READER_STREAM(reader)->table = NIL;
            current_read_complete = false;
            break;

        case FASL_OP_READER_DEFINITION:
            index = fast_read_table_index(reader);

            fasl_table_entry = &(FASL_READER_STREAM(reader)->table->as.vector.data[index]);

            fast_read(reader, fasl_table_entry, allow_loader_ops);

            /* This should throw if the FASL table was resized
             * during the call to read. */
            assert(fasl_table_entry == &(FASL_READER_STREAM(reader)->table->as.vector.data[index]));

            *retval = *fasl_table_entry;
            break;

        case FASL_OP_READER_REFERENCE:
            index = fast_read_table_index(reader);

            *retval = FASL_READER_STREAM(reader)->table->as.vector.data[index];
            break;

        case FASL_OP_EOF:
            *retval = lmake_eof();
            break;

        case FASL_OP_LOADER_DEFINEQ:
        case FASL_OP_LOADER_DEFINEA0:
            if (!allow_loader_ops)
                vmerror_fast_read(_T("loader definitions not allowed outside loader"), reader, NIL);

            fast_read_loader_definition(reader, opcode);
            current_read_complete = false;
            break;

        case FASL_OP_LOADER_APPLY0:
        case FASL_OP_LOADER_APPLYN:
            if (!allow_loader_ops)
                vmerror_fast_read(_T("loader function applications not allowed outside loader"), reader, NIL);

            fast_read_loader_application(reader, opcode);
            break;

        case FASL_OP_BEGIN_LOAD_UNIT:
            if (!allow_loader_ops)
                vmerror_fast_read(_T("load units are not allowed outside loader"), reader, NIL);

            fast_read(reader, &name, allow_loader_ops);

            dscwritef(DF_SHOW_FAST_LOAD_UNITS, ("; DEBUG: FASL entering unit ~s\n", name));
            break;

        case FASL_OP_END_LOAD_UNIT:
            if (!allow_loader_ops)
                vmerror_fast_read(_T("load units are not allowed outside loader"), reader, NIL);

            fast_read(reader, &name, allow_loader_ops);

            dscwritef(DF_SHOW_FAST_LOAD_UNITS, ("; DEBUG: FASL leaving unit ~s\n", name));
            break;

        case FASL_OP_LOADER_PUSH:
            fast_loader_stack_push(reader, FASL_READER_STREAM(reader)->accum);
            break;

        case FASL_OP_LOADER_DROP:
            fast_loader_stack_pop(reader);
            break;

        default:
            vmerror_fast_read("invalid opcode", reader, fixcons(opcode));
        }
    }
}
Exemple #11
0
void initTracing (void)
{
#ifdef THREADED_RTS
    initMutex(&trace_utx);
#endif

#ifdef DEBUG
#define DEBUG_FLAG(name, class) \
    class = RtsFlags.DebugFlags.name ? 1 : 0;

    DEBUG_FLAG(scheduler,    DEBUG_sched);

    DEBUG_FLAG(interpreter,  DEBUG_interp);
    DEBUG_FLAG(weak,         DEBUG_weak);
    DEBUG_FLAG(gccafs,       DEBUG_gccafs);
    DEBUG_FLAG(gc,           DEBUG_gc);
    DEBUG_FLAG(block_alloc,  DEBUG_block_alloc);
    DEBUG_FLAG(sanity,       DEBUG_sanity);
    DEBUG_FLAG(stable,       DEBUG_stable);
    DEBUG_FLAG(stm,          DEBUG_stm);
    DEBUG_FLAG(prof,         DEBUG_prof);
    DEBUG_FLAG(linker,       DEBUG_linker);
    DEBUG_FLAG(squeeze,      DEBUG_squeeze);
    DEBUG_FLAG(hpc,          DEBUG_hpc);
    DEBUG_FLAG(sparks,       DEBUG_sparks);
#endif

    // -Ds turns on scheduler tracing too
    TRACE_sched =
        RtsFlags.TraceFlags.scheduler ||
        RtsFlags.DebugFlags.scheduler;

    // -Dg turns on gc tracing too
    TRACE_gc =
        RtsFlags.TraceFlags.gc ||
        RtsFlags.DebugFlags.gc;

    TRACE_spark_sampled =
        RtsFlags.TraceFlags.sparks_sampled;

    // -Dr turns on full spark tracing
    TRACE_spark_full =
        RtsFlags.TraceFlags.sparks_full ||
        RtsFlags.DebugFlags.sparks;

    TRACE_user =
        RtsFlags.TraceFlags.user;

    eventlog_enabled = RtsFlags.TraceFlags.tracing == TRACE_EVENTLOG;

    /* Note: we can have any of the TRACE_* flags turned on even when
       eventlog_enabled is off. In the DEBUG way we may be tracing to stderr.
     */

    if (eventlog_enabled) {
        initEventLogging();
    }
}
Exemple #12
0
bool is_debug_flag_set(enum debug_flag_t flag)
{
     return DEBUG_FLAG(flag);
}
Exemple #13
0
CubitStatus CABodies::actuate()
{
  CubitStatus status = CUBIT_SUCCESS;

  if (hasActuated == CUBIT_TRUE) return CUBIT_SUCCESS;

  if (DEBUG_FLAG(138))
  {
    PRINT_DEBUG_138( "Actuating BODIES attribute for %s %d\n",
		     attribOwnerEntity->class_name(), attribOwnerEntity->id());
  }

  // create a TDParallel for the entity, if it doesn't already exist
  TDParallel *par = (TDParallel *) attrib_owner()->get_TD(&TDParallel::is_parallel);

  if (par != NULL) {
    if (par->is_interface() != m_interface) {
      PRINT_ERROR("TDParallel interface check is failed for %s %d.\n",
		  attrib_owner()->class_name(), attrib_owner()->id());
      return CUBIT_FAILURE;
    }

    // check to make sure it's the same body list
    par->get_shared_body_list()->reset();
    m_sharedBodies.reset();
    int size = par->get_shared_body_list()->size();

    for (int i = 0; i < size; i++) {
      if (par->get_shared_body_list()->get_and_step() != m_sharedBodies.get_and_step()) {
	PRINT_ERROR("Different body found for %s %d.\n",
		    attrib_owner()->class_name(), attrib_owner()->id());
	return CUBIT_FAILURE;
      }
    }

    par->get_shared_proc_list()->reset();
    m_sharedProcs.reset();
    size = par->get_shared_proc_list()->size();

    for (int i = 0; i < size; i++) {
      if (par->get_shared_proc_list()->get_and_step() != m_sharedProcs.get_and_step()) {
	PRINT_ERROR("Different processor found for %s %d.\n",
		    attrib_owner()->class_name(), attrib_owner()->id());
	return CUBIT_FAILURE;
      }
    }

    par->get_ghost_proc_list()->reset();
    m_ghostProcs.reset();
    size = par->get_ghost_proc_list()->size();

    for (int i = 0; i < size; i++) {
      if (par->get_ghost_proc_list()->get_and_step() != m_ghostProcs.get_and_step()) {
	PRINT_ERROR("Different ghost processor found for %s %d.\n",
		    attrib_owner()->class_name(), attrib_owner()->id());
	return CUBIT_FAILURE;
      }
    }

    if ((int)par->get_unique_id() != m_uniqueID) {
      PRINT_ERROR("Different unique ID found for %s %d.\n",
		  attrib_owner()->class_name(), attrib_owner()->id());
      return CUBIT_FAILURE;
    }
  }
  else {
    // else make a new one
    par = new TDParallel(attrib_owner(), &m_sharedBodies, &m_sharedProcs,
			 &m_ghostProcs, m_uniqueID, m_interface);
  }

  delete_attrib(CUBIT_TRUE);
  hasActuated = CUBIT_TRUE;

  return status;
}
Exemple #14
0
CubitStatus RefEntityName::add_refentity_name(RefEntity *entity,
                                              CubitString &name,
                                              bool update_attribs,
                                              bool check_name_validity)
{
  if (name == "")
    return CUBIT_FAILURE;
  
  CubitString in_name = name;
  bool warn_name_change = false;
  
  if (check_name_validity)
  {
    if (clean(name))
    {
      // Assign the invalid name anyway, then continue on and
      // assign the modified name.
      add_refentity_name(entity, in_name, false, false);
      warn_name_change = true;
    }
  }
  
  if (nameEntityList.move_to(name))
  {
    RefEntity *old_entity = nameEntityList.get()->value();
    if (old_entity == entity)
    {
        // Tried to assign same name to entity
      if ( DEBUG_FLAG(92) ) 
      {
        PRINT_INFO("Entity name '%s' already assigned to %s %d\n",
                   name.c_str(), 
                   entity->class_name(), entity->id());
        return CUBIT_FAILURE;
      }
      return CUBIT_SUCCESS;
    }
    else
    {
        // Tried to assign existing name to another entity
      if ( DEBUG_FLAG(92) )
        PRINT_WARNING("Entity name '%s' for %s %d is already used by %s %d\n",
                      name.c_str(),
                      entity->class_name(), entity->id(),
                      old_entity->class_name(), old_entity->id());
      if (get_fix_duplicate_names())
      {
        if (generate_unique_name(name))
        {
          if (warn_name_change)
          {
            PRINT_WARNING("Entity name '%s' can't be used in commands.\n"
                 "         Additional name '%s' assigned.\n",
              in_name.c_str(), name.c_str());
          }
          if ( DEBUG_FLAG(92) )
            PRINT_WARNING("\t%s %d name changed to '%s'\n",
            entity->class_name(), entity->id(), name.c_str());
          return add_refentity_name(entity, name, update_attribs, false);
        }
      }
      return CUBIT_FAILURE;
    }
  }

  if (warn_name_change)
  {
    PRINT_WARNING("Entity name '%s' can't be used in commands.\n"
      "         Additional name '%s' assigned.\n",
      in_name.c_str(), name.c_str());
  }

  RefEntityNameMap *entity_name =
    new RefEntityNameMap(name, entity);
  nameEntityList.insert(entity_name);
  
  if (update_attribs == CUBIT_TRUE)
  {
      // now tell the entity to update its name attribute
    CubitAttrib *attrib = entity->get_cubit_attrib(CA_ENTITY_NAME);
      // force update by resetting update flag
    attrib->has_updated(CUBIT_FALSE);
    attrib->update();
  }
  
  return CUBIT_SUCCESS;
}
Exemple #15
0
CubitStatus CAMergePartner::actuate_list(DLIList<RefEntity*> entity_list)
{

    // given a list of ref entities (usually all entities of a given type),
    // actuate the camp's on those entities
  RefEntity *ref_ent, *keeper;
  DLIList<CubitAttrib*> ca_list;
  DLIList<TopologyBridge*> bridge_list(entity_list.size());
  SDLCAMergePartnerList sorted_camp_list;
  int i;
  for(i = entity_list.size(); i > 0; i--)
  {
    ref_ent = entity_list.get_and_step();
    ca_list.clean_out();
    ref_ent->find_cubit_attrib_type(CA_MERGE_PARTNER, ca_list);
    assert(ca_list.size() < 2); // There should only be one
                                //  merge partner per entity
    if(ca_list.size() > 0)
    {
      CAMergePartner* attrib = dynamic_cast<CAMergePartner*>(ca_list.get());
      sorted_camp_list.append( attrib );
      TopologyEntity* te = dynamic_cast<TopologyEntity*>(ref_ent);
      TopologyBridge* bridge = te->bridge_manager()->topology_bridge();
      bridge_list.append(bridge);
    }
  }
  sorted_camp_list.sort();
  sorted_camp_list.reset();

  if (DEBUG_FLAG(90)) {
    for (i = sorted_camp_list.size(); i > 0; i--) {
      CAMergePartner *camp_ptr = sorted_camp_list.get_and_step();
      ref_ent = camp_ptr->attrib_owner();
      PRINT_DEBUG_90("%s %d, unique id = %d\n", ref_ent->class_name(),
                     ref_ent->id(), camp_ptr->merge_id());
    }
  }
  
    // now go through all the camp's for the entity list; peel off
    // camp's with the same id, and merge the associated entities together
  while (sorted_camp_list.size() > 0) 
  {
    DLIList<RefEntity*> refent_list;
    DLIList<CubitAttrib*> camp_list;
    keeper = NULL;

      // get the next list of entities with the same camp id
    sorted_camp_list.last();
    CAMergePartner *camp_ptr = sorted_camp_list.remove();
    sorted_camp_list.back();
    camp_list.append(camp_ptr);
    int current_id = camp_ptr->merge_id();
    while (sorted_camp_list.size() > 0 &&
           sorted_camp_list.get()->merge_id() == current_id) {
      camp_list.append(sorted_camp_list.remove());
      sorted_camp_list.back();
    }
    
    if (camp_list.size() == 1) continue;
    
    CubitBoolean has_actuated = camp_list.get()->has_actuated();

      // check the has actuated flag; if one is set, they all should be;
      // also, compile list of ref entities while we're at it
    for (current_id = camp_list.size(); current_id > 0; current_id--) {
      ref_ent = camp_list.get()->attrib_owner();
      refent_list.append(ref_ent);
      if (!keeper || ref_ent->id() < keeper->id()) keeper = ref_ent;
      assert(camp_list.get()->has_actuated() == has_actuated);
      camp_list.step();
    }

      // if they have already actuated, go on to next ones
    if (has_actuated == CUBIT_TRUE) continue;

      // otherwise merge
    if(refent_list.size() > 1)
      MergeTool::instance()->force_merge(refent_list);

        // remove the cubit attribute from the surviving parent
    keeper->remove_cubit_attrib(CA_MERGE_PARTNER);

  } // loop over existing camp's
  
  return CUBIT_SUCCESS;
}
Exemple #16
0
lref_t debug_print_object(lref_t obj, lref_t port, bool machine_readable)
{
     _TCHAR buf[STACK_STRBUF_LEN];

     if (DEBUG_FLAG(DF_PRINT_ADDRESSES))
          scwritef("#@~c&=", port, obj);

     lref_t tmp;
     size_t ii;
     lref_t slots;
     const _TCHAR *fast_op_name;

     switch (TYPE(obj))
     {
     case TC_NIL:
          WRITE_TEXT_CONSTANT(port, _T("()"));
          break;

     case TC_BOOLEAN:
          if (TRUEP(obj))
               WRITE_TEXT_CONSTANT(port, _T("#t"));
          else
               WRITE_TEXT_CONSTANT(port, _T("#f"));
          break;

     case TC_CONS:
          write_char(port, _T('('));
          debug_print_object(lcar(obj), port, machine_readable);

          for (tmp = lcdr(obj); CONSP(tmp); tmp = lcdr(tmp))
          {
               write_char(port, _T(' '));
               debug_print_object(lcar(tmp), port, machine_readable);
          }

          if (!NULLP(tmp))
          {
               WRITE_TEXT_CONSTANT(port, _T(" . "));
               debug_print_object(tmp, port, machine_readable);
          }

          write_char(port, _T(')'));
          break;

     case TC_FIXNUM:
          _sntprintf(buf, STACK_STRBUF_LEN, _T("%" SCAN_PRIiFIXNUM), FIXNM(obj));
          write_text(port, buf, _tcslen(buf));
          break;

     case TC_FLONUM:
          debug_print_flonum(obj, port, machine_readable);
          break;

     case TC_CHARACTER:
          if (machine_readable)
          {
               if (CHARV(obj) < CHARNAMECOUNT)
                    scwritef(_T("#\\~cs"), port, charnames[(size_t) CHARV(obj)]);
               else if (CHARV(obj) >= CHAREXTENDED - 1)
                    scwritef(_T("#\\<~cd>"), port, (int) CHARV(obj));
               else
                    scwritef(_T("#\\~cc"), port, (int) CHARV(obj));
          }
          else
               scwritef(_T("~cc"), port, (int) CHARV(obj));
          break;

     case TC_SYMBOL:
          if (NULLP(SYMBOL_HOME(obj)))
          {
               if (DEBUG_FLAG(DF_PRINT_FOR_DIFF))
                    scwritef("#:<uninterned-symbol>", port);
               else
                    scwritef("#:~a@~c&", port, SYMBOL_PNAME(obj), obj);
          }
          else if (SYMBOL_HOME(obj) == interp.control_fields[VMCTRL_PACKAGE_KEYWORD])
               scwritef(":~a", port, SYMBOL_PNAME(obj));
          else
          {
               /* With only a minimal c-level package implementation, we
                * just assume every symbol is private. */
               scwritef("~a::~a", port, SYMBOL_HOME(obj)->as.package.name, SYMBOL_PNAME(obj));
          }
          break;

     case TC_VECTOR:
          WRITE_TEXT_CONSTANT(port, _T("["));

          for (ii = 0; ii < obj->as.vector.dim; ii++)
          {
               debug_print_object(obj->as.vector.data[ii], port, true);

               if (ii + 1 < obj->as.vector.dim)
                    write_char(port, _T(' '));
          }

          write_char(port, _T(']'));
          break;

     case TC_STRUCTURE:
          WRITE_TEXT_CONSTANT(port, _T("#S("));

          debug_print_object(CAR(STRUCTURE_LAYOUT(obj)), port, true);

          for (ii = 0, slots = CAR(CDR(STRUCTURE_LAYOUT(obj)));
               ii < STRUCTURE_DIM(obj); ii++, slots = CDR(slots))
          {
               WRITE_TEXT_CONSTANT(port, _T(" "));
               debug_print_object(CAR(CAR(slots)), port, true);
               WRITE_TEXT_CONSTANT(port, _T(" "));
               debug_print_object(STRUCTURE_ELEM(obj, ii), port, true);
          }

          WRITE_TEXT_CONSTANT(port, _T(")"));
          break;

     case TC_STRING:
          debug_print_string(obj, port, machine_readable);
          break;
     case TC_HASH:
          debug_print_hash(obj, port, machine_readable);
          break;

     case TC_PACKAGE:
          scwritef("~u ~a", port, (lref_t) obj, obj->as.package.name);
          break;

     case TC_SUBR:
          scwritef("~u,~cd:~a", port, (lref_t) obj, SUBR_TYPE(obj), SUBR_NAME(obj));
          break;

     case TC_CLOSURE:
          if (DEBUG_FLAG(DF_PRINT_CLOSURE_CODE))
               scwritef("~u\n\tcode:~s\n\tenv:~s\n\tp-list:~s", port,
                        (lref_t) obj, CLOSURE_CODE(obj), CLOSURE_ENV(obj),
                        CLOSURE_PROPERTY_LIST(obj));

          else
               scwritef("~u", port, (lref_t) obj);
          break;

     case TC_VALUES_TUPLE:
          scwritef("~u ~s", port, (lref_t) obj, obj->as.values_tuple.values);
          break;

     case TC_MACRO:
          if (DEBUG_FLAG(DF_PRINT_CLOSURE_CODE))
               scwritef("~u ~s", port, (lref_t) obj, obj->as.macro.transformer);
          else
               scwritef("~u", port, (lref_t) obj);
          break;

     case TC_END_OF_FILE:
          scwritef("~u", port, (lref_t) obj);
          break;

     case TC_PORT:
          scwritef(_T("~u~cs~cs~cs ~cs ~s"), port,
                   obj,
                   PORT_INPUTP(obj) ? " (input)" : "",
                   PORT_OUTPUTP(obj) ? " (output)" : "",
                   BINARY_PORTP(obj) ? " (binary)" : "",
                   PORT_CLASS(obj)->name,
                   PORT_PINFO(obj)->port_name);
          break;

     case TC_FAST_OP:
          fast_op_name = fast_op_opcode_name(obj->header.opcode);

          if (fast_op_name)
               scwritef("#<FOP@~c&:~cs ~s ~s => ~s>", port, (lref_t) obj,
                        fast_op_name,
                        obj->as.fast_op.arg1,
                        obj->as.fast_op.arg2,
                        obj->as.fast_op.next);
          else
               scwritef("#<FOP@~c&:~cd ~s ~s => ~s>", port, (lref_t) obj,
                        obj->header.opcode,
                        obj->as.fast_op.arg1,
                        obj->as.fast_op.arg2,
                        obj->as.fast_op.next);
     break;

     case TC_FASL_READER:
          scwritef(_T("~u~s"), port,
                   obj,
                   FASL_READER_PORT(obj));
          break;

     case TC_UNBOUND_MARKER:
          scwritef("#<UNBOUND-MARKER>", port);
          break;

     case TC_FREE_CELL:
          scwritef("#<FREE CELL -- Forget a call to gc_mark? ~c&>", port, obj);
          break;

     default:
          scwritef("#<INVALID OBJECT - UNKNOWN TYPE ~c&>", port, obj);
     }

     return port;
}
Exemple #17
0
//-------------------------------------------------------------------------
// Purpose       : facet_surface: facets the surface.
//
// Special Notes : 
//
// Creator       : David White
//
// Creation Date : 03/01/02
//-------------------------------------------------------------------------
CubitStatus Faceter::facet_surface(DLIList <CubitFacet*> &results,
                                   DLIList <CubitPoint*> &point_list)
{
  if ( DEBUG_FLAG(129) )
  {
    GfxDebug::clear();
    GfxDebug::draw_ref_face_edges(thisRefFacePtr);
    GfxDebug::flush();
    int debug = 0;
    if ( debug )
    {
      GfxDebug::mouse_xforms();
      GfxDebug::flush();
    }
  }
  if ( thisRefFacePtr->number_of_Loops() > 1 )
    return CUBIT_FAILURE;
    //Get the ordered boundary loops.
  int ii, jj;
  DLIList <DLIList<CubitPoint*>*>  boundary_point_loops;
  DLIList <CubitPoint*> *tmp_list_ptr;
  CubitStatus stat = get_boundary_points( boundary_point_loops );
  if ( stat != CUBIT_SUCCESS )
  {
      //clean up the data...
    for ( ii = boundary_point_loops.size(); ii > 0; ii-- )
    {
      tmp_list_ptr = boundary_point_loops.pop();
      for ( jj = tmp_list_ptr->size(); jj > 0; jj-- )
        delete tmp_list_ptr->pop();
      delete tmp_list_ptr;
    }
    return stat;
  }
    //Set up the gridsearch.
  double ratio = gridCellScale, cell_size = 0.0;
  max_min_edge_ratio(boundary_point_loops, ratio, cell_size);
  if (ratio <= gridCellScale) {
    ratio = gridCellScale;
  }
    //Get all of the points into a single list.
  for ( ii = boundary_point_loops.size(); ii > 0; ii-- )
  {
    tmp_list_ptr = boundary_point_loops.get_and_step();
    for ( jj = tmp_list_ptr->size(); jj > 0; jj-- )
    {
      globalPointList->append(tmp_list_ptr->get_and_step());
    }
  }
  gridSearchPtr = new PointGridSearch(*globalPointList,
                                      cell_size,
                                      ratio);
      //fill in the grid...
  for ( ii = globalPointList->size(); ii > 0; ii-- )
    gridSearchPtr->add_point(globalPointList->get_and_step());

    //Now start faceting.
  stat = facet_loop( boundary_point_loops.get(), results );
    //clean up the data...
  for ( ii = boundary_point_loops.size(); ii > 0; ii-- )
    delete boundary_point_loops.pop();
  if ( stat != CUBIT_SUCCESS )
  {
      //clean the data and return..
    for ( ii = results.size(); ii > 0; ii-- )
      delete results.pop();
    for ( ii = globalPointList->size(); ii > 0; ii-- )
      delete globalPointList->pop();
    return stat;
  }
    //Didn't add any points...
  point_list += *globalPointList;
  return CUBIT_SUCCESS;
}
Exemple #18
0
CubitStatus RefEntityName::add_refentity_name(RefEntity *entity,
                                              DLIList<CubitString> &names,
                                              bool update_attribs, 
                                              bool check_name_validity)
{
  names.reset();
  //int num_new_names = names.size();

  DLIList<CubitString> new_names;
  
  for (int i=0; i<names.size(); i++)
  {
    CubitString name = names[i];
    CubitString in_name = name;
    CubitBoolean warn_name_change = CUBIT_FALSE;
    
      // first, clean the name
    if (check_name_validity)
    {
      if (clean(name))
      {
        // assign original name anyway, then
        // continue on and assign modified name.
        add_refentity_name(entity, in_name, false, false);
        warn_name_change = CUBIT_TRUE;
      }
    }
      // now, check for valid name
    CubitBoolean name_valid = CUBIT_FALSE;
    
    if (name == "")
    {
        // blank name entered - do nothing
    }
    
    else if (nameEntityList.move_to(name) &&
             nameEntityList.get()->value() == entity)
    {
        // Tried to assign same name to entity
      if ( DEBUG_FLAG(92) ) 
      {
          // check to see if it's the same as this entity's default name,
          // if so, it probably came in on an attribute, and we don't need
          // to hear about it; otherwise, write the warning
        CubitString def_name;
        entity->generate_default_name(def_name);
        if (name != def_name)
          PRINT_INFO("Entity name '%s' already assigned to %s %d\n",
                     name.c_str(), 
                     entity->class_name(), entity->id());
      }
    }
    else if (nameEntityList.move_to(name) &&
             nameEntityList.get()->value() != entity)
    {
        // Tried to assign existing name to another entity
      PRINT_DEBUG_92( "Entity name '%s' for %s %d is already used by %s %d\n",
                  name.c_str(), entity->class_name(), entity->id(),
                  nameEntityList.get()->value()->class_name(),
                  nameEntityList.get()->value()->id());
      
        // either we fix it and keep it, or we don't and get rid of it
      name_valid = CUBIT_FALSE;
      if (get_fix_duplicate_names())
      {
        if (generate_unique_name(name))
        {
          PRINT_DEBUG_92( "\t%s %d name changed to '%s'\n",
                          entity->class_name(), entity->id(), name.c_str());
          if(warn_name_change)
          {
            PRINT_WARNING("Entity name '%s' can't be used in commands.\n"
                 "         Additional name '%s' assigned.\n",
              in_name.c_str(), name.c_str());
          }
          
          name_valid = CUBIT_TRUE;
        }
      }
    }
    else
    {
      if(warn_name_change)
      {
        PRINT_WARNING("Entity name '%s' can't be used in commands.\n"
          "         Additional name '%s' assigned.\n",
          in_name.c_str(), name.c_str());
      }
      
        // else the name must be valid
      name_valid = CUBIT_TRUE;
    }
    
    if (name_valid == CUBIT_TRUE)
    {
        // name is valid
      if (name != in_name)
          // name was changed; change in name list too
        names[i] = name;

        // save this name to later
      new_names.append(names[i]);
    }
  }
  
  if (new_names.size() > 0)
  {
      // there are some valid, new names; add them, then update attribute
    new_names.reset();
    
    CubitString name;
    for (int i = new_names.size(); i > 0; i--)
    {
      name = new_names.get_and_step();
      if (nameEntityList.move_to(name) &&
          nameEntityList.get()->value() == entity) {
            PRINT_DEBUG_92("Already have name %s for %s %d.\n",
                           name.c_str(), entity->class_name(), entity->id());
      }
      
      else {
        nameEntityList.insert(new RefEntityNameMap(name, entity));
      }
    }
    
    if (update_attribs == CUBIT_TRUE)
    {
        // now tell the entity to update its name attribute
      CubitAttrib *attrib = entity->get_cubit_attrib(CA_ENTITY_NAME);
        // force update by resetting update flag
      attrib->has_updated(CUBIT_FALSE);
      attrib->update();
    }
  }
  
  return CUBIT_SUCCESS;
}
Exemple #19
0
void initTracing (void)
{
#ifdef THREADED_RTS
    initMutex(&trace_utx);
#endif

    DEBUG_FLAG(scheduler,    DEBUG_sched);
    DEBUG_FLAG(interpreter,  DEBUG_interp);
    DEBUG_FLAG(weak,         DEBUG_weak);
    DEBUG_FLAG(gccafs,       DEBUG_gccafs);
    DEBUG_FLAG(gc,           DEBUG_gc);
    DEBUG_FLAG(block_alloc,  DEBUG_block_alloc);
    DEBUG_FLAG(sanity,       DEBUG_sanity);
    DEBUG_FLAG(stable,       DEBUG_stable);
    DEBUG_FLAG(stm,          DEBUG_stm);
    DEBUG_FLAG(prof,         DEBUG_prof);
    DEBUG_FLAG(gran,         DEBUG_gran);
    DEBUG_FLAG(par,          DEBUG_par);
    DEBUG_FLAG(linker,       DEBUG_linker);
    DEBUG_FLAG(squeeze,      DEBUG_squeeze);
    DEBUG_FLAG(hpc,          DEBUG_hpc);

    PAR_FLAG(verbose,        PAR_DEBUG_verbose);
    PAR_FLAG(bq,             PAR_DEBUG_bq);
    PAR_FLAG(schedule,       PAR_DEBUG_schedule);
    PAR_FLAG(free,           PAR_DEBUG_free);
    PAR_FLAG(resume,         PAR_DEBUG_resume);
    PAR_FLAG(weight,         PAR_DEBUG_weight);
    PAR_FLAG(fetch,          PAR_DEBUG_fetch);
    PAR_FLAG(fish,           PAR_DEBUG_fish);
    PAR_FLAG(tables,         PAR_DEBUG_tables);
    PAR_FLAG(packet,         PAR_DEBUG_packet);
    PAR_FLAG(pack,           PAR_DEBUG_pack);
    PAR_FLAG(paranoia,       PAR_DEBUG_paranoia);

    GRAN_FLAG(event_trace,   GRAN_DEBUG_event_trace);
    GRAN_FLAG(event_stats,   GRAN_DEBUG_event_stats);
    GRAN_FLAG(bq,            GRAN_DEBUG_bq);
    GRAN_FLAG(pack,          GRAN_DEBUG_pack);
    GRAN_FLAG(checkSparkQ,   GRAN_DEBUG_checkSparkQ);
    GRAN_FLAG(thunkStealing, GRAN_DEBUG_thunkStealing);
    GRAN_FLAG(randomSteal,   GRAN_DEBUG_randomSteal);
    GRAN_FLAG(findWork,      GRAN_DEBUG_findWork);
    GRAN_FLAG(unused,        GRAN_DEBUG_unused);
    GRAN_FLAG(pri,           GRAN_DEBUG_pri);
    GRAN_FLAG(checkLight,    GRAN_DEBUG_checkLight);
    GRAN_FLAG(sortedQ,       GRAN_DEBUG_sortedQ);
    GRAN_FLAG(blockOnFetch,  GRAN_DEBUG_blockOnFetch);
    GRAN_FLAG(packBuffer,    GRAN_DEBUG_packBuffer);
    GRAN_FLAG(blockedOnFetch_sanity, GRAN_DEBUG_BOF_sanity);

    TRACE_FLAG(sched, TRACE_sched);
}
  /*! \fn ipopt_jac_g
   *
   *  \param [in]  [n]
   *  \param [in]  [x]
   *  \param [in]  [new_x]
   *  \param [in]  [m]
   *  \param [in]  [nele_jac]
   *  \param [out] [iRow]
   *  \param [out] [jCol]
   *  \param [out] [values]
   *  \param [ref] [user_data]
   *
   *  \author lochel
   */
  static Bool ipopt_jac_g(int n, double *x, Bool new_x, int m, int nele_jac,
                          int *iRow, int *jCol, double *values, void *user_data)
  {
    IPOPT_DATA *ipopt_data = (IPOPT_DATA*)user_data;

    if(values == NULL)
    {
      int i, j;
      int idx = 0;

      if(ipopt_data->useSymbolic == 1)
      {
        /*
         * SPARSE
         *
         */
        DEBUG_INFO(LOG_INIT, "ipopt using symbolic sparse jacobian G");
        if(DEBUG_FLAG(LOG_INIT))
        {
          DEBUG_INFO(LOG_INIT, "sparsity pattern");
          for(i=0; i<n; ++i)
          {
            printf("        | | column %3d: [ ", i+1);
            for(j=0; idx<ipopt_data->data->simulationInfo.analyticJacobians[INDEX_JAC_G].sparsePattern.leadindex[i]; ++j)
            {
              if(j+1 == ipopt_data->data->simulationInfo.analyticJacobians[INDEX_JAC_G].sparsePattern.index[idx])
              {
                idx++;
                printf("*");
              }
              else
                printf("0");
            }
            for(; j<m; ++j)
              printf("0");
            printf("]\n");
          }
          printf("\n");
        }

        idx = 0;
        for(i=0; i<n; ++i)
        {
          for(j=0; idx<ipopt_data->data->simulationInfo.analyticJacobians[INDEX_JAC_G].sparsePattern.leadindex[i]; ++j)
          {
            if(j+1 == ipopt_data->data->simulationInfo.analyticJacobians[INDEX_JAC_G].sparsePattern.index[idx])
            {
              jCol[idx] = i;
              iRow[idx] = j;
              idx++;
            }
          }
        }
      }
      else
      {
        /*
         * DENSE
         *
         */
        DEBUG_INFO(LOG_INIT, "ipopt using numeric dense jacobian G");
        idx = 0;
        for(i=0; i<n; ++i)
        {
          for(j=0; j<m; ++j)
          {
            jCol[idx] = i;
            iRow[idx] = j;
            idx++;
          }
        }
      }

      assert(idx == nele_jac);
    }
    else
    {
      /* return the values of the jacobian of the constraints */
      DEBUG_INFO(LOG_INIT, "ipopt jacobian G");

      if(ipopt_data->useSymbolic == 1)
      {
        functionJacG_sparse(ipopt_data->data, values);

        if(DEBUG_FLAG(LOG_INIT))
        {
          int i, j;
          int idx = 0;
          for(i=0; i<n; ++i)
          {
            printf("        | | column %3d: [ ", i+1);
            for(j=0; idx<ipopt_data->data->simulationInfo.analyticJacobians[INDEX_JAC_G].sparsePattern.leadindex[i]; ++j)
            {
              if(j+1 == ipopt_data->data->simulationInfo.analyticJacobians[INDEX_JAC_G].sparsePattern.index[idx])
              {
                printf("%10.5g ", values[idx]);
                idx++;
              }
              else
                printf("%10.5g ", 0.0);
            }
            for(; j<m; ++j)
              printf("%10.5g ", 0.0);
            printf("]\n");
          }
          printf("\n");
        }

      }
      else
      {
        int i, j;
        int idx = 0;
        double h = 1e-6;
        double hh;

        double *gp = (double*)malloc(m * sizeof(double));
        double *gn = (double*)malloc(m * sizeof(double));

        for(i=0; i<n; ++i)
        {
          hh = (abs(x[i]) > 1e-3) ? h*abs(x[i]) : h;
          x[i] += hh;
          ipopt_g(n, x, new_x, m, gp, user_data);
          x[i] -= 2.0*hh;
          ipopt_g(n, x, new_x, m, gn, user_data);
          x[i] += hh;

          for(j=0; j<m; ++j)
          {
            values[idx] = (gp[j]-gn[j])/(2.0*hh);
            idx++;
          }
        }

        free(gp);
        free(gn);

        if(DEBUG_FLAG(LOG_INIT))
        {
          int i, j;
          for(i=0; i<n; ++i)
          {
            for(j=0; j<m; ++j)
              printf("%10.5g ", values[j*n+i]);
            printf("\n");
          }
        }
      }
    }
    return TRUE;
  }
Exemple #21
0
/* A C function to do Lisp-style Formatted I/O ******************
 *
 * ~s - write the lisp object
 * ~a - display the lisp object
 * REVISIT: remove scvwritef ~u in favor of some kind of print_unreadable_object call
 * ~u - display the lisp object in unprintable fashion (ie. <type@addr...>
 *
 * ~cs - display the C string
 * ~cS - display the C string/arglist with a recursive call to scvwritef
 * ~cd - display the C integer
 * ~cf - display the C flonum
 * ~c& - display the C pointer
 * ~cc - display the C character
 * ~cC - display the C integer as an octal character constant
 * ~cB - display the C integer as a byte
 *
 * Prefixing a format code with a #\! (ie. ~!L) causes the corresponding
 * value to be returned from the function as a Lisp object.
 */
lref_t scvwritef(const _TCHAR * format_str, lref_t port, va_list arglist)
{
     char ch;

     if (NULLP(port))
          port = CURRENT_OUTPUT_PORT();

     assert(PORTP(port));


     _TCHAR buf[STACK_STRBUF_LEN];


     lref_t lisp_arg_value = NULL;
     _TCHAR *str_arg_value = NULL;
     _TCHAR char_arg_value = _T('\0');
     long int long_arg_value = 0;
     unsigned long int ulong_arg_value = 0;
     flonum_t flonum_arg_value = 0.0;

     lref_t unprintable_object = NIL;
     lref_t return_value = NIL;

     for (;;)
     {
          ch = *format_str;

          if (ch == '\0')
               break;

          bool return_next_value = false;

          format_str++;

          if (ch != '~')
          {
               write_char(port, ch);

               continue;
          }

          ch = *format_str;
          format_str++;

          if (ch == '!')
          {
               ch = *format_str;
               format_str++;

               return_next_value = true;
          }

          switch (ch)
          {
          case 's':
               lisp_arg_value = va_arg(arglist, lref_t);

               if (return_next_value)
                    return_value = lisp_arg_value;

               debug_print_object(lisp_arg_value, port, true);
               break;

          case 'a':
               lisp_arg_value = va_arg(arglist, lref_t);

               if (return_next_value)
                    return_value = lisp_arg_value;

               debug_print_object(lisp_arg_value, port, false);
               break;

          case 'u':
               unprintable_object = va_arg(arglist, lref_t);

               if (return_next_value)
                    return_value = unprintable_object;

               if (DEBUG_FLAG(DF_PRINT_FOR_DIFF))
                    scwritef("#<~cs@(no-addr)", port, typecode_name(TYPE(unprintable_object)));
               else
                    scwritef("#<~cs@~c&", port,
                             typecode_name(TYPE(unprintable_object)), unprintable_object);
               break;

          case '~':
               write_char(port, '~');
               break;

          case 'c':            /*  C object prefix */

               ch = *format_str;        /*  read the next format character */
               format_str++;

               switch (ch)
               {

               case 's':
                    str_arg_value = va_arg(arglist, _TCHAR *);

                    if (return_next_value)
                         return_value = strconsbuf(str_arg_value);

                    if (str_arg_value)
                         write_text(port, str_arg_value, _tcslen(str_arg_value));
                    else
                         WRITE_TEXT_CONSTANT(port, _T("<null>"));
                    break;

               case 'S':
                    str_arg_value = va_arg(arglist, _TCHAR *);

                    if (return_next_value)
                         return_value = scvwritef(str_arg_value, port, arglist);
                    else
                         scvwritef(str_arg_value, port, arglist);
                    break;

               case 'd':
                    long_arg_value = va_arg(arglist, long int);

                    if (return_next_value)
                         return_value = fixcons(long_arg_value);

                    _sntprintf(buf, STACK_STRBUF_LEN, _T("%d"), (int) long_arg_value);

                    write_text(port, buf, _tcslen(buf));
                    break;

               case 'x':
                    long_arg_value = va_arg(arglist, long int);

                    if (return_next_value)
                         return_value = fixcons(long_arg_value);

                    _sntprintf(buf, STACK_STRBUF_LEN, _T("%08lx"), long_arg_value);

                    write_text(port, buf, _tcslen(buf));
                    break;

               case 'f':
                    flonum_arg_value = va_arg(arglist, flonum_t);

                    if (return_next_value)
                         return_value = flocons(flonum_arg_value);

                    _sntprintf(buf, STACK_STRBUF_LEN, _T("%f"), flonum_arg_value);

                    write_text(port, buf, _tcslen(buf));
                    break;

               case '&':
                    _sntprintf(buf, STACK_STRBUF_LEN, _T("%p"), (void *) va_arg(arglist, void *));

                    if (return_next_value)
                         return_value = strconsbuf(buf);

                    write_text(port, buf, _tcslen(buf));
                    break;

               case 'c':
                    ulong_arg_value = va_arg(arglist, unsigned long int);

                    if (return_next_value)
                         return_value = fixcons(ulong_arg_value);

                    char_arg_value = (_TCHAR) ulong_arg_value;

                    write_text(port, &char_arg_value, 1);
                    break;

               case 'C':
                    ulong_arg_value = va_arg(arglist, unsigned long int);

                    if (return_next_value)
                         return_value = fixcons(ulong_arg_value);

                    _sntprintf(buf, STACK_STRBUF_LEN, _T("%03o"), (uint32_t) ulong_arg_value);
                    write_text(port, buf, _tcslen(buf));
                    break;

               case 'B':
                    ulong_arg_value = va_arg(arglist, unsigned long int);

                    if (return_next_value)
                         return_value = fixcons(ulong_arg_value);

                    _sntprintf(buf, STACK_STRBUF_LEN, _T("0x%02x"), (uint32_t) ulong_arg_value);
                    write_text(port, buf, _tcslen(buf));
                    break;

               default:
                    panic(_T("Invalid C object format character in scwritef"));
                    break;
               };
               break;

          default:
               panic(_T("Invalid format character in scwritef"));
               break;
          }

          return_next_value = false;
     }
     va_end(arglist);

     if (!NULLP(unprintable_object))
          scwritef(">", port);

     return return_value;
}
  /*! \fn ipopt_initialization
   *
   *  This function is used if ipopt is choosen for initialization.
   *
   *  \param [ref] [data]
   *  \param [ref] [initData]
   *  \param [in]  [useScaling]
   *
   *  \author lochel
   */
  int ipopt_initialization(DATA *data, INIT_DATA *initData, int useScaling)
  {
    int n = initData->nz;                /* number of variables */
    int m = (initData->nInitResiduals > initData->nz) ? 0 : initData->nInitResiduals;    /* number of constraints */
    double* x_L = NULL;                  /* lower bounds on x */
    double* x_U = NULL;                  /* upper bounds on x */
    double* g_L = NULL;                  /* lower bounds on g */
    double* g_U = NULL;                  /* upper bounds on g */

    double* x = NULL;                    /* starting point and solution vector */
    double* mult_g = NULL;               /* constraint multipliers at the solution */
    double* mult_x_L = NULL;             /* lower bound multipliers at the solution */
    double* mult_x_U = NULL;             /* upper bound multipliers at the solution */
    double obj;                          /* objective value */
    int i;                               /* generic counter */

    int nele_jac = n*m;                  /* number of nonzeros in the Jacobian of the constraints */
    int nele_hess = 0;                   /* number of nonzeros in the Hessian of the Lagrangian (lower or upper triangual part only) */

    IpoptProblem nlp = NULL;             /* ipopt-problem */
    enum ApplicationReturnStatus status; /* solve return code */

    IPOPT_DATA ipopt_data;

    ipopt_data.data = data;
    ipopt_data.initData = initData;
    ipopt_data.useScaling = useScaling;
    ipopt_data.useSymbolic = (initialAnalyticJacobianG(data) == 0 ? 1 : 0);

    if(ipopt_data.useSymbolic == 1)
    {
      nele_jac = data->simulationInfo.analyticJacobians[INDEX_JAC_G].sparsePattern.leadindex[n-1]; // sparse
      DEBUG_INFO1(LOG_INIT, "number of zeros in the Jacobian of the constraints (jac_g):    %d", n*m-nele_jac);
      DEBUG_INFO1(LOG_INIT, "number of nonzeros in the Jacobian of the constraints (jac_g): %d", nele_jac);
    }

    /* allocate space for the variable bounds */
    x_L = (double*)malloc(n * sizeof(double));
    x_U = (double*)malloc(n * sizeof(double));

    /* allocate space for the constraint bounds */
    g_L = (double*)malloc(m * sizeof(double));
    g_U = (double*)malloc(m * sizeof(double));

    /* allocate space for the initial point */
    x = (double*)malloc(n * sizeof(double));

    /* set values of optimization variable bounds */
    for(i=0; i<n; ++i)
    {
      x[i] = initData->start[i];
      x_L[i] = initData->min[i];
      x_U[i] = initData->max[i];
    }

    /* set values of constraint bounds */
    for(i=0; i<m; ++i)
    {
      g_L[i] = 0.0;
      g_U[i] = 0.0;
    }

    /* create the IpoptProblem */
    nlp = CreateIpoptProblem(
        n,              /* Number of optimization variables */
        x_L,            /* Lower bounds on variables */
        x_U,            /* Upper bounds on variables */
        m,              /* Number of constraints */
        g_L,            /* Lower bounds on constraints */
        g_U,            /* Upper bounds on constraints */
        nele_jac,       /* Number of non-zero elements in constraint Jacobian */
        nele_hess,      /* Number of non-zero elements in Hessian of Lagrangian */
        0,              /* indexing style for iRow & jCol; 0 for C style, 1 for Fortran style */
        &ipopt_f,       /* Callback function for evaluating objective function */
        &ipopt_g,       /* Callback function for evaluating constraint functions */
        &ipopt_grad_f,  /* Callback function for evaluating gradient of objective function */
        &ipopt_jac_g,   /* Callback function for evaluating Jacobian of constraint functions */
        &ipopt_h);      /* Callback function for evaluating Hessian of Lagrangian function */

    ASSERT(nlp, "creating of ipopt problem has failed");

    /* We can free the memory now - the values for the bounds have been
       copied internally in CreateIpoptProblem */
    free(x_L);
    free(x_U);
    free(g_L);
    free(g_U);

    /* Set some options. Note the following ones are only examples,
       they might not be suitable for your problem. */
    AddIpoptNumOption(nlp, "tol", 1e-7);

    AddIpoptIntOption(nlp, "print_level", DEBUG_FLAG(LOG_INIT) ? 5 : 0);
    AddIpoptIntOption(nlp, "max_iter", 5000);

    AddIpoptStrOption(nlp, "mu_strategy", "adaptive");
    AddIpoptStrOption(nlp, "hessian_approximation", "limited-memory");

    /* allocate space to store the bound multipliers at the solution */
    mult_g = (double*)malloc(m*sizeof(double));
    mult_x_L = (double*)malloc(n*sizeof(double));
    mult_x_U = (double*)malloc(n*sizeof(double));

    /* solve the problem */
    status = IpoptSolve(
        nlp,            /* Problem that is to be optimized */
        x,              /* Input: Starting point; Output: Optimal solution */
        NULL,           /* Values of constraint at final point */
        &obj,           /* Final value of objective function */
        mult_g,         /* Final multipliers for constraints */
        mult_x_L,       /* Final multipliers for lower variable bounds */
        mult_x_U,       /* Final multipliers for upper variable bounds */
        &ipopt_data);   /* Pointer to user data */

    setZ(initData, x);

    /* free allocated memory */
    FreeIpoptProblem(nlp);
    free(x);
    free(mult_g);
    free(mult_x_L);
    free(mult_x_U);

    /* debug output */
    DEBUG_INFO1(LOG_INIT, "ending with funcValue = %g", obj);
    DEBUG_INFO_AL(LOG_INIT, "| unfixed variables");
    for(i=0; i<initData->nz; i++)
      DEBUG_INFO_AL4(LOG_INIT, "| | [%ld] %s = %g [scaled: %g]", i+1, initData->name[i], initData->z[i], initData->zScaled[i]);
    DEBUG_INFO_AL(LOG_INIT, "| residuals (> 0.001)");
    for(i=0; i<data->modelData.nInitResiduals; i++)
      if(fabs(initData->initialResiduals[i]) > 1e-3)
        DEBUG_INFO_AL3(LOG_INIT, "| | [%ld] %g [scaled: %g]", i+1, initData->initialResiduals[i], (initData->residualScalingCoefficients[i] != 0.0) ? initData->initialResiduals[i]/initData->residualScalingCoefficients[i] : 0.0);

    if(status != Solve_Succeeded && status != Solved_To_Acceptable_Level)
      THROW("ipopt failed. see last warning. use [-lv LOG_INIT] for more output.");

    return (int)status;
  }
// The main midsurface function
// lower_tol, upper_tol and preview are optional
CubitStatus AutoMidsurfaceTool::midsurface(
	DLIList<Body*> &body_list_in,
	DLIList<BodySM*> &body_list_out,
    DLIList<Body*> &old_bodies_midsurfaced,
    DLIList<double> &thickness_out,
	double lower_limit,
	double upper_limit,
    CubitBoolean delete_midsurfaced,
    CubitBoolean preview)
{
    if(lower_limit == CUBIT_DBL_MAX)// no limit set
        lower_limit = -CUBIT_DBL_MAX;
    double lower_tol = CUBIT_DBL_MAX;
    double upper_tol = CUBIT_DBL_MAX;
    const double auto_thickness_margin = 0.05; // if the user wants to automatically find the search
	                                          // thickness then this var give the search margin around the
	                                          // guess
    ProgressTool* prog_tool = 0;
    if(body_list_in.size()>5)
        prog_tool = AppUtil::instance()->progress_tool();

	// At lease one body must be provided
	if(body_list_in.size() < 1)
	{
		PRINT_ERROR( "No bodies given for midsurfacing\n" );
		return CUBIT_FAILURE;
	}

	// The surfaceOverlapTool is persistent so we need to save the 
	// max_gap and such to restore them at the end or if we error out
	// save current settings
	double max_gap_save = SurfaceOverlapTool::instance()->get_gap_max();
	double min_gap_save = SurfaceOverlapTool::instance()->get_gap_min();
	int normal_type = SurfaceOverlapTool::instance()->get_normal_type();
	CubitBoolean cubit_bool_save = SurfaceOverlapTool::instance()->get_check_within_bodies();
    CubitBoolean skip_facing_surfaces = SurfaceOverlapTool::instance()->get_skip_facing_surfaces();

    // we want to only find overlap within a body
    SurfaceOverlapTool::instance()->set_check_within_bodies(CUBIT_TRUE);
    // 1=any, 2=opposite, 3=same  - we want to find only the overlaps that normals
    // pointing in the opposite directions
    SurfaceOverlapTool::instance()->set_normal_type(2);
    // Don't pickup surfaces that face each other
    SurfaceOverlapTool::instance()->set_skip_facing_surfaces(CUBIT_TRUE);

    // list of bodies that fail to midsurface
    DLIList<Body*> failing_bodies; 

    GeometryModifyEngine* gme = 0;
    GeometryQueryEngine* gqe = 0;

	// loop over every body and try to create midsurface(s)
	int i = 0;
	CubitStatus return_status = CUBIT_FAILURE;

    if(prog_tool)
        prog_tool->start(0,body_list_in.size());

    for(i = body_list_in.size();i--;)
    {
        if(prog_tool)
            prog_tool->step();

		Body* cur_body = body_list_in[i];
		if(!cur_body)
			continue;

		BodySM* body_sm = cur_body->get_body_sm_ptr();
		if(!body_sm)
			continue;

        if(cur_body->is_sheet_body())
        {
            PRINT_INFO("Body %d is a sheet body.\n",cur_body->id());
            continue;
        }

		// Grab the geometrymodify and geometryquery engines to use later
		gqe = cur_body->get_geometry_query_engine();
		gme = GeometryModifyTool::instance()->get_engine(body_sm);

		if(!gqe || !gme)
			continue;

		// Here are the steps to finding/creating the midsurface
		// 1. If the user did not give a thickness range to search then
		//    make an educated guess at the proper thickness range. The assumption
		//    is that the midsurface is a square and the thickness is constant.
		//    The resulting equation is a third order polynomial that is solved using
		//    a few newton iterations. The initial thickness guess is Volume/Area
		// 2. Using the given search distances use the SurfaceOverlapTool to find
		//    surface pairs.
        // 3. If there is only one surface pair then use the existing midsurface commands
		// 4. Find if the surface pairs represent two surface patches
		// 5. If there are only two surface patches try to offset one of the patches
		// 6. (this step is commented out for now) - If 5 fails or there are more than
        //           two surface patches then try the following:
		//         - Use the manual midsurface creation function to create midsurfaces for each
		//           pair of surfaces.
		//         - Unite all of the created midsurfaces together
		//         - remove any surfaces that have a curve touching a surface pair 
		//         - Regularize the resulting body
		// 7. Done

		{
			PRINT_DEBUG_198("AUTOMATICALLY calculating search range\n");
			DLIList<RefVolume*> vol_list;
			cur_body->ref_volumes(vol_list);
			double total_vol = 0;
            double total_vol_bb = 0;
			for(int vol_cnt = 0; vol_cnt < vol_list.size(); vol_cnt++)
			{
                CubitVector cg;
                double temp_volume;
                vol_list[vol_cnt]->mass_properties(cg,temp_volume);
                CubitBox vol_bb = vol_list[vol_cnt]->bounding_box();
                total_vol += temp_volume;
                total_vol_bb += vol_bb.x_range()*vol_bb.y_range()*vol_bb.z_range();
            }

            if(total_vol<0 || total_vol > total_vol_bb)
            {
                PRINT_INFO("Could not midsurface Body %d - try healing the body.\n",cur_body->id());
                failing_bodies.append(cur_body);
                continue;
            }
                
			PRINT_DEBUG_198("Volume of %f\n",total_vol);

			DLIList<RefFace*> face_list;
			cur_body->ref_faces(face_list);
			double total_surf = 0;
			for(int surf_cnt = 0; surf_cnt < face_list.size(); surf_cnt++)
				total_surf += face_list[surf_cnt]->area();
			PRINT_DEBUG_198("Area of %f\n",total_surf);

			double t_g = total_vol/(total_surf/2.0);
            double initial_guess = t_g;
			PRINT_DEBUG_198("Initial guess of thickness %f\n",t_g);
			// use a newton solver to get a more accurate estimate the thickness of the volume
			for(int n_i = 0;n_i<100;n_i++)
			{
				double tol_newton = GEOMETRY_RESABS;
				double t_gn = t_g + tol_newton;
				double f_prime = ((2.0*total_vol + sqrt(total_vol*t_g*t_g*t_g)*4.0 - total_surf*t_g)
					-(2.0*total_vol + sqrt(total_vol*t_gn*t_gn*t_gn)*4.0 - total_surf*t_gn))/
					(t_g-t_gn);

				// avoid divide by zero
				if(fabs(f_prime)<tol_newton)
					break;

				double t_old = t_g;
				t_g = t_g - (2.0*total_vol + sqrt(total_vol*t_g*t_g*t_g)*4.0 - total_surf*t_g)/f_prime;
				
				PRINT_DEBUG_198("Guess %d Thickness %f\n",n_i,t_g);
				if(fabs(t_g-t_old)<tol_newton)
				{
					PRINT_DEBUG_198("Converged with thickness of %f in %d steps\n",t_g,n_i);
					break;
				}
                if(t_g<0.0)
                {
					PRINT_DEBUG_198("thickness less than zero setting back to initial guess\n");
                    t_g = fabs(initial_guess);
					break;
                }
			}
			upper_tol = t_g + t_g*auto_thickness_margin;
			lower_tol = t_g - t_g*auto_thickness_margin;
            upper_tol = upper_tol <= upper_limit?upper_tol:upper_limit;
            lower_tol = lower_tol >= lower_limit?lower_tol:lower_limit;

			PRINT_DEBUG_198("Guessing a thickness of %f to %f\n",lower_tol,upper_tol);
		}

		// set the lower and upper search distances
		SurfaceOverlapTool::instance()->set_gap_max(upper_tol);
		SurfaceOverlapTool::instance()->set_gap_min(lower_tol);

		DLIList<RefFace*> ref_face_list,list1,list2;
        DLIList<RefEntity*> faces_to_draw; 
        cur_body->ref_faces(ref_face_list);
        // find the surface pairs
        SurfaceOverlapTool::instance()->find_overlapping_surfaces(ref_face_list,list1,list2,faces_to_draw);

        int tweak_iters = 4;
        for(int tweak = 0;tweak<tweak_iters;tweak++)
        {
            // if we didn't find anything then the part may be long and selender so grow the search thickness
            if(list1.size()==0 && list2.size() == 0)
            {
                if(tweak == tweak_iters-1 && lower_limit != -CUBIT_DBL_MAX && upper_limit != CUBIT_DBL_MAX)
                {
                    // on the last try use the user defined limits
                    lower_tol = lower_limit;
                    upper_tol = upper_limit;
                }
                else
                {
                    lower_tol = (upper_tol + lower_tol)/2.0;
                    upper_tol += lower_tol*auto_thickness_margin*2;
                    upper_tol = upper_tol <= upper_limit?upper_tol:upper_limit;
                    lower_tol = lower_tol >= lower_limit?lower_tol:lower_limit;
                }

                PRINT_DEBUG_198("Guessing again with thickness of %f to %f\n",lower_tol,upper_tol);
                SurfaceOverlapTool::instance()->set_gap_max(upper_tol);
                SurfaceOverlapTool::instance()->set_gap_min(lower_tol);
                SurfaceOverlapTool::instance()->find_overlapping_surfaces(ref_face_list,list1,list2,faces_to_draw);
            }

            DLIList<RefFace*> check_list;
            check_list += list1;
            check_list += list2;

            if(check_list.size() == 0 )
                continue;

            // make sure the pairs will match the solid within 10% or so
            if(!check_surf_pairs(lower_tol,upper_tol,check_list,cur_body))
            {
                list1.clean_out();
                list2.clean_out();
                continue;
            }
            break;
        }

        if(list1.size() != list2.size())
        {
            PRINT_INFO("Could not find workable surface pairs for Body %d - try using the Sheet Offset command. \n",cur_body->id());
            failing_bodies.append(cur_body);
            continue;
        }
		else if(list1.size() == 0 || list2.size() == 0)
		{
				PRINT_INFO("No surface pairs found for Body %d - try changing the search range\n",cur_body->id());
			failing_bodies.append(cur_body);
			continue;
		}

		// get the first pair and see if there are only two patches
		DLIList<RefFace*> red_faces;
		red_faces.append(list1[0]);
		DLIList<RefFace*> yellow_faces;
		yellow_faces.append(list2[0]);
		DLIList<RefFace*> paired_faces;
		paired_faces += list1;
		paired_faces += list2;
		paired_faces.uniquify_unordered();

		// red surfaces
		while(1)
		{
			int start_cnt = red_faces.size();
			DLIList<RefEdge*> red_edges;
			int j = 0;
			for(j =0;j<red_faces.size();j++)
				red_faces[j]->ref_edges(red_edges);
			red_edges.uniquify_unordered();
			for(j =0;j<red_edges.size();j++)
				red_edges[j]->ref_faces(red_faces);
			red_faces.uniquify_unordered();
			red_faces.intersect_unordered(paired_faces);
			if(start_cnt == red_faces.size())
				break;
		}

		// yellow surfaces
		while(1)
		{
			int start_cnt = yellow_faces.size();
			DLIList<RefEdge*> yellow_edges;
			int j = 0;
			for(j =0;j<yellow_faces.size();j++)
				yellow_faces[j]->ref_edges(yellow_edges);
			yellow_edges.uniquify_unordered();
			for(j =0;j<yellow_edges.size();j++)
				yellow_edges[j]->ref_faces(yellow_faces);
			yellow_faces.uniquify_unordered();
			yellow_faces.intersect_unordered(paired_faces);
			if(start_cnt == yellow_faces.size())
				break;
		}

        DLIList<BodySM*> results;
        bool midsurface_done = false;

        if(DEBUG_FLAG(198))
        {
            int j = 0;
            PRINT_INFO("Trying surface offset to create the mid_surface\n");
            PRINT_INFO("Red surface ");
            for(j = 0;j < red_faces.size();j++)
            {
                GfxDebug::draw_ref_face(red_faces[j],CUBIT_RED);
                PRINT_INFO("%d ",red_faces[j]->id());
            }

            PRINT_INFO("\nYellow surface ");
            for(j = 0;j < yellow_faces.size();j++)
            {
                GfxDebug::draw_ref_face(yellow_faces[j],CUBIT_YELLOW);
                PRINT_INFO("%d ",yellow_faces[j]->id());
            }

            PRINT_INFO("\n");
        }

        // first check to see if we can use the simple midsurface functions
        if(red_faces.size() == 1 && yellow_faces.size() == 1 &&
            paired_faces.size() == red_faces.size() + yellow_faces.size()) 
        {
            RefFace* face_1 = red_faces[0];
            RefFace* face_2 = yellow_faces[0];
            midsurface_done = false;

            if(face_1->geometry_type() == face_2->geometry_type())
            {
                Surface* surf_1 = face_1->get_surface_ptr();
                Surface* surf_2 = face_2->get_surface_ptr();
                BodySM* result_body;
                // grab the distance between surfaces
                CubitVector temp_vec0;
                CubitVector temp_vec1;
                double temp_dist = 0;
                gqe->entity_entity_distance(
                    face_1->get_surface_ptr(),
                    face_2->get_surface_ptr(),
                    temp_vec0,temp_vec1,temp_dist);

                switch(face_1->geometry_type())
                {
                case CONE_SURFACE_TYPE:
                    if(gme->get_conic_mid_surface(surf_1,surf_2,body_sm,result_body) == CUBIT_SUCCESS)
                    {
                        midsurface_done = true;
                        results.append(result_body);
                        thickness_out.append(fabs(temp_dist));
                    }
                    break;
                case PLANE_SURFACE_TYPE:
                    if(get_planar_mid_surface(face_1,face_2,body_sm,result_body,gme) == CUBIT_SUCCESS)
                    {
                        midsurface_done = true;
                        results.append(result_body);
                        thickness_out.append(fabs(temp_dist));
                    }
                    break;
                case SPHERE_SURFACE_TYPE:
                    if(gme->get_spheric_mid_surface(surf_1,surf_2,body_sm,result_body) == CUBIT_SUCCESS)
                    {
                        midsurface_done = true;
                        results.append(result_body);
                        thickness_out.append(fabs(temp_dist));
                    }
                    break;
                case TORUS_SURFACE_TYPE:
                    if(gme->get_toric_mid_surface(surf_1,surf_2,body_sm,result_body) == CUBIT_SUCCESS)
                    {
                        midsurface_done = true;
                        results.append(result_body);
                        thickness_out.append(fabs(temp_dist));
                    }
                    break;
                case CYLINDER_SURFACE_TYPE:
                    if(gme->get_conic_mid_surface(surf_1,surf_2,body_sm,result_body) == CUBIT_SUCCESS)
                    {
                        midsurface_done = true;
                        results.append(result_body);
                        thickness_out.append(fabs(temp_dist));
                    }
                    break;
                default:
                    break;
                }
            }
        }

		if(!midsurface_done &&
            paired_faces.size() == red_faces.size() + yellow_faces.size()) // just do the offset
		{
			int j = 0;
            DLIList<double> offset_distances;
            for(j = 0;j<list1.size();j++)
            {
                CubitVector temp_vec0;
                CubitVector temp_vec1;
				double temp_dist = 0;
				if(!gqe->entity_entity_distance(
					list1[j]->get_surface_ptr(),
					list2[j]->get_surface_ptr(),
					temp_vec0,temp_vec1,temp_dist))
				{
					break;
				}
				offset_distances.append(-temp_dist*.5);
			}

			DLIList<Surface*> red_surfs;
			for(j = 0;j<red_faces.size();j++)
				red_surfs.append(red_faces[j]->get_surface_ptr());

			DLIList<Surface*> yellow_surfs;
			for(j = 0;j<yellow_faces.size();j++)
				yellow_surfs.append(yellow_faces[j]->get_surface_ptr());

            // all of the surfaces are offset the same distance
			double offset_distance = offset_distances[0];
            bool old_error_flag = GET_ERROR_FLAG();
            SET_ERROR_FLAG(false); // don't throw any gme errors
			if( gme->create_offset_sheet(red_surfs,offset_distance,
				NULL,NULL,results))
            {
                midsurface_done = true;
                for(j = 0;j<results.size();j++) // for every body add a thickness
                    thickness_out.append(fabs(offset_distance*2.));
            }
            else if( gme->create_offset_sheet(yellow_surfs,offset_distance,
				NULL,NULL,results)) // try the other direction
            {
                midsurface_done = true;
                for(j = 0;j<results.size();j++) // for every body add a thickness
                    thickness_out.append(fabs(offset_distance*2.));
            }
            else
            {
                PRINT_INFO("Could not create midsurface for Body %d - try using the surface offset command\n",cur_body->id());
                failing_bodies.append(cur_body);
            }
            SET_ERROR_FLAG(old_error_flag); // turn errors back on
        }
        
        if(!midsurface_done && paired_faces.size() != red_faces.size() + yellow_faces.size())
        {
            PRINT_INFO("Could not find workable surface pairs for Body %d - try changing the search range or \n"
                "        using the Sheet Offset command.\n",cur_body->id());
        }

      /*if(!midsurface_done)
        {
			if(DEBUG_FLAG(198))
				PRINT_INFO("Trying the extend, unite, and trim method\n");

			// okay now remove duplicate pairs and unsupported pairs
			DLIList<Surface*> surf_list1;
			DLIList<Surface*> surf_list2;
			bool delete_and_exit = false;
			for(int j = 0;j<list1.size();j++)
			{
				RefFace* face_1 = list1[j];
				RefFace* face_2 = list2[j];

				if(DEBUG_FLAG(198))
				{
					PRINT_INFO("Red surface ");
					GfxDebug::draw_ref_face(face_1,CUBIT_RED);
					PRINT_INFO("%d ",face_1->id());

					PRINT_INFO("\nYellow surface ");
					GfxDebug::draw_ref_face(face_2,CUBIT_YELLOW);
					PRINT_INFO("%d ",face_2->id());

					PRINT_INFO("\n");
				}

				if(face_1->geometry_type() != 	face_2->geometry_type())
					continue;

				Surface* surf_1 = face_1->get_surface_ptr();
				surf_list1.append(surf_1);
				Surface* surf_2 = face_2->get_surface_ptr();
				surf_list2.append(surf_2);
				BodySM* result_body;
				switch(face_1->geometry_type())
				{
				case CONE_SURFACE_TYPE:
					if(gme->get_conic_mid_surface(surf_1,surf_2,body_sm,result_body) == CUBIT_SUCCESS)
						results.append(result_body);
					else
					    delete_and_exit = true;
					break;
				case PLANE_SURFACE_TYPE:
					if(get_planar_mid_surface(face_1,face_2,body_sm,result_body,gme) == CUBIT_SUCCESS)
						results.append(result_body);
					else
					    delete_and_exit = true;
					break;
				case SPHERE_SURFACE_TYPE:
					if(gme->get_spheric_mid_surface(surf_1,surf_2,body_sm,result_body) == CUBIT_SUCCESS)
						results.append(result_body);
					else
					    delete_and_exit = true;
					break;
				case TORUS_SURFACE_TYPE:
					if(gme->get_toric_mid_surface(surf_1,surf_2,body_sm,result_body) == CUBIT_SUCCESS)
						results.append(result_body);
					else
					    delete_and_exit = true;
					break;
				case CYLINDER_SURFACE_TYPE:
					if(gme->get_conic_mid_surface(surf_1,surf_2,body_sm,result_body) == CUBIT_SUCCESS)
						results.append(result_body);
					else
					    delete_and_exit = true;
					break;
				default:
					delete_and_exit = true;
					break;
				}

				if(delete_and_exit)
				{
					PRINT_WARNING("Failed to pair surface %d with surface %d\n",face_1->id(),face_2->id());
					break;
				}
			}

			if(delete_and_exit)
			{
				failing_bodies.append(cur_body);
    			gqe->delete_solid_model_entities(results);
				continue;
			}

			DLIList<BodySM*> unite_results;
			if(results.size()>1)
			{
				bool reg_result = GeometryModifyTool::instance()->boolean_regularize();
				GeometryModifyTool::instance()->boolean_regularize(true);
				if(gme->unite(results,unite_results)== CUBIT_SUCCESS)
				{
					// if the unite works just add them to the result list
					results = unite_results;
				}
				else
				{
					// clean up the created surfaces and move on to the next
					// body
					failing_bodies.append(cur_body);
					gqe->delete_solid_model_entities(results);
					GeometryModifyTool::instance()->boolean_regularize(reg_result);
					continue;
				}

				GeometryModifyTool::instance()->boolean_regularize(reg_result);
			}

			// trim the hanging surfaces 
			DLIList<Surface*> paired_surfs;
			paired_surfs += surf_list1;
			paired_surfs += surf_list2;

			DLIList<Curve*> all_curves;

			int k = 0;
			for(k = 0;k<results.size();k++)
				results[k]->curves(all_curves);

			all_curves.uniquify_unordered();

			DLIList<Surface*> remove_surfs;
			for(k = 0;k<all_curves.size();k++)
				for(int m = 0;m<paired_surfs.size();m++)
					if(curve_in_surface(all_curves[k],paired_surfs[m]))
						all_curves[k]->surfaces(remove_surfs);

			remove_surfs.uniquify_unordered();

			body_list_out += results;
			DLIList<BodySM*> tweak_results;
			if(gme->tweak_remove(remove_surfs,tweak_results,CUBIT_FALSE))
			{
				results = tweak_results;
			}
			else
			{
				// clean up the created surfaces and move on to the next
				// body
				failing_bodies.append(cur_body);
				gqe->delete_solid_model_entities(results);
				continue;
			}

			DLIList<BodySM*> regularize_results;
			// regularize the results
			for(k = 0;k < results.size();k++)
			{
				BodySM* new_body = 0;
				if(gme->regularize_body(results[k],new_body))
					regularize_results.append(new_body);
				else if(DEBUG_FLAG(198))
					PRINT_INFO("Regularize failure\n");
			}
            results = regularize_results;
        }*/

        if(!midsurface_done)
        {
           failing_bodies.append(cur_body);
           continue;
        }

        old_bodies_midsurfaced.append(cur_body);

        if(delete_midsurfaced && !preview)
            GeometryQueryTool::instance()->delete_Body(cur_body);

        return_status = CUBIT_SUCCESS;
        body_list_out += results;
    }

    if(prog_tool)
        prog_tool->end();

    PRINT_INFO("Successfully midsurface %d of %d bodies\n",body_list_out.size(),body_list_in.size());
    if(preview)
    {
        for(int k = 0;k<body_list_out.size();k++)
        {
            DLIList<Surface*> preview_surfaces;
            body_list_out[k]->surfaces(preview_surfaces);
            for(int p = 0;p<preview_surfaces.size();p++)
                GfxPreview::draw_surface_facets_shaded(preview_surfaces[p],CUBIT_BLUE);
        }
        GfxPreview::flush();
        if(gqe)
            gqe->delete_solid_model_entities(body_list_out);
        body_list_out.clean_out();
    }

	if(failing_bodies.size() > 0)
	{
        PRINT_INFO("\n");
		PRINT_INFO("Failed to midsurface Body ");
		for(i = 0;i<failing_bodies.size();i++)
			PRINT_INFO("%d ",failing_bodies[i]->id());
		PRINT_INFO("\n");
	}

	if(DEBUG_FLAG(198))
		GfxDebug::flush();

	SurfaceOverlapTool::instance()->set_check_within_bodies(cubit_bool_save);
	SurfaceOverlapTool::instance()->set_gap_max(max_gap_save);
	SurfaceOverlapTool::instance()->set_normal_type(normal_type);
	SurfaceOverlapTool::instance()->set_gap_min(min_gap_save);
    SurfaceOverlapTool::instance()->set_skip_facing_surfaces(skip_facing_surfaces);

	return return_status;
}