'===============================
'Loop SRFs export SHP contours.bas
'===============================
'Opens all SRF file in directory, loops though Plot objects to find contour maps,
'and exports those contour maps to SHP
'===============================
Sub Main

Debug.Clear

'Initialize Surfer
Dim Plot1, ContourLayer As Object
Set SurferApp = CreateObject("surfer.application")
SurferApp.Visible = True

'===============================
'User-defined variables
'===============================
file_extension	= "srf"
file_directory	= "C:\surfer\input\"
outpath = "C:\surfer\output\"
'===============================

'Make sure the file extension has no extra "." and the data directory has a trailing "\"
file_extension	= LCase(Right(file_extension,(Len(file_extension) - InStrRev(file_extension,"."))))
If  Len(file_directory)-InStrRev(file_directory,"\") <> 0 Then file_directory = file_directory + "\"

'Set the variable "srf_file" equal to each SRF file in the directory
srf_file = Dir( file_directory  + "*." + file_extension)

'While there are still SRF file in the directory that haven't been opened with this script...
While srf_file <> ""

	'Declare Plot as an object and open an SRF file
	Set Plot1 = SurferApp.Documents.Open(file_directory + srf_file)

	'Loop through all objects in the project
	For i = 1 To Plot1.Shapes.Count

		'If the object is a map frame...
		If Plot1.Shapes.Item(i).Type = srfShapeMapFrame Then

	    	'Loop through the items within the map frame
	        For j = 1 To Plot1.Shapes.Item(i).Overlays.Count

	        	'If the item is a contour map layer...
	            If Plot1.Shapes.Item(i).Overlays.Item(j).Type = srfShapeContourMap Then

	            	'Once you find a contour layer, get the naming convention set up
					Set ContourLayer = Plot1.Shapes.Item(i).Overlays.Item(j)

					'Save the contour layer name to a variable
					layer_name = ContourLayer.Name

					'Remove the file extension from the name
					layer_name	= Left(layer_name, Len(layer_name)-4)

					'Get the SRF Surfer project name, remove the extension, and add a dash
					srf_export_file	= Left(srf_file, Len(srf_file)-(Len(srf_file)-InStrRev(srf_file,".")+1) ) + "-"

					'Exports the contours to a 2D SHP file. File name is the SRF file name-Contour layer name.shp
					ContourLayer.ExportContours(FileName:=outpath + srf_export_file + layer_name + ".shp", Format:=srfConFormatShp2D)

	            End If
	        Next j
	   	End If
	Next i

	'Print the Surfer file name
	Debug.Print srf_file

	'Get next SRF file from the directory
	srf_file = Dir()

Wend

'Close Surfer
SurferApp.Quit

End Sub
