better handling of recursive definitions

diff --git a/libasn1compiler/asn1c_C.c b/libasn1compiler/asn1c_C.c
index a9aa23b..81ae971 100644
--- a/libasn1compiler/asn1c_C.c
+++ b/libasn1compiler/asn1c_C.c
@@ -1145,32 +1145,32 @@
 
 	p = MKID(expr->Identifier);
 	OUT("static ber_tlv_tag_t asn1_DEF_%s_tags[] = {\n", p);
-	INDENTED(
-		if(expr->tag.tag_class) {
+	INDENT(+1);
+	if(expr->tag.tag_class) {
+		tags_count++;
+		_print_tag(arg, expr, &expr->tag);
+		if(expr->tag.tag_mode != TM_EXPLICIT)
+			(*tags_impl_skip)++;
+	} else {
+		if(!choice_mode)
+			(*tags_impl_skip)++;
+	}
+	if(!choice_mode) {
+		if(!expr->tag.tag_class
+		|| (expr->meta_type == AMT_TYPE
+			&& expr->tag.tag_mode == TM_EXPLICIT)) {
+			struct asn1p_type_tag_s tag;
+			if(expr->tag.tag_class)
+				OUT(",\n");
+			tag.tag_class = TC_UNIVERSAL;
+			tag.tag_mode = TM_IMPLICIT;
+			tag.tag_value = expr_type2uclass_value[expr->expr_type];
+			_print_tag(arg, expr, &tag);
 			tags_count++;
-			_print_tag(arg, expr, &expr->tag);
-			if(expr->tag.tag_mode != TM_EXPLICIT)
-				(*tags_impl_skip)++;
-		} else {
-			if(!choice_mode)
-				(*tags_impl_skip)++;
 		}
-		if(!choice_mode) {
-			if(!expr->tag.tag_class
-			|| (expr->meta_type == AMT_TYPE
-				&& expr->tag.tag_mode == TM_EXPLICIT)) {
-				struct asn1p_type_tag_s tag;
-				if(expr->tag.tag_class)
-					OUT(",\n");
-				tag.tag_class = TC_UNIVERSAL;
-				tag.tag_mode = TM_IMPLICIT;
-				tag.tag_value = expr_type2uclass_value[expr->expr_type];
-				_print_tag(arg, expr, &tag);
-				tags_count++;
-			}
-		}
-		OUT("\n");
-	);
+	}
+	OUT("\n");
+	INDENT(-1);
 	OUT("};\n");
 
 	return tags_count;
diff --git a/libasn1compiler/asn1c_misc.c b/libasn1compiler/asn1c_misc.c
index 14a3649..2bdbd7c 100644
--- a/libasn1compiler/asn1c_misc.c
+++ b/libasn1compiler/asn1c_misc.c
@@ -85,8 +85,14 @@
 
 char *
 asn1c_type_name(arg_t *arg, asn1p_expr_t *expr, enum tnfmt _format) {
+	asn1p_expr_t *top_parent;
 	char *typename;
 
+	/* Rewind to the topmost parent expression */
+	if((top_parent = expr->parent_expr))
+		while(top_parent->parent_expr)
+			top_parent = top_parent->parent_expr;
+
 	switch(expr->expr_type) {
 	case A1TC_REFERENCE:
 		typename = expr->reference->components[
@@ -104,7 +110,9 @@
 
 			tmp.mod = tmp.expr->module;
 			return asn1c_type_name(&tmp, tmp.expr, _format);
-		} else if(_format == TNF_RSAFE) {
+		}
+
+		if(_format == TNF_RSAFE || _format == TNF_CTYPE) {
 			/*
 			 * The recursion-safe format is requested.
 			 * The problem here is that only constructed types
@@ -115,10 +123,13 @@
 			asn1p_expr_t *terminal;
 			terminal = asn1f_find_terminal_type_ex(
 				arg->asn, arg->mod, arg->expr);
-			if(terminal
-			&& (terminal->expr_type
-				& (ASN_BASIC_MASK | ASN_STRING_MASK)))
-				_format = TNF_CTYPE;
+			if(terminal) {
+				if(terminal->expr_type
+					& (ASN_BASIC_MASK | ASN_STRING_MASK))
+					_format = TNF_CTYPE;
+				if(terminal == top_parent)
+					_format = TNF_RSAFE;
+			}
 		}
 		break;
 #if 0