#!/usr/bin/perl -w

# (c) Copyright by Tels 1999. All Rights Reserved.
# 1999-11-12 v0.0.2 - from genmap
# 2000-04-23 v0.0.3 - adapted to new methods and Report.pm
#                     commandline parsing,
# 2000-05-22 v0.0.4 - hotregions/multibrushes

# from bunch.pm:
#   autoRoom sometimes generates the room around the wrong brush. If you have a small
#   air brush inside a larger air brush (for carpet or wall texturing), but the small
#   brush comes earlier, then autoRoom will generate a room around it, and later skip
#   the room around the larger because this would create nested rooms. It should prefer
#   the larger brush over the smaller one, tough. This is only important if brushes have
#   no mnoroom()/mroom() like when you suck in a mission file.
#   to be fixed sometime

use Cowgen::Bunch;  # for a bunch of brushes
use Cowgen::Report 
  qw(checkRooms checkObjects checkBrushes); # for various checks/fixes/reports
use Cowgen::Dromed; # for some Thief constants and specifics
use Cowgen::Texture;
use Cowgen::Gamfile;
use Cowgen::Config qw(loadConfig);
use Cowgen::Vbr;
use strict 'vars';

my $VERSION = 0.04;
my $time = time;

print "Check'n'Fix v$VERSION Report problems and fix mission files\n";
print "(c) Copyright by Tels 1999-2000. All Rights Reserved.\n\n";
print " Usage:     perl chknfix [-flags] infile [outfile]\n";
print " Flags:     fConfig      use alternative Config file\n";
print "            c            check only, do not fix\n";
print "            gGamfile     use alternative Gamfile\n";
print "            rReport      output report to this file\n";
print "            o            overwrite outfile if it exists\n";
print " Examples:  -fmy.cfg -dr Miss15.mis norooms.mis\n";
print "            -rreport.txt bad.mis fixed.mis\n";
print " See config/chknfix.cfg for more options.\n\n";

print "Warning: !! Read doc/chknfix.txt !!\n\n";

my (%params,$vbr);
my ($p,@p);
undef $params{f}; $params{c} = 0; $params{o} = 0; undef $params{g}; 

my $files = get_commandline(\%params,@ARGV);
my $infile = $files->[0]; my $outfile = $files->[1];
# fix commandline parameter
$infile = "bad15.mis" if (!defined $infile);
$outfile = "data/fixed.mis" if (!defined $outfile); 
$infile .= ".mis" if (($infile !~ /\.mis$/) && (!-e $infile));

# get configuration
my $cfg = loadConfig( $params{f} || "config/chknfix.cfg" );
my $e = $cfg->{mindistance}; $e = 0.05 if (!defined $e);
my $report = $cfg->{reportfile} || "";
my $gridsize = $cfg->{gridsize} || 0;
my $fix = (1-$params{c}) || $cfg->{dofix} || 0;
my $gamefile = $params{g} || $cfg->{gamfile}; # default is to take mission file

$vbr = Cowgen::Vbr->create($infile); # read container
print "Using file ",$vbr->template(),"\n";
my $gf = Cowgen::Gamfile->create( $gamefile || $vbr->gamesysName()); 
my $rep;

if (!$vbr->isDefined("BRLIST")) 
  {
  $rep = "\nCant generate report at $infile, it does not contain brushlist.\n"; 
  exit 2;
  }

# bunch from binary
my $bunch = Cowgen::Bunch->create( "$infile", $vbr, $gf);

# check/fix/report phase
$rep = "Report on Bunch ".$bunch->name();
$rep .= ".\nGenerated at ".scalar localtime()." by ChknFix $VERSION\n\n";
$rep .=  "$bunch->{name} contains:\n $bunch->{brushes} brushes,";
$rep .= " $bunch->{rooms} rooms,"; 
$rep .= " $bunch->{flows} flows,"; 
$rep .= " $bunch->{areas} areas,"; 
$rep .= " $bunch->{lights} brush lights"; 
$rep .= " and ".$bunch->numObjects()." objects in"; 
$rep .= " $bunch->{groups} groups.\n\n";
$rep .= " Notes: For objects/groups/areas the value listed is the object ID, it is\n";
$rep .= "        displayed by DromEd surrounded by () after the object name.\n";
$rep .= "        For brushes the time value is listed. This is displayed by DromEd\n";
$rep .= "        in the lower left corner right beside 'Time:'.\n";
$rep .= "        For faulty rooms all the non-existent base rooms are listed.\n";

# print areas/multibrushes
my $hr = $vbr->hotRegions();
$rep .= "\nList of area brushes (hot regions):\n";
foreach (keys %$hr)
  {
  $rep .= " $hr->{$_} ($_)\n";
  }
$hr = $vbr->multibrushes();
$rep .= "\nList of groups (multibrushes):\n";
foreach (keys %$hr)
  {
  $rep .= " $hr->{$_} ($_)\n";
  }

if (!$vbr->isDefined("TXLIST"))
  {
  $rep .= "\nNo texture list present, checks for rendundant textures disabled.\n";
  }
else
  {
  $rep .= "\nTexture list present, loading:\n";
  my $txt = Cowgen::Texture->create( $vbr->texturePalette() );
  $rep .= " Contains ".$txt->numTextures()." textures.\n";
  # get hash with number => 'family/name' mapping
  my $txthash = $txt->asHash();
  # put back in
  $vbr->texturePalette ( $txthash );
  }
print "Checking rooms, ";
checkRooms($bunch,$fix,$gridsize,$e,\$rep);
print "objects, ";
checkObjects($bunch,$fix,$gridsize,$e,\$rep);
print "brushes.\n";
checkBrushes($bunch,$fix,$gridsize,$e,\$rep);

# write out 
if ($fix != 0)
  {
  print "Writing fixed file to $outfile\n";
  $vbr->saveMission($gf,$bunch,$outfile);
  }

# EOF
1;

END
  {
  # write report
  if ($report ne "")
    { 
    print "Writing report to '$report'.\n";
    open FILE, ">$report" or die "Cant write $report: $!\n";
    print FILE $rep;
    close FILE;
    }
  else
    {
    print "No report file specified, suppressing report.\n";
    }
  my $seconds = time - $time;
  print "\nAll done. Took $seconds seconds. ALPHA! Check output carefully!\n";
  }

##########################################################################

sub get_commandline
  {
  # get commandline parameter(s), return in $params the params and as 
  # array the files
  my ($params,@ARGV) = @_;
  my $cmds = 'gd'; # switches with params (except s)
  my $files = []; 
  foreach (@ARGV)
    {
    if ($_ =~ /^\-/)
      {
      $_ =~ s/^\-//;
      if ($cmds =~ substr($_,0,1))
        {
        $params->{substr($_,0,1)} = substr($_,1,length($_)-1) || "";
        }
      else
        {
        @p = split //,$_;
        foreach $p (@p) { $params->{$p} = 1; }
        }
      }
    else
      { 
      push (@$files, $_);
      }
    }
  $files;
  }
