+my @report_lines;
+my @report_labels;
+
+my $label;
+my $sub_labels;
+open(my $report, '<:encoding(utf-8)', 'AZVO.txt');
+while( <$report> ) {
+ chomp;
+ if ( /^([^\t]+)\t+(.+)/ ) {
+ $label = $1;
+ push @report_labels, $label;
+ my $type = [ map { m/\s+/ ? [ split(/\s+/,$_) ] : [ $_, 'aut' ] } split (/\s*\+\s*/, $2) ];
+ push @report_lines, [ $label, @$type ];
+ } elsif ( /^\t+([^\t]+):\t+(\d+)(\w*)\t*(.*)$/ ) {
+ push @{ $sub_labels->{$label} }, [ $1, $2, $3, $4 ];
+ my $sub_label = $1;
+ pop (@report_labels) if ( $report_labels[ $#report_labels ] =~ m/^$label$/ ); # remove partial name
+ push @report_labels, $label . $sub_label;
+ } else {
+ die "ERROR: [$_]\n";
+ }
+}
+
+debug 'report_lines', \@report_lines;
+debug 'sub_labels', $sub_labels;
+debug 'report_labels', \@report_labels;
+
+my @departments = ( sort { lc($a) cmp lc($b) } keys %$azvo_stat_biblio );
+
+debug 'departments' => \@departments;
+
+my $department2col;
+$department2col->{ $departments[$_] } = $_ foreach ( 0 .. $#departments );
+my $label2row;
+$label2row->{ $report_labels[$_] } = $_ foreach ( 0 .. $#report_labels );
+
+my $table;
+
+sub table_count {
+ my $label = shift @_;
+ my $department = shift @_;
+ my $group = shift @_;
+ my @biblionumbers = @_;
+ my $unique;
+ $unique->{$_}++ foreach @biblionumbers;
+ my @bibs = keys %$unique;
+ $table->{ffzg}->{$group}->[ $label2row->{ $label } ]->[ $department2col->{$department} ] = scalar @bibs;
+ $table->{external}->{$group}->[ $label2row->{ $label } ]->[ $department2col->{$department} ] = scalar grep { $biblio_author_external->{$_} } @bibs;
+}
+
+foreach my $group ( '', keys %$azvo_group_title ) {
+
+foreach my $department ( @departments ) {
+ foreach my $line ( @report_lines ) {
+ my $label = $line->[0];
+ my @biblionumbers;
+ foreach ( 1 .. $#$line ) {
+ my ( $category, $type ) = @{ $line->[ $_ ] };
+ my $b = $azvo_stat_biblio->{ $department }->{$category}->{$type}->{$group};
+ push @biblionumbers, @$b if $b;
+ }
+ if ( $sub_labels->{$label} ) {
+ my $sub_stats;
+ foreach my $biblionumber ( @biblionumbers ) {
+ my $data = $biblio_data->{$biblionumber} || die "can't find biblionumber $biblionumber";
+ foreach my $sub_label ( @{ $sub_labels->{$label} } ) {
+ my ( $sub_label, $field, $sf, $regex ) = @$sub_label;
+ if ( ! $regex ) {
+ push @{ $sub_stats->{ $sub_label } }, $biblionumber;
+ last;
+ }
+ if ( $field < 100 ) {
+ if ( $data->{$field} =~ m/$regex/ ) {
+ push @{ $sub_stats->{ $sub_label } }, $biblionumber;
+ last;
+ }
+ } else {
+ if ( exists $data->{$field}->[0]->{$sf} && $data->{$field}->[0]->{$sf} =~ m/$regex/ ) {
+ push @{ $sub_stats->{ $sub_label } }, $biblionumber;
+ last;
+ }
+ }
+ }
+ }
+ foreach my $sub_label ( keys %$sub_stats ) {
+ my $full_label = $label . $sub_label;
+ table_count $full_label, $department, $group, @{ $sub_stats->{$sub_label} };
+ }
+ } else {
+ table_count $label, $department, $group, @biblionumbers;
+ }
+ }
+}
+
+} # group
+
+debug 'table', $table;