class List
	begin
		int value;  
		^List next;
	end

int freeNode = 0;
[ 20 ]List nodeHeap;

^List new( int value; ^List next; )
	begin
		^List node = nodeHeap[ freeNode++ ];
		node.value = value;
		node.next = next;
		return node;
	end

void printList( ^List a; ) 
	begin
		printf( "{ " );
		while a != null do
			printf( "%d", a.value );
			a = a.next;
			if a != null then
				printf( ", " );
			end
		end
		printf( " }" );
	end
	
void printlnList( ^List a; ) 
	begin
		printList( a );
		printf( "\n" );
	end

void displayInfo( ^char text; int level; ^List source1, source2, dest; )
	begin
		int i;
		for i = 0; i < level; i++ do
			print( "    " );
		end
		printf( "%s( %d, ", text, level );
		printList( source1 );
		printf( ", " );
		printList( source2 );
		printf( ", " );
		printList( dest );
		printf( " )\n" );
	end
	
void merge( int level; ^List source1, source2; ^^List dest; )
	begin
		displayInfo( "Enter merge", level, source1, source2, dest^ );
		if source1 == null then
			dest^ = source2;
		elif source2 == null then
			dest^ = source1;
		elif source1.value < source2.value then
			dest^ = new( source1.value, null );
			merge( level + 1, source1.next, source2, &dest^.next );
		elif source1.value > source2.value then
			dest^ = new( source2.value, null );
			merge( level + 1, source1, source2.next, &dest^.next );
		elif source1.value == source2.value then
			dest^ = new( source1.value, null );
			merge( level + 1, source1.next, source2.next, &dest^.next );
		end
		displayInfo( "Exit merge", level, source1, source2, dest^ );
	end
	
^List source1 =
	new( 1,
	new( 5,
		null ) );	
^List source2 =
	new( 2,
	new( 5,
	new( 7,
	new( 9,
		null ) ) ) );	
^List dest = null;
merge( 0, source1, source2, &dest );	// Inside this invocation
printlnList( source1 );
printlnList( source2 );
printlnList( dest^ );
