Beispiel #1
0
int main(void) {
    printargs(5, 2, 14, 84, 97, 15, 24, 48, -1);
    printargs(84, 51, -1);
    printargs(-1);
    printargs(1, -1);

    return 0;
}
Beispiel #2
0
void pipeRun(char * s, int totalPipes, char ** prePipe, char ** postPipe, int prePipeCount, int postPipeCount){
    int fd[2];

    pid_t pid1;
    pid_t pid2;


    parsePipe(totalPipes, s, &prePipe, &prePipeCount, &postPipe, &postPipeCount);
      
    #if TESTER
    printf("------->DEBUG: in main prePipeCount = %d<------\n", prePipeCount);
    printf("------->DEBUG: in main postPipeCount = %d<------\n", postPipeCount);
      

    printargs(prePipeCount, prePipe);
    printargs(postPipeCount, postPipe);
    #endif

    if( (pid1 = fork()) == 0){
        //in child 1 
        
        pipe(fd);

        if( (pid2 = fork()) == 0){
          //child 2
          close(fd[0]);
          close(1);
          close(2);
          dup2(fd[1], 1);
          close(fd[1]);

          //run first command
          execvp(prePipe[0],prePipe);
          exit(-1);
        } //end if

        waitpid(pid2, NULL, 0);
        
        close(fd[1]); // stop write end of pipe
        close(0); 
        dup2(fd[0],0);
        close(fd[0]);

        //run 2nd command
        execvp(postPipe[0], postPipe);
        exit(-1);
    }//end if

    waitpid(pid1, NULL,0);

    clean(prePipeCount, prePipe);
    clean(postPipeCount, postPipe);

}
Beispiel #3
0
int main()
{
  printargs(3,1,2,3,-4,-1);

  error("%s,%d,%s","abc",1232,"KK");
  return 0;
}
Beispiel #4
0
/* Write header to the given output stream */
static void
printheader(FILE *fout, const char *info)
{
	extern char	VersionID[];
						/* copy octree header */
	if (octname[0] == '!') {
		newheader("RADIANCE", fout);
		fputs(octname+1, fout);
		if (octname[strlen(octname)-1] != '\n')
			fputc('\n', fout);
	} else {
		FILE	*fin = fopen(octname, (outfmt=='a') ? "r" : "rb");
		if (fin == NULL)
			quit(1);
		checkheader(fin, OCTFMT, fout);
		fclose(fin);
	}
	printargs(gargc-1, gargv, fout);	/* add our command */
	fprintf(fout, "SOFTWARE= %s\n", VersionID);
	fputnow(fout);
	fputs("NCOMP=3\n", fout);		/* always RGB */
	if (info != NULL)			/* add extra info if given */
		fputs(info, fout);
	fputformat(formstr(outfmt), fout);
	fputc('\n', fout);			/* empty line ends header */
}
Beispiel #5
0
int main()
{
    char **argv = NULL, s[MAX];
    int argc;

    printf("Please enter a command (exit to exit) ");
    fgets(s, MAX, stdin);

    while(strcmp(s, "exit\n") != 0)
    {
        argc = makeargs(s, &argv);
        if(argc != -1)
        {
            printf("There are %d tokens.\nThe tokens are:\n", argc);
            printargs(argc, argv);
        }// end if

        forkIt(argc, argv);

        clean(argc, argv);
        argv = NULL;

        printf("Please enter a command (exit to exit) ");
        fgets(s, MAX, stdin);

    }// end while

}// end main
void runCommandNumber(History * head, int n, char * path){
	History * cur = head;
	
	while(cur != NULL && cur->number != n ){
		cur = cur -> next;
	}

	//This will happen if the input number isn't in the range
	if(cur == NULL){
		errorMessage();
		return;
	}
	
	char ** argv;
	int argc;


	argc = makeargs( cur -> cmd, &argv);

	#if TESTER
		printf("command = %s\n", cur -> cmd);
		printf("ARGC = %d<----\n", argc);
		printargs(argc, argv);
	#endif

	runCommand(argv, argc, path);
}
void printclause( ClauseType *clause )
{
	char nbuff[255];

	fprintf(fp,"\t\t%s", fcnname(clause->fptr, nbuff));
	printargs(clause->fptr,clause->argList);

}
Beispiel #8
0
int
sys_quotactl(struct tcb *tcp)
{
	/*
	 * The Linux kernel only looks at the low 32 bits of command and id
	 * arguments, but on some 64-bit architectures (s390x) this word
	 * will have been sign-extended when we see it.  The high 1 bits
	 * don't mean anything, so don't confuse the output with them.
	 */
	u_int32_t qcmd = tcp->u_arg[0];
	u_int32_t cmd = QCMD_CMD(qcmd);
	u_int32_t type = QCMD_TYPE(qcmd);
	u_int32_t id = tcp->u_arg[2];

	if (!verbose(tcp))
		return printargs(tcp);

	if (entering(tcp))
	{
		printxval(quotacmds, cmd, "Q_???");
		tprintf("|");
		printxval(quotatypes, type, "???QUOTA");
		tprintf(", ");
		printstr(tcp, tcp->u_arg[1], -1);
		tprintf(", ");
		switch (cmd)
		{
			case Q_V1_QUOTAON:
			case Q_QUOTAON:
				printxval(quota_formats, id, "QFMT_VFS_???");
				break;
			case Q_V1_GETQUOTA:
			case Q_V2_GETQUOTA:
			case Q_GETQUOTA:
			case Q_V1_SETQUOTA:
			case Q_V2_SETQUOTA:
			case Q_V1_SETUSE:
			case Q_V2_SETUSE:
			case Q_SETQLIM:
			case Q_SETQUOTA:
			case Q_XGETQUOTA:
			case Q_XSETQLIM:
				tprintf("%u", id);
				break;
			default:
				tprintf("%#lx", tcp->u_arg[2]);
				break;
		}
		tprintf(", ");
	} else
	{
		if (!tcp->u_arg[3])
			tprintf("NULL");
		else
			decode_cmd_data(tcp, cmd, tcp->u_arg[3]);
	}
	return 0;
}
Beispiel #9
0
int
main(		/* read in .OBJ file and convert */
	int	argc,
	char	*argv[]
)
{
	int	donames = 0;
	int	i;

	for (i = 1; i < argc && argv[i][0] == '-'; i++)
		switch (argv[i][1]) {
		case 'o':		/* object name */
			defobj = argv[++i];
			break;
		case 'n':		/* just produce name list */
			donames++;
			break;
		case 'm':		/* use custom mapfile */
			ourmapping = getmapping(argv[++i], &qlist);
			break;
		case 'f':		/* flatten surfaces */
			flatten++;
			break;
		default:
			goto userr;
		}
	if ((i > argc) | (i < argc-1))
		goto userr;
	if (i == argc)
		inpfile = "<stdin>";
	else if (freopen(inpfile=argv[i], "r", stdin) == NULL) {
		fprintf(stderr, "%s: cannot open\n", inpfile);
		exit(1);
	}
	if (donames) {				/* scan for ids */
		getnames(stdin);
		printf("filename \"%s\"\n", inpfile);
		printf("filetype \"Wavefront\"\n");
		write_quals(&qlist, qual, stdout);
		printf("qualifier %s begin\n", qlist.qual[Q_FAC]);
		printf("[%d:%d]\n", 1, faceno);
		printf("end\n");
	} else {				/* translate file */
		printf("# ");
		printargs(argc, argv, stdout);
		convert(stdin);
	}
	if (ndegen)
		printf("# %d degenerate faces\n", ndegen);
	if (n0norm)
		printf("# %d invalid (zero) normals\n", n0norm);
	exit(0);
userr:
	fprintf(stderr, "Usage: %s [-o obj][-m mapping][-n][-f] [file.obj]\n",
			argv[0]);
	exit(1);
}
Beispiel #10
0
int
syscall_entering_trace(struct tcb *tcp, unsigned int *sig)
{
	/* Restrain from fault injection while the trace executes strace code. */
	if (hide_log(tcp)) {
		tcp->qual_flg &= ~QUAL_INJECT;
	}

	switch (tcp->s_ent->sen) {
		case SEN_execve:
		case SEN_execveat:
#if defined SPARC || defined SPARC64
		case SEN_execv:
#endif
			tcp->flags &= ~TCB_HIDE_LOG;
			break;
	}

	if (!traced(tcp) || (tracing_paths && !pathtrace_match(tcp))) {
		tcp->flags |= TCB_FILTERED;
		return 0;
	}

	tcp->flags &= ~TCB_FILTERED;

	if (hide_log(tcp)) {
		return 0;
	}

	if (inject(tcp))
		tamper_with_syscall_entering(tcp, sig);

	if (cflag == CFLAG_ONLY_STATS) {
		return 0;
	}

#ifdef USE_LIBUNWIND
	if (stack_trace_enabled) {
		if (tcp->s_ent->sys_flags & STACKTRACE_CAPTURE_ON_ENTER)
			unwind_capture_stacktrace(tcp);
	}
#endif

	printleader(tcp);
	tprintf("%s(", tcp->s_ent->sys_name);
	int res = raw(tcp) ? printargs(tcp) : tcp->s_ent->sys_func(tcp);
	fflush(tcp->outf);
	return res;
}
Beispiel #11
0
int main()
{
  char **argv = NULL, s[] = "ls -l file";
  int argc=0;

  argv = makeargs(s, &argc);
  if(argc != -1)
  {
    printf("There are %d tokens.\nThe tokens are:\n", argc);
    printargs(argc, argv);

  }// end if

  clean(argc, argv);
  argv = NULL;

}// end main
Beispiel #12
0
void runAlias(Node * head, char * s, char * path){
	char command[1000];
	strcpy(command, findAlias(&head, s));
	
	char ** argv;
	int argc;


	argc = makeargs(command, &argv);

	#if TESTER
		printf("command = %s\n", command);
		printf("ARGC = %d<----\n", argc);
		printargs(argc, argv);
	#endif

	runCommand(argv, argc, path);
	


}
int main()
{
	char **argv = NULL, s[MAX];
	printf("Enter Strings serperated by space(exit to exit): ");
	fgets(s, MAX, stdin);
	strip(s);
  	int argc;
	while(strcmp(s, "exit") != 0){
  		argc = makeargs(s, &argv);
  		if(argc != -1)
  		{
    			printf("There are %d tokens.\nThe tokens are:\n", argc);
   			printargs(argc, argv);
			clean(argc, argv);
			
  		}// end if
	
		argv = NULL;
		printf("Enter Strings serperated by space(exit to exit): ");
		fgets(s, MAX, stdin);
		strip(s);
	}
}// end main
Beispiel #14
0
static int
trace_syscall_entering(struct tcb *tcp)
{
	int res, scno_good;

	scno_good = res = get_scno(tcp);
	if (res == 0)
		return res;
	if (res == 1)
		res = get_syscall_args(tcp);

	if (res != 1) {
		printleader(tcp);
		if (scno_good != 1)
			tprints("????" /* anti-trigraph gap */ "(");
		else if (tcp->qual_flg & UNDEFINED_SCNO)
			tprintf("%s(", undefined_scno_name(tcp));
		else
			tprintf("%s(", tcp->s_ent->sys_name);
		/*
		 * " <unavailable>" will be added later by the code which
		 * detects ptrace errors.
		 */
		goto ret;
	}

	if (   sys_execve == tcp->s_ent->sys_func
# if defined(SPARC) || defined(SPARC64)
	    || sys_execv == tcp->s_ent->sys_func
# endif
	   ) {
		hide_log_until_execve = 0;
	}

#if defined(SYS_socket_subcall) || defined(SYS_ipc_subcall)
	while (1) {
# ifdef SYS_socket_subcall
		if (tcp->s_ent->sys_func == sys_socketcall) {
			decode_socket_subcall(tcp);
			break;
		}
# endif
# ifdef SYS_ipc_subcall
		if (tcp->s_ent->sys_func == sys_ipc) {
			decode_ipc_subcall(tcp);
			break;
		}
# endif
		break;
	}
#endif

	if (!(tcp->qual_flg & QUAL_TRACE)
	 || (tracing_paths && !pathtrace_match(tcp))
	) {
		tcp->flags |= TCB_INSYSCALL | TCB_FILTERED;
		return 0;
	}

	tcp->flags &= ~TCB_FILTERED;

	if (cflag == CFLAG_ONLY_STATS || hide_log_until_execve) {
		res = 0;
		goto ret;
	}

#ifdef USE_LIBUNWIND
	if (stack_trace_enabled) {
		if (tcp->s_ent->sys_flags & STACKTRACE_CAPTURE_ON_ENTER)
			unwind_capture_stacktrace(tcp);
	}
#endif

	printleader(tcp);
	if (tcp->qual_flg & UNDEFINED_SCNO)
		tprintf("%s(", undefined_scno_name(tcp));
	else
		tprintf("%s(", tcp->s_ent->sys_name);
	if ((tcp->qual_flg & QUAL_RAW) && tcp->s_ent->sys_func != sys_exit)
		res = printargs(tcp);
	else
		res = tcp->s_ent->sys_func(tcp);

	fflush(tcp->outf);
 ret:
	tcp->flags |= TCB_INSYSCALL;
	/* Measure the entrance time as late as possible to avoid errors. */
	if (Tflag || cflag)
		gettimeofday(&tcp->etime, NULL);
	return res;
}
Beispiel #15
0
int main(int argc, char **argv)
{
   char *var;
   struct fileentry *fe;

   if(!osInit())
      exit(OS_EXIT_ERROR);

   if(argc > 1 &&
	  (strcmp(argv[1],"?")==0      ||
		strcmp(argv[1],"-h")==0     ||
		strcmp(argv[1],"--help")==0 ||
		strcmp(argv[1],"help")==0 ||
		strcmp(argv[1],"/h")==0     ||
		strcmp(argv[1],"/?")==0 ))
   {
      printargs(args);
      osEnd();
      exit(OS_EXIT_OK);
   }

   if(!parseargs(args,argc,argv))
   {
      osEnd();
      exit(OS_EXIT_ERROR);
   }

   jbNewList(&list);

   /* get outbound dir */

   if((var=getenv("CMOUTBOUND")))
      cfg_Dir=var;

   else
      cfg_Dir=OS_CURRENT_DIR;

   if(args[ARG_DIRECTORY].data)
      cfg_Dir=(char *)args[ARG_DIRECTORY].data;

   /* Get zone */

   if((var=getenv("CMOUTBOUNDZONE")))
      cfg_Zone=atoi(var);

   else
      cfg_Zone=2;

   if(args[ARG_ZONE].data)
      cfg_Zone=atoi((char *)args[ARG_ZONE].data);

   /* Get pattern */

   strcpy(cfg_Pattern.Zone,"*");
   strcpy(cfg_Pattern.Net,"*");
   strcpy(cfg_Pattern.Node,"*");
   strcpy(cfg_Pattern.Point,"*");

   if(args[ARG_PATTERN].data)
   {
      if(!Parse4DPat((char *)args[ARG_PATTERN].data,&cfg_Pattern))
      {
         printf("Invalid node pattern \"%s\"\n",(char *)args[ARG_PATTERN].data);
         osEnd();
         exit(OS_EXIT_ERROR);
      }
   }

   /* Get verbose flag */

   cfg_Verbose=FALSE;

   if(args[ARG_VERBOSE].data)
      cfg_Verbose=TRUE;

   /* Real program starts here */

   printf("CrashListOut " VERSION "\n\n");

   scandir_dir = NULL;
   scandir_boss = NULL;

   if(!osScanDir(cfg_Dir,scandirfunc))
   {
		uint32_t err=osError();
      printf("Failed to scan directory %s\n",cfg_Dir);
		printf("Error: %s",osErrorMsg(err));		
      return(FALSE);
   }

   sortlist(&list);

   printf("%-8.8s %-17.17s %-16.16s %7.7s   %s\n\n",
      "Type","Node","Last Change","B/F","File");

   if(list.First)
   {
      for(fe=(struct fileentry *)list.First;fe;fe=fe->Next)
      {
         if(fe->type == TYPE_REQUEST) DisplayReq(fe);
         else if(fe->flow)            DisplayFlow(fe);
         else                         DisplayPkt(fe);
      }

      if(!cfg_Verbose) printf("\n");
      printf("Totally %s bytes in %u files to send, %u requests.\n",unit(TotalBytes),TotalFiles,TotalRequests);
   }
   else
   {
      printf("Outbound directory is empty.\n");
   }

   jbFreeList(&list);

   exit(OS_EXIT_OK);
}
Beispiel #16
0
int
sys_sysctl(struct tcb *tcp)
{
	struct __sysctl_args info;
	int *name;
	unsigned long size;

	if (umove(tcp, tcp->u_arg[0], &info) < 0)
		return printargs(tcp);

	size = sizeof(int) * (unsigned long) info.nlen;
	name = (size / sizeof(int) != info.nlen) ? NULL : malloc(size);
	if (name == NULL ||
	    umoven(tcp, (unsigned long) info.name, size, (char *) name) < 0) {
		free(name);
		if (entering(tcp))
			tprintf("{%p, %d, %p, %p, %p, %lu}",
				info.name, info.nlen, info.oldval,
				info.oldlenp, info.newval, (unsigned long)info.newlen);
		return 0;
	}

	if (entering(tcp)) {
		int cnt = 0, max_cnt;

		tprints("{{");

		if (info.nlen == 0)
			goto out;
		printxval(sysctl_root, name[0], "CTL_???");
		++cnt;

		if (info.nlen == 1)
			goto out;
		switch (name[0]) {
		case CTL_KERN:
			tprints(", ");
			printxval(sysctl_kern, name[1], "KERN_???");
			++cnt;
			break;
		case CTL_VM:
			tprints(", ");
			printxval(sysctl_vm, name[1], "VM_???");
			++cnt;
			break;
		case CTL_NET:
			tprints(", ");
			printxval(sysctl_net, name[1], "NET_???");
			++cnt;

			if (info.nlen == 2)
				goto out;
			switch (name[1]) {
			case NET_CORE:
				tprints(", ");
				printxval(sysctl_net_core, name[2],
					  "NET_CORE_???");
				break;
			case NET_UNIX:
				tprints(", ");
				printxval(sysctl_net_unix, name[2],
					  "NET_UNIX_???");
				break;
			case NET_IPV4:
				tprints(", ");
				printxval(sysctl_net_ipv4, name[2],
					  "NET_IPV4_???");

				if (info.nlen == 3)
					goto out;
				switch (name[2]) {
				case NET_IPV4_ROUTE:
					tprints(", ");
					printxval(sysctl_net_ipv4_route,
						  name[3],
						  "NET_IPV4_ROUTE_???");
					break;
				case NET_IPV4_CONF:
					tprints(", ");
					printxval(sysctl_net_ipv4_conf,
						  name[3],
						  "NET_IPV4_CONF_???");
					break;
				default:
					goto out;
				}
				break;
			case NET_IPV6:
				tprints(", ");
				printxval(sysctl_net_ipv6, name[2],
					  "NET_IPV6_???");

				if (info.nlen == 3)
					goto out;
				switch (name[2]) {
				case NET_IPV6_ROUTE:
					tprints(", ");
					printxval(sysctl_net_ipv6_route,
						  name[3],
						  "NET_IPV6_ROUTE_???");
					break;
				default:
					goto out;
				}
				break;
			default:
				goto out;
			}
			break;
		default:
			goto out;
		}
	out:
		max_cnt = info.nlen;
		if (abbrev(tcp) && max_cnt > max_strlen)
			max_cnt = max_strlen;
		while (cnt < max_cnt)
			tprintf(", %x", name[cnt++]);
		if (cnt < info.nlen)
			tprints(", ...");
		tprintf("}, %d, ", info.nlen);
	} else {
		size_t oldlen = 0;
		if (info.oldval == NULL) {
			tprints("NULL");
		} else if (umove(tcp, (long)info.oldlenp, &oldlen) >= 0
			   && info.nlen >= 2
			   && ((name[0] == CTL_KERN
				&& (name[1] == KERN_OSRELEASE
				    || name[1] == KERN_OSTYPE
#ifdef KERN_JAVA_INTERPRETER
				    || name[1] == KERN_JAVA_INTERPRETER
#endif
#ifdef KERN_JAVA_APPLETVIEWER
				    || name[1] == KERN_JAVA_APPLETVIEWER
#endif
					)))) {
			printpath(tcp, (size_t)info.oldval);
		} else {
			tprintf("%p", info.oldval);
		}
		tprintf(", %lu, ", (unsigned long)oldlen);
		if (info.newval == NULL)
			tprints("NULL");
		else if (syserror(tcp))
			tprintf("%p", info.newval);
		else
			printpath(tcp, (size_t)info.newval);
		tprintf(", %lu", (unsigned long)info.newlen);
	}

	free(name);
	return 0;
}
Beispiel #17
0
int
main(
	int  argc,
	char  **argv
)
{
	double  d, expval = 1.0;
	int  i;

	progname = argv[0];
	mybright = &rgb_bright; /* default */

	for (i = 1; i < argc; i++)
		if (argv[i][0] == '-' || argv[i][0] == '+')
			switch (argv[i][1]) {
			case 'h':		/* header */
				header = argv[i][0] == '+';
				break;
			case 'H':		/* resolution string */
				resolution = argv[i][0] == '+';
				break;
			case 's':		/* skip bytes in header */
				skipbytes = atol(argv[++i]);
				break;
			case 'u':		/* unique values */
				uniq = argv[i][0] == '-';
				break;
			case 'o':		/* original values */
				original = argv[i][0] == '-';
				break;
			case 'g':		/* gamma correction */
				gamcor = atof(argv[i+1]);
				if (argv[i][0] == '+')
					gamcor = 1.0/gamcor;
				i++;
				break;
			case 'e':		/* exposure correction */
				d = atof(argv[i+1]);
				if (argv[i+1][0] == '-' || argv[i+1][0] == '+')
					d = pow(2.0, d);
				if (argv[i][0] == '-')
					expval *= d;
				scalecolor(exposure, d);
				doexposure++;
				i++;
				break;
			case 'R':		/* reverse byte sequence */
				if (argv[i][0] == '-') {
					ord[0]=BLU; ord[1]=GRN; ord[2]=RED;
				} else {
					ord[0]=RED; ord[1]=GRN; ord[2]=BLU;
				}
				break;
			case 'r':		/* reverse conversion */
				reverse = argv[i][0] == '-';
				break;
			case 'n':		/* non-interleaved RGB */
				interleave = argv[i][0] == '+';
				break;
			case 'b':		/* brightness values */
				putprim = argv[i][0] == '-' ? BRIGHT : ALL;
				break;
			case 'p':		/* primary controls */
				switch (argv[i][2]) {
				/* these two options affect -r conversion */
				case '\0':
					myprims[RED][CIEX] = atof(argv[++i]);
					myprims[RED][CIEY] = atof(argv[++i]);
					myprims[GRN][CIEX] = atof(argv[++i]);
					myprims[GRN][CIEY] = atof(argv[++i]);
					myprims[BLU][CIEX] = atof(argv[++i]);
					myprims[BLU][CIEY] = atof(argv[++i]);
					myprims[WHT][CIEX] = atof(argv[++i]);
					myprims[WHT][CIEY] = atof(argv[++i]);
					outprims = myprims;
					break;
				case 'x': case 'X': outprims = NULL; break;
				/* the following options affect +r only */
				case 'r': case 'R': putprim = RED; break;
				case 'g': case 'G': putprim = GRN; break;
				case 'b': case 'B': putprim = BLU; break;
				default: goto unkopt;
				}
				break;
			case 'd':		/* data only (no indices) */
				dataonly = argv[i][0] == '-';
				switch (argv[i][2]) {
				case '\0':
				case 'a':		/* ascii */
					format = 'a';
					fmtid = "ascii";
					break;
				case 'i':		/* integer */
					format = 'i';
					fmtid = "ascii";
					break;
				case 'b':		/* byte */
					dataonly = 1;
					format = 'b';
					fmtid = "byte";
					break;
				case 'W':		/* 16-bit swapped */
					swapbytes = 1;
				case 'w':		/* 16-bit */
					dataonly = 1;
					format = 'w';
					fmtid = "16-bit";
					break;
				case 'F':		/* swapped floats */
					swapbytes = 1;
				case 'f':		/* float */
					dataonly = 1;
					format = 'f';
					fmtid = "float";
					break;
				case 'D':		/* swapped doubles */
					swapbytes = 1;
				case 'd':		/* double */
					dataonly = 1;
					format = 'd';
					fmtid = "double";
					break;
				default:
					goto unkopt;
				}
				break;
			case 'x':		/* x resolution */
			case 'X':		/* x resolution */
				resolution = 0;
				if (argv[i][0] == '-')
					picres.rt |= XDECR;
				picres.xr = atoi(argv[++i]);
				break;
			case 'y':		/* y resolution */
			case 'Y':		/* y resolution */
				resolution = 0;
				if (argv[i][0] == '-')
					picres.rt |= YDECR;
				if (picres.xr == 0)
					picres.rt |= YMAJOR;
				picres.yr = atoi(argv[++i]);
				break;
			default:
unkopt:
				fprintf(stderr, "%s: unknown option: %s\n",
						progname, argv[i]);
				quit(1);
				break;
			}
		else
			break;
					/* recognize special formats */
	if (dataonly && format == 'b') {
		if (putprim == ALL)
			fmtid = "24-bit_rgb";
		else
			fmtid = "8-bit_grey";
	}
	if (dataonly && format == 'w') {
		if (putprim == ALL)
			fmtid = "48-bit_rgb";
		else
			fmtid = "16-bit_grey";
	}
					/* assign reverse ordering */
	rord[ord[0]] = 0;
	rord[ord[1]] = 1;
	rord[ord[2]] = 2;
					/* get input */
	if (i == argc) {
		fin = stdin;
	} else if (i < argc) {
		if ((fin = fopen(argv[i], "r")) == NULL) {
			fprintf(stderr, "%s: can't open file \"%s\"\n",
						progname, argv[i]);
			quit(1);
		}
		if (reverse && putprim != BRIGHT && i == argc-3) {
			if ((fin2 = fopen(argv[i+1], "r")) == NULL) {
				fprintf(stderr, "%s: can't open file \"%s\"\n",
						progname, argv[i+1]);
				quit(1);
			}
			if ((fin3 = fopen(argv[i+2], "r")) == NULL) {
				fprintf(stderr, "%s: can't open file \"%s\"\n",
						progname, argv[i+2]);
				quit(1);
			}
			interleave = -1;
		} else if (i != argc-1)
			fin = NULL;
		if (reverse && putprim != BRIGHT && !interleave) {
			fin2 = fopen(argv[i], "r");
			fin3 = fopen(argv[i], "r");
		}
		if (skipbytes && (fseek(fin, skipbytes, 0) || (fin2 != NULL &&
				(fseek(fin2, skipbytes, 0) ||
				fseek(fin3, skipbytes, 0))))) {
			fprintf(stderr, "%s: cannot skip %ld bytes on input\n",
					progname, skipbytes);
			quit(1);
		}
	}
	if (fin == NULL) {
		fprintf(stderr, "%s: bad # file arguments\n", progname);
		quit(1);
	}

	if (reverse) {
#ifdef _WIN32
		SET_FILE_BINARY(stdout);
		if (format != 'a' && format != 'i')
			SET_FILE_BINARY(fin);
#endif
					/* get header */
		if (header) {
			if (checkheader(fin, fmtid, stdout) < 0) {
				fprintf(stderr, "%s: wrong input format\n",
						progname);
				quit(1);
			}
			if (fin2 != NULL) {
				getheader(fin2, NULL, NULL);
				getheader(fin3, NULL, NULL);
			}
		} else
			newheader("RADIANCE", stdout);
					/* get resolution */
		if ((resolution && !fgetsresolu(&picres, fin)) ||
				picres.xr <= 0 || picres.yr <= 0) {
			fprintf(stderr, "%s: missing resolution\n", progname);
			quit(1);
		}
		if (resolution && fin2 != NULL) {
			RESOLU  pres2;
			if (!fgetsresolu(&pres2, fin2) ||
					pres2.rt != picres.rt ||
					pres2.xr != picres.xr ||
					pres2.yr != picres.yr ||
					!fgetsresolu(&pres2, fin3) ||
					pres2.rt != picres.rt ||
					pres2.xr != picres.xr ||
					pres2.yr != picres.yr) {
				fprintf(stderr, "%s: resolution mismatch\n",
						progname);
				quit(1);
			}
		}
						/* add to header */
		printargs(i, argv, stdout);
		if (expval < .99 || expval > 1.01)
			fputexpos(expval, stdout);
		if (outprims != NULL) {
			if (outprims != stdprims)
				fputprims(outprims, stdout);
			fputformat(COLRFMT, stdout);
		} else				/* XYZ data */
			fputformat(CIEFMT, stdout);
		putchar('\n');
		fputsresolu(&picres, stdout);	/* always put resolution */
		valtopix();
	} else {
#ifdef _WIN32
		SET_FILE_BINARY(fin);
		if (format != 'a' && format != 'i')
			SET_FILE_BINARY(stdout);
#endif
						/* get header */
		getheader(fin, checkhead, NULL);
		if (wrongformat) {
			fprintf(stderr,
				"%s: input not a Radiance RGBE picture\n",
					progname);
			quit(1);
		}
		if (!fgetsresolu(&picres, fin)) {
			fprintf(stderr, "%s: missing resolution\n", progname);
			quit(1);
		}
		if (header) {
			printargs(i, argv, stdout);
			if (expval < .99 || expval > 1.01)
				fputexpos(expval, stdout);
			fputformat(fmtid, stdout);
			putchar('\n');
		}
		if (resolution)			/* put resolution */
			fputsresolu(&picres, stdout);
		pixtoval();
	}

	quit(0);
	return 0; /* pro forma return */
}
int main(int argc, char** argv)
{

struct kuhler_data	kd1;

kd1.usb_mode_control_packet[silent] = (char[0x20]) silent_mode_control;
kd1.usb_mode_control_packet[extreme] = (char[0x20]) extreme_mode_control;
kd1.usb_mode_control_packet[custom] = (char[0x20]) custom_mode_control;

kd1.usb_status_packet[silent] = (char[0x20]) silent_status_control;
kd1.usb_status_packet[extreme] = (char[0x20]) extreme_status_control;
kd1.usb_status_packet[custom]  = (char[0x20]) custom_status_control;

// MUTEX Lock
		
	pthread_mutex_init(&kuhler_mutex,NULL);

	int c;
	int debug_level;
	int update_thread_enable = 1;

        while ((c = getopt(argc,argv,"d:hn")) != -1) {
                switch (c) {
                        case 'h' :
                                printargs();	
				exit(0);
                                break;
			case 'd' :
				debug_level = 1;
				break;
			case 'n' :
				update_thread_enable = 0;			
				break;
			default :
				debug_level = 0;
			}
	}

	// Init Log Factiity
	// EMERG,ALRT,CRIT,ERR,WARNING,NOTICE,INFO,DEBUG
	if (debug_level == 1) {
		setlogmask (LOG_UPTO(LOG_DEBUG));
		printf ("Debug Mode Enabled!\n");
	} else {
		setlogmask (LOG_UPTO(LOG_NOTICE));
	}

	openlog ("kuhlerd", LOG_CONS | LOG_PID | LOG_NDELAY , LOG_LOCAL1);
	syslog (LOG_NOTICE, "kuhlerd version %s Started",version_string);

	// Init kd_ptr
	kd_ptr = &kd1;
	
	struct control_packet cp;
	struct status_packet sp;
	
	shm_id_cp = shmget(shm_key_cp,sizeof(cp),IPC_CREAT | 0666);  //rw-,rw-,rw-
	shm_id_sp = shmget(shm_key_sp,sizeof(sp),IPC_CREAT | 0666);	 //rw,r--,r--

	if (shm_id_cp < 0 || shm_id_sp < 0) {
		syslog (LOG_ERR, "Failed to Allocate Shared Memory Segment \n");
		printf ("Kuhlerd : Failed to Allocate Shared Memory Segment\n");
		exit(1);
	}

	syslog (LOG_DEBUG, "Allocated Shared Memory Segment %d %d \n", shm_id_sp,shm_id_cp);

	cp_ptr = shmat(shm_id_cp,NULL,0);
	sp_ptr = shmat(shm_id_sp,NULL,0);

	if (cp_ptr == NULL || sp_ptr == NULL) {
		syslog (LOG_ERR, "Failed to Attach to Shared Memory Segment \n");
		printf ("Kuhlerd : Failed to Attach Shared Memory Segment\n");
		exit(1);
	}


	int r = 1;

	r = libusb_init(NULL);
	if (r < 0) {
		syslog (LOG_ERR, "Failed to Initialized libusb \n");
		fprintf(stderr, "Kuhlerd : failed to initialise libusb\n");
		exit(1);
	}

	r = find_kuhler920();
	if (r < 0) {
		syslog (LOG_ERR, "Could not find Kuhler 920/960 or open device \n");
		fprintf(stderr, "Kuhlerd : Could not find/open device\n");
		exit(1);
	}

	r = libusb_claim_interface(devh, 0);
	if (r < 0) {
		syslog (LOG_ERR, "Could not claim exclusive use of usb device \n");
		fprintf(stderr, "Kuhlerd : usb_claim_interface error %d\n", r);
		exit(1);
	}

	syslog (LOG_DEBUG,"Claimed Interface \n");
	printf("Kuhlerd : claimed interface\n");

	syslog (LOG_DEBUG,"Sending Init Packet\n");
	printf("Kuhlerd : Sending Init Packet\n");
	r = init_kuhler920();
	syslog (LOG_DEBUG,"Init Packet Sent, returned with status %d \n",r);
	printf("Kuhlerd : Init Packet Sent, returned with status %d \n",r);	
	//init_signals();
	syslog (LOG_DEBUG,"Creating Histogram Entries %d \n",r);
	init_histogram(sp_ptr);
	syslog (LOG_DEBUG,"Created Histogram Entries %d \n",r);

	int i=0;
	int current_mode = silent;

	 cp_sem = sem_open(cp_sem_name, O_CREAT , 0666,0); // 1 = unlocked , 0 = locked
	 sp_sem = sem_open(sp_sem_name, O_CREAT , 0666,0); // 1 = unlocked , 0 = locked

	// v0.5 -- HW BUSY Semaphore - IPC
	 kuhler_hw_busy_sem = sem_open(kuhler_hw_busy_sem_name,O_CREAT,0666,0);

	//if (cp_sem == NULL || sp_sem == NULL) {
	if (cp_sem == NULL || sp_sem == NULL || kuhler_hw_busy_sem == NULL) {
		syslog (LOG_ERR, "Failed to Create semaphores \n");
		printf ("Kuhlerd : failed to create semaphores\n");
		exit(1);
	}

	// Initialize Shared Memory For Safety
	cp_ptr->mode = silent;
	cp_ptr->cmd = 0;
	cp_ptr->led_r = (uint8_t) 0;
	cp_ptr->led_g = (uint8_t) 0;
	cp_ptr->led_b = (uint8_t) 0;
	cp_ptr->start_temp = 40;
	cp_ptr->full_temp = 55;

	change_mode(silent,kd_ptr);
	get_status_packet(sp_ptr);

	syslog (LOG_NOTICE, "Entering Main Loop\n");
	printf ("Kuhlerd : Entering Main Loop\n");
	int rv=-99;
	
	// Fork Off and Exit 
	pid_t pidd;
	pidd = fork();

	
	//if (pidd == 0) {
	init_signals();
	// create pthreads
	pthread_t upd;


	// new for V5 - update thread
	if (update_thread_enable == 1) {
		int pthread_val = pthread_create(&upd,NULL,update_thread,NULL);
		syslog(LOG_NOTICE, "Creating Update Thread \n");
		printf ("Kuhlerd : Creating Update Thread \n");
	} else {
		syslog(LOG_NOTICE, "Update thread disabled \n");
		printf ("Kuhlerd : Disabling Update Thread \n");
	}

	if (pidd !=0) {
		syslog(LOG_NOTICE, "Entering Daemon Mode, exiting \n");
		printf ("Kuhlerd : Entering Daemon Mode, exiting \n");
		exit (0);
	}

		while (i==0) {
		// wait for the semaphore to be unlocked - written to 1 by ctl program
		//printf ("Waiting for Semaphore Unlock %i\n",rv);
		// hw busy control semaphore initially LOCKED 
		sem_post(kuhler_hw_busy_sem);
		rv = sem_wait(cp_sem); // set to 0 -- blocking call
		
		// hw busy control semaphore initially LOCKED 
		//sem_post(kuhler_hw_busy_sem);

		if (cp_ptr->cmd == 1 ) {
			change_led_color(cp_ptr->led_r,cp_ptr->led_g,cp_ptr->led_b,cp_ptr->mode,kd_ptr);
			if (cp_ptr->mode == custom) {
				change_temp_threshold(cp_ptr->start_temp,cp_ptr->full_temp,kd_ptr);	
			}
			change_mode(cp_ptr->mode,kd_ptr);
			get_status_packet(sp_ptr);	// required after mode change
		} else {
			send_status_packet(cp_ptr->mode,kd_ptr);
			sleep(1);
			get_status_packet(sp_ptr);
			// unlock status packet semaphore
			sem_post(sp_sem);
			}
		} // end while
	}
Beispiel #19
0
int
main(
	int  argc,
	char  *argv[]
)
{
	int  ncolumns = 0;
	int  autolabel = 0;
	int  curcol = 0, x0 = 0, curx = 0, cury = 0, spacing = 0;
	int  xsgn, ysgn;
	char  *thislabel;
	int  an;
	SET_DEFAULT_BINARY();
	SET_FILE_BINARY(stdin);
	SET_FILE_BINARY(stdout);
	progname = argv[0];

	for (an = 1; an < argc && argv[an][0] == '-'; an++)
		switch (argv[an][1]) {
		case 'h':
			echoheader = !echoheader;
			break;
		case 'x':
			xsiz = atoi(argv[++an]);
			break;
		case 'y':
			ysiz = atoi(argv[++an]);
			break;
		case 'b':
			setcolr(bgcolr, atof(argv[an+1]),
					atof(argv[an+2]),
					atof(argv[an+3]));
			an += 3;
			break;
		case 'a':
			ncolumns = atoi(argv[++an]);
			break;
		case 's':
			spacing = atoi(argv[++an]);
			break;
		case 'o':
			curx = x0 = atoi(argv[++an]);
			cury = atoi(argv[++an]);
			break;
		case 'l':
			switch (argv[an][2]) {
			case 'a':
				autolabel++;
				break;
			case 'h':
				labelht = atoi(argv[++an]);
				break;
			case '\0':
				goto dofiles;
			default:
				goto userr;
			}
			break;
		case '\0':
		case 't':
			goto dofiles;
		default:
			goto userr;
		}
dofiles:
	newheader("RADIANCE", stdout);
	fputnow(stdout);
	for (nfile = 0; an < argc; nfile++) {
		if (nfile >= MAXFILE)
			goto toomany;
		thislabel = NULL;
		input[nfile].flags = 0;
		xsgn = ysgn = '-';
		while (an < argc && (argv[an][0] == '-' || argv[an][0] == '+'
				|| argv[an][0] == '=')) {
			switch (argv[an][1]) {
			case 't':
				checkthresh = 1;
				if (argv[an][0] == '-') {
					input[nfile].flags |= HASMIN;
					input[nfile].thmin = atof(argv[an+1]);
				} else if (argv[an][0] == '+') {
					input[nfile].flags |= HASMAX;
					input[nfile].thmax = atof(argv[an+1]);
				} else
					goto userr;
				an++;
				break;
			case 'l':
				if (strcmp(argv[an], "-l"))
					goto userr;
				thislabel = argv[++an];
				break;
			case '+':
			case '-':
			case '0':
				if (argv[an][0] != '=')
					goto userr;
				xsgn = argv[an][1];
				ysgn = argv[an][2];
				if (ysgn != '+' && ysgn != '-' && ysgn != '0')
					goto userr;
				break;
			case '\0':
				if (argv[an][0] == '-')
					goto getfile;
				goto userr;
			default:
				goto userr;
			}
			an++;
		}
getfile:
		if (argc-an < (ncolumns ? 1 : 3))
			goto userr;
		if (autolabel && thislabel == NULL)
			thislabel = argv[an];
		if (!strcmp(argv[an], "-")) {
			input[nfile].name = StandardInput;
			input[nfile].fp = stdin;
		} else {
			if (argv[an][0] == '!') {
				input[nfile].name = Command;
				input[nfile].fp = popen(argv[an]+1, "r");
			} else {
				input[nfile].name = argv[an];
				input[nfile].fp = fopen(argv[an], "r");
			}
			if (input[nfile].fp == NULL) {
				perror(argv[an]);
				quit(1);
			}
		}
		an++;
						/* get header */
		if (echoheader)
			printf("%s:\n", input[nfile].name);
		getheader(input[nfile].fp, headline, NULL);
		if (wrongformat) {
			fprintf(stderr, "%s: incompatible input format\n",
					input[nfile].name);
			quit(1);
		}
						/* get picture size */
		if (fgetresolu(&input[nfile].xres, &input[nfile].yres,
				input[nfile].fp) < 0) {
			fprintf(stderr, "%s: bad picture size\n",
					input[nfile].name);
			quit(1);
		}
		if (ncolumns > 0) {
			if (curcol >= ncolumns) {
				cury = ymax + spacing;
				curx = x0;
				curcol = 0;
			}
			input[nfile].xloc = curx;
			input[nfile].yloc = cury;
			curx += input[nfile].xres + spacing;
			curcol++;
		} else {
			input[nfile].xloc = atoi(argv[an++]);
			if (xsgn == '+')
				input[nfile].xloc -= input[nfile].xres;
			else if (xsgn == '0')
				input[nfile].xloc -= input[nfile].xres/2;
			input[nfile].yloc = atoi(argv[an++]);
			if (ysgn == '+')
				input[nfile].yloc -= input[nfile].yres;
			else if (ysgn == '0')
				input[nfile].yloc -= input[nfile].yres/2;
		}
		if (input[nfile].xloc < xmin)
			xmin = input[nfile].xloc;
		if (input[nfile].yloc < ymin)
			ymin = input[nfile].yloc;
		if (input[nfile].xloc+input[nfile].xres > xmax)
			xmax = input[nfile].xloc+input[nfile].xres;
		if (input[nfile].yloc+input[nfile].yres > ymax)
			ymax = input[nfile].yloc+input[nfile].yres;
		if (thislabel != NULL) {
			if (++nfile >= MAXFILE)
				goto toomany;
			input[nfile].name = Label;
			input[nfile].flags = 0;
			input[nfile].xres = input[nfile-1].xres;
			input[nfile].yres = labelht;
			if ((input[nfile].fp = lblopen(thislabel,
					&input[nfile].xres,
					&input[nfile].yres)) == NULL)
				goto labelerr;
			input[nfile].xloc = input[nfile-1].xloc;
			input[nfile].yloc = input[nfile-1].yloc +
					input[nfile-1].yres-input[nfile].yres;
		}
	}
	if (xsiz <= 0)
		xsiz = xmax;
	else if (xsiz > xmax)
		xmax = xsiz;
	if (ysiz <= 0)
		ysiz = ymax;
	else if (ysiz > ymax)
		ymax = ysiz;
					/* add new header info. */
	printargs(argc, argv, stdout);
	if (strcmp(ourfmt, PICFMT))
		fputformat(ourfmt, stdout);	/* print format if known */
	putchar('\n');
	fprtresolu(xsiz, ysiz, stdout);

	compos();
	
	quit(0);
userr:
	fprintf(stderr,
	"Usage: %s [-h][-x xr][-y yr][-b r g b][-a n][-s p][-o x0 y0][-la][-lh h] ",
			progname);
	fprintf(stderr, "[-t min1][+t max1][-l lab][=SS] pic1 x1 y1 ..\n");
	quit(1);
toomany:
	fprintf(stderr, "%s: only %d files and labels allowed\n",
			progname, MAXFILE);
	quit(1);
labelerr:
	fprintf(stderr, "%s: error opening label\n", progname);
	quit(1);
	return 1; /* pro forma return */
}
Beispiel #20
0
static int
trace_syscall_entering(struct tcb *tcp, unsigned int *sig)
{
	int res, scno_good;

	scno_good = res = get_scno(tcp);
	if (res == 0)
		return res;
	if (res == 1)
		res = get_syscall_args(tcp);

	if (res != 1) {
		printleader(tcp);
		tprintf("%s(", scno_good == 1 ? tcp->s_ent->sys_name : "????");
		/*
		 * " <unavailable>" will be added later by the code which
		 * detects ptrace errors.
		 */
		goto ret;
	}

#ifdef LINUX_MIPSO32
	if (SEN_syscall == tcp->s_ent->sen)
		decode_mips_subcall(tcp);
#endif

#if defined(SYS_socket_subcall) || defined(SYS_ipc_subcall)
	switch (tcp->s_ent->sen) {
# ifdef SYS_socket_subcall
		case SEN_socketcall:
			decode_socket_subcall(tcp);
			break;
# endif
# ifdef SYS_ipc_subcall
		case SEN_ipc:
			decode_ipc_subcall(tcp);
			break;
# endif
	}
#endif

	/* Restrain from fault injection while the trace executes strace code. */
	if (hide_log(tcp)) {
		tcp->qual_flg &= ~QUAL_FAULT;
	}

	switch (tcp->s_ent->sen) {
		case SEN_execve:
		case SEN_execveat:
#if defined SPARC || defined SPARC64
		case SEN_execv:
#endif
			tcp->flags &= ~TCB_HIDE_LOG;
			break;
	}

	if (!(tcp->qual_flg & QUAL_TRACE)
	 || (tracing_paths && !pathtrace_match(tcp))
	) {
		tcp->flags |= TCB_INSYSCALL | TCB_FILTERED;
		tcp->sys_func_rval = 0;
		return 0;
	}

	tcp->flags &= ~TCB_FILTERED;

	if (hide_log(tcp)) {
		res = 0;
		goto ret;
	}

	if (tcp->qual_flg & QUAL_FAULT)
		inject_syscall_fault_entering(tcp, sig);

	if (cflag == CFLAG_ONLY_STATS) {
		res = 0;
		goto ret;
	}

#ifdef USE_LIBUNWIND
	if (stack_trace_enabled) {
		if (tcp->s_ent->sys_flags & STACKTRACE_CAPTURE_ON_ENTER)
			unwind_capture_stacktrace(tcp);
	}
#endif

	printleader(tcp);
	tprintf("%s(", tcp->s_ent->sys_name);
	if (tcp->qual_flg & QUAL_RAW)
		res = printargs(tcp);
	else
		res = tcp->s_ent->sys_func(tcp);

	fflush(tcp->outf);
 ret:
	tcp->flags |= TCB_INSYSCALL;
	tcp->sys_func_rval = res;
	/* Measure the entrance time as late as possible to avoid errors. */
	if (Tflag || cflag)
		gettimeofday(&tcp->etime, NULL);
	return res;
}
Beispiel #21
0
int
main(int  argc, char  *argv[])
{
#define	 check(ol,al)		if (argv[i][ol] || \
				badarg(argc-i-1,argv+i+1,al)) \
				goto badopt
#define	 bool(olen,var)		switch (argv[i][olen]) { \
				case '\0': var = !var; break; \
				case 'y': case 'Y': case 't': case 'T': \
				case '+': case '1': var = 1; break; \
				case 'n': case 'N': case 'f': case 'F': \
				case '-': case '0': var = 0; break; \
				default: goto badopt; }
	char  *err;
	char  *recover = NULL;
	char  *outfile = NULL;
	char  *zfile = NULL;
	int  loadflags = ~IO_FILES;
	int  seqstart = 0;
	int  persist = 0;
	int  duped1 = -1;
	int  rval;
	int  i;
					/* record start time */
	tstart = time((time_t *)NULL);
					/* global program name */
	progname = argv[0] = fixargv0(argv[0]);
					/* option city */
	for (i = 1; i < argc; i++) {
						/* expand arguments */
		while ((rval = expandarg(&argc, &argv, i)) > 0)
			;
		if (rval < 0) {
			sprintf(errmsg, "cannot expand '%s'", argv[i]);
			error(SYSTEM, errmsg);
		}
		if (argv[i] == NULL || argv[i][0] != '-')
			break;			/* break from options */
		if (!strcmp(argv[i], "-version")) {
			puts(VersionID);
			quit(0);
		}
		if (!strcmp(argv[i], "-defaults") ||
				!strcmp(argv[i], "-help")) {
			printdefaults();
			quit(0);
		}
		rval = getrenderopt(argc-i, argv+i);
		if (rval >= 0) {
			i += rval;
			continue;
		}
		rval = getviewopt(&ourview, argc-i, argv+i);
		if (rval >= 0) {
			i += rval;
			continue;
		}
						/* rpict options */
		switch (argv[i][1]) {
		case 'v':				/* view file */
			if (argv[i][2] != 'f')
				goto badopt;
			check(3,"s");
			rval = viewfile(argv[++i], &ourview, NULL);
			if (rval < 0) {
				sprintf(errmsg,
				"cannot open view file \"%s\"",
						argv[i]);
				error(SYSTEM, errmsg);
			} else if (rval == 0) {
				sprintf(errmsg,
					"bad view file \"%s\"",
						argv[i]);
				error(USER, errmsg);
			}
			break;
		case 'p':				/* pixel */
			switch (argv[i][2]) {
			case 's':				/* sample */
				check(3,"i");
				psample = atoi(argv[++i]);
				break;
			case 't':				/* threshold */
				check(3,"f");
				maxdiff = atof(argv[++i]);
				break;
			case 'j':				/* jitter */
				check(3,"f");
				dstrpix = atof(argv[++i]);
				break;
			case 'a':				/* aspect */
				check(3,"f");
				pixaspect = atof(argv[++i]);
				break;
			case 'm':				/* motion */
				check(3,"f");
				mblur = atof(argv[++i]);
				break;
			case 'd':				/* aperture */
				check(3,"f");
				dblur = atof(argv[++i]);
				break;
			default:
				goto badopt;
			}
			break;
		case 'x':				/* x resolution */
			check(2,"i");
			hresolu = atoi(argv[++i]);
			break;
		case 'y':				/* y resolution */
			check(2,"i");
			vresolu = atoi(argv[++i]);
			break;
		case 'S':				/* slave index */
			check(2,"i");
			seqstart = atoi(argv[++i]);
			break;
		case 'o':				/* output file */
			check(2,"s");
			outfile = argv[++i];
			break;
		case 'z':				/* z file */
			check(2,"s");
			zfile = argv[++i];
			break;
		case 'r':				/* recover file */
			if (argv[i][2] == 'o') {		/* +output */
				check(3,"s");
				outfile = argv[i+1];
			} else
				check(2,"s");
			recover = argv[++i];
			break;
		case 't':				/* timer */
			check(2,"i");
			ralrm = atoi(argv[++i]);
			break;
#ifdef  PERSIST
		case 'P':				/* persist file */
			if (argv[i][2] == 'P') {
				check(3,"s");
				persist = PARALLEL;
			} else {
				check(2,"s");
				persist = PERSIST;
			}
			persistfile(argv[++i]);
			break;
#endif
		case 'w':				/* warnings */
			rval = erract[WARNING].pf != NULL;
			bool(2,rval);
			if (rval) erract[WARNING].pf = wputs;
			else erract[WARNING].pf = NULL;
			break;
		case 'e':				/* error file */
			check(2,"s");
			errfile = argv[++i];
			break;
		default:
			goto badopt;
		}
	}
	err = setview(&ourview);	/* set viewing parameters */
	if (err != NULL)
		error(USER, err);
					/* initialize object types */
	initotypes();
					/* initialize urand */
	if (rand_samp) {
		srandom((long)time(0));
		initurand(0);
	} else {
		srandom(0L);
		initurand(2048);
	}
					/* set up signal handling */
	sigdie(SIGINT, "Interrupt");
#ifdef SIGHUP
	sigdie(SIGHUP, "Hangup");
#endif
	sigdie(SIGTERM, "Terminate");
#ifdef SIGPIPE
	sigdie(SIGPIPE, "Broken pipe");
#endif
#ifdef SIGALRM
	sigdie(SIGALRM, "Alarm clock");
#endif
#ifdef	SIGXCPU
	sigdie(SIGXCPU, "CPU limit exceeded");
	sigdie(SIGXFSZ, "File size exceeded");
#endif
					/* open error file */
	if (errfile != NULL) {
		if (freopen(errfile, "a", stderr) == NULL)
			quit(2);
		fprintf(stderr, "**************\n*** PID %5d: ",
				getpid());
		printargs(argc, argv, stderr);
		putc('\n', stderr);
		fflush(stderr);
	}
#ifdef	NICE
	nice(NICE);			/* lower priority */
#endif
					/* get octree */
	if (i == argc)
		octname = NULL;
	else if (i == argc-1)
		octname = argv[i];
	else
		goto badopt;
	if (seqstart > 0 && octname == NULL)
		error(USER, "missing octree argument");
					/* set up output */
#ifdef  PERSIST
	if (persist) {
		if (recover != NULL)
			error(USER, "persist option used with recover file");
		if (seqstart <= 0)
			error(USER, "persist option only for sequences");
		if (outfile == NULL)
		duped1 = dup(fileno(stdout));	/* don't lose our output */
		openheader();
	} else
#endif
	if (outfile != NULL)
		openheader();
#ifdef	_WIN32
	SET_FILE_BINARY(stdout);
	if (octname == NULL)
		SET_FILE_BINARY(stdin);
#endif
	readoct(octname, loadflags, &thescene, NULL);
	nsceneobjs = nobjects;

	if (loadflags & IO_INFO) {	/* print header */
		printargs(i, argv, stdout);
		printf("SOFTWARE= %s\n", VersionID);
	}

	marksources();			/* find and mark sources */

	setambient();			/* initialize ambient calculation */

#ifdef  PERSIST
	if (persist) {
		fflush(stdout);
		if (outfile == NULL) {		/* reconnect stdout */
			dup2(duped1, fileno(stdout));
			close(duped1);
		}
		if (persist == PARALLEL) {	/* multiprocessing */
			preload_objs();		/* preload scene */
			shm_boundary = (char *)malloc(16);
			strcpy(shm_boundary, "SHM_BOUNDARY");
			while ((rval=fork()) == 0) {	/* keep on forkin' */
				pflock(1);
				pfhold();
				tstart = time((time_t *)NULL);
				ambsync();		/* load new values */
			}
			if (rval < 0)
				error(SYSTEM, "cannot fork child for persist function");
			pfdetach();		/* parent will run then exit */
		}
	}
runagain:
	if (persist) {
		if (outfile == NULL)			/* if out to stdout */
			dupheader();			/* send header */
		else					/* if out to file */
			duped1 = dup(fileno(stdout));	/* hang onto pipe */
	}
#endif
					/* batch render picture(s) */
	rpict(seqstart, outfile, zfile, recover);
					/* flush ambient file */
	ambsync();
#ifdef  PERSIST
	if (persist == PERSIST) {	/* first run-through */
		if ((rval=fork()) == 0) {	/* child loops until killed */
			pflock(1);
			persist = PCHILD;
		} else {			/* original process exits */
			if (rval < 0)
				error(SYSTEM, "cannot fork child for persist function");
			pfdetach();		/* parent exits */
		}
	}
	if (persist == PCHILD) {	/* wait for a signal then go again */
		if (outfile != NULL)
			close(duped1);		/* release output handle */
		pfhold();
		tstart = time((time_t *)NULL);	/* reinitialize */
		raynum = nrays = 0;
		goto runagain;
	}
#endif
	quit(0);

badopt:
	sprintf(errmsg, "command line error at '%s'", argv[i]);
	error(USER, errmsg);
	return 1; /* pro forma return */

#undef	check
#undef	bool
}
int
main(
	int	argc,
	char	**argv
)
{
	int	i;

	progname = argv[0];
	for (i = 1; i < argc && argv[i][0] == '-'; i++)
		switch (argv[i][1]) {
		case 'd':				/* debug output */
			i++;
			if (badarg(argc-i, argv+i, "s"))
				goto userr;
			if ((debugfp = fopen(argv[i], "w")) == NULL) {
				perror(argv[i]);
				exit(1);
			}
			SET_FILE_BINARY(debugfp);
			newheader("RADIANCE", debugfp);		/* start */
			printargs(argc, argv, debugfp);		/* header */
			break;
		case 'p':				/* picture position */
			if (badarg(argc-i-1, argv+i+1, "iiiiiiii"))
				goto userr;
			bounds[0][0] = atoi(argv[++i]);
			bounds[0][1] = atoi(argv[++i]);
			bounds[1][0] = atoi(argv[++i]);
			bounds[1][1] = atoi(argv[++i]);
			bounds[2][0] = atoi(argv[++i]);
			bounds[2][1] = atoi(argv[++i]);
			bounds[3][0] = atoi(argv[++i]);
			bounds[3][1] = atoi(argv[++i]);
			scanning = 2;
			break;
		case 'P':				/* pick position */
			scanning = 3;
			break;
		case 'i':				/* irradiance factor */
			i++;
			if (badarg(argc-i, argv+i, "f"))
				goto userr;
			irrad = atof(argv[i]);
			break;
		case 'm':				/* raw map output */
			rawmap = 1;
			break;
		case 'c':				/* color input */
			scanning = 0;
			break;
		default:
			goto userr;
		}
							/* open files */
	if (i < argc && freopen(argv[i], "r", stdin) == NULL) {
		perror(argv[i]);
		exit(1);
	}
	if (i+1 < argc && freopen(argv[i+1], "w", stdout) == NULL) {
		perror(argv[i+1]);
		exit(1);
	}
	if (scanning) {			/* load input picture header */
		SET_FILE_BINARY(stdin);
		if (checkheader(stdin, COLRFMT, NULL) < 0 ||
				fgetresolu(&xmax, &ymax, stdin) < 0) {
			fprintf(stderr, "%s: bad input picture\n", progname);
			exit(1);
		}
		if (scanning == 3) {
			if (i >= argc)
				goto userr;
			pickchartpos(argv[i]);
			scanning = 2;
		}
	} else {			/* else set default xmax and ymax */
		xmax = 512;
		ymax = 2*512/3;
	}
	if (scanning != 2) {		/* use default boundaries */
		bounds[0][0] = bounds[2][0] = .029*xmax + .5;
		bounds[0][1] = bounds[1][1] = .956*ymax + .5;
		bounds[1][0] = bounds[3][0] = .971*xmax + .5;
		bounds[2][1] = bounds[3][1] = .056*ymax + .5;
	}
	init();				/* initialize */
	if (scanning)			/* get picture colors */
		getpicture();
	else
		getcolors();
	compute();			/* compute color mapping */
	if (rawmap) {			/* print out raw correspondence */
		register int	j;

		printf("# Color correspondence produced by:\n#\t\t");
		printargs(argc, argv, stdout);
		printf("#\tUsage: pcwarp %s uncorrected.hdr > corrected.hdr\n",
				i+1 < argc ? argv[i+1] : "{this_file}");
		printf("#\t   Or: pcond [options] -m %s orig.hdr > output.hdr\n",
				i+1 < argc ? argv[i+1] : "{this_file}");
		for (j = 0; j < 24; j++)
			printf("%f %f %f    %f %f %f\n",
				colval(inpRGB[j],RED), colval(inpRGB[j],GRN),
				colval(inpRGB[j],BLU), colval(mbRGB[j],RED),
				colval(mbRGB[j],GRN), colval(mbRGB[j],BLU));
		if (scanning && debugfp != NULL)
			cwarp();		/* color warp for debugging */
	} else {			/* print color mapping */
						/* print header */
		printf("{\n\tColor correction file computed by:\n\t\t");
		printargs(argc, argv, stdout);
		printf("\n\tUsage: pcomb -f %s uncorrected.hdr > corrected.hdr\n",
				i+1 < argc ? argv[i+1] : "{this_file}");
		if (!scanning)
			printf("\t   Or: pcond [options] -f %s orig.hdr > output.hdr\n",
					i+1 < argc ? argv[i+1] : "{this_file}");
		printf("}\n");
		putmapping();			/* put out color mapping */
	}
	if (debugfp != NULL) {		/* put out debug picture */
		if (scanning)
			picdebug();
		else
			clrdebug();
	}
	exit(0);
userr:
	fprintf(stderr,
"Usage: %s [-d dbg.hdr][-P | -p xul yul xur yur xll yll xlr ylr][-i irrad][-m] input.hdr [output.{cal|cwp}]\n",
			progname);
	fprintf(stderr, "   or: %s [-d dbg.hdr][-i irrad][-m] -c [xyY.dat [output.{cal|cwp}]]\n",
			progname);
	exit(1);
	return 1; /* pro forma return */
}
Beispiel #23
0
int main(int argc, char **argv)
{
   osFile fh;
   uint32_t total,areas,totaldupes;
   time_t firsttime,t;
   uint32_t DayStatsWritten;
   char buf[200],date[30],date2[30];
   struct DiskAreaStats dastat;
   struct DiskNodeStats dnstat;
   struct StatsNode *sn;
   struct NodeStatsNode *nsn;
   struct jbList StatsList;
   struct jbList NodesList;
   uint32_t c,num,tot;
   uint16_t total8days[8];
   char sortmode;
   struct tm *tp;
   char *monthnames[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","???"};

   signal(SIGINT,breakfunc);
         
   if(!osInit())
      exit(OS_EXIT_ERROR);

   if(argc > 1 &&
	  (strcmp(argv[1],"?")==0      ||
		strcmp(argv[1],"-h")==0     ||
		strcmp(argv[1],"--help")==0 ||
		strcmp(argv[1],"help")==0 ||
		strcmp(argv[1],"/h")==0     ||
		strcmp(argv[1],"/?")==0 ))
   {
      printargs(args);
      osEnd();
      exit(OS_EXIT_OK);
   }

   if(!parseargs(args,argc,argv))
   {
      osEnd();
      exit(OS_EXIT_ERROR);
   }

   sortmode='a';
   
   if(args[ARG_SORT].data)
      sortmode=tolower(((char *)args[ARG_SORT].data)[0]);
      
   if(!strchr("amtdlu",sortmode))
   {
      printf("Unknown sort mode %c\n",sortmode);
      osEnd();
      exit(OS_EXIT_ERROR);
   }

   if(args[ARG_NOAREAS].data && args[ARG_NONODES].data)
   {
      printf("Nothing to do\n");
      osEnd();
      exit(OS_EXIT_ERROR);
   }

   printf("CrashStats "VERSION" © "  COPYRIGHT " Johan Billing\n");

   if(!(fh=osOpen(args[ARG_FILE].data,MODE_OLDFILE)))
   {
		uint32_t err=osError();
      printf("Error opening %s\n",(char *)args[ARG_FILE].data);
		printf("Error: %s\n",osErrorMsg(err));		
      osEnd();
      exit(OS_EXIT_ERROR);
   }

   osRead(fh,buf,4);
   buf[4]=0;

   if(strcmp(buf,STATS_IDENTIFIER)!=0)
   {
      printf("Unknown format of stats file\n");
      osClose(fh);
      osEnd();
      exit(OS_EXIT_ERROR);
   }

   osRead(fh,&DayStatsWritten,sizeof(uint32_t));

   total=0;
   totaldupes=0;
   firsttime=0;
   areas=0;

   for(c=0;c<8;c++)
   	total8days[c]=0;

   jbNewList(&StatsList);
   jbNewList(&NodesList);

   osRead(fh,&num,sizeof(uint32_t));
   c=0;

   if(!args[ARG_NOAREAS].data)
   {
      while(c<num && osRead(fh,&dastat,sizeof(struct DiskAreaStats))==sizeof(struct DiskAreaStats))
      {
         if(!args[ARG_GROUP].data || CheckFlags(dastat.Group,args[ARG_GROUP].data))
         {
            if(!(sn=osAlloc(sizeof(struct StatsNode))))
            {
               printf("Out of memory\n");
               jbFreeList(&StatsList);
               osClose(fh);
               osEnd();
               exit(OS_EXIT_ERROR);
            }

            jbAddNode(&StatsList,(struct jbNode *)sn);

            strcpy(sn->Tagname,dastat.Tagname);
            sn->Dupes=dastat.Dupes;
            sn->Total=dastat.TotalTexts;
            sn->FirstTime=dastat.FirstTime;
            sn->LastTime=dastat.LastTime;
            memcpy(&sn->Last8Days[0],&dastat.Last8Days[0],8*sizeof(uint16_t));

            sn->Average=CalculateAverage(&dastat.Last8Days[0],dastat.TotalTexts,DayStatsWritten,sn->FirstTime / (24*60*60));
         }

         if(dastat.FirstTime!=0)
            if(firsttime==0 || firsttime > dastat.FirstTime)
               firsttime=dastat.FirstTime;

         c++;
      }
   }
   else
   {
      while(c<num && osRead(fh,&dastat,sizeof(struct DiskAreaStats))==sizeof(struct DiskAreaStats))
         c++;
   }

   osRead(fh,&num,sizeof(uint32_t));
   c=0;

   if(!args[ARG_NONODES].data)
   {
      while(c<num && osRead(fh,&dnstat,sizeof(struct DiskNodeStats))==sizeof(struct DiskNodeStats))
      {
         if(!(nsn=osAlloc(sizeof(struct NodeStatsNode))))
         {
            printf("Out of memory\n");
            jbFreeList(&NodesList);
            jbFreeList(&StatsList);
            osClose(fh);
            osEnd();
            exit(OS_EXIT_ERROR);
         }

         jbAddNode(&NodesList,(struct jbNode *)nsn);

         Copy4D(&nsn->Node,&dnstat.Node);

         nsn->GotNetmails=dnstat.GotNetmails;
         nsn->GotNetmailBytes=dnstat.GotNetmailBytes;
         nsn->SentNetmails=dnstat.SentNetmails;
         nsn->SentNetmailBytes=dnstat.SentNetmailBytes;
         nsn->GotEchomails=dnstat.GotEchomails;
         nsn->GotEchomailBytes=dnstat.GotEchomailBytes;
         nsn->SentEchomails=dnstat.SentEchomails;
         nsn->SentEchomailBytes=dnstat.SentEchomailBytes;
         nsn->Dupes=dnstat.Dupes;

         nsn->Days=DayStatsWritten-dnstat.FirstTime % (24*60*60);
         if(nsn->Days==0) nsn->Days=1;

         nsn->FirstTime=dnstat.FirstTime;

         if(dnstat.FirstTime!=0)
            if(firsttime==0 || firsttime > dnstat.FirstTime)
               firsttime=dnstat.FirstTime;

         c++;
      }
   }
   else
   {
      while(c<num && osRead(fh,&dnstat,sizeof(struct DiskNodeStats))==sizeof(struct DiskNodeStats))
         c++;
   }

   osClose(fh);

   t=(time_t)DayStatsWritten * 24*60*60;

   tp=localtime(&firsttime);
   sprintf(date,"%02d-%s-%02d",tp->tm_mday,monthnames[tp->tm_mon],tp->tm_year%100);
   
   tp=localtime(&t);
   sprintf(date2,"%02d-%s-%02d",tp->tm_mday,monthnames[tp->tm_mon],tp->tm_year%100);

   printf("\nStatistics from %s to %s\n",date,date2);
   
   if(!ctrlc && !args[ARG_NOAREAS].data)
   {
      Sort(&StatsList,'a');
      Sort(&StatsList,sortmode);
      printf("\n");

      if(args[ARG_LAST7].data)
      {
         printf("Area                             ");

         for(c=1;c<8;c++)
         {
            t=(DayStatsWritten-c)*24*60*60;
            tp=localtime(&t);
            printf("   %02d",tp->tm_mday);
         }

         printf("   Total\n============================================================================\n");

         if(!ctrlc)
         {
            for(sn=(struct StatsNode *)StatsList.First;sn && !ctrlc;sn=sn->Next)
            {
               tot=0;

               for(c=1;c<8;c++)
                  tot+=sn->Last8Days[c];

               printf("%-33.33s %4d %4d %4d %4d %4d %4d %4d : %5d\n",
                  sn->Tagname,
                  sn->Last8Days[1],
                  sn->Last8Days[2],
                  sn->Last8Days[3],
                  sn->Last8Days[4],
                  sn->Last8Days[5],
                  sn->Last8Days[6],
                  sn->Last8Days[7],
                  tot);

               for(c=1;c<8;c++)
                  total8days[c]+=sn->Last8Days[c];

               areas++;
            }

            if(!ctrlc)
            {
               tot=0;

               for(c=1;c<8;c++)
                  tot+=total8days[c];

               printf("=============================================================================\n");
               sprintf(buf,"Totally in all %u areas",areas);

               printf("%-33.33s %4d %4d %4d %4d %4d %4d %4d : %5d\n",
                  buf,
                  total8days[1],
                  total8days[2],
                  total8days[3],
                  total8days[4],
                  total8days[5],
                  total8days[6],
                  total8days[7],
                  tot);
            }
         }
      }
      else
      {
         printf("Area                           First     Last         Msgs  Msgs/day   Dupes\n");
         printf("============================================================================\n");

         if(!ctrlc)
         {
            for(sn=(struct StatsNode *)StatsList.First;sn && !ctrlc;sn=sn->Next)
            {
               if(sn->LastTime==0)
               {
                  strcpy(date2,"<Never>");
               }
               else
               {
                  tp=localtime(&sn->LastTime);
                  sprintf(date2,"%02d-%s-%02d",tp->tm_mday,monthnames[tp->tm_mon],tp->tm_year%100);
               }

               if(sn->FirstTime==0)
               {
                  strcpy(date,"<Never>");
               }
               else
               {
                  tp=localtime(&sn->FirstTime);
                  sprintf(date,"%02d-%s-%02d",tp->tm_mday,monthnames[tp->tm_mon],tp->tm_year%100);
               }

               for(c=0;c<8;c++)
                  total8days[c]+=sn->Last8Days[c];

               total+=sn->Total;
               totaldupes+=sn->Dupes;
               areas++;

               printf("%-29.30s %-9.9s %-9.9s %7d   %7d %7d\n",sn->Tagname,date,date2,sn->Total,sn->Average,sn->Dupes);
            }
         }

         if(!ctrlc)
         {
            printf("============================================================================\n");
            sprintf(buf,"Totally in all %u areas",areas);
            printf("%-42s         %7d   %7d %7d\n",
               buf,
               total,
               CalculateAverage(&total8days[0],total,DayStatsWritten,firsttime / (24*60*60)),
               totaldupes);
         }
      }
   }

   if(!ctrlc && !args[ARG_NONODES].data)
   {
      SortNodes(&NodesList);

      printf("\n");
      printf("Nodes statistics\n");
      printf("================\n");

      for(nsn=(struct NodeStatsNode *)NodesList.First;nsn && !ctrlc;nsn=nsn->Next)
      {
         if(nsn->FirstTime==0)
         {
            strcpy(date,"<Never>");
         }
         else
         {
            tp=localtime(&nsn->FirstTime);
            sprintf(date,"%0d-%s-%0d",tp->tm_mday,monthnames[tp->tm_mon],tp->tm_year%100);
         }

         sprintf(buf,"%u:%u/%u.%u",nsn->Node.Zone,nsn->Node.Net,nsn->Node.Node,nsn->Node.Point);

			printf("%-30.40s Statistics since: %s\n\n",buf,date);
			printf("                                  Sent netmails: %u/%s\n",nsn->SentNetmails,unit(nsn->SentNetmailBytes));
			printf("                              Received netmails: %u/%s\n",nsn->GotNetmails,unit(nsn->GotNetmailBytes));
			printf("                                 Sent echomails: %u/%s\n",nsn->SentEchomails,unit(nsn->SentEchomailBytes));
			printf("                             Received echomails: %u/%s\n",nsn->GotEchomails,unit(nsn->GotEchomailBytes));
			printf("                                          Dupes: %u\n",nsn->Dupes);
         printf("\n");
      }
   }

   if(ctrlc)
   {
      printf("*** Break\n");
   }
   else
   {
      printf("\n");
   }

   jbFreeList(&StatsList);
   jbFreeList(&NodesList);

   osEnd();
   
   exit(OS_EXIT_OK);
}
Beispiel #24
0
int
main(int argc, char *argv[])
{
#define	 check(ol,al)		if (argv[i][ol] || \
				badarg(argc-i-1,argv+i+1,al)) \
				goto badopt
#define	 check_bool(olen,var)		switch (argv[i][olen]) { \
				case '\0': var = !var; break; \
				case 'y': case 'Y': case 't': case 'T': \
				case '+': case '1': var = 1; break; \
				case 'n': case 'N': case 'f': case 'F': \
				case '-': case '0': var = 0; break; \
				default: goto badopt; }
	char  *octnm = NULL;
	char  *err;
	int  rval;
	int  i;
					/* global program name */
	progname = argv[0] = fixargv0(argv[0]);
					/* set our defaults */
	shadthresh = .1;
	shadcert = .25;
	directrelay = 0;
	vspretest = 128;
	srcsizerat = 0.;
	specthresh = .3;
	specjitter = 1.;
	maxdepth = 6;
	minweight = 1e-2;
	ambacc = 0.3;
	ambres = 32;
	ambdiv = 256;
	ambssamp = 64;
					/* option city */
	for (i = 1; i < argc; i++) {
						/* expand arguments */
		while ((rval = expandarg(&argc, &argv, i)) > 0)
			;
		if (rval < 0) {
			sprintf(errmsg, "cannot expand '%s'", argv[i]);
			error(SYSTEM, errmsg);
		}
		if (argv[i] == NULL || argv[i][0] != '-')
			break;			/* break from options */
		if (!strcmp(argv[i], "-version")) {
			puts(VersionID);
			quit(0);
		}
		if (!strcmp(argv[i], "-defaults") ||
				!strcmp(argv[i], "-help")) {
			printdefaults();
			quit(0);
		}
		if (!strcmp(argv[i], "-devices")) {
			printdevices();
			quit(0);
		}
		rval = getrenderopt(argc-i, argv+i);
		if (rval >= 0) {
			i += rval;
			continue;
		}
		rval = getviewopt(&ourview, argc-i, argv+i);
		if (rval >= 0) {
			i += rval;
			continue;
		}
		switch (argv[i][1]) {
		case 'n':				/* # processes */
			check(2,"i");
			nproc = atoi(argv[++i]);
			if (nproc <= 0)
				error(USER, "bad number of processes");
			break;
		case 'v':				/* view file */
			if (argv[i][2] != 'f')
				goto badopt;
			check(3,"s");
			rval = viewfile(argv[++i], &ourview, NULL);
			if (rval < 0) {
				sprintf(errmsg,
				"cannot open view file \"%s\"",
						argv[i]);
				error(SYSTEM, errmsg);
			} else if (rval == 0) {
				sprintf(errmsg,
					"bad view file \"%s\"",
						argv[i]);
				error(USER, errmsg);
			}
			break;
		case 'b':				/* grayscale */
			check_bool(2,greyscale);
			break;
		case 'p':				/* pixel */
			switch (argv[i][2]) {
			case 's':				/* sample */
				check(3,"i");
				psample = atoi(argv[++i]);
				break;
			case 't':				/* threshold */
				check(3,"f");
				maxdiff = atof(argv[++i]);
				break;
			case 'e':				/* exposure */
				check(3,"f");
				exposure = atof(argv[++i]);
				if (argv[i][0] == '+' || argv[i][0] == '-')
					exposure = pow(2.0, exposure);
				break;
			default:
				goto badopt;
			}
			break;
		case 'w':				/* warnings */
			rval = erract[WARNING].pf != NULL;
			check_bool(2,rval);
			if (rval) erract[WARNING].pf = wputs;
			else erract[WARNING].pf = NULL;
			break;
		case 'e':				/* error file */
			check(2,"s");
			errfile = argv[++i];
			break;
		case 'o':				/* output device */
			check(2,"s");
			dvcname = argv[++i];
			break;
		case 'R':				/* render input file */
			check(2,"s");
			strcpy(rifname, argv[++i]);
			break;
		default:
			goto badopt;
		}
	}
	err = setview(&ourview);	/* set viewing parameters */
	if (err != NULL)
		error(USER, err);
						/* set up signal handling */
	sigdie(SIGINT, "Interrupt");
	sigdie(SIGTERM, "Terminate");
#if !defined(_WIN32) && !defined(_WIN64)
	sigdie(SIGHUP, "Hangup");
	sigdie(SIGPIPE, "Broken pipe");
	sigdie(SIGALRM, "Alarm clock");
#endif
					/* open error file */
	if (errfile != NULL) {
		if (freopen(errfile, "a", stderr) == NULL)
			quit(2);
		fprintf(stderr, "**************\n*** PID %5d: ",
				getpid());
		printargs(argc, argv, stderr);
		putc('\n', stderr);
		fflush(stderr);
	}
#ifdef	NICE
	nice(NICE);			/* lower priority */
#endif
					/* get octree */
	if (i == argc)
		octnm = NULL;
	else if (i == argc-1)
		octnm = argv[i];
	else
		goto badopt;
	if (octnm == NULL)
		error(USER, "missing octree argument");
					/* set up output & start process(es) */
	SET_FILE_BINARY(stdout);
	
	ray_init(octnm);		/* also calls ray_init_pmap() */
	
/* temporary shortcut, until winrview is refactored into a "device" */
#ifndef WIN_RVIEW
	rview();			/* run interactive viewer */


	devclose();			/* close output device */
#endif

	/* PMAP: free photon maps */
	ray_done_pmap();
	
#ifdef WIN_RVIEW
	return 1;
#endif
	quit(0);

badopt:
	sprintf(errmsg, "command line error at '%s'", argv[i]);
	error(USER, errmsg);
	return 1; /* pro forma return */

#undef	check
#undef	check_bool
}
Beispiel #25
0
int
main(		/* convert object files to an octree */
	int  argc,
	char  *argv[]
)
{
	FVECT  bbmin, bbmax;
	char  *infile = NULL;
	int  inpfrozen = 0;
	int  outflags = IO_ALL;
	OBJECT	startobj;
	int  i;

	progname = argv[0] = fixargv0(argv[0]);

	ot_initotypes();

	for (i = 1; i < argc && argv[i][0] == '-'; i++)
		switch (argv[i][1]) {
		case '\0':				/* scene from stdin */
			goto breakopt;
		case 'i':				/* input octree */
			infile = argv[++i];
			break;
		case 'b':				/* bounding cube */
			thescene.cuorg[0] = atof(argv[++i]) - OMARGIN;
			thescene.cuorg[1] = atof(argv[++i]) - OMARGIN;
			thescene.cuorg[2] = atof(argv[++i]) - OMARGIN;
			thescene.cusize = atof(argv[++i]) + 2*OMARGIN;
			break;
		case 'n':				/* set limit */
			objlim = atoi(argv[++i]);
			break;
		case 'r':				/* resolution limit */
			resolu = atoi(argv[++i]);
			break;
		case 'f':				/* freeze octree */
			outflags &= ~IO_FILES;
			break;
		case 'w':				/* supress warnings */
			nowarn = 1;
			break;
		default:
			sprintf(errmsg, "unknown option: '%s'", argv[i]);
			error(USER, errmsg);
			break;
		}
breakopt:
	SET_FILE_BINARY(stdout);
	if (infile != NULL) {		/* get old octree & objects */
		if (thescene.cusize > FTINY)
			error(USER, "only one of '-b' or '-i'");
		nfiles = readoct(infile, IO_ALL, &thescene, ofname);
		if (nfiles == 0)
			inpfrozen++;
	} else
		newheader("RADIANCE", stdout);	/* new binary file header */
	printargs(argc, argv, stdout);
	fputformat(OCTFMT, stdout);
	printf("\n");

	startobj = nobjects;		/* previous objects already converted */

	for ( ; i < argc; i++)		/* read new scene descriptions */
		if (!strcmp(argv[i], "-")) {	/* from stdin */
			readobj(NULL);
			outflags &= ~IO_FILES;
		} else {			/* from file */
			if (nfiles >= MAXOBJFIL)
				error(INTERNAL, "too many scene files");
			readobj(ofname[nfiles++] = argv[i]);
		}

	ofname[nfiles] = NULL;

	if (inpfrozen && outflags & IO_FILES) {
		error(WARNING, "frozen octree");
		outflags &= ~IO_FILES;
	}
						/* find bounding box */
	bbmin[0] = bbmin[1] = bbmin[2] = FHUGE;
	bbmax[0] = bbmax[1] = bbmax[2] = -FHUGE;
	for (i = startobj; i < nobjects; i++)
		add2bbox(objptr(i), bbmin, bbmax);
						/* set/check cube */
	if (thescene.cusize == 0.0) {
		if (bbmin[0] <= bbmax[0]) {
			for (i = 0; i < 3; i++) {
				bbmin[i] -= OMARGIN;
				bbmax[i] += OMARGIN;
			}
			for (i = 0; i < 3; i++)
				if (bbmax[i] - bbmin[i] > thescene.cusize)
					thescene.cusize = bbmax[i] - bbmin[i];
			for (i = 0; i < 3; i++)
				thescene.cuorg[i] =
					(bbmax[i]+bbmin[i]-thescene.cusize)*.5;
		}
	} else {
		for (i = 0; i < 3; i++)
			if (bbmin[i] < thescene.cuorg[i] ||
				bbmax[i] > thescene.cuorg[i] + thescene.cusize)
				error(USER, "boundary does not encompass scene");
	}

	mincusize = thescene.cusize / resolu - FTINY;

	for (i = startobj; i < nobjects; i++)		/* add new objects */
		addobject(&thescene, i);

	thescene.cutree = combine(thescene.cutree);	/* optimize */

	writeoct(outflags, &thescene, ofname);	/* write structures to stdout */

	quit(0);
	return 0; /* pro forma return */
}
int
main(
	int  argc,
	char  **argv
)
{
	int  dim = 0;
	FILE  *fp;
	int  i;

	if (argc > 1 && !strcmp(argv[1], "-d")) {
		argc--; argv++;
		dim = 1;
		SET_FILE_BINARY(stdin);
	} else if (argc > 2 && !strcmp(argv[1], "-c")) {
		SET_FILE_BINARY(stdin);
		SET_FILE_BINARY(stdout);
		setvbuf(stdin, NULL, _IONBF, 2);
		getheader(stdin, (gethfunc *)fputs, stdout);
		printargs(argc-2, argv+2, stdout);
		fputc('\n', stdout);
		fflush(stdout);
		execvp(argv[2], argv+2);
		perror(argv[2]);
		return 1;
	} else if (argc > 2 && !strcmp(argv[1], "-a")) {
		SET_FILE_BINARY(stdin);
		SET_FILE_BINARY(stdout);
		getheader(stdin, (gethfunc *)fputs, stdout);
		for (i = 2; i < argc; i++) {
			int	len = strlen(argv[i]);
			if (!len) continue;
			fputs(argv[i], stdout);
			if (argv[i][len-1] != '\n')
				fputc('\n', stdout);
		}
		fputc('\n', stdout);
		copycat();
		return 0;
	} else if (argc == 2 && !strcmp(argv[1], "-")) {
		SET_FILE_BINARY(stdin);
		SET_FILE_BINARY(stdout);
		getheader(stdin, NULL, NULL);
		copycat();
		return 0;
	}
	for (i = 1; i < argc; i++) {
		fputs(argv[i], stdout);
		if ((fp = fopen(argv[i], "r")) == NULL)
			fputs(": cannot open\n", stdout);
		else {
			if (dim) {
				fputs(": ", stdout);
				getdim(fp);
			} else {
				tabstr(":\n", NULL);
				getheader(fp, tabstr, NULL);
				fputc('\n', stdout);
			}
			fclose(fp);
		}
	}
	if (argc == 1) {
		if (dim) {
			getdim(stdin);
		} else {
			getheader(stdin, (gethfunc *)fputs, stdout);
			fputc('\n', stdout);
		}
	}
	return 0;
}
Beispiel #27
0
int
main(		/* compile a .OBJ file into a mesh */
	int  argc,
	char  *argv[]
)
{
	int  nmatf = 0;
	char  pathnames[12800];
	char  *pns = pathnames;
	char  *matinp[128];
	char  *cp;
	int  i, j;

	progname = argv[0];
	ofun[OBJ_FACE].funp = o_face;

	for (i = 1; i < argc && argv[i][0] == '-'; i++)
		switch (argv[i][1]) {
		case 'n':				/* set limit */
			objlim = atoi(argv[++i]);
			break;
		case 'r':				/* resolution limit */
			resolu = atoi(argv[++i]);
			break;
		case 'a':				/* material file */
			matinp[nmatf++] = argv[++i];
			break;
		case 'l':				/* library material */
			cp = getpath(argv[++i], getrlibpath(), R_OK);
			if (cp == NULL) {
				sprintf(errmsg,
					"cannot find library material: '%s'",
						argv[i]);
				error(USER, errmsg);
			}
			matinp[nmatf++] = strcpy(pns, cp);
			while (*pns++)
				;
			break;
		case 'w':				/* supress warnings */
			nowarn = 1;
			break;
		default:
			sprintf(errmsg, "unknown option: '%s'", argv[i]);
			error(USER, errmsg);
			break;
		}

	if (i < argc-2)
		error(USER, "too many file arguments");
					/* initialize mesh */
	cvinit(i==argc-2 ? argv[i+1] : "<stdout>");
					/* load material input */
	for (j = 0; j < nmatf; j++)
		readobj(matinp[j]);
					/* read .OBJ file into triangles */
	if (i == argc)
		wfreadobj(NULL);
	else
		wfreadobj(argv[i]);
	
	cvmeshbounds();			/* set octree boundaries */

	if (i == argc-2)		/* open output file */
		if (freopen(argv[i+1], "w", stdout) == NULL)
			error(SYSTEM, "cannot open output file");
	SET_FILE_BINARY(stdout);
	newheader("RADIANCE", stdout);	/* new binary file header */
	printargs(i<argc ? i+1 : argc, argv, stdout);
	fputformat(MESHFMT, stdout);
	fputc('\n', stdout);

	mincusize = ourmesh->mcube.cusize / resolu - FTINY;

	for (i = 0; i < nobjects; i++)	/* add triangles to octree */
		if (objptr(i)->otype == OBJ_FACE)
			addface(&ourmesh->mcube, i);

					/* optimize octree */
	ourmesh->mcube.cutree = combine(ourmesh->mcube.cutree);

	if (ourmesh->mcube.cutree == EMPTY)
		error(WARNING, "mesh is empty");
	
	cvmesh();			/* convert mesh and leaf nodes */

	writemesh(ourmesh, stdout);	/* write mesh to output */
	
	/* printmeshstats(ourmesh, stderr); */

	quit(0);
	return 0; /* pro forma return */
}
Beispiel #28
0
int main (int argc, char* argv [])
{
   #define check(ol, al) if (argv [i][ol] || \
                             badarg(argc - i - 1,argv + i + 1, al)) \
                            goto badopt
                            
   #define check_bool(olen, var) switch (argv [i][olen]) { \
                             case '\0': var = !var; break; \
                             case 'y': case 'Y': case 't': case 'T': \
                             case '+': case '1': var = 1; break; \
                             case 'n': case 'N': case 'f': case 'F': \
                             case '-': case '0': var = 0; break; \
                             default: goto badopt; \
                          }   

   int loadflags = IO_CHECK | IO_SCENE | IO_TREE | IO_BOUNDS, rval, i, j, n;
   char **portLp = photonPortList, **sensLp = photonSensorList,
        **amblp = NULL;
   struct stat pmstat;

   /* Global program name */
   progname = fixargv0(argv [0]);
   /* Initialize object types */
   initotypes();
   
   /* Parse options */
   for (i = 1; i < argc; i++) {
      /* Eggs-pand arguments */
      while ((rval = expandarg(&argc, &argv, i)))
         if (rval < 0) {
            sprintf(errmsg, "cannot eggs-pand '%s'", argv [i]);
            error(SYSTEM, errmsg);
         }
         
      if (argv[i] == NULL) 
         break;
         
      if (!strcmp(argv [i], "-version")) {
         puts(VersionID);
         quit(0);
      }
      
      if (!strcmp(argv [i], "-defaults") || !strcmp(argv [i], "-help")) {
         printdefaults();
         quit(0);
      }
      
      /* Get octree */
      if (i == argc - 1) {
         octname = argv [i];
         break;
      }
            
      switch (argv [i][1]) {
         case 'a': /* Ambient */
            switch (argv [i][2]) {
               case 'i': /* Ambient include */
               case 'I':
                  check(3, "s");
                  if (ambincl != 1) {
                     ambincl = 1;
                     amblp = amblist;
                  }
                  if (argv [i][2] == 'I') {	
                     /* Add modifiers from file */
                     rval = wordfile(amblp, AMBLLEN - (amblp - amblist),
                                     getpath(argv [++i], 
                                     getrlibpath(), R_OK));
                     if (rval < 0) {
                        sprintf(errmsg, 
                                "cannot open ambient include file \"%s\"",
                                argv [i]);
                        error(SYSTEM, errmsg);
                     }
                     amblp += rval;
                  } 
                  else {
                     /* Add modifier from next arg */
                     *amblp++ = savqstr(argv [++i]);
                     *amblp = NULL;
                  }
                  break;

               case 'e': /* Ambient exclude */
               case 'E':
                  check(3, "s");
                  if (ambincl != 0) {
                     ambincl = 0;
                     amblp = amblist;
                  }
                  if (argv [i][2] == 'E') { 
                     /* Add modifiers from file */
                     rval = wordfile(amblp, AMBLLEN - (amblp - amblist),
                                     getpath(argv [++i], 
                                     getrlibpath(), R_OK));
                     if (rval < 0) {
                        sprintf(errmsg,
                                "cannot open ambient exclude file \"%s\"", 
                                argv [i]);
                        error(SYSTEM, errmsg);
                     }
                     amblp += rval;
                  } 
                  else {
                     /* Add modifier from next arg */ 
                     *amblp++ = savqstr(argv [++i]);
                     *amblp = NULL;
                  }
                  break;
            
               case 'p': /* Pmap-specific */
                  switch (argv [i][3]) {			
                     case 'g': /* Global photon map */
                        check(4, "ss");
                        globalPmapParams.fileName = argv [++i];
                        globalPmapParams.distribTarget = 
                           parseMultiplier(argv [++i]);
                        if (!globalPmapParams.distribTarget) 
                           goto badopt;                         
                        globalPmapParams.minGather = 
                           globalPmapParams.maxGather = 0;
                        break;
            
                     case 'p': /* Precomputed global photon map */
                        check(4, "ssi");
                        preCompPmapParams.fileName = argv [++i];
                        preCompPmapParams.distribTarget = 
                           parseMultiplier(argv [++i]);
                        if (!preCompPmapParams.distribTarget) 
                           goto badopt;
                        preCompPmapParams.minGather = 
                           preCompPmapParams.maxGather = atoi(argv [++i]);
                        if (!preCompPmapParams.maxGather) 
                           goto badopt;
                        break;
            
                     case 'c': /* Caustic photon map */
                        check(4, "ss");
                        causticPmapParams.fileName = argv [++i];
                        causticPmapParams.distribTarget = 
                           parseMultiplier(argv [++i]);
                        if (!causticPmapParams.distribTarget) 
                           goto badopt;
                        break;
                  
                     case 'v': /* Volume photon map */
                        check(4, "ss");
                        volumePmapParams.fileName = argv [++i];
                        volumePmapParams.distribTarget = 
                           parseMultiplier(argv [++i]);
                        if (!volumePmapParams.distribTarget) 
                           goto badopt;                      
                        break;
                     
                     case 'd': /* Direct photon map */
                        check(4, "ss");
                        directPmapParams.fileName = argv [++i];
                        directPmapParams.distribTarget = 
                           parseMultiplier(argv [++i]);
                        if (!directPmapParams.distribTarget) 
                           goto badopt;
                        break;
                     
                     case 'C': /* Contribution photon map */
                        check(4, "ss");
                        contribPmapParams.fileName = argv [++i];
                        contribPmapParams.distribTarget =
                           parseMultiplier(argv [++i]);
                        if (!contribPmapParams.distribTarget)
                           goto badopt;
                        break;

                     case 'D': /* Predistribution factor */
                        check(4, "f");
                        preDistrib = atof(argv [++i]);
                        if (preDistrib <= 0)
                           error(USER, "predistrib factor must be > 0");
                        break;

                     case 'M': /* Max predistribution passes */
                        check(4, "i");
                        maxPreDistrib = atoi(argv [++i]);
                        if (maxPreDistrib <= 0)
                           error(USER, "max predistrib passes must be > 0");
                        break;

#if 1
                     /* Kept for backwards compat, to be phased out by -lr */
                     case 'm': /* Max photon bounces */
                        check(4, "i");
                        photonMaxBounce = atol(argv [++i]);
                        if (photonMaxBounce <= 0) 
                           error(USER, "max photon bounces must be > 0");
                        break;
#endif

#ifdef PMAP_EKSPERTZ                     
                     case 'i': /* Add region of interest */
                        check(4, "ffffff");                        
                        n = pmapNumROI;
                        pmapROI = realloc(pmapROI,
                                          ++pmapNumROI * sizeof(PhotonMapROI));
                        if (!pmapROI)
                           error(SYSTEM, "failed to allocate ROI");
                        pmapROI [n].min [0] = atof(argv [++i]);
                        pmapROI [n].min [1] = atof(argv [++i]);
                        pmapROI [n].min [2] = atof(argv [++i]);
                        pmapROI [n].max [0] = atof(argv [++i]);
                        pmapROI [n].max [1] = atof(argv [++i]);
                        pmapROI [n].max [2] = atof(argv [++i]);                        
                        for (j = 0; j < 3; j++)
                           if (pmapROI [n].min [j] >= pmapROI [n].max [j])
                              error(USER, "invalid region of interest "
                                    "(swapped min/max?)");
                        break;
#endif             

                     case 'P': /* Global photon precomp ratio */
                        check(4, "f");
                        finalGather = atof(argv [++i]);
                        if (finalGather <= 0 || finalGather > 1)
                           error(USER, "global photon precomputation ratio "
                                 "must be in range ]0, 1]");
                        break;
                     
                     case 'o': /* Photon port */ 
                     case 'O':
                        check(4, "s");
                        if (argv [i][3] == 'O') {	
                           /* Add port modifiers from file */
                           rval = wordfile(portLp, 
                                           MAXSET - (portLp - photonPortList),
                                           getpath(argv [++i],
                                           getrlibpath(), R_OK));
                           if (rval < 0) {
                               sprintf(errmsg, 
                                       "cannot open photon port file %s", 
                                       argv [i]);
                               error(SYSTEM, errmsg);
                           }
                           portLp += rval;
                        } 
                        else {
                           /* Add port modifier from next arg, mark end with
                            * NULL */
                           *portLp++ = savqstr(argv [++i]);
                           *portLp = NULL;
                        }
                        break;
                     
                     case 'r': /* Random seed */
                        check(4, "i");
                        randSeed = atoi(argv [++i]);
                        break;                   

                     case 's': /* Antimatter sensor */ 
                     case 'S':
                        check(4, "s");
                        if (argv[i][3] == 'S') {	
                           /* Add sensor modifiers from file */
                           rval = wordfile(sensLp, 
                                           MAXSET - (sensLp - photonSensorList),
                                           getpath(argv [++i], 
                                           getrlibpath(), R_OK));
                           if (rval < 0) {
                               sprintf(errmsg, 
                                       "cannot open antimatter sensor file %s",
                                       argv [i]);
                               error(SYSTEM, errmsg);
                           }
                           sensLp += rval;
                        } 
                        else {
                           /* Append modifier to sensor list, mark end with
                            * NULL */
                           *sensLp++ = savqstr(argv [++i]);
                           *sensLp = NULL;
                        }
                        break;

                     default: goto badopt;
                  }
                  break;
                  
               default: goto badopt;
            }
            break;
                
         case 'b': /* Back face visibility */
            if (argv [i][2] == 'v') {
               check_bool(3, backvis);
            }
            else goto badopt;
            break;
                   
         case 'd': /* Direct */
            switch (argv [i][2]) {
               case 'p': /* PDF samples */
                  check(3, "f");
                  pdfSamples = atof(argv [++i]);
                  break;
                  
               case 's': /* Source partition size ratio */
                  check(3, "f");
                  srcsizerat = atof(argv [++i]);
                  break;
                  
               default: goto badopt;
            }                   
            break;
                   
         case 'e': /* Diagnostics file */
            check(2, "s");
            diagFile = argv [++i];
            break;
                  
         case 'f': /* Force overwrite */
            if (argv [i][2] == 'o') {
               check_bool(3, clobber);
            }
            else goto badopt;
            break; 

#ifdef PMAP_EKSPERTZ
         case 'l': /* Limits */
            switch (argv [i][2]) {
               case 'd': /* Limit photon path distance */
                  check(3, "f");
                  photonMaxDist = atof(argv [++i]);
                  if (photonMaxDist <= 0)
                     error(USER, "max photon distance must be > 0");
                  break;
                 
               case 'r': /* Limit photon bounces */               
                  check(3, "i");               
                  photonMaxBounce = atol(argv [++i]);
                  if (photonMaxBounce <= 0) 
                     error(USER, "max photon bounces must be > 0");
                  break;
               
               default: goto badopt;
            }
            break;
#endif

         case 'm': /* Medium */
            switch (argv[i][2]) {
               case 'e':	/* Eggs-tinction coefficient */
                  check(3, "fff");
                  setcolor(cextinction, atof(argv [i + 1]),
                           atof(argv [i + 2]), atof(argv [i + 3]));
                  i += 3;
                  break;
                                
               case 'a':	/* Albedo */
                  check(3, "fff");
                  setcolor(salbedo, atof(argv [i + 1]), 
                           atof(argv [i + 2]), atof(argv [i + 3]));
                  i += 3;
                  break;
                                
               case 'g':	/* Scattering eccentricity */
                  check(3, "f");
                  seccg = atof(argv [++i]);
                  break;
                                
               default: goto badopt;
            }                   
            break;
            
#if NIX
         case 'n': /* Num parallel processes (NIX only) */
            check(2, "i");
            nproc = atoi(argv [++i]);
            
            if (nproc > PMAP_MAXPROC) {
               nproc = PMAP_MAXPROC;
               sprintf(errmsg, "too many parallel processes, clamping to "
                       "%d\n", nproc);
               error(WARNING, errmsg);
            }            
            break;                   
#endif

         case 't': /* Timer */
            check(2, "i");
            photonRepTime = atoi(argv [++i]);
            break;
            
         case 'v':   /* Verbosity */
            check_bool(2, verbose);
            break;
            
#ifdef EVALDRC_HACK
         case 'A':   /* Angular source file */
            check(2,"s");
            angsrcfile = argv[++i];
            break;                   
#endif

        default: goto badopt;
      }
   }
   
   /* Open diagnostics file */
   if (diagFile) {
      if (!freopen(diagFile, "a", stderr)) quit(2);
      fprintf(stderr, "**************\n*** PID %5d: ", getpid());
      printargs(argc, argv, stderr);
      putc('\n', stderr);
      fflush(stderr);
   }
   
#ifdef NICE
   /* Lower priority */
   nice(NICE);
#endif

   if (octname == NULL) 
      error(USER, "missing octree argument");
      
   /* Allocate photon maps and set parameters */
   for (i = 0; i < NUM_PMAP_TYPES; i++) {
      setPmapParam(photonMaps + i, pmapParams + i);
      
      /* Don't overwrite existing photon map unless clobbering enabled */
      if (photonMaps [i] && !stat(photonMaps [i] -> fileName, &pmstat) &&
          !clobber) {
         sprintf(errmsg, "photon map file %s exists, not overwritten",
                 photonMaps [i] -> fileName);
         error(USER, errmsg);
      }
   }
       
   for (i = 0; i < NUM_PMAP_TYPES && !photonMaps [i]; i++);   
   if (i >= NUM_PMAP_TYPES)
      error(USER, "no photon maps specified");
   
   readoct(octname, loadflags, &thescene, NULL);
#ifdef EVALDRC_HACK   
   if (angsrcfile)
      readobj(angsrcfile);    /* load angular sources */
#endif         
   nsceneobjs = nobjects;
   
   /* Get sources */
   marksources();

   /* Do forward pass and build photon maps */
   if (contribPmap)
      /* Just build contrib pmap, ignore others */
      distribPhotonContrib(contribPmap, nproc);
   else
      distribPhotons(photonMaps, nproc);
   
   /* Save photon maps; no idea why GCC needs an explicit cast here... */
   savePmaps((const PhotonMap**)photonMaps, argc, argv);
   cleanUpPmaps(photonMaps);
   
   quit(0);

badopt:
   sprintf(errmsg, "command line error at '%s'", argv[i]);
   error(USER, errmsg);

   #undef check
   #undef check_bool
   return 0;
}
Beispiel #29
0
int main(int argc, char **argv)
{
	osFile fh;
	char line[200],*dir,*buf;
	struct Node4D n4d;
	struct cmnlIdx idx;
		
   if(!osInit())
      exit(OS_EXIT_ERROR);

   if(argc > 1 &&
	  (strcmp(argv[1],"?")==0      ||
		strcmp(argv[1],"-h")==0     ||
		strcmp(argv[1],"--help")==0 ||
		strcmp(argv[1],"help")==0 ||
		strcmp(argv[1],"/h")==0     ||
		strcmp(argv[1],"/?")==0 ))
   {
      printargs(args);
      osEnd();
      exit(OS_EXIT_OK);
   }

   if(!parseargs(args,argc,argv))
   {
      osEnd();
      exit(OS_EXIT_ERROR);
   }

	if(args[ARG_DIRECTORY].data)
		dir=(char *)args[ARG_DIRECTORY].data;

	else		
		dir=getenv("CMNODELISTDIR");
	
	if(!dir)
	{
		printf("No directory specified and CMNODELISTDIR not set\n");
		osEnd();
		exit(OS_EXIT_ERROR);
	}
	
	if(!Parse4D((char *)args[ARG_NODE].data,&n4d))
	{
		printf("Invalid node %s\n",(char *)args[ARG_NODE].data);
		exit(OS_EXIT_ERROR);
	}

	if(!(fh=cmnlOpenNL(dir)))
	{
		printf("%s\n",cmnlLastError());
		exit(OS_EXIT_ERROR);
	}
	
	idx.zone=n4d.Zone;
	idx.net=n4d.Net;
	idx.node=n4d.Node;
	idx.point=n4d.Point;
	
	if(!cmnlFindNL(fh,dir,&idx,line,200))
	{
		cmnlCloseNL(fh);
		printf("%s\n",cmnlLastError());
		exit(OS_EXIT_ERROR);
	}

	cmnlCloseNL(fh);

	printf("Node %d:%d/%d.%d\n",idx.zone,idx.net,idx.node,idx.point);
	printf("Region %d, Hub %d\n",idx.region,idx.hub);

	strip(line);
	
	if(line[0]==',') 
	{
		buf="Node";
		strtok(line,","); /* Skip number */
	}
	else
	{
		buf=strtok(line,",");
		if(!buf) buf="";
		strtok(NULL,","); /* Skip number */
	}

	printf("Node is listed as a %s\n",buf);
	
	if((buf=strtok(NULL,",")))
	{
		printf("Name: %s\n",buf);
	}

	if((buf=strtok(NULL,",")))
	{
		printf("Location: %s\n",buf);
	}

	if((buf=strtok(NULL,",")))
	{
		printf("Sysop: %s\n",buf);
	}

	if((buf=strtok(NULL,",")))
	{
		printf("Phone: %s\n",buf);
	}

	if((buf=strtok(NULL,",")))
	{
		printf("Baud: %s\n",buf);
	}

	if((buf=strtok(NULL,"")))
	{
		printf("Flags: %s\n",buf);
	}

   osEnd();
   
   exit(OS_EXIT_OK);
}
Beispiel #30
0
int main(int argc, char **argv) {
  data d;
  glam2_aln *alns;
  int r;

  prog_name = "glam2";  /* for error messages */
  getargs(&d.a, argc, argv);
  init(&d);

  fputs("GLAM2: Gapped Local Alignment of Motifs\nVersion "
#include "glam2_version.h"
	"\n\n", d.out);
  printargs(d.out, argc, argv);
  print_misc_info(d.out, &d);
  putc('\n', d.out);
  XMALLOC(alns, d.a.runs);

  for (r = 0; r < d.a.runs; ++r) {
    glam2_aln *aln = &alns[r];
    if (!d.a.quiet) {
      fprintf(stderr, "Run %d... ", r+1);
      fflush(stderr);
    }
    aln_init(aln, d.seqs.seqnum, d.a.max_width, d.alph.size);
    d.sm.underflow_flag = 1;  /* do we care about underflow in start_aln? */
    start_aln(aln, &d);
    optimise_aln(aln, &d);
    if (d.sm.underflow_flag < (d.a.algorithm == 2 ? DBL_EPSILON : DBL_MIN))
      fprintf(stderr, "%s: accuracy loss due to numeric underflow (%g)\nIf the alignment looks suspect, try rerunning with higher -u, or maybe lower -b\n", prog_name, d.sm.underflow_flag);
    if (d.a.profile)
      print_aln_info(d.out, aln, &d);
  }

  if (!d.a.quiet) putc('\n', stderr);

  SORT(alns, d.a.runs, aln_cmp);
  if (!d.a.profile)
    print_alns(d.out, alns, &d);

  xfclose(d.out);			// close text output file

  // Create the HTML output and MEME format output
  char *glam2html, *glam2psfm, *command;
  int command_length, command_ret;
  // create the paths to the programs
  glam2html = make_path_to_file(get_meme_bin_dir(), "glam2html");
  glam2psfm = make_path_to_file(get_meme_bin_dir(), "glam2psfm");
  // allocate memory for the command
  command_length = strlen(glam2html) + strlen(d.txt_filename) + strlen(d.html_filename) + 50;
  command = xmalloc(command_length);
  // run glam2html
  sprintf(command, "%s < %s > %s",  glam2html, d.txt_filename, d.html_filename);
  if ((command_ret = system(command)) != 0) {
    report_external_failure("glam2html", command_ret);
    fprintf(stderr, "Warning: failed to convert output to HTML!\n");
  }
  // run glam2psfm
  sprintf(command, "%s < %s > %s", glam2psfm, d.txt_filename, d.psfm_filename);
  if ((command_ret = system(command)) != 0) {
    report_external_failure("glam2psfm", command_ret);
    fprintf(stderr, "Warning: failed to convert output to MEME format motif!\n");
  }
  free(command);
  free(glam2psfm);
  free(glam2html);

  return 0;
}