#!/usr/bin/perl -w
#
#  Little program to rebuild the plr_index file for ASCII pfiles.
#
#  It's not perfect by any means yet, and it blatantly shows off my
#  lack of skill with perl, but in general, it's better than just
#  saying "Ooops, involuntary pwipe."
#
#  It takes advantage of the fact that the ascii pfiles are given the
#  player's name.  If you've changed this, it won't work as-is.
#
#  The newly fixed index will probably need editing.  You'll have
#  some duplicate idnums, and probably a few other problems, but
#  nothing too major.
#
#  The only information lost is the flags saved in the index file.

# This is the full directory path up to and including the "pfiles" directory.
# Set as it is, it is meant to be run while you are in the lib directory.
$source_dir="pfiles";

sub handle_subdir  {
  #Build the index of files in this subdir.
  my ($dir) = @_;
  opendir(SDIR, $dir) || warn "can't opendir $dir: $!";
    my @files = grep {!/^\./} readdir(SDIR);
  closedir SDIR;

  #Go through the files one by one, get the real idnum, level, and last
  # and push them to the list.
  for my $i ( 0 .. $#files ) {
    stat("$dir/$files[$i]");
	next if not -f _;
	find_real_id($files[$i]);
    if ($id ne 0) {$data = sprintf("%d %s %d %s %d",$id,$files[$i],$lvl,$flags,$last); push @list, $data;}
  }
}

sub find_real_id($$) {
    my ($fname) = @_;
	my $dir=substr($fname,0,1);
	open(PLAYER,"<","$source_dir\/$dir\/$fname") or warn "Can't open $dir\/$fname for reading: $!";
	$flags = 0;
	while(<PLAYER>) {
	    if ($_ =~ m/^Levl: (\d+)/) { $lvl=$1; }
	    if ($_ =~ m/^Id  : (\d+)/) { $id=$1; }
	    if ($_ =~ m/^Last: (\d+)/) { $last=$1; }
    }
}

sub write_em() {
my $fixed_pfile = "$source_dir/plr_index.fixed";
open(NPFILE,">",$fixed_pfile) or die "Can't open fixed pfile ($fixed_pfile) for writing: $!";
	#Sort the index by idnum.
	#Yeah, this is disgusting looking.
	@players = sort { ($a =~ /^(\d+)\s/)[0] <=> ($b =~ /^(\d+)\s/)[0] } @list;
	for my $d ( 0 .. $#list ) {
	    print(NPFILE "$players[$d]\n") or die "Can't write to $fixed_pfile: $!";
	}
	print(NPFILE "~\n") or die "Can't write to $fixed_pfile: $!";
close NPFILE;
}

#  Start by building an index of the top level directories.  usually a-z, but never know.
opendir(DIR, $source_dir) || die "can't opendir $source_dir: $!";
  @toplevel = grep {!/^\./} readdir(DIR);
closedir DIR;

#  Now step thru them.
for $i ( 0 .. $#toplevel ) {
  stat("$source_dir/$toplevel[$i]");
  handle_subdir("$source_dir/$toplevel[$i]") if -d _;
}

#Now write the new player index.  It will be in the $source_dir, named
# plr_index.fixed
write_em();
