#!/bin/sh
#############################################################################
#
# raster2shp.sh
#
# SCRIPT:   	convert maps to shp
# AUTHOR(S):	Paolo Zatelli - 2008/04/27
# PURPOSE:  	converts all the *raster* maps in a directory tree, according
#		to a pattern, to ESRI Shapefile (with point features)
#		with the name of the directory they are found in.
#
# REQUIREMENTS	it must run in a GRASS shell
#
# COPYRIGHT:	2008 Paolo Zatelli
# LICENSE:	GPL 2.0 or (at your option) any later version
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#############################################################################
echo "Looks for files, according to a pattern, in the directory tree and converts all the raster"
echo "maps to ESRI Shapefile (with point features) with the name of the directory they are found in."

# patter of the file to be converted
file_pattern='w001001.adf'
#file_pattern='*.adf'

# directory where the Shapefile are saved, absolute or relative (to the current directory) path
outdir="./"

# nothing to modify below this line

#check for GRASS shell
if test "$GISBASE" = ""; then
 echo "You must be in GRASS GIS to run this program." 1>&2
 exit 1
fi

find . -name $file_pattern | while read FILE
do
	# extract the upper level directory name the file is in:
	# the path string is reversed, the first field up to '/' is taken
	# and the result is reversed back to the original order
	map_name=`dirname "$FILE"| rev | cut -d '/' -f1 | rev`

	echo "creating map: $map_name importing file file $FILE"

	# GRASS work starts here
	# variables are:
	# $FILE -> name of the file to be imported (with full path);
	# $map_name -> name of the directory (just the directory name, not the complete path) where the file resides.

	# importing
	r.in.gdal in=$FILE out=$map_name

	# set region to the map
	g.region rast=$map_name

	# raster to vector
	# maps' names are the same, but input is a raster map, output is vector
	r.to.vect input=$map_name output=$map_name feature=point 

	# export as shape
	v.out.ogr input=$map_name type=point dsn=$outdir olayer=$map_name layer=1 format=ESRI_Shapefile 

	# cleanup
	g.remove rast=$map_name
	g.remove vect=$map_name

done

