#!/usr/cogent/bin/gamma

/*
 * The syntax of Gamma is very similar to C.  Programmers familiar with C
 * will find they can immediately start programming in Gamma.  This first
 * example program demonstrates the basic similarities between Gamma and
 * the C language, and some important differences which highlight the
 * power of Gamma.
 *
 * This file is best viewed with a tab width of 4.
 *
 * This program prints a personalized "Hello world" message repeatedly.
 *
 * Demonstrates:
 *		variable naming
 *		function definitions and basic control structures
 *		command line arguments
 *		QNX usage messages
 */

/*
 * Gamma ships with a number of canned library routines which can be
 * included using the 'require' and 'require_lisp' functions.  Since
 * Gamma implements the underlying SCADALisp lisp interpreter as well
 * as the Gamma language, it is possible to read files created for
 * either language.
 *
 * The Usage library implements a few simple functions for dealing
 * with QNX_style usage messages.  You can get help on a Gamma program
 * by using the 'use' command at the QNX prompt.
 */

require_lisp ("Usage");

__USAGE = "
#define __USAGE
#%C [name [repeat-count]]
#
#    This program prints a message saying hello to the given name for
#    repeat-count iterations.
#endif
";

/*
 * This function iterates, saying hello to the given name.  In Gamma,
 * all functions return a value, which is the result of the last
 * evaluated expression in the function.  In this case, we return
 * the string "ok".
 */

function say_hello (name, n)
{
	local		i;
	
	for (i=0; i < n; i++)
		princ ("Hello ", name, "\n");
	"ok";
}

/*
 * A program may optionally have a function main() declared, in which
 * case Gamma will execute the main function after all of the program
 * file has been read in.  If no main() exists, then the programmer
 * must explicitly call a function or enter an event loop at some point
 * while reading the file.  Any code which is not a function definition
 * will be automatically run AS THE FILE IS READ.  This is useful
 * for providing feedback to the user while loading.
 */

function main ()
{
	/*
	 * Define some locally scoped variables.  Notice that Gamma
	 * implements abstract data typing, so it is not necessary to
	 * declare the variable type.
	 */
	
	local repeat = 1, name = "world";
	
	/*
	 * Access the command line arguments.  argv is a list of the command
	 * line arguments, as strings, where the first argument is the
	 * program name.
	 */

	// The second argument (cadr(argv)) is the name, if present
	if (cadr (argv))
		name = cadr (argv);

	// The third argument (caddr(argv)) is the number of iterations,
	// if present
	if (caddr (argv))
		repeat = number (caddr (argv));

	// now print the message
	result = say_hello (name, repeat);
	
	// print the result
	princ (result, "\n");
}
