#!/usr/bin/perl
# See http://www.openkore.com/wiki/index.php/Field_file_format
# for information about the file formats.
use strict;

my $i = 0;
foreach my $name (sort(listMaps("."))) {
	$i++;
	print "$i\t$name\n";
	gat2fld("$name.gat", "$name.fld");
}


sub listMaps {
	my ($dir) = @_;
	my $handle;

	opendir($handle, $dir);
	my @list = grep { /\.gat$/i && -f $_ } readdir $handle;
	closedir $handle;

	foreach my $file (@list) {
		$file =~ s/\.gat$//i;
	}

	return @list;
}


##
# void gat2fld(String gat, String fld)
#
# Convert a .GAT file to the specifid .FLD file.
sub gat2fld {
	my ($gat, $fld) = @_;
	my ($in, $out, $data);

	if (!open $in, "<", $gat) {
		print "Cannot open $gat for reading.\n";
		exit 1;
	}
	if (!open $out, ">", $fld) {
		print "Cannot open $fld for writing.\n";
		exit 1;
	}

	binmode $in;
	binmode $out;

	# Read header. Yes we're assuming that maps are never
	# larger than 2^16-1 blocks.
	read($in, $data, 14);
	print $out pack("v", unpack("V", substr($data, 6, 4)));
	print $out pack("v", unpack("V", substr($data, 10, 4)));

	while (read($in, $data, 20)) {
		my $type = unpack("C", substr($data, 16, 1));
			if ($type == 0 || $type == 3) {
				# Walkable water
				print $out pack("C", 0);
			} else {
				print $out pack("C", $type);
			}
	}

	close $in;
	close $out;
} 
