#!/usr/bin/perl -s

undef $/;

my $usage = "
  -c  removes result files
  -h  displays this help and exits
  -n  only reorders .dat files

";

if ($h) {print $usage;exit}

my (%file);

my $file;
for $file (<*.dat>)
{
  open(File,$file) || die;
  $file{$file} = <File>;
  close(File);
}
undef $file;

my $file_name;
unless ($n) {open(Index,">index") || die}
for $file_name (sort keys %file)
{
  my (@new_topics,@rnew_topics);
  my $new_file_name = $file_name;
  $new_file_name =~ s/\.dat$//;
  print Index "$new_file_name\n";
  if ($c)
  {
    unlink($new_file_name);
    next;
  }
  open(OldFile,">$file_name") || die;
  unless ($n) {open(NewFile,">$new_file_name") || die};
  my @topics = split(/\n%\n/,$file{$file_name});
  my $topic;
  for $topic (@topics)
  {
    push(@new_topics,trata_topico($topic));
  }
  print OldFile join("\n%\n",sort @new_topics);
  for $topic (sort @new_topics)
  {
    $topic =~ s/#\n/\n/;
    push(@rnew_topics,$topic);
  }
  undef $topic;
  print NewFile join("\n%\n",sort @rnew_topics) unless $n;
  close(OldFile);
  close(NewFile);
}
close(Index);
undef $file_name;

sub trata_topico {
  my $topic = $_[0];
  my $topic_name;
  $topic =~ s/(.*)\n/$topic_name = $1;""/e;
  if ($topic_name =~ /#$/)
  {
    $topic = "$topic_name\n$topic";
  }
  else
  {
    $topic = "$topic_name\n" . join("\n",sort(split(/\n/,$topic)));
  }
  return $topic;
}

unlink "index" if $c;
