#include <stdio.h>
#include <string.h>
#include "Loader.h"

/*** Use:
 *** UnixLoader "OSLmKey" API_file API_offset Kernel_file Kernel_offset \
 ***                      MemAlign MinMem MaxMem
 ***/

/*
 *	Types
 */
typedef struct { char name [256] ; int offset ; } SubFileDescr ;

/*
 *	Static data
 */
static SubFileDescr SFD_API, SFD_Kernel ;
static int MemAlign,MinMem,MaxMem ;

static FILE * OpenSubFile ( SubFileDescr SFD,
			    enum LoaderError_Code LEC, char* ErrMessage )
{
	FILE *f = fopen (SFD.name,"rb") ;
	if (f==NULL) LoaderError ( LEC,ErrMessage ) ;
	fseek (f,SFD.offset,SEEK_SET) ;
	return f ;
}

static void ParseThoseF___ingOptions (int argc, char **argv) {

 /*  For the moment, an external script should allow a more user-friendly
 |* interface. Options in a far future.
 |*  What we do is:
 |* - verify the number of args, and that some key is the first argument.
 |* - read name and offset for API file
 |* - read name and offset for i386 Kernel file
 |* - read memory alignment, minimal & maximal memory size asked for.
 \*/

  if (argc<8)				LoaderError (LE_WRONG_NUM_ARGS,
					"Wrong number of arguments") ;
  if (!strcmp("OSLmKey",argv[1]))	LoaderError (LE_KEY_NOT_FOUND,
					"You must use the script to load") ;
  strcpy (SFD_API.name,argv[2]) ;
  strcpy (SFD_Kernel.name,argv[4]) ;
  sscanf (argv[3], "%u", &SFD_API.offset) ;
  sscanf (argv[5], "%u", &SFD_Kernel.offset) ;
  sscanf (argv[6], "%u", &MemAlign) ;
  sscanf (argv[7], "%u", &MinMem) ;
  sscanf (argv[8], "%u", &MaxMem) ;
}

int main (int argc, char **argv) {
  FILE * A,* K ;
  ParseThoseF___ingOptions (argc,argv) ;
  A = OpenSubFile ( SFD_API,
		    LE_API_NOT_FOUND, "Unix API file not found" ) ;
  K = OpenSubFile ( SFD_Kernel,
		    LE_KERNEL_NOT_FOUND, "i386 Kernel file not found" ) ;
  Exec_OSLm_object ( A,K, MemAlign,MinMem,MaxMem ) ;
}
