Beispiel #1
0
int main(int argc, char* argv[])
{
	int tafd = -1;
	void* fptr = NULL;
	if(argparse(argc, argv) == 0)
		return 1;

	tafd = open(args.inputFile, O_RDONLY | O_BINARY);
	if(tafd < 0)
	{
		perror("Error opening TA file");
		return tafd;
	}
	fptr = readFileToMemory(tafd);
	if(fptr == NULL)
		goto End;

	if(args.TAUnit == 0)
		TAPrintCommonInfo((unsigned char*)fptr, getFileSize(tafd));
	else
		TAReadUnit((unsigned char*)fptr, getFileSize(tafd), args.TAUnit, args.partition, args.outputMode);


	releaseMappedMemory(fptr, getFileSize(tafd));
End:
	close(tafd);
	return 0;
}
Beispiel #2
0
int main(int argc, char *argv[])
{
  if (argparse(argc, argv) == -1) {
    exit(1);
  }

  exit(0);
}
Beispiel #3
0
int main(int argc, char** argv)
{
    int ret = 0;
    std::size_t numSnps;
#if MPI_FOUND
    MPI_Init(&argc, &argv);
#endif
    Argument<bool> help('h', "help", "Show this help", true, false);
    Argument<bool> version('v', "version", "Version information", true, false);
    Argument<std::string> hapA('d', "hapA", "Hap file for population A", false, false, "");
    Argument<std::string> hapB('e', "hapB", "Hap file for population B", false, false, "");
    Argument<std::string> map('m', "map", "Map file", false, false, "");
    Argument<double> cutoff('c', "cutoff", "EHH cutoff value (default: 0.05)", false, false, 0.05);
    Argument<double> minMAF('f', "minmaf", "Minimum allele frequency (default: 0.05)", false, false, 0.00);
    Argument<double> binfac('b', "bin", "Frequency bin size (default: 0.02)", false, false, 0.02);
    Argument<unsigned long long> scale('s', "scale", "Gap scale parameter in bp, used to scale gaps > scale parameter as in Voight, et al.", false, false, 20000);
    Argument<std::string> outfile('o', "out", "Output file", false, false, "out.txt");
    ArgParse argparse({&help, &version, &hapA, &hapB, &map, &outfile, &cutoff, &minMAF, &scale, &binfac}, "Usage: xpehhbin --map input.map --hapA inputA.hap --hapB inputB.hap");
    if (!argparse.parseArguments(argc, argv)) 
    {
        ret = 1;
        goto out;
    }
    if (help.value())
    {
        argparse.showHelp();
        goto out;
    }
    else if (version.value())
    {
        argparse.showVersion();
        goto out;
    }
    else if (!hapA.wasFound() || !hapB.wasFound() || !map.wasFound())
    {
        std::cout << "Please specify --hapA, --hapB, and --map." << std::endl;
        ret = 2;
        goto out;
    }
    
    numSnps = HapMap::querySnpLength(hapA.value().c_str());
    std::cout << "Haplotypes in population A: " << numSnps << std::endl;
    numSnps = HapMap::querySnpLength(hapB.value().c_str());
    std::cout << "Haplotypes in population B: " << numSnps << std::endl;
    
    calcXpehh(hapA.value(), hapB.value(), map.value(), outfile.value(), cutoff.value(), minMAF.value(), (double) scale.value(), binfac.value());

out:
#if MPI_FOUND
    MPI_Barrier(MPI_COMM_WORLD);

    MPI_Finalize();
#endif
    return ret;
}
Beispiel #4
0
/********************************* M A I N ********************************/
int main (
	int argc,
	char **argv
) {
	char		**newargs = NULL;
	LST_LIST	*configlist;
	ConfigType	*config;
	int  		 status = TRUE;

	printf ("MakeScan (c) Echidna 1990\n");

	if (!(argc == 2 && argv[1][0] == '?' && argv[1][1] == '\0')) {
		newargs = argparse (argc, argv, Template);
	}
	if (!newargs) {
		if (GlobalErrMsg) {
			printf ("%s\n", GlobalErrMsg);
		}
		printarghelp (Usage, Template);
	} else {
		DebugSwitch = (int  )((long)newargs[ARG_DEBUG]);
		if ((configlist = ReadConfigurationFile (newargs[ARG_CONFIG]))) {
			if (DebugSwitch) {
				PrintConfigList (configlist);
			}
			if (newargs[ARG_RULE]) {
				strupr (newargs[ARG_RULE]);
				if (!(config = (ConfigType*)LST_FindName (configlist, newargs[ARG_RULE]))) {
					SetGlobalErr (ERR_GENERIC);
					GEprintf1 ("No such rule '%s'", newargs[ARG_RULE]);
					status = FALSE;
				}
			} else {
				config = (ConfigType*)LST_Head (configlist);
			}
			if (status) {
				if (!CreateFiles (config, newargs[ARG_MAKEFILE])) {
					status = FALSE;
				}
			}
		} else {
			status = FALSE;
		}

		if (GlobalErr) {
			printf ("%s\n", GlobalErrMsg);
			status = FALSE;
		}
	}
	return (status ? 0 : 20);
}
Beispiel #5
0
int main(int argc, char **argv)
{
	char			**newargs;

	newargs = argparse (argc, argv, Template);

	if (!newargs) {
		EL_printf ("%s\n", GlobalErrMsg);
		printarghelp (Usage, Template);
		return EXIT_FAILURE;
	} else {
		if (FileNewer (ARG_SRCFILE, ARG_TARGFILE))
		{
			EL_printf ("%s", ARG_SRCFILE);
		}
		return EXIT_SUCCESS;
	}
}
Beispiel #6
0
void test_argparse_1()
{
	struct opt_style style1[] = {
		{ OPTSTYLE_YES, "-a" }, OPT_STYLE_NULL
	};
	struct opt_type type[] = {
		{ style1 }, OPT_TYPE_NULL
	};
	struct opt_parsed parsed[1] = { -1 };

	int argc = 1;
	const char *argv[] = {
		"-a",
	};

	int res;

	res = argparse(argc, argv, type, parsed);

	CU_ASSERT_EQUAL(1, parsed[0].yesno);
	CU_ASSERT_EQUAL(1, res);
}
Beispiel #7
0
void test_argparse_7()
{
	struct opt_style style1[] = {
		{ OPTSTYLE_NEXT, "-a" }, OPT_STYLE_NULL
	};
	struct opt_type type[] = {
		{ style1 }, OPT_TYPE_NULL
	};
	struct opt_parsed parsed[1] = { -1 };

	int argc = 2;
	const char *argv[] = {
		"-a", "XYZ",
	};

	int res;

	res = argparse(argc, argv, type, parsed);

	CU_ASSERT_PTR_EQUAL(argv[1], parsed[0].ptr);
	CU_ASSERT_EQUAL(2, res);
}
Beispiel #8
0
int main(int argc, char *argv[], char *envp[]) {


    argparse(argc, argv, &conf);

    if (!conf.valid) {
	fprintf(stderr, "Usage:\n  tracer [-x trace.xml | -p trace.pl] /path/to/command [args]\n");
	return EXIT_FAILURE;
    }
    
    int offset = 3;
    
    if (conf.output == NULL) {
	output = stdout;
	offset = 1;
    } else {
	output = fopen(conf.output, "w");

	if (output == NULL) {
	    fprintf(stderr, "Unable to open output file!\n");
	    return 1;
	}
    }
    
	
	
    child_pid = fork();

    if (child_pid == 0)
	child(&argv[offset], envp); //samostatne polozky pro jmeno a char** args, tzn. nzev bin je (args-1)
    else
	parent();
    
    if (output != stdout)
	fclose(output);
    
    return 0;
}
Beispiel #9
0
void test_argparse_6()
{
	struct opt_style style1[] = {
		{ OPTSTYLE_AFTER, "-a" },
		{ OPTSTYLE_AFTER, "-b" },
		{ OPTSTYLE_AFTER, "-c" }, OPT_STYLE_NULL
	};
	struct opt_type type[] = {
		{ style1 }, OPT_TYPE_NULL
	};
	struct opt_parsed parsed[1] = { -1 };

	int argc = 1;
	const char *argv[] = {
		"-bXYZ",
	};

	int res;

	res = argparse(argc, argv, type, parsed);

	CU_ASSERT_PTR_EQUAL(argv[0] + 2, parsed[0].ptr);
	CU_ASSERT_EQUAL(1, res);
}
Beispiel #10
0
int
handle(const int fd, db_t *db, sbuf_t *in, sbuf_t *out)
{
	ssize_t err;
	ssize_t len;

	char *key;
        uint32_t klen;
	uint32_t vlen;

	int  argc;
	int  arglen;
	char argv[ARGC_MAX][ARGV_MAX];

	if ((err = sbuf_recv(fd, in, &len)) <= 0 && len == 0) {
		if (err == -1) {
			fprintf(stdout, "db-server: socket %d recv %s\n", fd, strerror(errno));
		}
		return HANDLE_CLOSE;
	}

	arglen = argparse(in->buf, in->len, &argc, argv, ARGC_MAX);
	if (argc < 1 || arglen == -1) {
		fprintf(stderr, "db-server: socket %d malformed request\n", fd);

		return HANDLE_CLOSE;
	}

	if (strcmp(argv[0], "set") == 0 && argc >= 5) {
		key  = argv[1];
		klen = strlen(key);

		vlen = atoi(argv[4]);
		if (vlen + arglen > in->max) {
			fprintf(stderr, "db-server: socket %d too large value\n", fd);

			return HANDLE_CLOSE;
		}

		if (vlen + arglen > in->len) {
			return HANDLE_NEEDMOREIN;
		}

		if (db_put(db, key, klen, in->buf + arglen, vlen) == DB_OK) {
			out->len = sprintf(out->buf, "STORED\r\n");
		} else {
			out->len = sprintf(out->buf, "ERROR\r\n");
		}
	} else if (strcmp(argv[0], "get") == 0 && argc >= 2) {
		key  = argv[1];
		klen = strlen(key);

		if ((vlen = db_get(db, key, klen, valbuf, VALBUF_LEN)) != 0) {
			if (vlen > VALBUF_LEN)
				return HANDLE_CLOSE;

			out->len = snprintf(out->buf, out->max,
			                  "VALUE %.*s %d %d\r\n%.*s\r\nEND\r\n",
			                  klen, key, 0, vlen, vlen, valbuf);
		} else {
			out->len = sprintf(out->buf, "END\r\n");
		}
	} else if (strcmp(argv[0], "delete") == 0 && argc >= 2) {
		key  = argv[1];
		klen = strlen(key);

		if ((db_del(db, key, klen)) != 0) {
			out->len = snprintf(out->buf, out->max, "DELETED\r\n");
		} else {
			out->len = snprintf(out->buf, out->max, "NOT_FOUND\r\n");
                }
        } else {
		return HANDLE_CLOSE;
	}

	if ((err = sbuf_send(fd, out, &len)) <= 0 && len == 0) {
		if (err == -1) {
			fprintf(stdout, "db-server: socket %d send %s\n", fd, strerror(errno));
		}
		return HANDLE_CLOSE;
	}

	if (out->off < out->len) {
		return HANDLE_NEEDMOREOUT;
	}

	return HANDLE_FINISH;
}
Beispiel #11
0
int
main(int argc, char **argv)
{
    int             retval;

    /*
     * Some versions of cron(8) and at(1) set SIGCHLD to SIG_IGN.
     * This is kinda dumb, because it breaks assumprions made in
     * libc (like pclose, for instance).  It also blows away most
     * of Cook's process handling.  We explicitly set the SIGCHLD
     * signal handling to SIG_DFL to make sure this signal does what
     * we expect no matter how we are invoked.
     */
#ifdef SIGCHLD
    signal(SIGCHLD, SIG_DFL);
#else
    signal(SIGCLD, SIG_DFL);
#endif

    /*
     * initialize things
     * (order is critical here)
     */
    progname_set(argv[0]);
    str_initialize();
    id_initialize();
    lex_initialize();

    /*
     * parse the COOK environment variable
     */
    arglex_init_from_env(argv[0], argtab);
    argparse(OPTION_LEVEL_ENVIRONMENT);

    /*
     * parse the command line
     */
    arglex_init(argc, argv, argtab);
    argparse(OPTION_LEVEL_COMMAND_LINE);

    option_tidy_up();

    log_open();

    /*
     * turn on progress stars if they asked for them
     */
    if (option_test(OPTION_STAR))
        star_enable();

    /*
     * If we were asked to update the fingerprints, do it here.
     * We don't actually ant to read in the cookbook.
     */
    if (option.fingerprint_update)
    {
        fp_tweak();
        quit(0);
    }

    /*
     * read in the cook book
     *
     * If there are #include-cooked directives,
     * we may need to do it more than once.
     */
    if (!option.o_book)
        fatal_intl(0, i18n("no book found"));
    for (;;)
    {
        int             status;
        size_t          j;

        builtin_initialize();

        /*
         * instanciate the command line variable assignments
         */
        for (j = 0; j < option.o_vardef.nstrings; ++j)
        {
            char            *s;
            char            *cp;
            string_ty       *name;
            string_ty       *value;
            string_list_ty  wl;
            opcode_context_ty *ocp;

            s = option.o_vardef.string[j]->str_text;
            cp = strchr(s, '=');
            assert(cp);
            if (!cp)
                continue;
            name = str_n_from_c(s, cp - s);
            value = str_from_c(cp + 1);
            str2wl(&wl, value, (char *)0, 0);
            str_free(value);
            ocp = opcode_context_new(0, 0);
            opcode_context_id_assign(ocp, name, id_variable_new(&wl), 0);
            opcode_context_delete(ocp);
            str_free(name);
            string_list_destructor(&wl);
        }

        set_command_line_goals();

        parse(option.o_book);
        status = cook_auto_required();
        if (status < 0)
            quit(1);
        if (!status)
            break;
        id_reset();
        cook_reset();
    }

    /*
     * work out what to cook.
     * If no targets have been given, use the first explicit recipe.
     */
    set_command_line_goals();
    if (!option.o_target.nstrings)
        cook_find_default(&option.o_target);
    assert(option.o_target.nstrings);

    /*
     * cook the target
     */
    if (option.pairs)
        retval = cook_pairs(&option.o_target);
    else if (option.script)
        retval = cook_script(&option.o_target);
    else if (option.web)
        retval = cook_web(&option.o_target);
    else
        retval = cook(&option.o_target);

#ifdef DEBUG
    fflush_slowly_report();
#endif

    quit(retval);
    /*NOTREACHED*/
    return 0;
}
Beispiel #12
0
int
main(int argc, char *argv[])

{
    char *env_top;
    char **preset_argv;
    int preset_argc = 0;
    void *mask;
    int need_mini = 1;

    struct statics statics;
    globalstate *gstate;

    /* get our name */
    if (argc > 0)
    {
	if ((myname = strrchr(argv[0], '/')) == 0)
	{
	    myname = argv[0];
	}
	else
	{
	    myname++;
	}
    }

    /* binary compatibility check */
#ifdef HAVE_UNAME
    {
	struct utsname uts;

	if (uname(&uts) == 0)
	{
	    if (strcmp(uts.machine, UNAME_HARDWARE) != 0)
	    {
		fprintf(stderr, "%s: incompatible hardware platform\n",
			myname);
		exit(EX_UNAVAILABLE);
	    }
	}
    }
#endif

    /* initialization */
    gstate = (globalstate *)calloc(1, sizeof(globalstate));
    gstate->statics = &statics;
    time_mark(NULL);

    /* preset defaults for various options */
    gstate->show_usernames = Yes;
    gstate->topn = DEFAULT_TOPN;
    gstate->delay = DEFAULT_DELAY;
    gstate->fulldraw = Yes;
    gstate->use_color = Yes;
    gstate->interactive = Maybe;

    /* preset defaults for process selection */
    gstate->pselect.idle = Yes;
    gstate->pselect.system = No;
    gstate->pselect.fullcmd = No;
    gstate->pselect.command = NULL;
    gstate->pselect.uid = -1;
    gstate->pselect.mode = 0;

    /* use a large buffer for stdout */
#ifdef HAVE_SETVBUF
    setvbuf(stdout, stdoutbuf, _IOFBF, BUFFERSIZE);
#else
#ifdef HAVE_SETBUFFER
    setbuffer(stdout, stdoutbuf, BUFFERSIZE);
#endif
#endif

    /* get preset options from the environment */
    if ((env_top = getenv("TOP")) != NULL)
    {
	preset_argv = argparse(env_top, &preset_argc);
	preset_argv[0] = myname;
	do_arguments(gstate, preset_argc, preset_argv);
    }

    /* process arguments */
    do_arguments(gstate, argc, argv);

#ifdef ENABLE_COLOR
    /* If colour has been turned on read in the settings. */
    env_top = getenv("TOPCOLOURS");
    if (!env_top)
    {
	env_top = getenv("TOPCOLORS");
    }
    /* must do something about error messages */
    color_env_parse(env_top);
    color_activate(gstate->use_color);
#endif

    /* in order to support forward compatability, we have to ensure that
       the entire statics structure is set to a known value before we call
       machine_init.  This way fields that a module does not know about
       will retain their default values */
    memzero((void *)&statics, sizeof(statics));
    statics.boottime = -1;

    /* call the platform-specific init */
    if (machine_init(&statics) == -1)
    {
	exit(EX_SOFTWARE);
    }

    /* create a helper list of sort order names */
    gstate->order_namelist = string_list(statics.order_names);

    /* look up chosen sorting order */
    if (gstate->order_name != NULL)
    {
	int i;

	if (statics.order_names == NULL)
	{
	    message_error(" This platform does not support arbitrary ordering");
	}
	else if ((i = string_index(gstate->order_name,
				   statics.order_names)) == -1)
	{
	    message_error(" Sort order `%s' not recognized", gstate->order_name);
	    message_error(" Recognized sort orders: %s", gstate->order_namelist);
	}
	else
	{
	    gstate->order_index = i;
	}
    }

    /* initialize extensions */
    init_username();

    /* initialize termcap */
    gstate->smart_terminal = screen_readtermcap(gstate->interactive);

    /* determine interactive state */
    if (gstate->interactive == Maybe)
    {
	gstate->interactive = smart_terminal;
    }

    /* if displays were not specified, choose an appropriate default */
    if (gstate->displays == 0)
    {
	gstate->displays = gstate->smart_terminal ? Infinity: 1;
    }

    /* we don't need a mini display when delay is less than 2
       seconds or when we are not on a smart terminal */
    if (gstate->delay <= 1 || !smart_terminal)
    {
	need_mini = 0;
    }

    /* set constants for username/uid display */
    if (gstate->show_usernames)
    {
	gstate->header_text = format_header("USERNAME");
	gstate->get_userid = username;
    }
    else
    {
	gstate->header_text = format_header("   UID  ");
	gstate->get_userid = itoa7;
    }
    gstate->pselect.usernames = gstate->show_usernames;

    /* initialize display */
    if ((gstate->max_topn = display_init(&statics)) == -1)
    {
	fprintf(stderr, "%s: can't allocate sufficient memory\n", myname);
	exit(EX_OSERR);
    }

    /* check for infinity and for overflowed screen */
    if (gstate->topn == Infinity)
    {
	gstate->topn = INT_MAX;
    }
    else if (gstate->topn > gstate->max_topn)
    {
#if 0
	message_error(" This terminal can only display %d processes",
		      gstate->max_topn);
#endif
    }

#ifdef ENABLE_COLOR
    /* producing a list of color tags is easy */
    if (gstate->show_tags)
    {
	color_dump(stdout);
	exit(EX_OK);
    }
#endif

    /* hold all signals while we initialize the screen */
    mask = hold_signals();
    screen_init();

    /* set the signal handlers */
    set_signals();

    /* longjmp re-entry point */
    /* set the jump buffer for long jumps out of signal handlers */
    if (setjmp(jmp_int) != 0)
    {
	/* this is where we end up after processing sigwinch or sigtstp */

	/* tell display to resize its buffers, and get the new length */
	if ((gstate->max_topn = display_resize()) == -1)
	{
	    /* thats bad */
	    quit(EX_OSERR);
	    /*NOTREACHED*/
	}

	/* set up for a full redraw, and get the current line count */
	gstate->fulldraw = Yes;

	/* safe to release the signals now */
	release_signals(mask);
    }
    else
    {
	/* release the signals */
	release_signals(mask);

	/* some systems require a warmup */
	/* always do a warmup for batch mode */
	if (gstate->interactive == 0 || statics.flags.warmup)
	{
	    struct system_info system_info;
	    struct timeval timeout;

	    time_mark(&(gstate->now));
	    get_system_info(&system_info);
	    (void)get_process_info(&system_info, &gstate->pselect, 0);
	    timeout.tv_sec = 1;
	    timeout.tv_usec = 0;
	    select(0, NULL, NULL, NULL, &timeout);

	    /* if we've warmed up, then we can show good states too */
	    gstate->show_cpustates = Yes;
	    need_mini = 0;
	}
    }

    /* main loop */
    while ((gstate->displays == -1) || (--gstate->displays > 0))
    {
	do_display(gstate);
	if (gstate->interactive)
	{
	    if (need_mini)
	    {
		do_minidisplay(gstate);
		need_mini = 0;
	    }
	    do_command(gstate);
	}
	else
	{
	    do_wait(gstate);
	}
    }

    /* do one last display */
    do_display(gstate);

    quit(EX_OK);
    /* NOTREACHED */
    return 1; /* Keep compiler quiet. */
}
Beispiel #13
0
int main( int argc, char* args[] ) {
    auto arguments = argparse(argc, args);
    try {
        SDL::SDL sdl;
        SDL::Window win;
        SDL::Renderer rend ( win );
        SDL::TTF font ( FONT_PATH );
        SDL::Image img;


        gImage.insertPaths(arguments);
        if ( !gImage.loadFromFile(rend.renderer))  {
            printf("Failed to load image...");
        } else {

            SDL_Rect srcrect, dstrect;
            SDL_Event e;
            SDL_Point mouse_image_coords;

            //default src and dst rectangles of images. No clipping and fitting everything on the window
            srcrect = {0,0, gImage.getWidth(), gImage.getHeight()};
            dstrect = center_fit( gImage.getWidth(), gImage.getHeight(), SCREEN_WIDTH, SCREEN_HEIGHT );

            while( !uInput.quit() ) {
                while( SDL_PollEvent( &e ) != 0 ) {
                    uInput.handleEvent(&e);

                    if (uInput.next()) {
                        gImage.next();
                        if ( !gImage.loadFromFile(rend.renderer) ) {
                            printf("Failed to load image...");
                        } else {
                            srcrect = {0,0, gImage.getWidth(), gImage.getHeight()};
                            dstrect = center_fit( gImage.getWidth(), gImage.getHeight(), SCREEN_WIDTH, SCREEN_HEIGHT );
                        }
                    }
                    if (uInput.previous()) {
                        gImage.previous();
                        if ( !gImage.loadFromFile(rend.renderer) ) {
                            printf("Failed to load image...");
                        } else {
                            srcrect = {0,0, gImage.getWidth(), gImage.getHeight()};
                            dstrect = center_fit( gImage.getWidth(), gImage.getHeight(), SCREEN_WIDTH, SCREEN_HEIGHT );
                        }
                    }

                    SDL_SetRenderDrawColor( rend.renderer, 0x00, 0x00, 0x00, 0xFF );
                    SDL_RenderClear( rend.renderer);

                    //click and drag around
                    if (uInput.mouseIsDown()) {
                        update_position( uInput.getRelativeMotion(), &dstrect );
                    }



                    mouse_image_coords = rect_coordinates(uInput.getMousePosition(), dstrect);
                    update_zoom(uInput.getWheel(), mouse_image_coords, &dstrect);

                    gImage.render(rend.renderer, &srcrect, &dstrect);
                    SDL_RenderPresent( rend.renderer);
                }
            }
        }
    } catch (std::string str) {
        std::cout << str << "\n";
    }
    return 0;
}
Beispiel #14
0
int main(int argc, char **argv)
{
	char			**newargs;

	LST_InitList (FileList);

	newargs = argparse (argc, argv, Template);

	if (!newargs) {
		EL_printf ("%s\n", GlobalErrMsg);
		printarghelp (Usage, Template);
		return EXIT_FAILURE;
	} else {

		Verbose      =  SWITCH_VALUE(ARG_VERBOSE);
		Pack         = !SWITCH_VALUE(ARG_PACK);
		LittleEndian = !SWITCH_VALUE(ARG_BIGENDIAN);
		HeaderNdxs   =  SWITCH_VALUE(ARG_CONST);

		if (ARG_HDFORMAT)	hdformat   = ARG_HDFORMAT;
		if (ARG_BYTES)		PadSize    = EL_atol (ARG_BYTES);

		if (ARG_HEADER && !HeaderNdxs)
		{
			BinOffsets = FALSE;
		}

		//
		// load all requested files
		//
		{
			LST_LIST	*nameList;
			LST_NODE	*nd;

			nameList = MULTI_ARGLINKEDLIST(ARG_INFILES);
			nd       = LST_Head (nameList);
			
			while (!LST_EndOfList (nd))
			{

				int				 fh;
				long			 size;
				char			*filename;
				
				filename = LST_NodeName (nd);

				fh = CHK_ReadOpen (filename);
				{
					size = CHK_FileLength (fh);
			
					if (size == 0)
					{
						WarnMess ("File '%s' is zero bytes long\n", filename);
					}

					if (Pack)
					{
						if (Verbose)
						{
							EL_printf ("Reading %14s : size %6ld", filename, size);
						}

						if (size)
						{
							buf = CHK_AllocateMemory (size, filename);
							CHK_Read (fh, buf, size);
						}
					}

					//
					// see if it's the same as a previous file
					//
					{
						FileContents	*fc;
						FileContents	*newfc;

						newfc = (FileContents*)CHK_CreateNode (sizeof (FileContents), filename, "FileContents");

						if (Pack)
						{
							fc = (FileContents*)LST_Head (FileList);
							while (!LST_EndOfList (fc))
							{
								if (fc->Size)
								{
									if (!memcmp (fc->Data, buf, size))
									{
										break;
									}
								}
								fc = (FileContents*)LST_Next (fc);
							}
						}

						if (Pack && !LST_EndOfList (fc))
						{
							//
							// it was the same
							//
							newfc->Offset = fc->Offset;
							if (Verbose)
							{
								EL_printf (" : Same as %s", LST_NodeName(fc));
							}
							CHK_DeallocateMemory (buf, "FileContents");
						}
						else
						{
							//
							// it was different
							//
							newfc->Size   = size;
							newfc->Offset = CurrentAddress;

							size  = (size + PadSize - 1) / PadSize;
							size *= PadSize;

							newfc->PadSize = size;

							CurrentAddress += size;

							if (Pack)
							{
								newfc->Data = buf;
							}
						}

						CHK_Close (fh);
				
						if (Pack && Verbose)
						{
							EL_printf ("\n");
						}
						LST_AddTail (FileList, newfc);
						TotalFiles++;
					}
				}

				nd = LST_Next (nd);
			}
		}

/******************************* Write Files ******************************/
		if (!ErrorCount)
		{
			FILE			*fp;
			int				 fh;
			FileContents	*fc;
			UINT32			 offsetTableSize;
			UINT32			 ndxCount = 0;

			fh = CHK_WriteOpen (ARG_OUTFILE);

			if (ARG_HEADER)
			{
				fp = CHK_fopen (ARG_HEADER, "w");
			}

			if (!BinOffsets)
			{
				offsetTableSize = 0;
			}
			else
			{
				offsetTableSize = (TotalFiles + 1) * sizeof (UINT32);
			}

			if (Verbose)
			{
				EL_printf ("Writing %ld bytes to file %s\n", CurrentAddress + offsetTableSize, ARG_OUTFILE);
			}

			fc = (FileContents*)LST_Head (FileList);
			while (!LST_EndOfList (fc))
			{
				UINT32	offset;

				offset = fc->Offset + offsetTableSize;

				if (ARG_HEADER)
				{
					char	work[EIO_MAXPATH];
					UINT32	hoffset;

					hoffset = (HeaderNdxs) ? ndxCount : offset;

					strcpy (work, EIO_Filename(LST_NodeName(fc)));
					strupr (work);

					{
						char	*s;

						s = work;
						while (*s)
						{
							if (*s == '.' || *s == '-')
							{
								*s = '_';
							}
							s++;
						}
					}

					CHK_fprintf (fp,
						hdformat,
						work,
						hoffset
						);
					CHK_fprintf (fp, "\n");
				}

				if (BinOffsets)
				{
					if (LittleEndian)
					{
						MakeLilLong (offset);
					}
					else
					{
						MakeBigLong (offset);
					}
					CHK_Write (fh, &offset, sizeof (UINT32));
				}

				ndxCount++;
			
				fc = (FileContents*)LST_Next (fc);
			}

			if (BinOffsets)
			{
				UINT32	zero = 0;

				CHK_Write (fh, &zero, sizeof (UINT32));
			}

			fc = (FileContents*)LST_Head (FileList);
			while (!LST_EndOfList (fc))
			{
				if (fc->Size)
				{
					if (Verbose)
					{
						EL_printf ("Writing %7ld bytes from %s\n", fc->Size, LST_NodeName (fc));
					}

					if (Pack)
					{
						if (fc->Size)
						{
							CHK_Write (fh, fc->Data, fc->Size);
						}
					}
					else
					{
						int		infh;
						long	bytes;
						
						#define	BUF_SIZE	(1024*1024)
						
						buf  = CHK_AllocateMemory (BUF_SIZE, "copy buffer");
						infh = CHK_ReadOpen (LST_NodeName(fc));
						
						bytes = fc->Size;
						while (bytes)
						{
							long	len;

							len = min (bytes, BUF_SIZE);
							CHK_Read (infh, buf, len);
							CHK_Write (fh, buf, len);
							
							bytes -= len;
						}
						
						CHK_Close (infh);
						
						CHK_DeallocateMemory (buf, "copy buffer");
					}
				}
				
				{
					UINT32	pad;

					pad = fc->PadSize - fc->Size;
					while (pad)
					{
						UINT32	part;

						part = min (pad, 256);
						CHK_Write (fh, ZeroData, part);
						pad -= part;
					}
				}

				fc = (FileContents*)LST_Next (fc);
			}

			CHK_Close (fh);

		}
/************************************  ************************************/
	}

	if (GlobalErr) {
		EL_printf ("%s\n", GlobalErrMsg);
		return EXIT_FAILURE;
	}

	if (ErrorCount)
	{
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
Beispiel #15
0
int main(int argc, char **argv)
{
	char			**newargs;
	char			 destDirSep = DIRSEP;

	#if _EL_PLAT_WIN32__
	char			*destEOL    = "\x0d\x0a";
	#elif _EL_PLAT_MACOS__
	char			*destEOL    = "\x0d";
	#elif _EL_PLAT_SGI__
	char			*destEOL    = "\x0a";
	#endif

	newargs = argparse (argc, argv, Template);

	if (!newargs) {
		EL_printf ("%s\n", GlobalErrMsg);
		printarghelp (Usage, Template);
		return EXIT_FAILURE;
	} else {

		FILE	*infp;
		FILE	*outfp;
		short	 lineno = 0;

		Verbose  =  SWITCH_VALUE(ARG_VERBOSE);

		if (ARG_MODE)
		{
			long	mode;

			mode = EL_atol (ARG_MODE);
			switch (mode)
			{
			case 0:	// native
				break;
			case 1: // ms-dos
				destDirSep = '\\';
				destEOL    = "\x0d\x0a";
				break;
			case 2: // mac
				destDirSep = ':';
				destEOL    = "\x0d";
				break;
			case 3: // unix
				destDirSep = '/';
				destEOL    = "\x0a";
				break;
			case 4: // 3do
				destDirSep = '/';
				destEOL    = "\x0d";
				break;
			default:
				EL_printf ("Error: Unknown mode #%ld\n", mode);
				return EXIT_FAILURE;
			}
		}

		infp = fopen (ARG_INFILE, "rb");
		if (!infp)
		{
			EL_printf ("Couldn't open '%s'\n", ARG_INFILE);
			exit (EXIT_FAILURE);
		}

		outfp = fopen (ARG_OUTFILE, "wb");
		if (!outfp)
		{
			EL_printf ("Couldn't open '%s'\n", ARG_OUTFILE);
			exit (EXIT_FAILURE);
		}

		while (getline (InLine, MAXLINE, infp))
		{
			char	*s;
			char	 quote;

			lineno++;

			s = SkipWhiteSpace (InLine);
			while (isspace (*s))
			{
				s++;
			}

			if (!strncmp (s, "#include", 8))
			{
				//
				// found include line, translate it
				//
				s += 8;
				s  = SkipWhiteSpace (s);

				if (Verbose)
				{
					EL_printf ("Old:#%4d:%-60s\n", lineno, InLine);
				}

				switch (*s)
				{
				case '<':
					quote = '>';
					break;
				case '"':
					quote = '"';
					break;
				default:
					EL_printf ("Error1: Malformed Include at line %d in file %s\n", lineno, ARG_INFILE);
					exit (EXIT_FAILURE);
				}

				s++;

				while (*s && *s != quote)
				{
					if (
						(*s == '\\') ||
						(*s == '/')  ||
						(*s == ':')
					   )
					{
						*s = destDirSep;
					}
					s++;
				}

				if (*s != quote)
				{
					EL_printf ("Error2: Malformed Include at line %d in file %s\n", lineno, ARG_INFILE);
					exit (EXIT_FAILURE);
				}

				if (Verbose)
				{
					EL_printf ("New:#%4d:%-60s\n", lineno, InLine);
				}

			}

			fputs (InLine, outfp);
			fputs (destEOL, outfp);
		}
		fclose (infp);
		fclose (outfp);

		{
			FileDateType	fdt;

			if (!EIO_GetFileDate (ARG_INFILE, &fdt)) {
				goto cleanup;
			}

			if (!EIO_SetFileDate (ARG_OUTFILE, &fdt)) {
				goto cleanup;
			}
		}

		{
			FileAttribType	fat;

			if (!EIO_GetFileAttrib (ARG_INFILE, &fat)) {
				goto cleanup;
			}

			if (!EIO_SetFileAttrib (ARG_OUTFILE, &fat)) {
				goto cleanup;
			}

		}

		{
			FileCommentType	fct;

			if (!EIO_GetFileComment (ARG_INFILE, &fct)) {
				goto cleanup;
			}

			if (!EIO_SetFileComment (ARG_OUTFILE, &fct)) {
				goto cleanup;
			}
		}
	}

cleanup:
	if (GlobalErr) {
		EL_printf ("%s\n", GlobalErrMsg);
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}