/*-------------------------------------------------------------------------------

Hit ctrl-enter to execute.

Description:

	This script demonstrates how to read and write to files
	It opens the specified source file, reads every nth line, and
	writes the output to a desination file as named

	Copyright © 2001 Gatan Inc.

--------------------------------------------------------------------------------*/


// Specify the source and destination files 
string fileIn = "Component Example.s"						
string fileOut = "Junk.s"	

// Write the current directory path to a string						
string current_path = GetSpecialDirectory(2)

// Determine the line interval between writing out lines						
number everyNthLine = 4										

// Post an OK dialog asking for confirmation of the file transfer
// If cancel is clicked, exit 
if (!OKCancelDialog("Get every " + everyNthLine +       \
		"th from file "+fileIn +" and put into file " + fileOut+"?")) 		
	exit(0)	
																								
// Create variables to hold input and output file reference values
number in, out
												
// Try the following within parenthesis - if an error occurs, the program will proceed to 'Recover'
Try															
{
	// Open the specified source file using the current directory path
	// and create the destination file, in the current directory
	in  = OpenFileForReadingAndWriting(current_path + fileIn) 														
	out = CreateFileForWriting(current_path + fileOut)
	
	// Create a string variable to hold the read line, initialise the loop variable i,
	// and loop through the lines of the opened file. The commands within the while{} loop
	// will be executed while ReadFileLine returns true i.e. while there is text to be read	
	string line											
	number i=0												
	while ( ReadFileLine(in, line) )					
	{
		// Loop (everyNthLine - 1) times, reading out a new line each time; 
		// Note -1 included as an additional line is read in the while statement	
		for (i=0; i < everyNthLine-1; i++)					
			ReadFileLine(in, line)
		// Write the nth line to the destination file
		WriteFile(out, line) 								
	}
}

// Recover - where the script ends up regardless
Recover														
{
	// Close source and destination files if still open
	IF (in != 0) CloseFile( in ) 							
	IF (out != 0) CloseFile( out )
	
	// Finally, if the output file was not open, an error must have occurred so Throw an error with an appropriate message.						
	ELSE Throw("The operation could not be performed." + "\nEnsure the path " + current_path + filein + " is valid" )  	
							
}

