#!/usr/bin/perl
# Generate GRASS 5.7 ascii file containing random closed polygons
# Generated vector may be used for tests of v.clean 

$gisdbase = `g.gisenv get=GISDBASE`;
$location_name = `g.gisenv get=LOCATION_NAME`;
$mapset = `g.gisenv get=MAPSET`;

chomp ($gisdbase); chomp ($location_name); chomp ($mapset);

$loc = "$gisdbase/$location_name/$mapset";

$npoly = 100;     # number of polygons
$size = 0.1;    # maximum size of polygon as a portion of region 
$nseg = 50;     # number of segments in polygon

for($i=0; $i<=$#ARGV; $i++){
  if( $ARGV[$i] =~ /npoly=(.+)/){ $npoly = $1;  }
  elsif( $ARGV[$i] =~ /size=(.+)/){ $size = $1;  }
  elsif( $ARGV[$i] =~ /nseg=(.+)/){ $nseg = $1;  }
}

$ymax = `g.region -g | grep ^n= `; chomp $ymax; $ymax =~ s/n=(.*)/$1/;
$ymin = `g.region -g | grep ^s= `; chomp $ymin; $ymin =~ s/s=(.*)/$1/;
$xmax = `g.region -g | grep ^e= `; chomp $xmax; $xmax =~ s/e=(.*)/$1/;
$xmin = `g.region -g | grep ^w= `; chomp $xmin; $xmin =~ s/w=(.*)/$1/;

# Center 
$xc = ($xmax + $xmin) / 2;
$yc = ($ymax + $ymin) / 2;

# Smaller size of region
$dx = $xmax - $xmin;
$dy = $ymax - $ymin;
if ( $dx < $dy ) { $dmin = $dx;} else { $dmin = $dy;}

# Minimum and maximum radius of polygons
$maxsize = $dmin * $size;
$minsize = $maxsize * 0.7;

# Minimum and maximum radius of centers of polygons
$rcmax = $dmin / 2 - $maxsize; 
$rcmin = $rcmax * 0.2;

$fascii = "$loc/dig_ascii/clean.test";
mkdir "$loc/dig_ascii/";
open(ASCII, ">$fascii") or die "Cannot open: $fascii\n"; 

print ASCII  "ORGANIZATION: GRASS Development Team
DIGIT DATE:   1/9/2002
DIGIT NAME:   -
MAP NAME:     clean test
MAP DATE:     2002
MAP SCALE:    10000
OTHER INFO:   Random closed polygons
ZONE:         0
MAP THRESH:   0.500000
VERTI:\n";      

for ( $i = 0; $i < $npoly; $i++ ) {
    # random center of polygon
    $ang = rand ( 6.28318 );
    $r = rand ( $rcmax - $rcmin ) + $rcmin;
    $xpc = $xc + $r * cos ( $ang );
    $ypc = $yc + $r * sin ( $ang );

    $np = $nseg + 1;
    print ASCII "A $np\n";

    $dang = 6.28318 / $nseg;
    for ( $j = 0; $j < $np; $j++ ) {
        if ( $j > 0 and $j < $np - 1 ) {
	    $ang = $dang * $j;
            $r =  rand ( $maxsize - $minsize ) + $minsize;
        } else {
	    $ang = 0;   # last point
            $r = ($maxsize + $minsize) / 2; 
        }
	$x = $xpc + $r * cos ( $ang );
	$y = $ypc + $r * sin ( $ang );
	print ASCII " $y  $x\n";      

    }
}

close ASCII;

