/*****************************************************************/
/**                                                             **/
/**             (C) Copyright 1992 the Regents of the           **/
/**        University of California.  All Rights Reserved.      **/
/**                                                             **/
/**        This work was produced under the sponsorship of      **/
/**         the U.S. Department of Energy.  The Government      **/
/**                retains certain rights therein.              **/
/**                                                             **/
/**                         Written by                          **/
/**         Distributed Programming Environments Project        **/
/**           Computer Software and Networking Division,        **/
/**                   Livermore Computer Center,                **/
/**            Lawrence Livermore National Laboratory           **/
/**                                                             **/
/*****************************************************************/

#include "abs.h"
#include "symtab.h"
#include "argument.h"
#include "gen_code.h"
#include <elros/typetags.h>
#include "c_varieties.h"

#define NAMEBUFSIZE 500
#define BITS2BYTES(X) ((X)/8+((X)%8>0))
int namebufndx;
char *namebufptr;
extern interface_element *ieptr;
extern char *input_file;
extern int yylineno;

/* Counters used for identifying ops, consts, and types */
static int global_op_count = 0;
static int gen_const_number = 0;
static int gen_type_number = 0;

/* symbol_element definitions */

symbol_element::symbol_element()
{
	 set_name("");
	 kind = SYM_UNKNOWN;
	 interf = NULL;
}

void symbol_element::set_name(char* nn)
{
	 if (namebufndx) {
	    if ((namebufndx+strlen(nn)+1) > NAMEBUFSIZE) {
	       namebufptr = (char*) calloc(NAMEBUFSIZE,sizeof(char));
               if (!namebufptr) nomem();
	       namebufndx = 0;
            }
	 }
	 else {
	       namebufptr = (char*) malloc(NAMEBUFSIZE*sizeof(char));
               if (!namebufptr) nomem();
	       namebufndx = 0;
	 }
	 strcpy(namebufptr+namebufndx,nn);
	 name =	namebufptr+namebufndx;
	 namebufndx += (strlen(nn)+1);
}

/* symbol_list definitions */

int symbol_list::search(char* n,link *&tmplinkptr)
{
	 symbol_element *septr;
	 reset();
	 while(next(tmplinkptr)) {
	    septr = (symbol_element*)tmplinkptr;
	    if (strcmp(n,septr->get_name()) == 0)
	       return (1); 
	 }
	 return(0);
}


/* type_element_list definitions */

void type_element_list::update_incomplete_types(type_element *teptr)
{
   link *tmplinkptr;
   type_element *tmpteptr;
   boolean found = FALSE;
   int n = strlen(teptr->get_name());

   reset();
   while(next(tmplinkptr)) {
     tmpteptr = ((type_element_ptr *)tmplinkptr)->ptr;
     /* Need to see if forward referenced name is what is being defined
        by teptr.  The forward refefenced name is the last n characters 
        of tmpteptr's type_name, where n is the number of characters of
        teptr's name. */
     if (!strncmp(tmpteptr->type_name+strlen(tmpteptr->type_name)-n,
                  teptr->get_name(),
                  n)){
       link *l;

       found = TRUE;

       /* Complete type_element, share abstr_type_element */
       tmpteptr->abstr_type_ptr = teptr->abstr_type_ptr;
       if (tmpteptr->freeable == -1) /* Undefined */
         tmpteptr->freeable = teptr->freeable;

       /* Update rules for incomplete type element */
       teptr->get_rules_ptr()->reset();
       while(teptr->get_rules_ptr()->next(l))
         tmpteptr->get_rules_ptr()->append(new rules_element((rules_element*)l));
       ieptr->constant_gen->add_encoding(tmpteptr);

       /* delete the entry from the list, now complete */
       prev(tmplinkptr); 
       getnext(tmplinkptr);
     }
   }

   if (found) {
     if (teptr->abstr_type_ptr->kind != AKIND_RECORD &&
         teptr->abstr_type_ptr->kind != AKIND_UNION)
       report_error("error ?",
                    "Forward referenced type is not a Record or Union: \"%s\".",
                    teptr->get_name());
     forward_types_ptr->append(new type_element_ptr(teptr));
   }

}

void type_element_list::gen_encode_decode_routines(FILE* out)
{
   link *tmplinkptr;
   type_element *teptr;

   reset();
   while(next(tmplinkptr)) {
      teptr = ((type_element_ptr *)tmplinkptr)->ptr;
      if (teptr->abstr_type_ptr != NULL) {
	 teptr->gen_encode_decode(out,0);
	 teptr->gen_encode_decode(out,1);
      }
      else
	 BUG_CHECK("type_element has NULL abstr_type_ptr field");
   }

}

void type_element_list::gen_free_routines(FILE* out)
{
   link *tmplinkptr;
   type_element *teptr;

   reset();
   while(next(tmplinkptr)) {
      teptr = ((type_element_ptr *)tmplinkptr)->ptr;
      if (teptr->freeable) 
        teptr->gen_free_routine(out);
   }
}

/* printer_list definitions */

void printer_list::append_printer_element(printer_element* peptr)
{
   append(peptr);
}

void printer_list::gen_print_routines(FILE* out)
{
   link *tmplinkptr;
   abstr_type_element *ateptr;
   printer_element *peptr;

   reset();
   while(next(tmplinkptr)) {
      peptr = (printer_element*)tmplinkptr;
      ateptr = peptr->get_abstr_type_element_ptr();
      ateptr->gen_print_decl(out);
   }
   fprintf(out,"\n");
   reset();
   while(next(tmplinkptr)) {
      peptr = (printer_element*)tmplinkptr;
      ateptr = peptr->get_abstr_type_element_ptr();
      ateptr->gen_print(out);
   }

}

printer_element::printer_element(abstr_type_element *ateptr)
{
   abstr_type_element_ptr = ateptr;
}

/* interface_list definitions */

int interface_list::srch_dcls(char* n,link *&tmplinkptr)
{
	 link *tl;
	 symbol_list* tptr;
	 reset();
	 while(next(tl)) {
	    if (tptr = ((interface_element*)tl)->types_ptr)
	       if (tptr->search(n,tmplinkptr))
		  return 1;
	 }
	 return 0;
}

int interface_list::srch_ops(char* n,link *&tmplinkptr)
{
	 link *tl;
	 symbol_list* optr;
	 reset();
	 while(next(tl)) {
	    if (optr = ((interface_element*)tl)->operations_ptr)
	       if (optr->search(n,tmplinkptr))
		  return 1;
	 }
	 return 0;
}

/* primitive_list definitions */

abstr_type_element* primitive_list::append_primitive(abstr_type_element* ateptr)
      {
	 link *tmplinkptr;
	 abstr_type_element *tmpateptr;

	 reset();
	 while(next(tmplinkptr)) {
	    tmpateptr = (abstr_type_element*)tmplinkptr;
	    if (tmpateptr->get_kind() == ateptr->get_kind() &&
		tmpateptr->get_length() == ateptr->get_length() &&
		tmpateptr->get_length2() == ateptr->get_length2() )

	        return tmpateptr; /* this primitive is already on the list */
	    
	 }
	 append(ateptr);
	 return ateptr;
}

/* interface_element definitions */

interface_element::interface_element()
{
	 operations_ptr = NULL;
	 types_ptr = NULL;
	 names_ptr = NULL;
	 variables_ptr = NULL;
	 constant_table_name = NULL;
	 information_name = NULL;
	 optable_gen = NULL;
	 constant_gen = NULL;
}

interface_element::interface_element(char *name)
{
	 set_name(name);
	 operations_ptr = NULL;
	 types_ptr = NULL;
	 names_ptr = NULL;
	 variables_ptr = NULL;

	 constant_table_name = (char*)malloc(15+strlen(name)+1);
         if (!constant_table_name) nomem();
	 sprintf(constant_table_name,"__ROe_%s_constant",name);

	 information_name = (char*)malloc(18+strlen(name)+1);
         if (!information_name) nomem();
	 sprintf(information_name,"__ROc_%s_information",name);

	 optable_gen = new optable_generator;
	 constant_gen = new constant_generator;

	 global.interface_name = name;
	 global.constant_table_name = constant_table_name;
	 global.information_name = information_name;
}

void interface_element::dump_ops(int indent)
{
	link *tmplinkptr;

	if (operations_ptr == NULL) {
	   INDENTX3(indent);fprintf(yyout,"there are no operations\n");
	}
	else {
	   operations_ptr->reset();
	   while (operations_ptr->next(tmplinkptr)) {
	      ((operation_element *) tmplinkptr)->p_operation(indent); 
	   }
        }
}

void interface_element::append_op(operation_element* oe)
{
	 if (operations_ptr == NULL)
	    operations_ptr = new symbol_list;
         operations_ptr->append((link*)oe);
}

void interface_element::dump_types(int indent)
{
	link *tmplinkptr;

	if (types_ptr == NULL) {
	   INDENTX3(indent);fprintf(yyout,"there are no types\n");
	}
	else {
	   types_ptr->reset();
	   while (types_ptr->next(tmplinkptr)) {
	      ((type_element *) tmplinkptr)->p_type_element(indent);
	   }
        }
}

void interface_element::append_type(type_element* te)
      {
	 if (types_ptr == NULL)
	    types_ptr = new symbol_list;
         types_ptr->append((link*)te);
}

void interface_element::append_name(name_element* ne)
{
	 if (names_ptr == NULL)
	    names_ptr = new symbol_list;
         names_ptr->append((link*)ne);
}

void interface_element::dump_names()
{
	link *tmplinkptr;

	if (names_ptr == NULL)
	   fprintf(yyout,"|  there are no names\n");
	else {
	   names_ptr->reset();
	   while (names_ptr->next(tmplinkptr)) 
	      ((name_element *) tmplinkptr)->p_name_element(1); 
        }
}

void interface_element::dump_variables()
{
	link *tmplinkptr;

	if (variables_ptr == NULL)
	   fprintf(yyout,"|  there are no variables\n");
	else {
	   fprintf(yyout,"|  variables:");
	   variables_ptr->reset();
	   while (variables_ptr->next(tmplinkptr)) {
	      INDENTX3(6);
	      fprintf(yyout,"%s\n",((symbol_element *) tmplinkptr)->get_name());
	   }
        }
}

symbol_element*  interface_element::lookup_op(char* name)
{
	link *tmplinkptr;
	symbol_element *septr;
        if (operations_ptr) {
	  operations_ptr->reset();
	  while (operations_ptr->next(tmplinkptr)) {
	    septr = (symbol_element*)tmplinkptr;
	    if (strcmp(name,septr->get_name()) == 0)
	      return septr;
	  }
        }
	return NULL;
}

symbol_element*  interface_element::lookup_type(char* name)
{
	link *tmplinkptr;
	symbol_element *septr;
        if (types_ptr) {
	  types_ptr->reset();
	  while (types_ptr->next(tmplinkptr)) {
	    septr = (symbol_element*)tmplinkptr;
	    if (strcmp(name,septr->get_name()) == 0)
	      return septr;
	  }
        }
	return NULL;
}

symbol_element*  interface_element::lookup_name(char* name)
{
	link *tmplinkptr;
	symbol_element *septr;
        if (names_ptr) {
	  names_ptr->reset();
	  while (names_ptr->next(tmplinkptr)) {
	    septr = (symbol_element*)tmplinkptr;
	    if (strcmp(name,septr->get_name()) == 0)
	      return septr;
	  }
        }
	return NULL;
}

symbol_element*  interface_element::lookup_var(char* name)
{
	link *tmplinkptr;
	symbol_element *septr;
        if (variables_ptr) {
	  variables_ptr->reset();
	  while (variables_ptr->next(tmplinkptr)) {
	    septr = (symbol_element*)tmplinkptr;
	    if (strcmp(name,septr->get_name()) == 0)
	      return septr;
	  }
        }
	return NULL;
}

/* operation_element definitions */

operation_element::operation_element()
{
   kind_op = KIND_UNKNOWN;
   params_ptr = NULL;
   internal_number = global_op_count++;
   op_num = NULL;
   inv_part = NULL;
   res_part = NULL;
   modal_list_ptr = NULL;
}

operation_element::operation_element(op_kind k,
			             char* nam,
			             char* num,
			             parameter_list* pl)
{
    name = nam;
    kind_op = k;
    params_ptr = pl;
    internal_number = global_op_count++;
    op_num = num;
    inv_part = NULL;
    res_part = NULL;
    modal_list_ptr = NULL;
}

/* for CALLs */
operation_element::operation_element (op_kind k,
				      char* nam,
				      char* num,
				      modal_list* mlptr,
				      operation_element* oe_i,
				      operation_element* oe_r)
{
   name = nam;
   kind_op = k;
   params_ptr = NULL;
   internal_number = -1; /* the inv_part and res_part get 
			    internal numbers instead */
   op_num = num;
   inv_part = oe_i;
   res_part = oe_r;
   modal_list_ptr = mlptr;
}

/* for INVOKES,RESULTS, and REJECTS */
operation_element::operation_element(op_kind k, 
				     char* nam, 
				     char* num)
{
   name = nam;
   kind_op = k;
   params_ptr = NULL;
   internal_number = global_op_count++;
   op_num = num;
   inv_part = NULL;
   res_part = NULL;
   modal_list_ptr = NULL;
}

void operation_element::set_op_num(char*nn)
{
   if (nn) {
      if (namebufndx) {
	 if ((namebufndx+strlen(nn)+1) > NAMEBUFSIZE) {
	    namebufptr = (char*) calloc(NAMEBUFSIZE,sizeof(char));
            if (!namebufptr) nomem();
	    namebufndx = 0;
	 }
      }
      else {
	    namebufptr = (char*) malloc(NAMEBUFSIZE*sizeof(char));
            if (!namebufptr) nomem();
	    namebufndx = 0;
      }
      strcpy(namebufptr+namebufndx,nn);
      op_num = namebufptr+namebufndx;
      namebufndx += (strlen(nn)+1);
   }
   else
      op_num = NULL;
}

void operation_element::process_arguments(argument_list *arglist)
{
   if (kind_op == KIND_CALL)
      BUG_CHECK("operation_element::process_arguments called improperly");

   if (params_ptr == NULL || 
			 (params_ptr->length() == 0))
   {
      if (arglist->length() > 0)
	 report_error("error 5",
		      "Argument(s) encountered where none expected.",
		      NULL);
      return;
   }

   if (arglist->length() > 0 && params_ptr->length() > 0 &&
       arglist->get_pos_or_named() != params_ptr->get_pos_or_named())
      if (params_ptr->get_pos_or_named() == 
				     TYPE_PARAM_LIST) {
	 report_error("error 18",
		      "Argument(s) in Interface specification are positional.",
		      NULL);
	 return;
      }
      else { 
	 report_error("error 25",
		      "Argument(s) in Interface specification are named.",
		      NULL);
	 return;
      }
   params_ptr->resolve(arglist);
}

void operation_element::process_call_arguments(argument_list *callarglist,
					       argument_list *&inarglist,
					       argument_list *&outarglist)
{
   inarglist = new argument_list(callarglist->get_pos_or_named());
   outarglist = new argument_list(callarglist->get_pos_or_named());

   if (kind_op != KIND_CALL)
      BUG_CHECK("operation_element::process_call_arguments was called with the wrong kind of operation");
   if (modal_list_ptr == NULL)
   {
      if (callarglist->length() > 0)
         report_error("error 19",
		      "Arguments encountered where none expected.",
		      NULL);
      return;
   }

   if (callarglist->length() > 0) { 
       
      if (modal_list_ptr->length() == 0) {
	 report_error("error 6",
		      "Argument(s) encountered where none expected.",
		      NULL);
	 return;
      }
      else {
	 if (callarglist->get_pos_or_named() != 
		        modal_list_ptr->get_pos_or_named()) {
	    if (modal_list_ptr->get_pos_or_named() == 
					   TYPE_PARAM_LIST) {
	       report_error("error 13",
			    "Call arguments in Interface specification are positional.",
			    NULL);
	       return;
	    }
	    else { 
	       report_error("error 12",
			    "Call arguments in Interface specification are named.",
			    NULL);
	       return;
	    }
	 }
      }
   }

   modal_list_ptr->resolve(callarglist,inarglist,outarglist);
}

void operation_element::gen_give(FILE *out,
				 char *op_id_var,
				 char *link_id_var,
				 argument_list *arglist,
				 char *e_label,
				 boolean dont_V_semaphore)
{
   if (kind_op == KIND_CALL)
      BUG_CHECK("operation_element::gen_give was called on a KIND_CALL");

   fprintf(out,"\n{ /* %s */\n",name);
   INDENT(out,1);
   fprintf(out,"int __RO_operation = %d;\n",internal_number);
   if (op_id_var) {
      INDENT(out,1);
      fprintf(out,"long __RO_id = (%s);\n",op_id_var);
   }
   if (link_id_var) {
      INDENT(out,1);
      fprintf(out,"long __RO_lid = (%s);\n",link_id_var);
   }
   if (global.gen_log)
      if (kind_op == KIND_INVOKE)
      {
         INDENT(out,1);
	 if (op_id_var)
	    fprintf(out,
		    "long __RO_INVOKEid_value = %s;\n",op_id_var);
	 else
	    fprintf(out,
		    "long __RO_INVOKEid_value = (%s)->sending_invokeID;\n",
		    GETINSTNAME);
         INDENT(out,1);
	 fprintf(out,"long *__RO_invokeID = &__RO_INVOKEid_value;\n");
         INDENT(out,1);
	 fprintf(out,"long *__RO_linkedID = %s;\n",link_id_var ? "&__RO_lid" : "NULL");
      }
      else
      {
         INDENT(out,1);
	 fprintf(out,"long *__RO_invokeID = %s;\n",op_id_var ? "&__RO_id" : "NULL");
         INDENT(out,1);
	 fprintf(out,"long *__RO_linkedID = %s;\n",link_id_var ? "&__RO_lid" : "NULL");
      }
   INDENT(out,1);
   fprintf(out,"unsigned long __RO_l, __RO_l2, __RO_size;\n\n");
   INDENT(out,1);
   if (dont_V_semaphore) {
      fprintf(out,"/* Don't P(%s->exclusion); */\n",GETINSTNAME);
      if (global.gen_log)
	 gen_log_operation(out,1,"CALLING",GETINSTNAME,"__RO_invokeID","__RO_linkedID",e_label);
   }
   else {
      fprintf(out,"P(%s->exclusion);\n",GETINSTNAME);
      if (global.gen_log)
	 gen_log_operation(out,1,"GIVING",GETINSTNAME,"__RO_invokeID","__RO_linkedID",e_label);
   }

   INDENT(out,1);
   if (op_id_var)
      if (link_id_var)
	 fprintf(out,"if ((%s->sendRO_start)(%s,&__RO_id,&__RO_lid,&__RO_operation))\n",
	     GETINSTNAME,GETINSTNAME);
      else
	 fprintf(out,"if ((%s->sendRO_start)(%s,&__RO_id,NULL,&__RO_operation))\n",
	     GETINSTNAME,GETINSTNAME);
   else
      if (link_id_var)
	 fprintf(out,"if ((%s->sendRO_start)(%s,NULL,&__RO_lid,&__RO_operation))\n",
	     GETINSTNAME,GETINSTNAME);
      else
	 fprintf(out,"if ((%s->sendRO_start)(%s,NULL,NULL,&__RO_operation))\n",
	     GETINSTNAME,GETINSTNAME);
   gen_exception_goto(out,2,GETINSTNAME,e_label);

   if (params_ptr && (params_ptr->length() == 0) && 
				  (kind_op == KIND_RESULT)) {
      /* non-default result with 0 args */
      INDENT(out,1);
      fprintf(out,"__ROr_SENDP_2element(%s,__ROe_Null,%s);\n",GETINSTNAME,e_label);
   }
   link *l;
   for (arglist->reset(); arglist->next(l); )
   {
      argument *a = (argument *)l;

      a->gen_sendP(out,e_label);
   }

   INDENT(out,1);
   if (params_ptr && params_ptr->get_wrapping())
      fprintf(out,"__ROr_SENDP_2element(%s,__ROe_EOC,%s);\n",GETINSTNAME,e_label);

   fprintf(out,"\n");
   INDENT(out,1);
   fprintf(out,"if ((%s->sendRO_end)(%s,&__RO_operation))\n",GETINSTNAME,GETINSTNAME);
   gen_exception_goto(out,2,GETINSTNAME,e_label);

   fprintf(out,"\n");
   INDENT(out,1);
   if (dont_V_semaphore) {
      fprintf(out,"/* Don't V(%s->exclusion); */\n",GETINSTNAME);
      fprintf(out,"} /* End %s */\n\n",name);
      INDENT(out,1);
      FPRINTF(out,"if (%s->sendPPDU_end(%s))\n",
				 GETINSTNAME,GETINSTNAME);
      gen_exception_goto(out,2,GETINSTNAME,GETEXCEPTIONLAB);
   }
   else {
      fprintf(out,"V(%s->exclusion);\n",GETINSTNAME);
      fprintf(out,"} /* End %s */\n\n",name);
   }
}

void operation_element::gen_accept_on(FILE *out,
				      argument_list *arglist,
				      boolean ellipses_present,
				      char *e_label,
				      boolean on_callop)
{
   fprintf(out,"\n");
   INDENT(out,1);
   fprintf(out,"case %d: /* ON %s */\n",internal_number,name);
   if (on_callop) {
      if (global.gen_log)
	 gen_log_operation(out,2,"RETURNING",GETINSTNAME,"__RO_invokeID","__RO_linkedID",e_label);
   }
   else {
      if (global.gen_log) 
	 gen_log_operation(out,2,"ACCEPTING",GETINSTNAME,"__RO_invokeID","__RO_linkedID",e_label);
   }

   INDENT(out,2);
   fprintf(out,"{\n");
   INDENT(out,3);
   fprintf(out,"/* ON clause */\n");
   if ((kind_op == KIND_REJECT) || 
		   ((kind_op == KIND_RESULT) && !params_ptr))
      ;   /* don't emit code */
   else {
      INDENT(out,3);
      fprintf(out,"int __RO_EOC = 0;\n");
      INDENT(out,3);
      if (params_ptr && params_ptr->length()) {
	 fprintf(out,"unsigned char __RO_bits[%d];\n",BYTE_CEILING(params_ptr->length()));
	 for (int i=0; i<BYTE_CEILING(params_ptr->length()); i++)
	 {
	    INDENT(out,3);
	    fprintf(out,"__RO_bits[%d] = 0;\n",i);
	 }
      }
      if (params_ptr && params_ptr->get_wrapping())
	 get_set_and_eoc(arglist, ellipses_present, e_label);
      else {
	 if (params_ptr && (params_ptr->length() == 0)) {
	    if (kind_op == KIND_RESULT) 
	       get_NULL_arg(e_label);
	    /* need new message like 
	    __ROx_ASN_EXPECTENEOCFORRESULTW/NOARGS */
	    gen_getheader(out,3,e_label,GETINSTNAME,TAG_EOC,"__ROx_MAGIC");
	 }
	 else /* length == 1 */
	    get_args_and_eoc(arglist,ellipses_present,e_label);
      }
   }
   /* Generate the code to set any unreceived 
      array variable length specifiers to 0 */
   {

      link *l;
      for (arglist->reset(); arglist->next(l); )
      {
	 argument *a = (argument *)l;
	 if ((a->mode == MODE_INOUT)||(a->mode == MODE_OUT)){
	    if (a->length_expression2) {
	       INDENT(out,3);
	       fprintf(out,
		       "if (!(__RO_bits[%d] & %d))\n", 
		       a->list_position/8,
		       1<<a->list_position%8);
	       INDENT(out,4);
	       fprintf(out,
			"(%s) = 0;\n",
			a->length_expression2);
	    }
	    else if (a->length_expression1) {
	       INDENT(out,3);
	       fprintf(out,
			"if (!(__RO_bits[%d] & %d))\n", 
			a->list_position/8,
			1<<a->list_position%8);
	       INDENT(out,4);
	       fprintf(out,
			"(%s) = 0;\n",
			a->length_expression1);
	    }
	 }
      }
   }
   INDENT(out,3);
   fprintf(out,
	   "if ((%s->getRO_end)(%s,&__RO_operation))\n",
	   GETINSTNAME,
	   GETINSTNAME);
   gen_exception_goto(out,4,GETINSTNAME,e_label);

   if (global.gen_log)
      gen_log_operation(out,
                        3,
			"END accepting",
			GETINSTNAME,
			"__RO_invokeID",
			"__RO_linkedID",
			e_label);

   fprintf(out,"\n");
   INDENT(out,3);
   fprintf(out,"V(%s->exclusion);\n",GETINSTNAME);
   INDENT(out,3);
   fprintf(out,"/* End ON clause */\n");
   /* Closing brace for ON clause is in onop_stmt code */
}

void operation_element::get_args_and_eoc( argument_list *arglist,
					  boolean ellipses_present,
					  char *e_label)
{
   link *l;
   int arglist_length;

   gen_getheader(out,3,e_label,GETINSTNAME);
   INDENT(out,3);
   fprintf(out,"while (!__RO_EOC)\n");
   INDENT(out,3);
   fprintf(out,"{\n");
   INDENT(out,4);
   fprintf(out,"switch(__RO_type)\n");
   INDENT(out,4);
   fprintf(out,"{\n");

   arglist_length = arglist->length();
   if (arglist_length)
      for (arglist->reset(); arglist->next(l); )
      {
	 argument *a = (argument *)l;
	 a->gen_getP(
	    out,
	    ellipses_present,
	    e_label);
      }
   else {
      INDENT(out,4);
      fprintf(out,"case 0x%8.8x:\n",TAG_Null);
      INDENT(out,5);
      fprintf(out,"break;\n");
   }

   INDENT(out,4);
   fprintf(out,"case 0x%8.8x:\n",TAG_EOC);
   INDENT(out,5);
   fprintf(out,"__RO_EOC = 1;\n");
   INDENT(out,5);
   fprintf(out,"continue;\n");

   /* Deal with the bad argument tag case */

   if (!arglist->get_unwrapped_Any_present()) {
      INDENT(out,4);
      fprintf(out,"default:\n");
      if (!ellipses_present) {
	 INDENT(out,5);
	 fprintf(out,"{__RO_RAISE_MISSING_ARG(%s,__RO_operation,__RO_type,%s);}\n",
		   GETINSTNAME,e_label);
      }
      INDENT(out,5);
      fprintf(out,"break;\n");
   }

   INDENT(out,4);
   fprintf(out,"} /* End of SWITCH (__RO_type) for arguments */\n");
   gen_getheader(out,4,e_label,GETINSTNAME);
   INDENT(out,3);
   fprintf(out,"} /* End of WHILE (!__RO_EOC) for arguments */\n");
}

void operation_element::get_set_and_eoc( argument_list *arglist,
					 boolean ellipses_present,
					 char *e_label)
{
   gen_getheader(out,3,e_label,GETINSTNAME,TAG_SET,"__ROx_EL_EXPECTARGSET");
   if (arglist)
      get_args_and_eoc(arglist,ellipses_present,e_label);
   else
      gen_getheader(out,3,e_label,GETINSTNAME,TAG_EOC,"__ROx_MAGIC");/* need new message like __ROx_ASN_EXPECTENDOFSETWITHNOARGS */
   gen_getheader(out,3,e_label,GETINSTNAME,TAG_EOC,"__ROx_MAGIC");/* need new message like __ROx_ASN_EXPECTENDOFOP */
}

void operation_element::get_NULL_arg(char *e_label)
{
   gen_getheader(out,2,e_label,GETINSTNAME,TAG_Null,"__ROx_MAGIC");/* need new message like ___ROx_EL_EXPECTTAGNULL*/
   INDENT(out,2);
   fprintf(out,"if (__RO_length != 0)\n");
   gen_exception(out,
		 3,
		 "__ROx_MAGIC",/* need new message like 
				___ROx_EL_EXPECTZEROLENGTH */
		 e_label,
		 GETINSTNAME);
}

void operation_element::p_operation(int indent)
{
	 INDENTX3(indent);fprintf(yyout,"operation:");
	 fprintf(yyout,"%s\n",get_name());
	 switch (kind_op) {
	 case KIND_INVOKE:
	    fprintf(yyout,"|     kind_op:invoke\n");
	    break;
	 case KIND_RESULT:
	    fprintf(yyout,"|     kind_op:result\n");
	    break;
	 case KIND_ERROR:
	    fprintf(yyout,"|     kind_op:error\n");
	    break;
	 case KIND_REJECT:
	    fprintf(yyout,"|     kind_op:reject\n");
	    break;
	 case KIND_CALL:
	    fprintf(yyout,"|     kind_op:call\n");
	    break;
	 case KIND_UNKNOWN:
	 default:  
	    fprintf(yyout,"|     kind_op:<null>\n");
	    BUG_CHECK("Unknown kind of operation");
         }
	 fprintf(yyout,"|     internal number:%d\n",internal_number);
	 fprintf(yyout,"|     op num:%s\n",op_num);
	 dump_params();
}

void operation_element::dump_params()
{

	if (params_ptr == NULL)
	   fprintf(yyout,"|     there is no parameter list\n");
	else 
	   params_ptr->dump_parameter_list();
}

/* parameter_list definitions */

parameter_list::parameter_list()
{
	 pos_or_named = NO_PARAM_LIST;
	 wrapping = FALSE;
	 unwrapped_Any_present = FALSE;
}

parameter_list::parameter_list(int p_or_n)
{
	 pos_or_named = p_or_n;
	 wrapping = FALSE;
	 unwrapped_Any_present = FALSE;
}

void parameter_list::dump_parameter_list()
{
	  link *tmplinkptr;
	  
	   reset();
	   next(tmplinkptr); 
	   if (tmplinkptr)
	      if (pos_or_named == NAMED_PARAM_LIST) {
		 ((param_element *) tmplinkptr)->p_param();
		 while (next(tmplinkptr)) {
		    ((param_element *) tmplinkptr)->p_param();
		 }
	      }
	      else {
		 ((param_element *) tmplinkptr)->p_param();
		 while (next(tmplinkptr)) {
		    ((param_element *) tmplinkptr)->p_param();
		 }
	      }
           else
	      fprintf(yyout,"|     the parameter list is empty\n");
	   while (next(tmplinkptr)) {
	      ((param_element *) tmplinkptr)->p_param();
	   }
}

void parameter_list::auto_tag()
{
	 link *l;
	 int i;

	 if (length() > 1)
	    for (reset(),i=1; next(l); i++)
	    {
	       param_element *pp = (param_element *)l;

	       pp->get_type_element_ptr()->get_rules_ptr()->insert(
		   new rules_element(CLASS_CONTEXT,FORM_CONSTRUCTED,i,NOTHING_SEEN));
	       ieptr->constant_gen->add_encoding(pp->get_type_element_ptr());
	    }
	 else
	 {
	    reset(); next(l);
	    param_element *pp = (param_element *)l;
	    ieptr->constant_gen->add_encoding(pp->get_type_element_ptr());
	 }
}

void parameter_list::resolve(argument_list *arglist)
{
	 link *l,*pl;


	 arglist->set_unwrapped_Any_present(get_unwrapped_Any_present());
	 if (pos_or_named == NAMED_PARAM_LIST) {
	    for (reset(); next(pl); )
	    {
	       argument *a;
	       param_element *p = (param_element *)pl;

	       if (arglist->search_name(p->get_name_ptr()->get_name(),a))
	       {
		  a->set_name(p->get_name_ptr()->get_name());
		  a->set_type(p->get_name_ptr()->get_type_element_ptr());
		  a->set_mode(p->get_mode());
		  a->set_list_position(p->get_list_position());
		  a->set_num_id(p->get_num_id());
	       }
	       else
		  arglist->append(new argument(p));
	    }
	    if (arglist->length() < length())
	       BUG_CHECK("Not enough named arguments were resolved in g/a");
	    if (arglist->length() > length())
	       report_error("error 21",
			    "Too many named arguments for this operation.",
			    NULL);
	 }
	 else {
	    boolean moreargs,moreparms;

	    for (reset(),arglist->reset();
		 moreparms = next(pl),moreargs=arglist->next(l), moreparms&&moreargs;
		 )
	    {
	       argument *a = (argument *)l;
	       param_element *p = (param_element *)pl;

	       a->set_type(p->get_type_element_ptr());
	       a->set_mode(p->get_mode());
	       a->set_list_position(p->get_list_position());
	       a->set_num_id(p->get_num_id());
	    }
	    if (moreargs)
	       report_error("error 20",
			    "Too many arguments for this operation.",
			    NULL);
	    while (moreparms)
	    {
	       arglist->append(new argument((param_element *)pl));
	       moreparms = next(pl);
	    }
	 }
}

/* conc_part_element definitions */

conc_part_element::conc_part_element()
{
   encoded_offset = 0;
   encoded_length = 0;
   optional_flag = 0;
   optional_value = NULL;
   optional_name = NULL;
   default_flag = 0;
   default_value = NULL;
   default_name = NULL;
}

void conc_part_element::encode(bytearray &clist,char *comment)
{
   link *l;
   encoded_offset = clist.offset();
   for (rules_ptr->reset(); rules_ptr->next(l); )
   {
      rules_element *e = (rules_element *)l;

      e->encode(clist);
   }

   encoded_length = clist.offset()-encoded_offset;
   if (encoded_length) {
      clist.reset();
      clist.prev(l);
      ((singlebyte *)l)->set_comment(comment);
   }

}

void conc_part_element::gen_name(char *&default_or_optional_name)
{
	 char buf[64];

	 sprintf(buf,"__ROc_%s_%d",ieptr->get_name(),gen_const_number++);
	 default_or_optional_name = (char*)malloc(strlen(buf)+1);
         if (!default_or_optional_name) nomem();
	 strcpy(default_or_optional_name,buf);
}

/* type_element definitions */

void type_element::p_type_element(int indent)
{
	 INDENTX3(indent);fprintf(yyout,"type:");
	 fprintf(yyout,"%s\n",get_name());
	 indent += 1;
	 INDENTX3(indent);fprintf(yyout,"optional flag:%d\n",optional_flag);
	 INDENTX3(indent);fprintf(yyout,"optional value:%s\n",optional_value);
	 INDENTX3(indent);fprintf(yyout,"default flag:%d\n",default_flag);
	 INDENTX3(indent);fprintf(yyout,"default value:%s\n",default_value);
	 dump_rules(indent);
	 if (abstr_type_ptr == NULL) {
	    INDENTX3(indent);fprintf(yyout,"there are no abstract types\n");
	 }
	 else
	    abstr_type_ptr->p_abstr_type(indent);

}

void type_element::dump_rules(int indent)
{
	link *tmplinkptr;

	if (rules_ptr == NULL) {
	   INDENTX3(indent);fprintf(yyout,"there are no rules\n");
	}
	else {
	   INDENTX3(indent);fprintf(yyout,"rules:\n");
	   rules_ptr->reset();
	   while (rules_ptr->next(tmplinkptr)) {
	      ((rules_element *) tmplinkptr)->p_rule(indent+1); 
	   }
        }
}

void type_element::set_type_name(char *s)
{  int len = strlen(s) + strlen(ieptr->get_name()) + 15;
   type_name = (char *)malloc(len);
   if (!type_name) nomem();
   sprintf(type_name,"struct __ROt_%s_%s",ieptr->get_name(),s);
}

type_element::type_element()
{
	 element_number = 0;
	 abstr_type_ptr = NULL;
         indirect = 0;
         freeable = 0;
         type_name = NULL;
	 leading_tags = NULL;
}

type_element::type_element(char *elem_name, char *forward_type_name)
/* Constructor for a component of a DynamicArray where the component  */
/* type is a forward reference */
{
	 set_name(elem_name);
	 element_number = 0;
	 abstr_type_ptr = NULL;
	 rules_ptr= new list;
         indirect = 0;
         /* Since this is a forward reference, component type will have 
            to be to a Record/Union. We will have to complete the 
            freeability when we see the forward type def. */
         freeable = -1;
         set_type_name(forward_type_name);
	 leading_tags = NULL;
         /* Put this on the freeable_types list, but will only generate
            free routine if still freeable after incomplete_types list is
            updated with type def. */
         freeable_types_ptr->append(new type_element_ptr(this));
}

type_element::type_element(char *elem_name,
 			   char *forward_type_name,
                           list *rules,
                           int free_flag,
                           boolean is_indirect)
/* Constructor for a field of a Record/Union where the field type is a */
/* forward reference */
{
         link *l;

	 set_name(elem_name);
	 element_number = 0;
	 abstr_type_ptr = NULL;
	 rules_ptr= new list;
         if (rules != NULL) {
	   for (rules->reset();rules->next(l);) 
	      rules_ptr->append(new rules_element((rules_element*)l));
         }

         indirect = 1;
         if (!is_indirect)
           report_error("error ?",
                        "Forward reference requires (*) here:  \"%s\".",
                        elem_name);

         if (free_flag == -1)
           freeable = global.freeable;
         else 
           freeable = free_flag;

         set_type_name(forward_type_name);
	 leading_tags = NULL;

         if (freeable)
           freeable_types_ptr->append(new type_element_ptr(this));
}


type_element::type_element(abstr_type_element* ate,
                           list* rules,
                           boolean optional_present,
                           int free_flag)
/* This is the constructor for Records, Unions, and Arrays */
{
	 link *l;
         type_element *teptr;
         abstr_type_element *ateptr;

	 optional_flag = optional_present;
	 abstr_type_ptr = ate;
	 rules_ptr= new list;
	 for (rules->reset();rules->next(l);) 
	    rules_ptr->append(new rules_element((rules_element*)l));
	 element_number = 0;
         indirect = 0;
         type_name = NULL; /* Set after gen_typedef() */
	 leading_tags = NULL;

         switch (ate->get_kind()) {
           case AKIND_ARRAY:
             ate->get_components()->reset();
             ate->get_components()->next(l);
             teptr = (type_element *)l;

	     if (ateptr = teptr->abstr_type_ptr)
	       if (ateptr->kind == AKIND_INTEGER) {
	         ate->set_veckind(INTVEC);
	       }
	       else if (ateptr->kind == AKIND_REAL) {
	         ate->set_veckind(REALVEC);
	       }
             
             if (free_flag == -1) {
               if (ate->dynorstat == ARRAYKIND_DYNAMIC)
                 freeable = global.freeable || teptr->freeable;
               else
                 freeable = teptr->freeable;
             }
             else
               freeable = free_flag;
             break;

           case AKIND_RECORD:
           case AKIND_UNION:
             if (free_flag == -1) {
               freeable = 0;
               for (ate->get_components()->reset();
                    ate->get_components()->next(l); ) {
                 teptr = (type_element *)l;
                 freeable |= teptr->freeable;
               }
             }
             else
               freeable = free_flag;
             break;

           default:
             freeable = 0;
       }
       if (freeable)
          freeable_types_ptr->append(new type_element_ptr(this));
}


type_element::type_element(char* n,
			   abstr_type_element* ate, 
			   list* rules,
			   int off,
			   int leng,
                           boolean is_freeable)
/* Constructor for previously defined types--i.e., TYPEID's */
{
	 set_name(n);
	 abstr_type_ptr = ate;
	 rules_ptr = new list;
	 link *l;
	 for (rules->reset();rules->next(l);) 
	    rules_ptr->append(new rules_element((rules_element*)l));
	 encoded_offset = off;
	 encoded_length = leng;
	 element_number = 0;
         freeable = is_freeable;
         indirect = 0;
	 type_name = ate->typedef_name; /* Already typedef'd */
	 leading_tags = NULL;
}

type_element::type_element(char* n,
			   abstr_type_element* ate,
			   rules_element* rule)
/* Constructor for primitive types */
{
	 set_name(n);
	 abstr_type_ptr = ate;
	 if (ate->kind != AKIND_ANY) {
	    rules_ptr = new list;
	    rules_ptr->append(new rules_element(rule));
	 }
	 element_number = 0;
         indirect = 0;
         if (ate->length == 0 && ate->get_kind() != AKIND_NULL) 
         /* Indefinite length string type */
           freeable = global.freeable;
         else
           freeable = 0;
	 type_name = ate->typedef_name;
	 leading_tags = NULL;
}

type_element::type_element(type_element *teptr,
                           list *rptr,
                           int free_flag,
			   boolean is_indirect)
/* Constructor for component types of Records/Unions/Arrays */
/* where the component type is a primitive or backward reference */
{
         link *l;

	 set_name(teptr->get_name());
	 abstr_type_ptr = teptr->abstr_type_ptr;
	 if (rptr)
	    rules_ptr = rptr;
	 else
	    rules_ptr = new list;
	 if (teptr->rules_ptr) {
	     teptr->rules_ptr->reset();
	     while(teptr->rules_ptr->next(l))
		rules_ptr->append(new rules_element((rules_element*)l));
	 }
	 reconcile();
	 element_number = 0;

         indirect = is_indirect;
         if (indirect) {
            switch (abstr_type_ptr->kind) {
              case AKIND_RECORD:
              case AKIND_UNION:
                break;
              default:
                report_error("error ?",
                             "Indirection (*) allowed only to Record or Union type: \"%s\".",
                             teptr->get_name());
                break;
            }
         }

         type_name = teptr->type_name;
         if (type_name == NULL)
           type_name = teptr->abstr_type_ptr->typedef_name;

         if (free_flag == -1)
           freeable = teptr->freeable;
         else
           freeable = free_flag;

	 leading_tags = NULL;

         if (freeable)
           freeable_types_ptr->append(new type_element_ptr(this));
}

void type_element::gen_copy_default(FILE *out, int z,char *target)
{
   int len1,len2;

   len1 = abstr_type_ptr->get_length();
   len2 = abstr_type_ptr->get_length2();
   INDENT(out,z);
   switch (abstr_type_ptr->get_kind())
   {
      case AKIND_BOOLEAN:
      case AKIND_INTEGER:
      case AKIND_NULL: /* Not really relevant */
      case AKIND_ENUMERATED:
      case AKIND_OBJECTIDENTIFIER:
      case AKIND_REAL:
      case AKIND_BITSTRING:
      case AKIND_OCTETSTRING:
      case AKIND_TELETEXSTRING:
      case AKIND_VIDEOTEXSTRING:
      case AKIND_IA5STRING:
      case AKIND_GENERALSTRING:
         fprintf(out,"__ROr_CPYP_%s(%s,&(%s),%d,%d);\n",
                primitive_name[abstr_type_ptr->get_kind()],
                default_name,
                target,
		len1,
		len2);
         break;
      case AKIND_NUMERICSTRING:
      case AKIND_PRINTABLESTRING:
      case AKIND_GRAPHICSTRING:
      case AKIND_VISIBLESTRING:
         fprintf(out,"__ROr_CPYP_%s(%s,%s,%d,%d);\n",
                primitive_name[abstr_type_ptr->get_kind()],
                default_name,
                target,
		len1,
		len2);
         break;

   }
}

list *type_element::get_leading_tags()
{
/* Revised 8/14/92 to "save" the generated tags.  (ls) */

  if (!leading_tags) {
    list *other;
    link *l;

    leading_tags = new list;

    if (abstr_type_ptr->get_kind() == AKIND_UNION && !(rules_ptr->length())) {

/* There is a hazard for recursive types here--you can loop recursively
   forever if recursive unions, trying to find leading tags.  A solution
   to this is not immediately apparent... */

      for (abstr_type_ptr->get_components()->reset();
	   abstr_type_ptr->get_components()->next(l);) {
	 other = ((type_element *)l)->get_leading_tags();
         if (other) {
	   for (other->reset(); other->next(l);)
	     leading_tags->append(new tag_element(((tag_element *)l)->get_tag_bytes()));
         }
      }
    }
    else
    {
      if (rules_ptr->length()) {
	 rules_ptr->reset();
	 rules_ptr->next(l);
	 leading_tags->append(new tag_element(((rules_element *)l)->class_and_value()));
      }
    }
  }

  return(leading_tags);
}

void type_element::gen_leadingTAG_cases(FILE *out, int indent)
{
   list *taglist;
   link *l;

   taglist = get_leading_tags();
   if (taglist->length() == 0) {
      INDENT(out,indent);
      fprintf(out,"default:\n");
   }
   else {
      for (taglist->reset(); taglist->next(l); ) {
         tag_element *t = (tag_element *)l;
	 INDENT(out,indent);
	 fprintf(out,"case 0x%8.8x:\n",t->get_tag_bytes());
      }
   }
}

void type_element::gen_leadingTAG_iftest(FILE *out, int indent)
{
   list *taglist;
   link *l;

   INDENT(out,indent);
   if (abstr_type_ptr->get_kind()==AKIND_ANY) {
      fprintf(out,"if(1");
   }
   else {
      fprintf(out,"if(0");
   }
   taglist = get_leading_tags();
   for (taglist->reset(); taglist->next(l); ) {
     tag_element *t = (tag_element *)l;
     fprintf(out,"\n");
     INDENT(out,indent+1);
     fprintf(out,"%s", abstr_type_ptr->get_kind()==AKIND_ANY ? "&&" : "||");
     fprintf(out," __RO_type == 0x%8.8x",t->get_tag_bytes());
   }
   fprintf(out,")\n");
}

void type_element::gen_consts(FILE *out)
{
    unsigned long nelems;
    char *constval;
    char *constvalname;

	 if (optional_flag && optional_value)
	 {
	    gen_name(optional_name);
            constval = gen_val_const(optional_value,&nelems);
            constvalname = 0;
            if (!abstr_type_ptr->length) {
               constvalname = (char *)malloc(strlen(optional_name)+4);
               if (!constvalname) nomem();
               sprintf(constvalname,"%s_val",optional_name);
               dump_val_const(out,constvalname,constval,nelems);
            }
	    fprintf(out,"static ");
	    abstr_type_ptr->gen_type(out,0,optional_name);
	    fprintf(out," = ");
	    dump_value(out,constval,constvalname,nelems);
	    fprintf(out,";\n");
            if (constval != optional_value)
               free(constval);
            if (constvalname != 0)
               free(constvalname);
	 }

	 if (default_flag && default_value)
	 {
	    gen_name(default_name);
            constval = gen_val_const(default_value,&nelems);
            constvalname = 0;
            if (!abstr_type_ptr->length) {
               constvalname = (char *)malloc(strlen(default_name)+4);
               if (!constvalname) nomem();
               sprintf(constvalname,"%s_val",default_name);
               dump_val_const(out,constvalname,constval,nelems);
            }
	    fprintf(out,"static ");
	    abstr_type_ptr->gen_type(out,0,default_name);
	    fprintf(out," = ");
	    dump_value(out,constval,constvalname,nelems);
	    fprintf(out,";\n");
            if (constval != default_value)
               free(constval);
            if (constvalname != 0)
               free(constvalname);
	 }
}

EXTERN_FUNCTION ( 
		  int __ROr_convert_Boolean_const,
		  (void*, unsigned long, unsigned long, unsigned long, char*) 
		)
EXTERN_FUNCTION ( 
		  int __ROr_convert_BitString_const,
		  (void*, unsigned long, unsigned long, unsigned long, char*) 
		)
EXTERN_FUNCTION ( 
		  int __ROr_convert_OctetString_const,
		  (void*, unsigned long, unsigned long, unsigned long, char*) 
		)
EXTERN_FUNCTION ( 
		  int __ROr_convert_Integer_const,

		  (void*, unsigned long, unsigned long,
		   unsigned long, char*,__RO_Type_Info*) 
		)
EXTERN_FUNCTION ( 
		  int __ROr_convert_Real_const,

		  (void*, unsigned long, unsigned long,
		   unsigned long, char*,__RO_Type_Info*) 
		)

char * type_element::gen_val_const(char *string, unsigned long *nelems)
{
	 unsigned long l1,l2;
	 int stlen;
	 int i,commas;
	 unsigned long vl;	/* value length */
	 char *charsptr;

	 /* global_params is a global variable initialized
	    in decls.h and WILL NOT!!! go away when reading 
	    of param.dat file is done */

         extern __RO_Type_Info global_params;

	 l1 = abstr_type_ptr->length;
	 l2 = abstr_type_ptr->length2;
	 switch (abstr_type_ptr->kind) {
	 case AKIND_OBJECTIDENTIFIER:
	    stlen = strlen(string);
	    charsptr = (char*)malloc(stlen+1);
            if (!charsptr) nomem();
	    commas = 0;
	    for(i=0; i<stlen; i++)
	       if (string[i] == '.') {
		  charsptr[i] = ',';
		  commas += 1;
	       }
	       else
		  charsptr[i] = string[i];
	    charsptr[stlen] = '\0';
            *nelems = commas+1;
	    break;
	 case AKIND_BOOLEAN:
	    vl = __RO_BOOLEAN_SIZE(&global_params,l1);
	    charsptr = (char*)malloc((size_t)vl);
            if (!charsptr) nomem();
	    i = __ROr_convert_Boolean_const(charsptr,vl,l1,0,string);
            if (i) report_error("error ?","Bad constant: %s",string);
            *nelems = vl;
	    break;
	 case AKIND_TELETEXSTRING:
	 case AKIND_VIDEOTEXSTRING:
	 case AKIND_IA5STRING:
	 case AKIND_GENERALSTRING:
            /* string is quoted string, don't count quotes in len field */
            *nelems = strlen(string) - 2;
            charsptr = string;
            break;
	 case AKIND_NUMERICSTRING:
	 case AKIND_PRINTABLESTRING:
	 case AKIND_VISIBLESTRING:
	 case AKIND_GRAPHICSTRING:
            *nelems = 0;
            charsptr = string;
	    break;
	 case AKIND_BITSTRING:
	    {
	       __RO_ByteString *stptr;

	       stptr = (__RO_ByteString*)
		            malloc((l1 ? (size_t)BITS2BYTES(l1)
                                       : sizeof(char *))   + 
			           sizeof(unsigned long));
               if (!stptr) nomem();
	       i = __ROr_convert_BitString_const(stptr,
					     BITS2BYTES(l1),
					     l1,
					     l2,
					     string);
               if (i) report_error("error ?","Bad constant: %s",string);
               *nelems = stptr->len;
               charsptr = (char *)stptr;
	    }
	    break;
	 case AKIND_OCTETSTRING:
	    {
	       __RO_ByteString *stptr;

	       stptr = (__RO_ByteString*)
		          malloc((l1 ? (size_t)l1 : sizeof(char *)) + 
			         sizeof(unsigned long)    );
               if (!stptr) nomem();
	       i = __ROr_convert_OctetString_const(stptr,
					     l1,
					     l1,
					     l2,
					     string);
               if (i) report_error("error ?","Bad constant: %s",string);
               *nelems = stptr->len;
               charsptr = (char *)stptr;
	    }
	    break;
	 case AKIND_ENUMERATED:
	 case AKIND_INTEGER:
	    if (__RO_IS_NATIVE_TYPE(&global_params,Integer_lengths,l1,0)) {
               charsptr = string;
               *nelems = 0;
            }
	    else {
	       vl = __RO_INTEGER_SIZE(&global_params,l1);
	       charsptr = (char*)malloc((size_t)vl);
               if (!charsptr) nomem();
	       i = __ROr_convert_Integer_const(charsptr,vl,l1,0,
					       string,&global_params);
               if (i) report_error("error ?","Bad constant: %s",string);
               *nelems = vl;
	    }
	    break;
	 case AKIND_REAL:
	    vl = __RO_REAL_SIZE(&global_params,l1,l2);
	    if (__RO_IS_NATIVE_REAL(&global_params,l1,l2,vl)) {
               charsptr = string;
               *nelems = 0;
            }
	    else {
	       charsptr = (char*)malloc((size_t)vl);
               if (!charsptr) nomem();
	       i = __ROr_convert_Real_const(charsptr,vl,l1,l2,
					    string,&global_params);
               if (i) report_error("error ?","Bad constant: %s",string);
               *nelems = vl;
	    }
	    break;
	 default:
            report_error("error ?","Optional and Default values not allowed for non-primitive types.",NULL);
	 }

         return (charsptr);
      }

void type_element::dump_val_const(FILE* out,
				    char *valname,
				    char *value,
				    unsigned long nelems)
{
   switch (abstr_type_ptr->kind) {
      case AKIND_OBJECTIDENTIFIER:
         fprintf(out,"static unsigned long %s[] = { %s };\n",valname,value);
         break;

      case AKIND_BITSTRING:
         fprintf(out,"static unsigned char %s[] = ",valname);
         if (abstr_type_ptr->length)
            fprintf(out,"{ ");
         dump_list(out,((__RO_ByteString_indef *)value)->val,BITS2BYTES(nelems));
         if (abstr_type_ptr->length)
            fprintf(out," }");
         fprintf(out,";\n");
         break;

      case AKIND_OCTETSTRING:
         fprintf(out,"static unsigned char %s[] = ",valname);
         if (abstr_type_ptr->length)
            fprintf(out,"{ ");
         dump_list(out,((__RO_ByteString_indef *)value)->val,nelems);
         if (abstr_type_ptr->length)
            fprintf(out," }");
         fprintf(out,";\n");
         break;

      case AKIND_NUMERICSTRING:
      case AKIND_PRINTABLESTRING:
      case AKIND_VISIBLESTRING:
      case AKIND_GRAPHICSTRING:
      case AKIND_TELETEXSTRING:
      case AKIND_VIDEOTEXSTRING:
      case AKIND_IA5STRING:
      case AKIND_GENERALSTRING:
         fprintf(out,"static char %s[] = %s;\n",valname,value);
         break;
   }
}

void type_element::dump_value(FILE* out,
			      char *value,
			      char *valname, 
			      unsigned long nelems)
{
   switch (abstr_type_ptr->kind) {
      case AKIND_OBJECTIDENTIFIER:
         fprintf(out,"{ %d, ",nelems);
         if (abstr_type_ptr->length)
            fprintf(out,"{ %s }",value);
         else
            fprintf(out,"%s",valname);
         fprintf(out,"}");
         break;

      case AKIND_BOOLEAN:
         dump_list(out,value,nelems);
         break;

      case AKIND_NUMERICSTRING:
      case AKIND_PRINTABLESTRING:
      case AKIND_VISIBLESTRING:
      case AKIND_GRAPHICSTRING:
         fprintf(out,"%s", (abstr_type_ptr->length) ? value : valname);
         break;

      case AKIND_TELETEXSTRING:
      case AKIND_VIDEOTEXSTRING:
      case AKIND_IA5STRING:
      case AKIND_GENERALSTRING:
         fprintf(out,"{ %d, %s }",nelems,
                                  (abstr_type_ptr->length) ? value : valname);
         break;

      case AKIND_BITSTRING:
         fprintf(out,"{ %d, ",nelems);
         if (abstr_type_ptr->length)
            dump_list(out,((__RO_ByteString *)value)->val,BITS2BYTES(nelems));
         else
            fprintf(out,"%s",valname);
         fprintf(out,"}");
         break;
         
      case AKIND_OCTETSTRING:
         fprintf(out,"{ %d, ",nelems);
         if (abstr_type_ptr->length)
            dump_list(out,((__RO_ByteString *)value)->val,nelems);
         else
            fprintf(out,"%s",valname);
         fprintf(out,"}");
         break;
         
      case AKIND_ENUMERATED:
      case AKIND_INTEGER:
      case AKIND_REAL:
         if (nelems == 0)
            fprintf(out,"%s",value);
         else
            dump_list(out,value,nelems);
         break;

      default:
	 BUG_CHECK("bad KIND value in dump_value");
   }
}

void type_element::dump_list(FILE* out,void *charsptr,unsigned long bytes)
{
      int i;
      fprintf(out,"{");
      for (i=0; i<bytes-1; i++)
	 fprintf(out,"0x%x,",((unsigned char*)charsptr)[i]);
      fprintf(out,"0x%x}",((unsigned char*)charsptr)[i]);
}

void type_element::gen_encode_decode(FILE *out, int n_or_d)
{
   abstr_type_element *ateptr = abstr_type_ptr;
   int indent = 0;
  
   if ( n_or_d ? ateptr->encode_name
               : ateptr->decode_name ) /* Already generated */
     return; 

   if (n_or_d) {
     ateptr->encode_name = (char *)malloc(strlen(ateptr->print_name)+1);
     if (!ateptr->encode_name) nomem();
     strcpy(ateptr->encode_name,ateptr->print_name);
     ateptr->encode_name[4] = 'n';
   }
   else {
     ateptr->decode_name = (char *)malloc(strlen(ateptr->print_name)+1);
     if (!ateptr->decode_name) nomem();
     strcpy(ateptr->decode_name,ateptr->print_name);
     ateptr->decode_name[4] = 'd';
   }
   
   fprintf(out,
	   n_or_d 
	      ? "static int %s(p,inst,e_off,e_len,eocs)\n"
	      : ((ateptr->get_kind() == AKIND_UNION)
	 	  ? "static int %s(p,inst,__RO_type,__RO_length)\n"
		  : "static int %s(p,inst)\n"),
           n_or_d 
              ? ateptr->encode_name
              : ateptr->decode_name);

   fprintf(out,"   %s *p;\n", type_name);
   fprintf(out,"   __RO_Instance_Record_ptr inst;\n");

   if (n_or_d) { /* encode */
     fprintf(out,"   int e_off;\n");
     fprintf(out,"   int e_len;\n");
     fprintf(out,"   int eocs;\n");
   }
   else { /* decode */
     if (abstr_type_ptr->get_kind() == AKIND_UNION) {
       fprintf(out,"   __RO_int32 __RO_type;\n");
       fprintf(out,"   unsigned long __RO_length;\n");
     }
   }

   fprintf(out,"{\n");

   if (n_or_d) { /* encode */
      /* construct the name of the constant table */
      char *const_name = (char*)malloc(strlen(ieptr->get_name())+16);
      if (!const_name) nomem();
      sprintf(const_name, "__ROe_%s_constant",ieptr->get_name());

      gen_sendP(out,
		indent+1,
		"*p",
		NULL,
		"inst",
		const_name,
		"E_LAB",
		TRUE,
		TRUE);
   }
   else { /* decode */
      /* Nested __RO_type, __RO_length */
      if (abstr_type_ptr->get_kind() != AKIND_UNION) {
	 fprintf(out,"   __RO_int32 __RO_type;\n");
	 fprintf(out,"   unsigned long __RO_length;\n\n");
      }
      gen_getP(out, 
	       indent+1, 
	       "*p", 
	       NULL, 
	       "E_LAB", 
	       "inst", 
	       TRUE, 
	       TRUE);
   }
   INDENT(out,indent+1);
   fprintf(out,"return(0);\n");
   INDENT(out,indent+1);
   fprintf(out,"E_LAB: return(1);\n");

   INDENT(out,indent);
   fprintf(out,"}\n\n");
}

void type_element::gen_free_routine(FILE *out)
{
   abstr_type_element *ateptr = abstr_type_ptr;
   link *l;
   type_element *t;
   int i;

/* Note:  because of ordering of entries on freeable_types_ptr list,
   component free routines are usually generated before parents; hence
   the free_name of each component should already be known. However,
   if a type is forward referenced, we have to construct the name of
   the free routine that will be generated later... */

   char *free_name;
   char forward_free_name[64];

   if (ateptr->free_name  /* free routine has already been generated */
       || !freeable)      /* or type itself (parent) is not freeable */
      return;             /* Don't generate again */

   ateptr->free_name = (char*)malloc(strlen(ateptr->print_name)+1);
   if (!ateptr->free_name) nomem();
   strcpy(ateptr->free_name,ateptr->print_name);
   ateptr->free_name[4] = 'f';

   /* generate declarations for forward referenced free routines */
   switch (ateptr->get_kind()) {
   /* only records and unions can forward reference free routines */
   /* dynamic array forward references are special -- no free routine 
      is referenced */
   case AKIND_RECORD:
   case AKIND_UNION:
      for (ateptr->get_components()->reset();
           ateptr->get_components()->next(l);
          )
      {
         t = (type_element *)l;
         if (t->freeable && !t->abstr_type_ptr->free_name) { /* forward ref */
            strcpy(forward_free_name,t->abstr_type_ptr->print_name);
            forward_free_name[4] = 'f';
            fprintf(out,"static int %s();\n\n",forward_free_name);
         }
      } 
      break;
   default:
      break;
   } /* switch */

   /* generate function definition */
   fprintf(out, "static int %s(p)\n", ateptr->free_name);
   if (type_name)
      fprintf(out,"   %s *p;\n", type_name);
   else
      fprintf(out,"   %s *p;\n", ateptr->typedef_name);
   fprintf(out,"{\n");

   switch (ateptr->get_kind()) {
     case AKIND_ARRAY:
        ateptr->get_components()->reset();
	ateptr->get_components()->next(l);
        t = (type_element *)l;

        /* Don't have to worry about forward references here--the component
           type must either be a backward reference, or unfreeable since
           we can't inherit freeability from a forward type */
        free_name = t->abstr_type_ptr->free_name;

        if (ateptr->dynorstat == ARRAYKIND_DYNAMIC || t->freeable) {

        /* DynamicArray val's are always freeable, and if their components
           are freeable, have to free them too.  Static arrays are freeable
           if their components are freeable. */

	  if (ateptr->dynorstat == ARRAYKIND_STATIC) {
	    fprintf(out,"   int i;\n");
            fprintf(out,"   for (i = 0; i < %d; i++) {\n", 
                        ateptr->element_count);
	    fprintf(out,"      %s(&((*p)[i]));\n",free_name);
            fprintf(out,"   }\n");
	  }
	  else { /* DynamicArray */
            fprintf(out,"   if (p->val) {\n");
            if (t->freeable) { /* Have to free components as well as val */
	      fprintf(out,"      int i;\n"); 
              fprintf(out,"      for (i = 0; i < p->len; i++) {\n");
	      fprintf(out,"         %s(&(p->val[i]));\n", free_name);
              fprintf(out,"      }\n");
            }
            fprintf(out,"      free(p->val);\n");
            fprintf(out,"      p->val = 0;\n");
            fprintf(out,"      p->len = 0;\n");
  	    fprintf(out,"   }\n");
	  }
        }
        break;

     case AKIND_RECORD:
       for (ateptr->get_components()->reset();
 	    ateptr->get_components()->next(l);
	    )
       {
         t = (type_element *) l;

         if (t->freeable) {
            if (t->abstr_type_ptr->free_name)
              free_name = t->abstr_type_ptr->free_name;
            else {
              free_name = forward_free_name;
              strcpy(free_name,t->abstr_type_ptr->print_name);
              free_name[4] = 'f';
            }
            if (t->indirect) {
              fprintf(out,"   if(");
              if (t->get_optional_flag() && !t->get_optional_value())
                 fprintf(out,"!p->__%s_absent && ",t->get_name());
              fprintf(out,"p->%s) {\n", t->get_name());

	      fprintf(out,"      %s(p->%s);\n", free_name, t->get_name());
              fprintf(out,"      free(p->%s);\n", t->get_name());
              fprintf(out,"      p->%s = 0;\n",t->get_name());
              fprintf(out,"   }\n");
            }
            else {
              if (t->get_optional_flag() && !t->get_optional_value())
                fprintf(out,"   if (!p->__%s_absent)\n   ",t->get_name());
	      fprintf(out,"   %s(%sp->%s);\n",
	                   free_name,
                           ((t->abstr_type_ptr->pointer_already &&
                             t->abstr_type_ptr->get_kind() == AKIND_ARRAY) 
                            || t->indirect) ? "" : "&",
		           t->get_name());
            }
         }

       } /* for components */
       break;

     case AKIND_UNION:
       fprintf(out,"   switch(p->tag) {\n");
       for (ateptr->get_components()->reset(), i=0;
 	    ateptr->get_components()->next(l);
            i++
	    )
       {
         t = (type_element *) l;
         if (t->freeable) {
            fprintf(out,"   case %d:\n",i);
            if (t->abstr_type_ptr->free_name)
              free_name = t->abstr_type_ptr->free_name;
            else {
              free_name = forward_free_name;
              strcpy(free_name,t->abstr_type_ptr->print_name);
              free_name[4] = 'f';
            }
            if (t->indirect) {
              fprintf(out,"      if (p->un.%s) {\n", t->get_name());
	      fprintf(out,"         %s(p->un.%s);\n", free_name, t->get_name());
              fprintf(out,"         free(p->un.%s);\n", t->get_name());
              fprintf(out,"         p->un.%s = 0;\n",t->get_name());
              fprintf(out,"      }\n");
            }
            else {
	      fprintf(out,"      %s(%sp->un.%s);\n",
	                   free_name,
                           ((t->abstr_type_ptr->pointer_already && 
                             t->abstr_type_ptr->get_kind() == AKIND_ARRAY)
                            || t->indirect) ? "" : "&",
		           t->get_name());
            }
            fprintf(out,"      break;\n");
         }
       } /* for components */
       fprintf(out,"   }\n");
       break;

     case AKIND_OBJECTIDENTIFIER:
       if (ateptr->length == 0) { 
         fprintf(out,"   if (p->comp != NULL) {\n");
         fprintf(out,"      free(p->comp);\n");
         fprintf(out,"      p->comp = 0;\n");
         fprintf(out,"      p->size = 0;\n");
         fprintf(out,"   }\n");
       }
       break;
       
     case AKIND_BITSTRING:
     case AKIND_OCTETSTRING:
     case AKIND_VIDEOTEXSTRING:
     case AKIND_TELETEXSTRING:
     case AKIND_IA5STRING:
     case AKIND_GENERALSTRING:
       if (ateptr->length == 0) { 
         fprintf(out,"   if (p->val != NULL) {\n");
         fprintf(out,"      free(p->val);\n");
         fprintf(out,"      p->val = 0;\n");
         fprintf(out,"      p->len = 0;\n");
         fprintf(out,"   }\n");
       }
       break;

     case AKIND_VISIBLESTRING:
     case AKIND_PRINTABLESTRING:
     case AKIND_NUMERICSTRING:
     case AKIND_GRAPHICSTRING:
       if (ateptr->length == 0) {
         fprintf(out,"   if (*p != NULL) {\n");
         fprintf(out,"      free(*p);\n");
         fprintf(out,"      *p = 0;\n");
         fprintf(out,"   }\n");
       }
       break;

     default:
       break;
   } /* end switch */

   fprintf(out,"   return(0);\n");
   fprintf(out,"}\n\n");
   return;
}


/* instance_list definitions */

void instance_list::delete_instances(int bd)
{
	 link *tlink;
	 reset();
	 while(getnext(tlink)) {
	    if (((instance_element*)tlink)->bracedepth < bd) {
	       insert(tlink);
	       break;
	    }
	 }
}

/* instance_element definitions */

instance_element::instance_element()
{
	 interf = NULL;
	 type = TYPE_UNKNOWN;
	 bracedepth = 0;
}

instance_element::instance_element (char* n, 
				    int bd, 
				    interface_element* ieptr,
				    inst_type t)
{
	 name = n;
	 interf = ieptr;
	 type = t;
	 bracedepth = bd;
	 kind = SYM_INST;
}

void instance_element::p_instance(int indent)
{
	 INDENTX3(indent);
	 fprintf(yyout,"name:%s\n",name);
	 INDENTX3(indent);
	 switch (type) {
   	 case TYPE_CONTROL:
	    fprintf(yyout,"type:control\n");
	    break;
	 case TYPE_DATA:
	    fprintf(yyout,"type:data\n");
	    break;
	 case TYPE_UNKNOWN:
	 default:
	    fprintf(yyout,"type:<null>\n");
	    BUG_CHECK("unknown type of instance declaration");
         }
	 INDENTX3(indent);
	 fprintf(yyout,"Interface:%s\n",interf->get_name());
	 INDENTX3(indent);
	 fprintf(yyout,"bracedepth:%d\n",bracedepth);
}

/* active_instance_element definitions */

active_instance_element:: active_instance_element()
{
	 inst_element_ptr = NULL;
	 exception_label = NULL;
	 ok_label = NULL;
	 iidvar  = NULL;
	 lidvar  = NULL;
}

active_instance_element:: active_instance_element(instance_element* iep,
						  char *el, 
						  char *ol)
{
	 inst_element_ptr = iep;
	 exception_label = el;
	 ok_label = ol;
	 iidvar  = NULL;
	 lidvar  = NULL;
}

active_instance_element:: active_instance_element(instance_element* iep,
						  char *el, 
						  char *ol,
						  char *iid,
						  char *lid)
{
	 inst_element_ptr = iep;
	 exception_label = el;
	 ok_label = ol;
	 iidvar  = iid;
	 lidvar  = lid;
}

active_instance_element *active_instance_list:: get_active_instance()
{
	 link *tmplinkptr;
	 reset();
	 next(tmplinkptr);
	 return (active_instance_element*)tmplinkptr;
}

/*encoding_rules definitions */

encoding_rules::encoding_rules()
{
	 rules_ptr = new list;
}

encoding_rules::encoding_rules(list* l)
{
	 rules_ptr = l;
}

void encoding_rules::reconcile()
{
	 link *l;
	 int what_form;
	 boolean more,delete_rule;

	 if (!rules_ptr)
	    return;
	 rules_ptr->reset();
	 rules_ptr->prev(l);
	 if (!l)
	    return;
	 what_form = ((rules_element *)l)->get_form();

	 rules_ptr->reset();
	 more = rules_ptr->next(l);
	 while (more)
	 {
	    rules_element *e = (rules_element *)l;

	    delete_rule = ((global.explicit_tagging) && 
			  (e->get_implicit_flag() == IMPLICIT_SEEN)) 
		                 || 
			  ((global.explicit_tagging == 0) && 
			  (e->get_implicit_flag() != EXPLICIT_SEEN));
	    if (delete_rule)
	       more = rules_ptr->getnext(l);
	    else
	       more = rules_ptr->next(l);
	 }
	 rules_ptr->reset();
	 rules_ptr->prev(l);
	 ((rules_element *)l)->set_form(what_form);
	 while (rules_ptr->prev(l))
	    ((rules_element *)l)->set_form(FORM_CONSTRUCTED);
}

__RO_int32 encoding_rules::tag_value(int which)
{
	 link *l;

	    for (rules_ptr->reset(); rules_ptr->next(l) && which--; )
		  ;
	     rules_element *e = (rules_element *)l;
	     return(e ? e->class_and_value() : 0);
}

int encoding_rules::eoc_count()
{
	 link *l;
	 int count;
	 
	 for (count=0,rules_ptr->reset(); rules_ptr->next(l); )
	 {
	    rules_element *e = (rules_element *)l;
	    count += e->get_form() == FORM_CONSTRUCTED;
	 }
	 return(count);
}

/* name_element definitions */

name_element::name_element()
{
	 type_element_ptr = NULL;
	 usage = 0;
}

void name_element::p_name_element(int indent)
{
	 INDENTX3(indent);fprintf(yyout,"name:");
	 fprintf(yyout,"%s\n",get_name());
	 indent += 1;
	 INDENTX3(indent);fprintf(yyout,"type:");
	 fprintf(yyout,"%s\n",type_element_ptr->get_name());
	 INDENTX3(indent);fprintf(yyout,"usage:%d\n",usage);
}

/* abstr_type_element definitions */

abstr_type_element::abstr_type_element()
{
	 kind = AKIND_UNKNOWN;
	 length = 0;
	 length2 = 0;
	 typedef_name = NULL;
	 element_count = 0;
	 setorseq = PARADIGM_UNKNOWN;
	 autotagged = global.tagging;
	 components = NULL;
	 print_name = free_name = encode_name = decode_name =  NULL;
	 pointer_already = FALSE;
	 dynorstat = ARRAYKIND_UNKNOWN;
	 veckind = NOVEC;
}

abstr_type_element::abstr_type_element(abstr_kind k,
				       symbol_list* l,
				       boolean a)
{
	 if (k == AKIND_ARRAY)
	    BUG_CHECK("wrong constructor for Arrays or strings");
	 kind = k;
	 length = 0;
	 length2 = 0;
	 typedef_name = NULL;
	 element_count = 0;
	 setorseq = PARADIGM_UNKNOWN;
	 autotagged = a;
	 components = l;
	 print_name = free_name = encode_name = decode_name =  NULL;
	 pointer_already = FALSE;
	 dynorstat = ARRAYKIND_UNKNOWN;
	 veckind = NOVEC;
}

abstr_type_element::abstr_type_element(abstr_kind k,
				       symbol_list* l)
{
	 if (k == AKIND_ARRAY)
	    BUG_CHECK("wrong constructor for Arrays");
	 kind = k;
	 length = 0;
	 length2 = 0;
	 typedef_name = NULL;
	 element_count = 0;
	 setorseq = PARADIGM_UNKNOWN;
	 autotagged = global.tagging;
	 components = l;
	 print_name = free_name = encode_name = decode_name =  NULL;
	 pointer_already = FALSE;
	 dynorstat = ARRAYKIND_UNKNOWN;
	 veckind = NOVEC;
}

abstr_type_element::abstr_type_element(abstr_kind k,
				       symbol_list* l,
				       boolean a,
				       paradigm p)
{
	 if (k == AKIND_ARRAY)
	    BUG_CHECK("wrong constructor for Arrays");
	 kind = k;
	 length = 0;
	 length2 = 0;
	 typedef_name = NULL;
	 element_count = 0;
	 setorseq = p;
	 autotagged = a;
	 components = l;
	 print_name = free_name = encode_name = decode_name =  NULL;
	 pointer_already = FALSE;
	 dynorstat = ARRAYKIND_UNKNOWN;
	 veckind = NOVEC;
}

abstr_type_element::abstr_type_element(abstr_kind k,
				       boolean a,
				       paradigm p,
				       arraykind ak)
{
	 kind = k;
	 length = 0;
	 length2 = 0;
	 typedef_name = NULL;
	 element_count = 0;
	 setorseq = p;
	 autotagged = a;
	 components = NULL; /* set by set_components */
	 print_name = free_name = encode_name = decode_name =  NULL;
	 pointer_already = ((k == AKIND_ARRAY) && (ak == ARRAYKIND_STATIC));
	 dynorstat = ak;
	 veckind = NOVEC;
}

abstr_type_element::abstr_type_element(abstr_kind k,int l1,int l2)
{
	 typedef_name = NULL;
	 kind = k;
	 length = l1;
	 length2 = l2;
	 element_count = 0;
	 setorseq = PARADIGM_UNKNOWN;
	 autotagged = global.tagging;
	 components = NULL;
	 print_name = free_name = encode_name = decode_name =  NULL;
	 pointer_already = 
			  k == AKIND_VISIBLESTRING ||
			  k == AKIND_GRAPHICSTRING ||
			  k == AKIND_PRINTABLESTRING ||
			  k == AKIND_NUMERICSTRING;
	 dynorstat = ARRAYKIND_UNKNOWN;
	 veckind = NOVEC;
}

void abstr_type_element::p_abstr_type(int indent)
{
	 INDENTX3(indent);fprintf(yyout,"abstract type:\n");
	 indent += 1;
	 INDENTX3(indent);
	 switch (kind) {
	 case AKIND_RECORD:
	    fprintf(yyout,"kind:Record\n");
	    break;
	 case AKIND_ARRAY:
	    fprintf(yyout,"kind:Array\n");
	    break;
	 case AKIND_UNION:
	    fprintf(yyout,"kind:Union\n");
	    break;
	 case AKIND_REAL:
	    fprintf(yyout,"kind:Real\n");
	    break;
	 case AKIND_BITSTRING:
	    fprintf(yyout,"kind:BitString\n");
	    break;
	 case AKIND_OBJECTIDENTIFIER:
	    fprintf(yyout,"kind:ObjectIdentifier\n");
	    break;
	 case AKIND_BOOLEAN:
	    fprintf(yyout,"kind:Boolean\n");
	    break;
	 case AKIND_INTEGER:
	    fprintf(yyout,"kind:Integer\n");
	    break;
	 case AKIND_OCTETSTRING:
	    fprintf(yyout,"kind:Octetstring\n");
	    break;
	 case AKIND_ENUMERATED:
	    fprintf(yyout,"kind:Enumerated\n");
	    break;
	 case AKIND_NULL:
	    fprintf(yyout,"kind:Null\n");
	    break;
	 case AKIND_NUMERICSTRING:
	    fprintf(yyout,"kind:NumericString\n");
	    break;
	 case AKIND_PRINTABLESTRING:
	    fprintf(yyout,"kind:PrintableString\n");
	    break;
	 case AKIND_TELETEXSTRING:
	    fprintf(yyout,"kind:TeletexString\n");
	    break;
	 case AKIND_VIDEOTEXSTRING:
	    fprintf(yyout,"kind:VideoString\n");
	    break;
	 case AKIND_VISIBLESTRING:
	    fprintf(yyout,"kind:VisibleString\n");
	    break;
	 case AKIND_IA5STRING:
	    fprintf(yyout,"kind:IA5String\n");
	    break;
	 case AKIND_GRAPHICSTRING:
	    fprintf(yyout,"kind:GraphicString\n");
	    break;
	 case AKIND_GENERALSTRING:
	    fprintf(yyout,"kind:GeneralString\n");
	    break;
	 case AKIND_ANY:
	    fprintf(yyout,"kind:Any\n");
	    break;
	 case AKIND_UNKNOWN:
	    fprintf(yyout,"kind:unknown\n");
	    break;
	 default:
	    fprintf(yyout,"kind:<null>\n");
         }
	 switch (kind) {
	 case AKIND_RECORD:
	    dump_components(indent);
	    break;
	 case AKIND_ARRAY:
	    dump_components(indent);
	    break;
	 case AKIND_UNION:
	    dump_components(indent);
	    break;
	 default:   /* primitive */
	    INDENTX3(indent);fprintf(yyout,"length:%d\n",length);
	    INDENTX3(indent);fprintf(yyout,"length2:%d\n",length2);
	    dump_components(indent);
	    break;
	 }
}

void abstr_type_element::dump_components(int indent)
{
	link *tmplinkptr;

	if (components == NULL) {
	   INDENTX3(indent);fprintf(yyout,"there are no components\n");
	}
	else {
	   components->reset();
	   while (components->next(tmplinkptr)) {
	      ((type_element *) tmplinkptr)->p_type_element(indent);
	   }
        }
}

void abstr_type_element::gen_typedef(FILE* out,char *user_name)
{
	 extern interface_element *ieptr;
	 char buffer[64];
	 printer_element *peptr;

	 if (!typedef_name) {
	    switch (kind) {
	    case AKIND_RECORD:
	    case AKIND_ARRAY:
	    case AKIND_UNION:
	       if (user_name)
		  sprintf(buffer,"__ROt_%s_%s",
				 ieptr->get_name(),
				 user_name);
	       else
		  sprintf(buffer,"__ROt_%s_%d",
				 ieptr->get_name(),
				 gen_type_number++);
	       break;
	    default:     /* kind is scalar primitive */
	       sprintf(buffer,"__ROt_%s_%d_%d",
			      user_name,
			      length,
			      length2);
	       break;
	    }

            /* Send typedef to 'out' file */
	    fprintf(out,"typedef ");
	    gen_type(out,0,buffer);
	    fprintf(out,";\n\n");

            if ( in_interface_spec ) { /* Send typedef to ..t file too */
               fprintf(types,"typedef ");
               gen_type(types,0,buffer);
               fprintf(types,";\n\n");
            }

	    typedef_name = (char*)malloc(strlen(buffer)+1);
            if (!typedef_name) nomem();
	    strcpy(typedef_name,buffer);
	    print_name = (char*)malloc(strlen(buffer)+1);
            if (!print_name) nomem();
	    strcpy(print_name,buffer);
	    print_name[4] = 'p';
	    if (kind==AKIND_RECORD || kind==AKIND_ARRAY  || 
		kind==AKIND_UNION) {

	       peptr = new printer_element(this);
	       printer_list_ptr->append_printer_element(peptr);
	    }
	    else
	       gen_print(prim);
	 }
}

void abstr_type_element::gen_print_decl(FILE *out)
{
         fprintf(out,"static int %s();\n",print_name);
}

void abstr_type_element::gen_print(FILE* out)
{
	 link *l;
	 int z = 1;

	 fprintf(out,"static int %s(file,value,name,indent,lead)\n",print_name);
	 fprintf(out,"   FILE *file;\n");
	 fprintf(out,"   %s *value;\n",typedef_name);
	 fprintf(out,"   char *name;\n   int indent;\n   char *lead;\n{\n");
	 fprintf(out,"   __ROp_NAME(file,name,indent,lead);\n");
	 switch(kind) 
	 {
	    case AKIND_BOOLEAN:
	       fprintf(out,"   __ROr_fprint_and_free(file,__ROr_format_Boolean(value,sizeof(*value),%d,0));\n",length);
	       fprintf(out,"   __ROp_RETURN(file);\n");
	       break;
	    case AKIND_ENUMERATED:
	    case AKIND_INTEGER:
	       fprintf(out,"   __ROr_fprint_and_free(file,__ROr_format_Integer(value,sizeof(*value),%d,0,&__ROc_type_information));\n",length);
	       fprintf(out,"   __ROp_RETURN(file);\n");
	       break;
	    case AKIND_REAL:
	       fprintf(out,"   __ROr_fprint_and_free(file,__ROr_format_Real(value,sizeof(*value),%d,%d,&__ROc_type_information));\n",length,length2);
	       fprintf(out,"   __ROp_RETURN(file);\n");
	       break;
	    case AKIND_OBJECTIDENTIFIER:
	       fprintf(out,"   __ROr_fprint_and_free(file,__ROr_format_ObjectIdentifier(value->comp,value->size,%d,%d));\n",length,length2);
	       fprintf(out,"   __ROp_RETURN(file);\n");
	       break;
	    case AKIND_BITSTRING:
	       fprintf(out,"   __ROr_fprint_and_free(file,__ROr_format_BitString(value->val,value->len,%d,%d));\n",length,length2);
	       fprintf(out,"   __ROp_RETURN(file);\n");
	       break;
	    case AKIND_OCTETSTRING:
	       fprintf(out,"   __ROr_fprint_and_free(file,__ROr_format_OctetString(value->val,value->len,%d,0));\n",length);
	       fprintf(out,"   __ROp_RETURN(file);\n");
	       break;
	    case AKIND_TELETEXSTRING:
	    case AKIND_VIDEOTEXSTRING:
	    case AKIND_IA5STRING:
	    case AKIND_GENERALSTRING:
	       fprintf(out,"   __ROr_fprint_and_free(file,__ROr_format_GeneralString(value->val,value->len,%d,0));\n",length);
	       fprintf(out,"   __ROp_RETURN(file);\n");
	       break;
	    case AKIND_NUMERICSTRING:
	    case AKIND_PRINTABLESTRING:
	    case AKIND_GRAPHICSTRING:
	    case AKIND_VISIBLESTRING:
	       fprintf(out,"   __ROr_fprint_and_free(file,__ROr_format_CharString(value,strlen(value),%d,0));\n",length);
	       fprintf(out,"   __ROp_RETURN(file);\n");
	       break;
	    case AKIND_NULL:
	       fprintf(out,"   __ROp_NULL(file);\n");
	       fprintf(out,"   __ROp_RETURN(file);\n");
	       break;
	    case AKIND_ANY:
	       fprintf(out,"   __ROr_fprint_and_free(file,__ROr_format_OctetString(value->pointer,value->count,value->size,0));\n");
	       fprintf(out,"   __ROp_RETURN(file);\n");
	       break;
	    case AKIND_RECORD:
	    {
	       INDENT(out,z);
	       fprintf(out,"__ROp_LBRACE(file,indent,lead);\n");
	       for (components->reset();
		    components->next(l);
		    )
	       {
		  type_element *t = (type_element *)l;

		  if (t->get_optional_flag() && !t->get_optional_value()) {
		     INDENT(out,z);
		     fprintf(out,"if(!(value->__%s_absent)) {\n",
				 t->get_name());
		     z += 1;
		  }
		  if (t->indirect) {
		     INDENT(out,z);
		     fprintf(out,"if(value->%s)\n",
				 t->get_name());
		     INDENT(out,z+1);
		     fprintf(out,"%s(file,(value->%s),\"%s\",indent+1,lead);\n",
			t->abstr_type_ptr->print_name,
			t->get_name(),
			t->get_name());
		     INDENT(out,z);
		     fprintf(out,"else {\n");
		     INDENT(out,z+1);
		     fprintf(out,"__ROp_NAME(file,\"%s\",indent+1,lead);\n",t->get_name());
		     INDENT(out,z+1);
		     fprintf(out,"fprintf(file,\"<null>\\n\");\n");
		     INDENT(out,z);
		     fprintf(out,"}\n");
		  }
		  else {
		     INDENT(out,z);
		     fprintf(out,"%s(file,%s(value->%s),\"%s\",indent+1,lead);\n",
			t->abstr_type_ptr->print_name,
			t->abstr_type_ptr->pointer_already ? "" : "&",
			t->get_name(),t->get_name());
		  }
		  if (t->get_optional_flag() && !t->get_optional_value()) {
		     z -= 1;
		     INDENT(out,z);
		     fprintf(out,"}\n");
		  }
	       }
	       INDENT(out,z);
	       fprintf(out,"__ROp_RBRACE(file,indent,lead);\n");
	       break;
	    }
	    case AKIND_UNION:
	    {
	       int i;

	       INDENT(out,z);
	       fprintf(out,"__ROp_RETURN(file);\n");
	       INDENT(out,z);
	       fprintf(out,"switch (value->tag)\n\t{\n");
	       for (components->reset(),i=0;
		    components->next(l);
		    i++)
	       {
		  type_element *t = (type_element *)l;

		  INDENT(out,z);
		  fprintf(out,"case %d:\n",i);

		  if (t->indirect) {
		     INDENT(out,z+1);
		     fprintf(out,"if(value->un.%s)\n",
				 t->get_name());
		     INDENT(out,z+2);
		     fprintf(out,"%s(file,(value->un.%s),\"[%s]\",indent+1,lead);\n",
			t->abstr_type_ptr->print_name,
			t->get_name(),
			t->get_name());
		     INDENT(out,z+1);
		     fprintf(out,"else {\n");
		     INDENT(out,z+2);
		     fprintf(out,"__ROp_NAME(file,\"%s\",indent+1,lead);\n",t->get_name());
		     INDENT(out,z+2);
		     fprintf(out,"fprintf(file,\"<null>\\n\");\n");
		     INDENT(out,z+1);
		     fprintf(out,"}\n");
		  }
		  else {
		     INDENT(out,z+1);
		     fprintf(out,"%s(file,%c(value->un.%s),\"[%s]\",indent+1,lead);\n",
			t->abstr_type_ptr->print_name,
			t->abstr_type_ptr->pointer_already ? ' ':'&',
			t->get_name(),t->get_name());
		  }
		  INDENT(out,z+1);
		  fprintf(out,"break;\n");
	       }
	       INDENT(out,z);
	       fprintf(out,"}\n");
	       break;
	    }
	    case AKIND_ARRAY:
	       {
		  type_element *t;

		  components->reset();
		  components->next(l);
		  t = (type_element *)l;
		  INDENT(out,z);
		  fprintf(out,"{\n");
		  INDENT(out,z);
		  fprintf(out,"unsigned long i;\n");
		  INDENT(out,z);
		  fprintf(out,"char ia[8];\n");
		  INDENT(out,z);
		  fprintf(out,"__ROp_LBRACE(file,indent,lead);\n");
		  switch (dynorstat) {
		     case ARRAYKIND_STATIC:
			INDENT(out,z);
			fprintf(out,"for (i=0; i<%d; i++) {\n",element_count);
			INDENT(out,z+1);
			fprintf(out,"sprintf(ia,\"%%lu\",i);\n");
			INDENT(out,z+1);
			fprintf(out,
                                "%s(file,%c((*value)[i]),ia,indent+1,lead);\n",
			        t->abstr_type_ptr->print_name,
			        t->abstr_type_ptr->pointer_already ? ' ':'&');
			INDENT(out,z);
			fprintf(out,"}\n");
			break;
		     case ARRAYKIND_DYNAMIC:
			INDENT(out,z);
			fprintf(out,"for (i=0; i<value->len; i++) {\n");
			INDENT(out,z+1);
			fprintf(out,"sprintf(ia,\"%%lu\",i);\n");
			INDENT(out,z+1);
			fprintf(out,
                               "%s(file,%c(value->val[i]),ia,indent+1,lead);\n",
			       t->abstr_type_ptr->print_name,
			       t->abstr_type_ptr->pointer_already ? ' ':'&');
			INDENT(out,z);
			fprintf(out,"}\n");
			break;
		     case ARRAYKIND_UNKNOWN:
		     default:
			BUG_CHECK("unknown kind of Array (should be static or dynamic)");
		  }
		  INDENT(out,z);
		  fprintf(out,"__ROp_RBRACE(file,indent,lead);\n");
		  INDENT(out,z);
		  fprintf(out,"}\n");
		  break;
	       }
	    case AKIND_UNKNOWN:
	       BUG_CHECK("unknown kind in abstr_type_element::gen_print");
	       break;
	  }
	 fprintf(out,"}\n\n");
}

void abstr_type_element::gen_type(FILE* out,int indent,char *type_spec)
{
	 if (typedef_name) {
	    INDENT(out,indent);
            fprintf(out,"%s %s",typedef_name,type_spec);
	 }
	 else {
	    switch(kind)
	    {
	    case AKIND_BOOLEAN:
	       INDENT(out,indent);
	       putout_type(out,
			   "unsigned ",
			   type_spec, 
			   __ROc_Boolean_lengths);
	       break;
	    case AKIND_INTEGER:
	    case AKIND_ENUMERATED:
	       INDENT(out,indent);
	       putout_type(out,
			   "",
			   type_spec,
			   __ROc_Integer_lengths);
	       break;
	    case AKIND_REAL:
	       INDENT(out,indent);
	       if (length <= __ROc_Real_lengths[0].maxlength && 
				 length2 <= __ROc_Real_lengths[0].maxlength2)
		  fprintf(out,"float %s",type_spec);
	       else if (length <= __ROc_Real_lengths[1].maxlength &&
				 length2 <= __ROc_Real_lengths[1].maxlength2)
		  fprintf(out,"double %s",type_spec);
	       else if (length <= __ROc_Real_lengths[2].maxlength &&
				 length2 <= __ROc_Real_lengths[2].maxlength2)
		  fprintf(out,"long double %s",type_spec);
	       else 
		  fprintf(out,
		      "struct { unsigned char val[%d]; } %s",
			      BITS2BYTES(length)+BITS2BYTES(length2)+1,type_spec);
	       break;
	    case AKIND_OBJECTIDENTIFIER:
	       INDENT(out,indent);
	       fprintf(out,"struct {int size; ");
               if (length)
	          fprintf(out,"unsigned long comp[%d];} %s",length,type_spec);
               else
	          fprintf(out,"unsigned long *comp;} %s",type_spec);
	       break;
	    case AKIND_BITSTRING:
	       INDENT(out,indent);
	       fprintf(out,"struct {unsigned long len; ");
               if (length)
	          fprintf(out,"unsigned char val[%d];} %s",
			      BITS2BYTES(length),type_spec);
               else
	          fprintf(out,"unsigned char *val;} %s", type_spec);
	       break;
	    case AKIND_OCTETSTRING:
	       INDENT(out,indent);
	       fprintf(out,"struct {unsigned long len; ");
               if (length)
	          fprintf(out,"unsigned char val[%d];} %s",length,type_spec);
               else
	          fprintf(out,"unsigned char *val;} %s",type_spec);
	       break;
	    case AKIND_TELETEXSTRING:
	    case AKIND_VIDEOTEXSTRING:
	    case AKIND_IA5STRING:
	    case AKIND_GENERALSTRING:
	       INDENT(out,indent);
	       fprintf(out,"struct {unsigned long len; ");
               if (length)
	          fprintf(out,"char val[%d];} %s",length,type_spec);
               else
	          fprintf(out,"char *val;} %s",type_spec);
	       break;
	    case AKIND_NUMERICSTRING:
	    case AKIND_PRINTABLESTRING:
	    case AKIND_GRAPHICSTRING:
	    case AKIND_VISIBLESTRING:
	       INDENT(out,indent);
               if (length)
	          fprintf(out,"char %s[%d]",type_spec,length+1);
               else
	          fprintf(out,"char *%s",type_spec);
	       break;
	    case AKIND_NULL:
	       INDENT(out,indent);
	       fprintf(out,"void *%s",type_spec);
	       break;
	    case AKIND_ANY:
	       INDENT(out,indent);
	       fprintf(out,"__RO_Memory %s",type_spec);
	       break;
	    case AKIND_ARRAY:
	       {
		  link *l;

		  components->reset();
		  components->next(l);
		  type_element *t = (type_element *)l;
		  switch (dynorstat) {
		  case ARRAYKIND_STATIC:
		     t->abstr_type_ptr->gen_type(out,0,type_spec);
		     fprintf(out,"[%d]",element_count);
		     break;
		  case ARRAYKIND_DYNAMIC:
		     fprintf(out,"struct %s {\n",type_spec);
		     INDENT(out,indent+1);
		     fprintf(out,"unsigned long len;\n");
                     if (t->type_name) {
                       INDENT(out,indent+1);
                       fprintf(out,"%s *val;\n",t->type_name);
                     }
		     else 
		       t->abstr_type_ptr->gen_type(out,indent+1,"*val;\n");
		     INDENT(out,indent);
		     fprintf(out,"} %s",type_spec);
		     break;
		  case ARRAYKIND_UNKNOWN:
		  default:
		     BUG_CHECK("unknown kind of Array (should be static or dynamic)");
		  }
	       }
	       break;
	    case AKIND_RECORD:
	       INDENT(out,indent);
	       {
		  link *l;
                  type_element *t;

		  fprintf(out,"struct %s {\n",type_spec);
		  for (components->reset();
		       components->next(l);
		       )
		  {
		     t = (type_element *)l;
		     if (t->type_name) /* Named reference */ {
                        INDENT(out,indent+1);
			fprintf(out,"%s %s %s",
				    t->type_name,
				    t->indirect ? "*" : "",
				    t->get_name());
                     }
		     else 
			t->abstr_type_ptr->gen_type(out,indent+1,
                                                        t->get_name());

		     fprintf(out,";\n");
		     if (t->get_optional_flag() && !t->get_optional_value())
		     {
		       INDENT(out,indent+1);
		       fprintf(out,"int __%s_absent;\n",t->get_name());
		     }
		  }
		  INDENT(out,indent);
		  fprintf(out,"} %s",type_spec);
	       }
	       break;
	    case AKIND_UNION:
	       INDENT(out,indent);
	       {
		  link *l;
		  int i;

		  fprintf(out,"struct %s {\n",type_spec);
		  INDENT(out,indent+1);
		  fprintf(out,"int tag;\n");
		  INDENT(out,indent+1);
		  fprintf(out,"union {\n");
		  for (components->reset(),i=1;
		       components->next(l);
		       i++)
		  {
		     type_element *t = (type_element *)l;

		     if (t->type_name) {
                        INDENT(out,indent+2);
			fprintf(out,"%s %s %s",
				    t->type_name,
				    t->indirect ? "*" : "",
				    t->get_name());
		     }
		     else 
			t->abstr_type_ptr->gen_type(out,indent+2,t->get_name());
		     fprintf(out,";\n");
		  }
		  INDENT(out,indent+1);
		  fprintf(out,"} un;\n");
		  INDENT(out,indent);
		  fprintf(out,"} %s",type_spec);
	       }
	       break;
	    case AKIND_UNKNOWN:
	    default:
	       printf("*** internal error, bad KIND\n");
	       break;
	    }
         }
}

void abstr_type_element::putout_type(FILE* out,
				     char* unsignedornull,
				     char *type_spec,
				     __RO_type_lengths *len_array)
{
   if (length <= len_array[0].maxlength)
		  fprintf(out,"%schar %s",unsignedornull,type_spec);
   else if (length <= len_array[1].maxlength)
		  fprintf(out,"%sshort int %s",unsignedornull,type_spec);
   else if (length <= len_array[2].maxlength)
		  fprintf(out,"%sint %s",unsignedornull,type_spec);
   else if (length <= len_array[3].maxlength)
		  fprintf(out,"%slong %s",unsignedornull,type_spec);
   else if (length <= len_array[4].maxlength)
		  fprintf(out,"%slong long %s",unsignedornull,type_spec);
   else 
      fprintf(out,"struct { unsigned char val[%d]; } %s",length,type_spec);
}

void abstr_type_element::tag_elements(boolean auto_tag)
{
   link *l;
   int i;
   type_element *t;
   int canonical_form;
   list *tmp;

   for (components->reset(),i=0; components->next(l); i++)
   {
      t = (type_element *)l;

      if (auto_tag)
      {

         if ((tmp = t->get_rules_ptr()) && tmp->length()>0)
         {

		/* Fetch the first tag to get the form, and delete it, since
		   we're impliciting it.  */

            t->get_rules_ptr()->reset();
            t->get_rules_ptr()->getnext(l);
            canonical_form = ((rules_element *)l)->get_form();
         }
         else
		/* we know we're constructed, since it's a union
		   (we hope). */
            canonical_form = FORM_CONSTRUCTED;

         t->get_rules_ptr()->insert
             (new rules_element(CLASS_CONTEXT,canonical_form,i,NOTHING_SEEN));
      }
      ieptr->constant_gen->add_encoding(t);
   }

}

/* tag_element definitions */

tag_element::tag_element(__RO_int32 val)
{  tag_bytes = val;
}

/* rules_element definitions */

EXTERN_FUNCTION ( int __ROr_enc_tag , (char*, int*, int*, int*, int*) )
#define __encode_tag	__ROr_enc_tag

rules_element::rules_element()
{
  tag_class = 0;
  tag_form = 0;
  tag_value = 0;
  implicit_flag = 0;
}

rules_element::rules_element(abstr_kind k)
{
	 static tagged_value[22][3] = {

	  CLASS_UNIVERSAL,FORM_PRIMITIVE,9,  /*AKIND_REAL,		 0 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,3,  /*AKIND_BITSTRING,		 1 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,6,  /*AKIND_OBJECTIDENTIFIER,	 2 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,1,  /*AKIND_BOOLEAN,		 3 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,2,  /*AKIND_INTEGER,		 4 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,4,  /*AKIND_OCTETSTRING,	 5 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,10, /*AKIND_ENUMERATED	 	 6 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,5,  /*AKIND_NULL,		 7 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,18, /*AKIND_NUMERICSTRING,	 14 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,19, /*AKIND_PRINTABLESTRING,	 15 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,20, /*AKIND_TELETEXSTRING,	 16 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,21, /*AKIND_VIDEOTEXSTRING,	 17 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,26, /*AKIND_VISIBLESTRING,	 18 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,22, /*AKIND_IA5STRING,		 19 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,25, /*AKIND_GRAPHICSTRING,	 20 */
	  CLASS_UNIVERSAL,FORM_PRIMITIVE,27  /*AKIND_GENERALSTRING,	 21 */
	 };

	 if (k == AKIND_UNION) {
	    tag_class = CLASS_APPLICATION;
	    tag_form = FORM_CONSTRUCTED;
	    tag_value =  0;
	 }
	 else if (k == AKIND_RECORD || k == AKIND_ARRAY) {
	    BUG_CHECK("rules_element not expecting an Array or Record");
	 }
	 else {                             /* primitive type */
	    tag_class = tagged_value[k][0];
	    tag_form = tagged_value[k][1];
	    tag_value = tagged_value[k][2];
	 }
	 implicit_flag = 0;
}

rules_element::rules_element(abstr_kind k,paradigm par)
{
	 if (k == AKIND_RECORD || k == AKIND_ARRAY) {
	    tag_class = CLASS_UNIVERSAL;
	    tag_form = FORM_CONSTRUCTED;
	    switch (par) {
	    case PARADIGM_SEQUENCE:
	       tag_value = 16;
	       break;
	    case PARADIGM_SET:
	       tag_value = 17;
	       break;
	    case PARADIGM_UNKNOWN:
	    default:
	       BUG_CHECK("unknown kind of paradigm");
	    }
	 }
	 else 
	    printf("*** rules_element expected an array or record\n");
	 implicit_flag = 0;
}

rules_element::rules_element(int cl,int f,int v,implicitness i)
{
	 tag_class = cl;
	 tag_form = f;
	 tag_value = v;
	 implicit_flag = i;
}


rules_element::rules_element(rules_element* re)
{
	 tag_class = re->tag_class;
	 tag_form = re->tag_form;
	 tag_value = re->tag_value;
	 implicit_flag = re->implicit_flag;
}

void rules_element::p_rule(int indent)
{
	 INDENTX3(indent);fprintf(yyout,"class:");
	 switch (tag_class) {
	 case CLASS_UNIVERSAL:
	    fprintf(yyout,"Universal     ");
	    break;
	 case CLASS_APPLICATION:
	    fprintf(yyout,"Application   ");
	    break;
	 case CLASS_CONTEXT:
	    fprintf(yyout,"Context       ");
	    break;
	 case CLASS_PRIVATE:
	    fprintf(yyout,"Private       ");
	    break;
	 default:
	    fprintf(yyout,"<null>        ");
         }
	 fprintf(yyout,"tag value:%d\n",tag_value);
}

__RO_int32 rules_element::class_and_value()
{
      return (tag_value | (tag_class<<30));
}

void rules_element::encode(bytearray &bytelist)

{
   int cl_i = tag_class,form_i = tag_form,tag_i = tag_value;
   unsigned char buffer[8];
   singlebyte *b;
   int len=0;

   __encode_tag((char *)buffer,&len,&cl_i,&form_i,&tag_i);

   for (int i=0; i<len; i++)
      bytelist.append(b = new singlebyte(buffer[i]));
   if (tag_form == FORM_CONSTRUCTED)
      bytelist.append(b = new singlebyte(0x80));
}

/* param_element definitions */

param_element::param_element(name_element *n,
			     arg_mode m, 
			     int p)
{
   type_element_ptr = NULL;
   name_ptr = n;
   mode = m;
   list_position = p;
   num_id = n->get_name();
}

param_element:: param_element(type_element* te,
			      arg_mode m,
			      int p)
{
   type_element_ptr = te;
   name_ptr = NULL;
   mode = m;
   list_position = p;
   num_id = (char*)malloc(64);
   if (!num_id) nomem();
   sprintf(num_id,"(%d)", p+1);
}

void param_element::p_param()
{
   if (name_ptr) {
      fprintf(yyout,"|     named arg:");
      fprintf(yyout,"%s\n",name_ptr->get_name());
   }
   else {
      fprintf(yyout,"|     positional arg:");
   }
   switch (mode) {
   case MODE_IN:
      fprintf(yyout,"|        mode:in\n");
      break;
   case MODE_OUT:
      fprintf(yyout,"|        mode:out\n");
      break;
   case MODE_INOUT:
      fprintf(yyout,"|        mode:inout\n");
      break;
   case MODE_UNKNOWN:
   default:
      fprintf(yyout,"|        mode:<null>\n");
      BUG_CHECK("unknown mode");
   }
}

/* modal_param definitions */

modal_param::modal_param(param_element* i, param_element* o)
{
   in = i;
   out = o;
}

/* modal list definitions */

modal_list::modal_list(int porn)
{
   pos_or_named = porn;
}

void modal_list::resolve( argument_list *callarglist,
			  argument_list *inarglist,
			  argument_list *outarglist)
{
   link *l,*pl;

   if (pos_or_named == TYPE_PARAM_LIST)
   {
      boolean moreparms,moreargs;

      for (reset(),callarglist->reset();
           moreparms = next(pl),moreargs = callarglist->next(l),
			moreargs && moreparms;
           )
      {
         argument *a = (argument *)l;
         modal_param *p = (modal_param *)pl;

         if (p->in)
            inarglist->append(new argument(p->in,a));
         if (p->out)
            outarglist->append(new argument(p->out,a));
      }
      if (moreargs)
         report_error("error 22",
		      "Too many arguments in Call operation.",
		      NULL);

      while (moreparms)
      {
         modal_param *p = (modal_param *)pl;

         if (p->in)
            inarglist->append(new argument(p->in));
         if (p->out)
            outarglist->append(new argument(p->out));
         moreparms = next(pl);
      }
   }
   else
   {
      argument *a;

      for (reset(); next(pl); )
      {
         modal_param *p = (modal_param *)pl;

         if (callarglist->search_name(p->get_name(),a))
         {
            if (p->in)
               inarglist->append(new argument(p->in,a));
            if (p->out)
               outarglist->append(new argument(p->out,a));
         }
         else
         {
            callarglist->append(new argument((char *)NULL,
					     (char *)NULL,
					     (char *)NULL));
            if (p->in)
               inarglist->append(new argument(p->in));
            if (p->out)
               outarglist->append(new argument(p->out));
         }
      }
      if (callarglist->length() < length())
         BUG_CHECK("Not enough named arguments were resolved in Call");
      if (callarglist->length() > length())
         report_error("error 23",
		      "Too many named arguments in Call operation.",
		       NULL);
   }

}

char *modal_param::get_name()
{
   if (in)
      return(in->get_name_ptr()->get_name());
   else if (out)
      return(out->get_name_ptr()->get_name());
   else
   {
      BUG_CHECK("'in' and 'out' pointer from a Modal_parameter are NULL");
      return("");
   }
}




/* dmatrix definitions */

dmatrix::dmatrix(int r,int c)
{ 
   rows = r+1;
   cols = c+1;
   values = (DMATRIX_ELEMENT *)malloc(sizeof(int)*rows*cols);
   if (!values) nomem();
   for (int i=0; i<rows*cols; i++)
      values[i] = -1;
}

dmatrix::~dmatrix()
{
   free((char *)values);
}

boolean dmatrix::lesscol(int l, int r)
{
   for (int i=0; i<rows; i++)
      if (get(i,l)<get(i,r))
         return(TRUE);
      else if (get(i,l) > get(i,r))
         return(FALSE);
   return(FALSE);
}

void dmatrix::sort()
{
   for (int i=0; i<cols-1; i++)
      for (int j=i; j<cols; j++)
         if (!lesscol(i,j))
            for (int k=0; k<rows; k++)
            {
               DMATRIX_ELEMENT temp = get(k,i);
               put(k,i,get(k,j));
               put(k,j,temp);
            }
}

void dmatrix::print(FILE *pf,char *title)
{
   fprintf(pf,"***%s\n",title);
   for (int i=0; i<rows; i++)
   {
      fprintf(pf,"\n");
      for (int j=0; j<cols; j++)
         fprintf(pf,"%5d",get(i,j));
   }
}
/* end of dmatrix definitions */

/* bytes definitions */

void bytearray::generate(FILE *out,char *name)
{
   link *l;
   int i;

   fprintf(out,"\nstatic unsigned char %s[] = {\n/*0*/\t",name);
   for (reset(),i=1; next(l); i++)
   {
      singlebyte *b = (singlebyte *)l;

      b->print(out,i);
   }
   fprintf(out," NULL};\n\n");

}

void singlebyte::print(FILE *out,int index)
{
   fprintf(out,"0x%2.2x,",value);
   if (comment)
      fprintf(out,"\t/* %s */\n/*%d*/\t",comment,index);
}

/* end of bytes definitions */

/* gen_optables definitions */

void optable_generator::add_operation(operation_element *op)
{
   operation_link *oplink = new operation_link;
   int i;

   oplink->op = op;
   if (op->op_num)
   {
      if ((i = oplink->convert()) > maxoidsize)
         maxoidsize = i;
      oplink->give_offset = give_encodes.length();
      if (oplink->op->kind_op == KIND_REJECT)
      {
         give_encodes.append(new singlebyte((unsigned char)(0x80 + oplink->opoid->comp[0])));
         encode_op_Integer(give_encodes,&(oplink->opoid->comp[1]));
      }
      else if (oplink->opoid->size == 1)
      {
         give_encodes.append(new singlebyte((unsigned char)0x02));
         encode_op_Integer(give_encodes,&(oplink->opoid->comp[0]));
      }
      else
      {
         give_encodes.append(new singlebyte((unsigned char)0x06));
         encode_op_ObjectIdentifier(give_encodes,oplink->opoid);
      }

	/* Add comment */
      {
         link *l;

         give_encodes.reset();
         give_encodes.prev(l);
         ((singlebyte *)l)->set_comment(op->op_num);
      }
      oplink->give_length = give_encodes.length() - oplink->give_offset;
   }
   else
   {
      oplink->opoid = NULL;
      oplink->give_offset = 0;
      oplink->give_length = 0;
   }

   all.append(oplink);
}

void optable_generator::generate(FILE *out)
{
   char buf[64];

	/* Put out __ROp_xxx print routines */

   printer_list_ptr->gen_print_routines(out);
   printer_list_ptr->clear();

	/* Put out __ROe_xxx_Give_encodes */

   sprintf(give_encodes_name,"__ROe_%s_Give_encodes",ieptr->get_name());
   give_encodes.generate(out,give_encodes_name);


	/* Put out __ROc_xxx_Arg_table */

   gen_argtable(out);


	/* Put out __ROc_xxx_Give_table */

   gen_givetable(out);


	/* Put out __ROc_xxx_?A_table's */

   sprintf(accepttables_name,"__ROc_%s_Accept_tables",ieptr->get_name());

   gen_accepttable(out,&all,KIND_INVOKE,'I');
   gen_accepttable(out,&all,KIND_RESULT,'R');
   gen_accepttable(out,&all,KIND_ERROR,'E');
   gen_accepttable(out,&all,KIND_REJECT,'J');

   fprintf(out,"\nstatic __RO_Accept_table_Entries %s = {\n",
           accepttables_name);
   fprintf(out,"\t(__RO_Accept_table_Entry_Ptr) __ROc_%s_IA_table,\n",
           ieptr->get_name());
   fprintf(out,"\t(__RO_Accept_table_Entry_Ptr) __ROc_%s_RA_table,\n",
           ieptr->get_name());
   fprintf(out,"\t(__RO_Accept_table_Entry_Ptr) __ROc_%s_EA_table,\n",
           ieptr->get_name());
   fprintf(out,"\t(__RO_Accept_table_Entry_Ptr) __ROc_%s_JA_table,\n",
           ieptr->get_name());
   fprintf(out,"};\n\n");

   /* Put out __ROc_xxx_print_table */

   gen_printtable(out);

   /* Put out __ROc_xxx_free_table */

   gen_freetable(out,freeable_types_ptr);

   /* Put out __ROc_xxx_information */

   fprintf(out,"\nstatic __RO_Instance_Info %s = {\n",global.information_name);
   fprintf(out,"\t\"%s\",\t/* Interface name */\n",global.interface_name);
   fprintf(out,"\t%d,\t/* maximum nesting */\n",maxnest);
   fprintf(out,"\t%d,\t/* longest operation oid */\n",maxoidsize);
   fprintf(out,"\t__RO_SEND_BUFFER_SIZE,\n");
   fprintf(out,"\t__RO_RECEIVE_BUFFER_SIZE,\n");
   fprintf(out,"\t%s,\n",printtable_name);
   fprintf(out,"\t%s,\n",freetable_name);
   fprintf(out,"\t%s,\n",givetable_name);
   fprintf(out,"\t(__RO_Accept_table_Entries *) %s,\n",accepttables_name);
   fprintf(out,"\t__ROm_capable_ASN_1,\t/* Rules capable flags */\n");
   fprintf(out,"\t&__ROc_type_information,\n");
   fprintf(out,"\t__ROc_%s_acn,\t/* Application-context-name */\n",
		global.interface_name);
   fprintf(out,"\t__ROc_%s_pcn,\t/* Presentation-context-name */\n",
		global.interface_name);
   fprintf(out,"};\n\n");

   fprintf(out,"static __RO_Instance_Info *%s = &%s;\n",
		global.interface_name,global.information_name);


}

void optable_generator::gen_freetable(FILE *out,type_element_list *freelist)
{
   link *l,*ll;
   type_element_list *done = new type_element_list();

   sprintf(freetable_name,"__ROc_%s_Free_table",ieptr->get_name());
   fprintf(out,"\nstatic __RO_Free_table_Entry %s[] = {\n",freetable_name);
   for (freelist->reset(); freelist->next(l); ) {
     type_element *t = ((type_element_ptr *)l)->ptr;
     if (t->abstr_type_ptr->free_name
         && ieptr->lookup_type(t->get_name())) {
       /* If free routine was generated and this is a type */
       boolean already_done;
       already_done = 0;
       done->reset();
       while (done->next(ll)) {
         if (!strcmp(t->get_name(),((type_element_ptr *)ll)->ptr->get_name())) {
           already_done = 1;
           break;
         }
       }
       if (!already_done) {
         fprintf(out,"\t{\"%s\",\t%s},\n",t->get_name(),
		 t->abstr_type_ptr->free_name);
         done->append(new type_element_ptr(t));
       }
     }
   }
   fprintf(out,"\t{NULL,NULL}\n};\n\n");
   /* Delete "done" list ??? */
}

void optable_generator::gen_printtable(FILE *out)
{
   link *l;

   sprintf(printtable_name,"__ROc_%s_Print_table",ieptr->get_name());
   fprintf(out,"\nstatic __RO_Print_table_Entry %s[] = {\n",printtable_name);
   if (ieptr->types_ptr) {
      for (ieptr->types_ptr->reset(); ieptr->types_ptr->next(l); ) {
	 type_element *t = (type_element *)l;
	 if (t->abstr_type_ptr->print_name)
	    fprintf(out,"\t{\"%s\",\t%s},\n",t->get_name(),
			   t->abstr_type_ptr->print_name);
      }
   }
   fprintf(out,"\t{NULL,NULL}\n};\n\n");
}

void optable_generator::gen_argtable(FILE *out)
{
   link *l;
   int argument_index = 0;
   int pcount;
   parameter_list *pl;
   operation_link *oplink;
   type_element *teptr;
   list *tags;
   name_element *neptr;

   sprintf(arg_table_name,"__ROc_%s_Arg_table",ieptr->get_name());
   fprintf(out,"\nstatic __RO_Argument_table_Entry %s[] = {\n",arg_table_name);
   for (all.reset(); all.next(l); )
   {
      oplink = (operation_link *)l;
 
      pl = oplink->op->params_ptr;
      if (pl) {  
	 oplink->arg_offset = argument_index;
	 for (pl->reset(),pcount=1; pl->next(l); pcount++)  {
	    if (pl->get_pos_or_named() == NAMED_PARAM_LIST) {
	       neptr = ((param_element *)l)->get_name_ptr();
	       teptr = neptr->get_type_element_ptr();
	    }
	    else 
	       teptr = ((param_element *)l)->get_type_element_ptr();
	    tags = teptr->get_leading_tags();
 
	    for (tags->reset(); tags->next(l); ) {
	       fprintf(out,"{%d,\t0x%8.8x,",
		    oplink->op->internal_number,
		    ((tag_element*)l)->get_tag_bytes());
	       if (pl->get_pos_or_named() == NAMED_PARAM_LIST) 
		  fprintf(out,"\t\"%s\"},\n",
			  neptr->get_name());
	       else
		  fprintf(out,"\t\"%d (%s)\"},\n",
			  pcount,teptr->get_name());
	    }
	    argument_index++;
	 }
      }
   }
   fprintf(out,"{-1,0,0}\n};\n\n");
}

void optable_generator::gen_givetable(FILE *out)
{
   link *l;

   sprintf(givetable_name,"__ROc_%s_Give_table",ieptr->get_name());
   fprintf(out,"\nstatic __RO_Give_table_Entry %s[] = {\n",givetable_name);

   maxnest = 0;
   for (all.reset(); all.next(l); )
   {
      operation_link *oplink = (operation_link *)l;

      switch(oplink->op->kind_op)
      {
      case KIND_INVOKE: fprintf(out,"{\t__RO_INVOKE,\n"); break;
      case KIND_RESULT: fprintf(out,"{\t__RO_RESULT,\n"); break;
      case KIND_ERROR: fprintf(out,"{\t__RO_ERROR,\n"); break;
      case KIND_REJECT: fprintf(out,"{\t__RO_REJECT,\n"); break;
      case KIND_CALL: fprintf(out,"{\t__RO_INVOKE,\n"); break;
      case KIND_UNKNOWN:
      default:  BUG_CHECK("unknown kind of operation");
      }
      fprintf(out,"\t%d,\n",oplink->opoid
			    ? (oplink->opoid->size == 1
			       ? oplink->opoid->comp[0]
			       : -1)
			    : -1);
      if (oplink->give_length)
	 fprintf(out,"\t%s+%d,\n",give_encodes_name,oplink->give_offset);
      else
	 fprintf(out,"\tNULL,\n");
      fprintf(out,"\t%d,\n",oplink->give_length);
      fprintf(out,"\t__RO_OIDTREE_%sHDR,\n",
	  (oplink->op->params_ptr &&
	   oplink->op->params_ptr->get_wrapping()) ? "SET" : "NO");
      fprintf(out,"\t\"%s\",\n",oplink->op->get_name());
      if(oplink->op->params_ptr && oplink->op->params_ptr->length()>0 )
	 fprintf(out,"\t%s+%d},\n\n",arg_table_name,oplink->arg_offset);
      else
	 fprintf(out,"\tNULL},\n");

   }
   fprintf(out,"\t{NULL,NULL,NULL,NULL,NULL,NULL,NULL}\n");
   fprintf(out,"};\n\n");
}

struct acceptnum
{
   int index;
   long value;
   int ret;
   int lo,hi;
   struct acceptnum *children;
   struct acceptnum *next;
};

int optable_generator::accept_descend (dmatrix &ids,
				       int row,
				       int colstart,
				       int colstop,
				       struct acceptnum **parent)
{
   struct acceptnum **node = parent;
   long current;
   int i,count = 0;

   if (colstart > colstop || ids.get(row,colstart) == -1)
   {
      *parent = NULL;
      return(count);
   }
   
   *node = (struct acceptnum *)malloc(sizeof(struct acceptnum));
   if (!*node) nomem();

   current = (*node)->value = ids.get(row,colstart);
   if (ids.get(row+1,colstart) == -1)
      (*node)->ret = (int)ids.get(maxoidsize+1,colstart++);
   else
      (*node)->ret = -1;
   (*node)->children = NULL;
   (*node)->next = NULL;

   for ( count=1,i=colstart; i<=colstop && ids.get(row,i)==current; i++)
      ;
   count += accept_descend(ids,row,  i,       colstop,&((*node)->next));
   count += accept_descend(ids,row+1,colstart,i-1,    &((*node)->children));

   return(count);
}

int optable_generator::accept_number(struct acceptnum *base,int &total_count)
{
   int return_count;

   for (struct acceptnum *ptr=base; ptr; ptr=ptr->next)
      ptr->index = ++total_count;
   return_count = total_count;
   for ( ; base; base=base->next)
      if (base->children)
      {
         base->lo = total_count+1;
         base->hi = accept_number(base->children,total_count);
      }
      else
         base->lo = base->hi = -1;
   return(return_count);
}

void optable_generator::accept_gen(FILE *out,struct acceptnum *base)
{
   if (!base)
      return;

   for (struct acceptnum *ptr=base; ptr; ptr=ptr->next)
      fprintf(out,"/*%d*/\t{%d,\t%d,\t%d,\t%d},\n",ptr->index,
					ptr->value,ptr->ret,
					ptr->lo,ptr->hi);
   for ( ; base; base=base->next)
      accept_gen(out,base->children);
}

void optable_generator::gen_accepttable(FILE *out,
					list *oplist,
					op_kind opkind,
					char which)
{
   dmatrix *ids;
   int i,j,opcount;
   link *l;

	/* Count up how many operations we will process, and
	   create an appropriately sized matrix */

   for (oplist->reset(),opcount=0; oplist->next(l); )
   {
      operation_link *oplink = (operation_link *)l;

      opcount += oplink->op->kind_op == opkind;
   }
   ids = new dmatrix(maxoidsize+1,opcount);


	/* Convert the operation number values into the matrix format */

   for (oplist->reset(),i=0; oplist->next(l); )
   {
      operation_link *oplink = (operation_link *)l;

      if (oplink->op->kind_op == opkind)
      {
         if (oplink->opoid)
            for (j=0; j<oplink->opoid->size; j++)
               ids->put(j,i,oplink->opoid->comp[j]);
         ids->put(maxoidsize+1,i,oplink->op->internal_number);
         i++;
      }
   }

	/* Sort the matrix columns */

   ids->sort();
#ifdef ELROS_DEBUG
   ids->print(stdout,"IDS");
#endif


	/* Descend the matrix and create an OID-Tree. */

   struct acceptnum base;
   base.index = 0;
   base.ret = opcount
              ? (ids->get(0,1) == -1 ? (int)ids->get(maxoidsize+1,1) : -1)
              : -1;
   base.next = NULL;
   base.value = accept_descend(*ids,0,base.ret == -1 ? 1 : 2,opcount,
                               &base.children);


	/* Number the nodes in the OID-Tree, and set the child indexes. */

   if (base.children)
   {
      base.lo = 1;
      base.hi = accept_number(base.children,0);
   }
   else
      base.lo = base.hi = -1;


	/* Generate the accept table. */

   fprintf(out,"static __RO_Accept_table_Entry __ROc_%s_%cA_table[] = {\n",
           ieptr->get_name(),which);
   accept_gen(out,&base);
   fprintf(out,"};\n\n");

}

int operation_link::convert()
{
   int i,ct;

   for (i=0,ct=0; i<strlen(op->op_num); i++)
      ct += op->op_num[i] == '.' || op->op_num[i] == ' ';

   opoid = (struct opoid_skeleton *)
		malloc(sizeof(struct opoid_skeleton)+(ct*sizeof(long)));
   if (!opoid) nomem();

   opoid->size = 0;
   opoid->comp[opoid->size] = 0;
   for (i=0; i<strlen(op->op_num); i++)
      if (op->op_num[i] == '.' || op->op_num[i] == ' ')
         opoid->comp[++opoid->size] = 0;
      else
         opoid->comp[opoid->size] = 
             opoid->comp[opoid->size]*10 + op->op_num[i]-'0';
   return(++opoid->size);
}

/* end of gen_optables definitions */
/* encode_op definitions */


/*
	Embedded Language for Remote Operations Services
	ELROS

	AUTHOR:		Robyne M. Sumpter	
			Network Systems Division

	DATE WRITTEN:	7/9/90
*/
/*
	ROUTINE:	encode_op_Integer	

PURPOSE:
	Encode and integer value in ASN.1, load it into a buffer and
	if full, send the buffer.
	Enumerated types are encoded as the integer value of the 
	enumerated element.  This routine is "#define"d to be the 
	encode integer routine.


IN:
	blist - list of bytes to add encoded byte to.
	value - integer to encode

OUT:
	blist - updated


CALLED ROUTINES:
	encode_op_length
	

	
MODIFICATION HISTORY:
8/15/90 - JAG
	Changed for use in preprocessor

*/

#include <elros/enc_dcd.h>

void encode_op_Integer( bytearray &blist, long *value)
{
   static int valuelength = sizeof(long);
   static int maxlength = sizeof(long);
   int		i,numbytes;
   long		mask,
		sign,
		valuedata = *value;
   char		*dataptr;


   sign = *value >= 0 ? *value : *value ^ (-1);
   mask = 0x1ff << (((numbytes = valuelength) - 1) * 8 - 1);
   while (numbytes > 1 && (sign & mask) == 0)
	mask >>= 8, numbytes--;


   encode_op_length( blist, &numbytes );


   if( numbytes > maxlength )
   {
      printf("numbytes>maxlength in encode_op_Integer\n");
      exit(1);
   }
   
	
   dataptr = (char*)malloc(numbytes)+numbytes;
   if (!dataptr) nomem();

   for (i=numbytes;
        i-- > 0;
        valuedata >>= 8)
      *--dataptr = (char)(valuedata & 0xff);

   for (i=0; i<numbytes; i++)
      blist.append(new singlebyte(*dataptr++));
}

/*
	ROUTINE:	encode_op_ObjectIdentifier

PURPOSE:


IN:
	blist - list of bytes to be added to
	value - pointer to oid structure

OUT:
	blist - list with encoded bytes added


CALLED ROUTINES:
	

	
MODIFICATION HISTORY:
8/15/90 - jag
	Converted for use in the preprocessor

*/

#include <elros/enc_dcd.h>
 
void encode_op_ObjectIdentifier( bytearray &blist, struct opoid_skeleton *value )
{
   int i,m,n;
   long *mp,*np;
   long j,*ip;
   unsigned char 	*dataptr,
			*endptr,
			*oid_bytes;
   
   np = 0;  /* keep C++ quiet. */

   					/* Get space for oid bytes 	*/
   if( !(np = (long *)malloc((unsigned)(value->size) * sizeof(*np)) ))
      nomem();
   
					/* Find out how many bytes are needed */
    for(i = n = 0, ip = (long *)value->comp, mp = np; i < value->size; i++, ip++ )
    {
 
	if( ip == (long *)value->comp )
	    j = *ip++ * 40, i++, j+= *ip;
	else
	    j = *ip;

	m = 0;
	do 
	{
	    m++;
	    j >>= 7;
	} while ( j );
	n += (int)(*mp++ = m);
    }


    encode_op_length( blist, &n );


    if( !(oid_bytes = (unsigned char *)malloc( (int)n )) )
       nomem();

    dataptr = oid_bytes;
    for( i = 0, ip = (long *)value->comp, mp = np; i < value->size; i++, ip++ )
    {

 	if( ip == (long *)(value->comp ) )
	    j = *ip++ * 40, i++, j += *ip;
	else
	    j = *ip;

	endptr = dataptr + (m = (int)(*mp++)) - 1;
	for( dataptr = endptr; m-- > 0; j >>= 7 )
	    *dataptr-- = (char)((j & 0x7f) | 0x80);
	*endptr &= ~0x80;

	dataptr = endptr + 1;
    }


	/* Send the data */

   for (i=0; i<n; i++)
      blist.append(new singlebyte(oid_bytes[i]));


   free( (char *)oid_bytes );
   free( (char *)np );


}


/*
	ROUTINE:	encode_op_length	

PURPOSE:


IN:
	blist - byte array to be added to
	length - pointer to length value to encode

OUT:
	blist - list with encoded bytes added


CALLED ROUTINES:
	

	
MODIFICATION HISTORY:
8/15/90 - JAG
	Converted for use in preprocessor

*/

#include <elros/enc_dcd.h>

static unsigned int high_byte = 0xff << ( (sizeof(unsigned int) - 1) * 8);

void encode_op_length( bytearray &blist, int *length )


    {

    unsigned int mask;
    int i;


					/* if the length is less than 128,
					   write the length byte and return */
   if(*length < ASN_LEN_SMAX)
   {
      blist.append(new singlebyte(*length & 0xff));
      return;
   }

					/* if the length is greater than 127,
					   write it out a byte at a time */

    mask = high_byte;

    for(i = sizeof(unsigned int) - 1; i >= 0; i--)
      {

      if((*length & mask) != 0)
	{
	break;
	}

      mask = mask >> 8;

      }


    blist.append(new singlebyte( (i + 1) | ASN_LEN_XTND));

    for(; i>= 0; i--)
      {
      blist.append(new singlebyte( (*length & mask) >> (i*8) ));
      mask = mask >> 8;
      }

}

/* end of encode_op definitions */
/* constant_generator definitions */

void constant_generator::add_encoding(type_element *t)
{
   char description[64];

   sprintf(description,"Type '%s'", t->get_name());
   if (t->get_rules_ptr())
      t->encode(constant_bytes,description);
}

void constant_generator::add_encoding(name_element *n)
{
   char description[64];

   sprintf(description,"Name '%s'", n->get_name());
   if (n->get_type_element_ptr()->get_rules_ptr())
      n->get_type_element_ptr()->encode(constant_bytes,description);
}

void constant_generator::generate(FILE *out)
{

	/* Put out __ROe_xxx_constant */

   if (!constant_bytes.isempty())
   {
      constant_bytes.generate(out,ieptr->constant_table_name);
   }

}
/* end of constant_generator definitions */
/* other definitions */

void dump_interfaces(interface_list* il)
{
    link *tmplinkptr;
    int count = 0;
    il->reset();
    while (il->next(tmplinkptr)) {
       count++;
       fprintf(yyout,"Interface:");
       fprintf(yyout,"%s\n",((interface_element*) tmplinkptr)->get_name());
       ((interface_element*)tmplinkptr)->dump_ops(1);
       ((interface_element*)tmplinkptr)->dump_types(1);
       ((interface_element*)tmplinkptr)->dump_names();
       ((interface_element*)tmplinkptr)->dump_variables();
    }
    if (count == 0)
       fprintf(yyout,"There are no Interfaces\n");
}

void dump_primitive_types(list* ll)
{
    link *tmplinkptr;
    int count = 0;
    ll->reset();
    fprintf(yyout,"primitive types:\n");
    while (ll->next(tmplinkptr)) {
       count++;
       ((abstr_type_element *) tmplinkptr)->p_abstr_type(1);
    }
    if (count == 0)
       fprintf(yyout,"There are no primitive types\n");
}

void dump_instances(symbol_list* sl)
{
    link *tmplinkptr;
    if (sl == NULL || sl->length() == 0) 
	fprintf(yyout,"|  there are no instances\n");
    else {
       sl->reset();
       while (sl->next(tmplinkptr))
	  {
	  fprintf(yyout,"instance:\n");
	  ((instance_element *) tmplinkptr)->p_instance(1);
       }
    }
}

void dumpnamebuf()
{
    int i;
    fprintf(yyout,"the character buffer follows:\n");
    if (namebufptr == NULL)
       fprintf(yyout,"the character buffer is empty\n");
    else {
       for (i=0;i<NAMEBUFSIZE;i++)
	  if (namebufptr[i] == '\0')
	     fprintf(yyout,"0");
	  else
	     putc(namebufptr[i],yyout);
       fprintf(yyout,"the end of the character buffer\n");
    }
}
