#!/usr/bin/perl

use warnings;
use strict;
my %ref;
my $ref=\%ref;
my %strong;
my $strong=\%strong;
my ($type, $add)=("","");
my $glist0="";
my $glist="";
my @list_sort=();
my $list_to_sort="";
for my $file (glob("*/*/*/*")) {
  open(IN, $file) ;
  $glist .= "$file\n" if !($file=~/_\d\b/) && !($file=~/\/macro\//);
  while (<IN>) { my $line = $_;
    if ($line=~ /<strong>([^<]+)<\/strong>/) { $strong{$1} .= " $file"};
    next if !($line =~ /gl_keywords=/ || $line =~ /gl_type=/) ;
    $type=$1 if($line=~/gl_type=(.*)/);
    $add =$1 if($line=~/!set gl_keywords=(.*)/);
    chomp $add; chomp $type;
    next if ($type=~ /dynamic/);
    @list_sort=split('/', $file);
    $list_to_sort .= "$list_sort[0],$list_sort[1],$list_sort[3],$list_sort[2]\n";
  }
  $type='main' if !($type);
  $ref{$add} .= "$file/$type " if ($add);
  $type=""; $add="";
};

@list_sort=sortuniq(split("\n",join("\n", sortuniq(split("\n",$list_to_sort)))));
$glist="";
for my $line (@list_sort){
  if($line) {
    my @l=split(',', $line);
    $glist .= "$l[0]/$l[1]/$l[3]/$l[2]\n";
  }
}

my $Text="generated by mkindex.pl\n\n";
while (my ($key, $value) = each(%ref) ) {
  my $s= join(",",sortuniq(split(' ', $value)));
  $Text .= $key . ":" . $s . "\n" ;
}
out("connexe_domain",$Text);

$Text="";
while (my ($key, $value) = each(%strong) ) {
  my $s= join(",",sortuniq(split(' ', $value)));
  $Text .= $key . ":" . $s . "\n" ;
}
out("strong_index",join("\n",sortuniq(split("\n",$Text))));
out("glist",$glist);

sub sortuniq {
  my $prev = "not $_[0]";
  grep { $_ ne $prev && ($prev = $_, 1) } sort @_;
}

sub out { my ($bloc, $text) = @_;
  open  (OUT, ">$bloc") ;
  print OUT $text ; close OUT;
}
