module linker;

import StdInt,StdFile,StdArray,StdBool,StdChar,StdString,StdClass;

import elf_linker,set_return_code;

/*
file_names = [
	"_startup0.o","_startup1.o","_startup2.o","_system.o","t.o","nfib.o"
];

library_file_names = [
	"kernel_library"
];
*/

/*
n_args :: Int;
n_args = code {
	ccall n_args "-I"
}

program_arg :: !Int -> {#Char};
program_arg i = code {
	ccall program_arg "I-S"
}

parse_arguments = program_arguments 1 n_args;
{
	program_arguments n n_args
		| n>=n_args
			= ([],[]);
		| size argument>=2 && argument.[0]=='-' && argument.[1]=='l'
			= (files1,[argument % (2,size argument-1):libraries1]);
			= ([argument:files1],libraries1);
		{}{
			argument=program_arg n;
			(files1,libraries1)=program_arguments (inc n) n_args;
		}
}
*/

import ArgEnv;

parse_arguments
	# args=getCommandLine;
	# n_args=size args;
	# a = program_arguments 1;
	{
		program_arguments n
			| n>=n_args
				= ([],[]);
			| size argument>=2 && argument.[0]=='-' && argument.[1]=='l'
				= (files1,[argument % (2,size argument-1):libraries1]);
				= ([argument:files1],libraries1);
			{}{
				argument=args.[n];
				(files1,libraries1)=program_arguments (inc n);
			}
	}
	= a;

Start world
	# (file_names,library_file_names) = parse_arguments;
	# [output_object_file_name:file_names] = file_names;
	# ((ok,undefined_symbols),world) = accFiles (link_elf_files2 file_names output_object_file_name) world;
	# world = set_return_code (if ok 0 (-1)) world;
	# (stdout,world) = stdio world;
	= print_errors undefined_symbols stdout;

print_errors [] f
	= f;
print_errors [error:errors] f
	= print_errors errors (fwritec '\n' (fwrites error f));

link_elf_files2 file_names exec_file_name files
	# (ok,undefined_symbols,files) = link_elf_files file_names exec_file_name files;
	= ((ok,undefined_symbols),files);

