#!/usr/bin/perl

use warnings;
use strict;

{
    my $n          = shift () || 1;
    my $do_all     = shift ();
    my $skip_print = shift ();

    my @tps = start_tps ( $n );

    while ( 1 ) {
        print_parens ( @tps ) if ! $skip_print;
        @tps = next_tps ( @tps );
        if ( not defined $tps[0] ) {
            last if not $do_all;
            @tps = start_tps ( ++$n );
        }
    }
}

sub start_tps {
    my ( $n ) = @_;
    return map { (2 * $_)-1 } 1..$n;
}

sub next_tps {
    my @tps = @_;

    foreach ( 0 .. scalar @tps - 2 ) {
        if ( $tps[$_] < $tps[$_+1] - 1 ) {
            ++$tps[$_];
            @tps[0..$_-1] = start_tps ( $_ );
            return @tps;
        }
    }
    return undef;
}

sub print_parens {
    my @tps = @_;
    my @parens = map { '(' } 1 .. 2*(scalar @tps);
    $parens[$_] = ')' foreach @tps;
    printf "%d: %s\n", scalar @tps, join "", @parens;
}

