#perl -w

use strict;
use File::Stat;

my $UPDATE = 0;
my $CLEAN = 0; # Get rid of old/erroneous/extra dxf files!

my $TILESIZE = 1000;
my $RESOLUTION = 0.40;

my $xmlfmt =
q(<?xml version="1.0" encoding="ISO-8859-1"?>

<OcadScript>
  <File.New>
    <File>c:\Program Files\OCAD\OCAD 2018 Mapping Solution\Symbol\Orienteering Map ISOM 2017 10 000.ocd</File>
  </File.New>

  <File.SaveAs>
    <File>C:\data\Orientering\GeoNorge\%s\%s</File>
  </File.SaveAs> 

   <File.Import.Dxf>
    <Directory>C:\data\Orientering\GeoNorge\%s</Directory>
    <NewOffset>true</NewOffset>
    <Angle>0.0</Angle>
  </File.Import.Dxf>

  <Map.ConvertLayer>
    <CrtFile>C:\data\Orientering\fkb_2017_mapant.crt</CrtFile>
  </Map.ConvertLayer>

  <Map.OptimizeRepair>
    <Enabled>true</Enabled>
  </Map.OptimizeRepair>
  
  <Map.ScaleAndCoordinateSystem>
	<CoordinateSystem>2033</CoordinateSystem>
  </Map.ScaleAndCoordinateSystem>

  <View.EntireMap>
	<Enabled>true</Enabled>
  </View.EntireMap>
  
  <View.Mode>spotColorMode</View.Mode>

  <!-- Select all power lines -->
  <Select.ObjectsBySymbol>
		<SymbolNumber>510.000</SymbolNumber>
		<SymbolNumber>511.000</SymbolNumber>
  </Select.ObjectsBySymbol>
	
  <Object.ChangeVertexTypesTo>
		<Type>CornerVertex</Type>
  </Object.ChangeVertexTypesTo>	
	
  <!-- Select all railroads, fill background with impassable area symbol -->
  <Select.ObjectsBySymbol>
		<SymbolNumber>509.000</SymbolNumber>
  </Select.ObjectsBySymbol>	
	
	<Object.Fill>		
		<SymbolNumber>509.001</SymbolNumber>
	</Object.Fill>	
	
  <!-- create 415 boundary around 412 Cultivated land -->
  <Select.ObjectsBySymbol>
		<SymbolNumber>412.000</SymbolNumber>
  </Select.ObjectsBySymbol>	
	
	<Object.Fill>		
		<SymbolNumber>415.000</SymbolNumber>
	</Object.Fill>	
	
	<!-- clear selection -->
	<Select.ObjectsBySymbol>
    </Select.ObjectsBySymbol>	
  
  <File.Save>
    <Enabled>true</Enabled>
  </File.Save>
  
  <File.Export>
	<File>C:\data\Orientering\GeoNorge\%s\%s</File>
	<Format>GIF</Format>
	<Resolution>%1.0f</Resolution>
	<Anti-Aliasing>true</Anti-Aliasing>
	<ColorCorrection>true</ColorCorrection>
	<Tiles>
	  <Enabled>true</Enabled>
	  <Width>%1.0f</Width>
	  <Height>%1.0f</Height>
    </Tiles>
	<PartOfMap>
	  <L>%s</L>
	  <B>%s</B>
	  <R>%s</R>
	  <T>%s></T>
	</PartOfMap>
	<GeoRef>
		<Enabled>true</Enabled>
		<PixelSize>%f</PixelSize>
		<CreateWorldFile>true</CreateWorldFile>
	</GeoRef>
  </File.Export>
  
  <File.Save>
    <Enabled>true</Enabled>
  </File.Save>
  
  <File.Save>
    <Enabled>false</Enabled>
  </File.Save>
  
   <File.Close>
    <Enabled>true</Enabled>
  </File.Close>

  <File.Exit>
    <Enabled>true</Enabled>
  </File.Exit>
</OcadScript>);

sub dodir
{
	my ($dir) = @_;
	
	my $xmlname = "fkb_".$dir.".xml";
	my $ocadname = $dir."_fkb.ocd";
	my $pngname = $dir."_fkb.gif";
	
	if ($CLEAN) {
		my $unlink = 0;
		opendir(D, $dir);
		foreach (readdir(D)) {
			next unless (/\.dxf$/i);
			next if (/^33N\d/);
			printf("del %s\\%s\n", $dir, $_);
			unlink($dir."/".$_);
			$unlink++;
		}
		closedir(D);
		exit if ($unlink);
	}

	if ($UPDATE) {	# Check input and output file dates: Are any updates needed?
		opendir(D, $dir);
		my @sourcefiles = readdir(D);
		closedir(D);
		my $lastupdate = 0;
		foreach (@sourcefiles) {
			my $fn = $dir.'/'.$_;
			my $st = stat($fn);
			if ((/\.dxf$/i) && (my $t = $st->mtime) > $lastupdate) {
				$lastupdate = $t;
			}
		}
		return -1 unless ($lastupdate); # No files found!
		my $ot = stat($ocadname);
		my $pt = stat($pngname);
		if (defined($ot) && defined($pt) && 
			$ot->mtime < $lastupdate &&
			$pt->mtime < $lastupdate) {
			return 0;	# No update needed!
		}
	}
	
	# Check min/max extent
	opendir(D, $dir); my @dxffiles = readdir(D); closedir(D);
	my ($xmin,$ymin,$xmax,$ymax) = (1e38,1e38,-1e38,-1e38);
	foreach (@dxffiles) {
		next unless (/\.dxf$/);
		open(F, '<', $dir.'/'.$_);
		my $buffer;
		sysread(F, $buffer, 200);
		close(F);
		$buffer =~ s/\r//g;

		next unless($buffer =~ /\$EXTMIN\n10\n([\d\.\-]+)\n20\n([\d\.]+)\n/);
		if ($buffer =~ /\$EXTMIN\n10\n([\d\.]+)\n20\n([\d\.]+)\n9\n\$EXTMAX\n10\n([\d\.]+)\n20\n([\d\.]+)\n/) {
			my ($x0,$y0,$x1,$y1) = ($1,$2,$3,$4);
			$xmin = $x0 if ($x0 < $xmin);
			$ymin = $y0 if ($y0 < $ymin);
			$xmax = $x1 if ($x1 > $xmax);
			$ymax = $y1 if ($y1 > $ymax);
		}
	}
	die("DXF extents missing!") unless ($xmax > $xmin && $ymax > $ymin);

	$xmin = int($xmin/$TILESIZE)*$TILESIZE;
	$ymin = int($ymin/$TILESIZE)*$TILESIZE;
	$xmax = (int(($xmax-0.1)/$TILESIZE)+1)*$TILESIZE;
	$ymax = (int(($ymax-0.1)/$TILESIZE)+1)*$TILESIZE;

	open(X, '>', $xmlname) || die("Could not write to $xmlname");

	my $WIDTH = $TILESIZE / $RESOLUTION;
	printf(X $xmlfmt, $dir, $ocadname, $dir, $dir, $pngname, 254 / $RESOLUTION, $WIDTH, $WIDTH, $xmin, $ymin, $xmax,$ymax, $RESOLUTION);
	close(X);
	my $cmd = q("c:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" ).$xmlname;
	printf(STDERR "%s\n", $cmd);
	my $res = `$cmd`;
	
	# Run OCAD once more to clean up the working file:
	$cmd = q("c:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" );
	my $r2 = `$cmd`;
	return 1;	# TRUE, new files created. :-)
}


my $dir = shift;
dodir($dir);
