/*
 * Copyright (C) 2003-2018 Vladimir A. Smirnov
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <v_lib.h>
#include "cspace.h"
#include "eval.h"
#include "efunc.h"
#include "util.h"
#include "decomp.h"
#include "ipltrans.h"
#include "messages.h"
#include "istrings.h"

int main(int argc,char *argv[])
{
	CALLER_NAME(main)
	vhandle_t script;
	vboolean result = true;
	u32_t nbytes = 0, nbytes_out;
	logStartConsoleLog();
	logUpperLevel(LOG_INFO);
	if(argc != 2)
	{
		conPuts(ipl_usage);
		return -1;
	}
	if(STR_EQ(argv[1],"--help"))
	{
		conPuts(ipl_usage);
		goto normal_exit;
	}
	if(STR_EQ(argv[1],"--help-ipl"))
	{
		iplHelp();
		goto normal_exit;
	}
	if(STR_EQ(argv[1],"--help-nsl"))
	{
		conPuts("===============================\nNSL unary operations:\n");
		nslListUnaryOperations();
		conPuts("===============================\nNSL binary operations:\n");
		nslListBinaryOperations();
		conPuts("===============================\nNSL statements:\n");
		nslListStatements();
		goto normal_exit;
	}
	script = lexParseFile(argv[1],IPL_OPEN_BRACE IPL_CLOSE_BRACE \
		IPL_OPEN_BRACKET IPL_CLOSE_BRACKET IPL_COMMA IPL_SEMICOLON);
	if(script == LIBV_INVALID_HANDLE)
	{
		ERROR_GENERIC_2ARG(ipl_unable_to_open,argv[1]);
		return -1;
	}
	lexSetInteger(script,LEX_COMMENT_CHAR,IPL_COMMENT_CHAR);
	lexEnable(script,LEX_ONE_CHAR_COMMENTS);
	lexEnable(script,LEX_ALIAS_TRANSLATION);
	result = evalGlobals(script);
	if(result)
	{
		random_gen = ranCreateGenerator(random_seed);
		tic_start = timeTickCount();
		V_ASSERT(random_gen);
		result = evalTargets(script);
	}
	memStats(&nbytes,NULL,NULL);
	ranDestroyGenerator(random_gen);
	cspaceCollectGarbage();
	evalCollectGarbage();
	evalFreeFunctions();
	lexDestroy(script);
	iplFreeTransforms();
normal_exit:;
	logStopConsoleLog();
	memStats(&nbytes_out,NULL,NULL);
	printf(ipl_exit_status,
		result ? ipl_success : ipl_error, nbytes, nbytes_out);
	return (result) ? 0 : -1;
}
