int main(const int argc, const char *argv[]) { int nextarg; NaClLogModuleInit(); NaClLogSetVerbosity(LOG_FATAL); if (0 != setvbuf(stdout, g_standard_output_buffer, _IOLBF, sizeof g_standard_output_buffer)) { NaClLog(LOG_FATAL, "vdiff: setvbuf failed\n"); } #if NACL_LINUX || NACL_OSX srandom(time(NULL)); #endif VDiffInitializeAvailableDecoders(); nextarg = ParseArgv(argc, argv); if (nextarg == argc) { if (gPrefix == 0) RunRegressionTests(); TestAllInstructions(); } else { int i; gVerbose = TRUE; for (i = nextarg; i < argc; ++i) { TestOneInstruction(argv[i]); } } PrintStats(); /* exit with non-zero error code if there were errors. */ exit(gVDiffStats.errors != 0); }
static void Test(const char *str) { char **av; printf("Test: <%V>\n", str); av = ParseArgv(str, 0); PrintArgv(av); }
int main(int argc, char *argv[]) { char **input_files; char *output_file; char *arg_string; int num_input_files; int inmincid; Loop_Options *loop_options; Program_Data program_data; /* Save time stamp and args */ arg_string = time_stamp(argc, argv); /* Get arguments */ if (ParseArgv(&argc, argv, argTable, 0) || (argc < 3)) { (void) fprintf(stderr, "\nUsage: %s [options] <in1.mnc> [...] <out.mnc>\n", argv[0]); (void) fprintf(stderr, " %s -help\n\n", argv[0]); exit(EXIT_FAILURE); } input_files = &argv[1]; num_input_files = argc - 2; output_file = argv[argc-1]; /* Open the first input file and get the vector length */ inmincid = miopen(input_files[0], NC_NOWRITE); if (get_vector_length(inmincid) > 1) { (void) fprintf(stderr, "Input file %s is not a scalar file\n", input_files[0]); exit(EXIT_FAILURE); } /* Set up looping options */ loop_options = create_loop_options(); set_loop_clobber(loop_options, clobber); set_loop_verbose(loop_options, verbose); #if MINC2 set_loop_v2format(loop_options, v2format); #endif /* MINC2 */ set_loop_datatype(loop_options, datatype, is_signed, valid_range[0], valid_range[1]); set_loop_output_vector_size(loop_options, num_input_files); set_loop_buffer_size(loop_options, (long) buffer_size * 1024); set_loop_first_input_mincid(loop_options, inmincid); set_loop_accumulate(loop_options, TRUE, 0, NULL, NULL); /* Do loop */ voxel_loop(num_input_files, input_files, 1, &output_file, arg_string, loop_options, do_makevector, (void *) &program_data); exit(EXIT_SUCCESS); }
void main(int argc, const char *argv[]) { if (ParseArgv(argc, argv)) exit(1); if (Options.printUsage) PrintUsage(argv[0]); else StartModel(); exit(0); }
int main(int argc, char *argv[]) { VIO_General_transform gt; char *xfmfile; int i; static ArgvInfo argTable[] = { {"-center", ARGV_FLOAT, (char *) 3, (char *)cent, "Force center of rotation and scale."}, {"-version", ARGV_FUNC, (char *) print_version_info, (char *)MNI_AUTOREG_LONG_VERSION, "Print out version info and exit."}, {NULL, ARGV_END, NULL, NULL, NULL} }; for(i=0; i<3; i++) { cent[i] = 0.0; } if (ParseArgv(&argc, argv, argTable, 0) || (argc<2)) { (void) fprintf(stderr, "Usage: %s file.xfm [file.mnc] [options] \n", argv[0]); exit(EXIT_FAILURE); } prog_name = argv[0]; xfmfile = argv[1]; if (argc>2) { print ("mnc = %s\n",argv[2]); if (! get_cog(argv[2], cent) ) { print("Cannot calculate the COG of volume %s\n.", argv[2] ); exit(EXIT_FAILURE); } } if (input_transform_file(xfmfile, >)!=VIO_OK) { (void)fprintf(stderr, "Error reading transformation file.\n"); exit(EXIT_FAILURE); } process_general_transform( > ); exit(EXIT_SUCCESS); }
TCGbool TCGClient::ParseArgFile(const TCGchar* fname, stCmdArgs &args) { auto_file f(fopen(fname, "r")); TCGchar line[CMD_LEN] = {0}; TCGchar* argv[ARG_ITEMS]={NULL}; TCGbool loop = 1; if (!f.file_) { TCGLOG(TCG_INFO, TCG_CLIENT_OS, "No config file TCGPlayer.conf @ /sdcard/Tencent/, use Default config replay"); return TCG_TRUE; //use default } fgets(line,CMD_LEN,f.file_); if(line == NULL) { PrintHelp(); return TCG_FALSE; } //Handle use echo xxx > TCGPlayer.conf method generate config file if (line[strlen(line)-1] == 10) { line[strlen(line)-1] = '\0'; } argv[1] = strtok(line," "); if(argv[1] == NULL) { argv[1] = line; } loop++; while(loop < ARG_ITEMS) { argv[loop] = strtok(NULL," "); if(argv[loop] == NULL) break; loop++; } return ParseArgv(loop,argv,args); }
int main(int argc, char *argv[]) { Volume volume; volume_input_struct input_info; char *filename; double v0, v1, v2, wx, wy, wz; static char *dim_names[] = {ANY_SPATIAL_DIMENSION, ANY_SPATIAL_DIMENSION, ANY_SPATIAL_DIMENSION}; milog_init(argv[0]); /* Check arguments */ if (ParseArgv(&argc, argv, argTable, 0) || argc != 5) { (void) fprintf(stderr, "Usage: %s <image file> <voxel index 1 (slowest)> <index 2> <index 3>\n", argv[0]); exit(EXIT_FAILURE); } filename = argv[1]; v0 = atof(argv[2]); v1 = atof(argv[3]); v2 = atof(argv[4]); /* Open the image file */ set_print_function(print_to_stderr); if (start_volume_input(filename, 3, dim_names, MI_ORIGINAL_TYPE, TRUE, 0.0, 0.0, TRUE, &volume, NULL, &input_info) != OK) { (void) fprintf(stderr, "Error opening file %s for input.\n", filename); exit(EXIT_FAILURE); } /* Convert the voxel to world coordinates */ convert_3D_voxel_to_world(volume, v0, v1, v2, &wx, &wy, &wz); /* Write out the result */ (void) printf("%.20g %.20g %.20g\n", wx, wy, wz); exit(EXIT_SUCCESS); }
TCGbool TCGClient::Init(TCGint argc, TCGchar **argv, const TCGchar* fname) { #ifdef Android if (!ParseArgFile(PLAY_CONF_FILE, g_args)) { return ; } #elif defined(WIN32) || defined(__APPLE__) if (!ParseArgv(argc, argv, g_args)) { return TCG_FALSE; } #endif GetScreenResolution(); GetScreenPosition(); ConnectServer(); m_stream.SetCompressFlag(g_args.compressedFile); return TCG_TRUE; }
int main(int argc, const char* argv[]) { try { std::locale::global(std::locale("C")); std::unique_ptr<Platform::Application> app(Platform::Application::Create()); return app->Run(ParseArgv(argc, argv)); } catch (const Error& e) { StdOut << e.ToString() << std::endl; return 1; } catch (const std::exception& e) { StdOut << e.what() << std::endl; return 1; } catch (...) { StdOut << "Unhandled exception" << std::endl; return 1; } }
int main(int argc, char *argv[]) { char *infile, *outfile; char *arg_string; Loop_Options *loop_options; int inmincid; Lookup_Data lookup_data; /* Save time stamp and args */ arg_string = time_stamp(argc, argv); /* Get arguments */ if (ParseArgv(&argc, argv, argTable, 0) || (argc != 3)) { (void) fprintf(stderr, "\nUsage: %s [options] <in.mnc> <out.mnc>\n", argv[0]); (void) fprintf(stderr, " %s -help\n\n", argv[0]); exit(EXIT_FAILURE); } infile = argv[1]; outfile = argv[2]; /* Get the appropriate lookup table */ if ((lookup_file != NULL) || (lookup_string != NULL)) { lookup_data.lookup_table = read_lookup_table(lookup_file, lookup_string); } else { switch (lookup_type) { case LU_GRAY: lookup_data.lookup_table = &gray_lookup; break; case LU_HOTMETAL: lookup_data.lookup_table = &hotmetal_lookup; break; case LU_SPECTRAL: lookup_data.lookup_table = &spectral_lookup; break; case LU_TABLE: break; default: fprintf(stderr, "Unknown lookup type: %d\n", lookup_type); break; } } /* Get the null value */ lookup_data.null_value = get_null_value(lookup_data.lookup_table->vector_length, null_value_string); /* Open the input file and get the range */ inmincid = miopen(infile, NC_NOWRITE); if (!discrete_lookup && (lookup_range[0] == DEFAULT_RANGE)) { get_full_range(inmincid, lookup_range); } if (lookup_min != DEFAULT_RANGE) lookup_range[0] = lookup_min; if (lookup_max != DEFAULT_RANGE) lookup_range[1] = lookup_max; /* Set up lookup information */ lookup_data.invert = invert_table; lookup_data.range[0] = lookup_range[0]; lookup_data.range[1] = lookup_range[1]; lookup_data.discrete = discrete_lookup; /* Set up looping options */ loop_options = create_loop_options(); set_loop_clobber(loop_options, clobber); set_loop_verbose(loop_options, verbose); #if MINC2 set_loop_v2format(loop_options, minc2_format); #endif /* MINC2 */ set_loop_datatype(loop_options, datatype, is_signed, valid_range[0], valid_range[1]); set_loop_convert_input_to_scalar(loop_options, TRUE); set_loop_output_vector_size(loop_options, lookup_data.lookup_table->vector_length); set_loop_buffer_size(loop_options, (long) buffer_size * 1024); set_loop_first_input_mincid(loop_options, inmincid); /* Do loop */ voxel_loop(1, &infile, 1, &outfile, arg_string, loop_options, do_lookup, (void *) &lookup_data); /* Free stuff */ if (lookup_data.null_value != NULL) free(lookup_data.null_value); if (lookup_data.lookup_table->free_data) { free(lookup_data.lookup_table->table); free(lookup_data.lookup_table); } exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { /* NIFTI stuff */ nifti_image *nii_ptr; nifti_image nii_rec; int nii_dimids[MAX_NII_DIMS]; int nii_dir[MAX_NII_DIMS]; int nii_map[MAX_NII_DIMS]; unsigned long nii_lens[MAX_NII_DIMS]; int nii_ndims; static int nifti_filetype; static int nifti_datatype; static int nifti_signed = 1; /* MINC stuff */ int mnc_fd; /* MINC file descriptor */ nc_type mnc_type; /* MINC data type as read */ int mnc_ndims; /* MINC image dimension count */ int mnc_dimids[MAX_VAR_DIMS]; /* MINC image dimension identifiers */ long mnc_dlen; /* MINC dimension length value */ double mnc_dstep; /* MINC dimension step value */ int mnc_icv; /* MINC image conversion variable */ int mnc_vid; /* MINC Image variable ID */ long mnc_start[MAX_VAR_DIMS]; /* MINC data starts */ long mnc_count[MAX_VAR_DIMS]; /* MINC data counts */ int mnc_signed; /* MINC if output voxels are signed */ double real_range[2]; /* MINC real range (min, max) */ double input_valid_range[2]; /* MINC valid range (min, max) */ double output_valid_range[2]; /* Valid range of output data. */ double nifti_slope; /* Slope to be applied to output voxels. */ double nifti_inter; /* Intercept to be applied to output voxels. */ double total_valid_range; /* Overall valid range (max - min). */ double total_real_range; /* Overall real range (max - min). */ /* Other stuff */ char out_str[1024]; /* Big string for filename */ char att_str[1024]; /* Big string for attribute values */ int i; /* Generic loop counter the first */ int j; /* Generic loop counter the second */ char *str_ptr; /* Generic ASCIZ string pointer */ int r; /* Result code. */ static int vflag = 0; /* Verbose flag (default is quiet) */ static ArgvInfo argTable[] = { {NULL, ARGV_HELP, NULL, NULL, "Output voxel data type specification"}, {"-byte", ARGV_CONSTANT, (char *)DT_INT8, (char *)&nifti_datatype, "Write voxel data in 8-bit signed integer format."}, {"-short", ARGV_CONSTANT, (char *)DT_INT16, (char *)&nifti_datatype, "Write voxel data in 16-bit signed integer format."}, {"-int", ARGV_CONSTANT, (char *)DT_INT32, (char *)&nifti_datatype, "Write voxel data in 32-bit signed integer format."}, {"-float", ARGV_CONSTANT, (char *)DT_FLOAT32, (char *)&nifti_datatype, "Write voxel data in 32-bit floating point format."}, {"-double", ARGV_CONSTANT, (char *)DT_FLOAT64, (char *)&nifti_datatype, "Write voxel data in 64-bit floating point format."}, {"-signed", ARGV_CONSTANT, (char *)1, (char *)&nifti_signed, "Write integer voxel data in signed format."}, {"-unsigned", ARGV_CONSTANT, (char *)0, (char *)&nifti_signed, "Write integer voxel data in unsigned format."}, {NULL, ARGV_HELP, NULL, NULL, "Output file format specification"}, {"-dual", ARGV_CONSTANT, (char *)FT_NIFTI_DUAL, (char *)&nifti_filetype, "Write NIfTI-1 two-file format (.img and .hdr)"}, {"-ASCII", ARGV_CONSTANT, (char *)FT_NIFTI_ASCII, (char *)&nifti_filetype, "Write NIfTI-1 ASCII header format (.nia)"}, {"-nii", ARGV_CONSTANT, (char *)FT_NIFTI_SINGLE, (char *)&nifti_filetype, "Write NIfTI-1 one-file format (.nii)"}, {"-analyze", ARGV_CONSTANT, (char *)FT_ANALYZE, (char *)&nifti_filetype, "Write an Analyze two-file format file (.img and .hdr)"}, {NULL, ARGV_HELP, NULL, NULL, "Other options"}, {"-quiet", ARGV_CONSTANT, (char *)0, (char *)&vflag, "Quiet operation"}, {"-verbose", ARGV_CONSTANT, (char *)1, (char *)&vflag, "Quiet operation"}, {NULL, ARGV_END, NULL, NULL, NULL} }; ncopts = 0; /* Clear global netCDF error reporting flag */ /* Default NIfTI file type is "NII", single binary file */ nifti_filetype = FT_UNSPECIFIED; nifti_datatype = DT_UNKNOWN; if (ParseArgv(&argc, argv, argTable, 0) || (argc < 2)) { fprintf(stderr, "Too few arguments\n"); return usage(); } if (!nifti_signed) { switch (nifti_datatype) { case DT_INT8: nifti_datatype = DT_UINT8; break; case DT_INT16: nifti_datatype = DT_UINT16; break; case DT_INT32: nifti_datatype = DT_UINT32; break; } } switch (nifti_datatype){ case DT_INT8: case DT_UINT8: mnc_type = NC_BYTE; break; case DT_INT16: case DT_UINT16: mnc_type = NC_SHORT; break; case DT_INT32: case DT_UINT32: mnc_type = NC_INT; break; case DT_FLOAT32: mnc_type = NC_FLOAT; break; case DT_FLOAT64: mnc_type = NC_DOUBLE; break; } if (argc == 2) { strcpy(out_str, argv[1]); str_ptr = strrchr(out_str, '.'); if (str_ptr != NULL && !strcmp(str_ptr, ".mnc")) { *str_ptr = '\0'; } } else if (argc == 3) { strcpy(out_str, argv[2]); str_ptr = strrchr(out_str, '.'); if (str_ptr != NULL) { /* See if a recognized file extension was specified. If so, * we trim it off and set the output file type if none was * specified. If the extension is not recognized, assume * that we will form the filename by just adding the right * extension for the selected output format. */ if (!strcmp(str_ptr, ".nii")) { if (nifti_filetype == FT_UNSPECIFIED) { nifti_filetype = FT_NIFTI_SINGLE; } *str_ptr = '\0'; } else if (!strcmp(str_ptr, ".img") || !strcmp(str_ptr, ".hdr")) { if (nifti_filetype == FT_UNSPECIFIED) { nifti_filetype = FT_NIFTI_DUAL; } *str_ptr = '\0'; } else if (!strcmp(str_ptr, ".nia")) { if (nifti_filetype == FT_UNSPECIFIED) { nifti_filetype = FT_NIFTI_ASCII; } *str_ptr = '\0'; } } } else { fprintf(stderr, "Filename argument required\n"); return usage(); } /* Open the MINC file. It needs to exist. */ mnc_fd = miopen(argv[1], NC_NOWRITE); if (mnc_fd < 0) { fprintf(stderr, "Can't find input file '%s'\n", argv[1]); return (-1); } /* Find the MINC image variable. If we can't find it, there is no * further processing possible... */ mnc_vid = ncvarid(mnc_fd, MIimage); if (mnc_vid < 0) { fprintf(stderr, "Can't locate the image variable (mnc_vid=%d)\n", mnc_vid); return (-1); } /* Find out about the MINC image variable - specifically, how many * dimensions, and which dimensions. */ r = ncvarinq(mnc_fd, mnc_vid, NULL, NULL, &mnc_ndims, mnc_dimids, NULL); if (r < 0) { fprintf(stderr, "Can't read information from image variable\n"); return (-1); } if (mnc_ndims > MAX_NII_DIMS) { fprintf(stderr, "NIfTI-1 files may contain at most %d dimensions\n", MAX_NII_DIMS); return (-1); } /* Initialize the NIfTI structure */ nii_ptr = &nii_rec; init_nifti_header(nii_ptr); /* For now we just use the mnc2nii command line as the description * field. Probably we should use something better, perhaps a * combination of some other standard MINC fields that might * provide more information. */ str_ptr = nii_ptr->descrip; for (i = 0; i < argc; i++) { char *arg_ptr = argv[i]; if ((str_ptr - nii_ptr->descrip) >= MAX_NII_DESCRIP) { break; } if (i != 0) { *str_ptr++ = ' '; } while (*arg_ptr != '\0' && (str_ptr - nii_ptr->descrip) < MAX_NII_DESCRIP) { *str_ptr++ = *arg_ptr++; } *str_ptr = '\0'; } nii_ptr->fname = malloc(strlen(out_str) + 4 + 1); nii_ptr->iname = malloc(strlen(out_str) + 4 + 1); strcpy(nii_ptr->fname, out_str); strcpy(nii_ptr->iname, out_str); switch (nifti_filetype) { case FT_ANALYZE: strcat(nii_ptr->fname, ".hdr"); strcat(nii_ptr->iname, ".img"); break; case FT_NIFTI_SINGLE: strcat(nii_ptr->fname, ".nii"); strcat(nii_ptr->iname, ".nii"); break; case FT_NIFTI_DUAL: strcat(nii_ptr->fname, ".hdr"); strcat(nii_ptr->iname, ".img"); break; case FT_NIFTI_ASCII: strcat(nii_ptr->fname, ".nia"); strcat(nii_ptr->iname, ".nia"); break; default: fprintf(stderr, "Unknown output file type %d\n", nifti_filetype); return (-1); } /* Get real voxel range for the input file. */ miget_image_range(mnc_fd, real_range); /* Get the actual valid voxel value range. */ miget_valid_range(mnc_fd, mnc_vid, input_valid_range); /* Find the default range for the output type. Our output file * will use the full legal range of the output type if it is * an integer. */ if (nifti_datatype == DT_UNKNOWN) { nii_ptr->datatype = DT_FLOAT32; /* Default */ mnc_type = NC_FLOAT; mnc_signed = 1; } else { nii_ptr->datatype = nifti_datatype; mnc_signed = nifti_signed; } if (vflag) { fprintf(stderr, "MINC type %d signed %d\n", mnc_type, mnc_signed); } miget_default_range(mnc_type, mnc_signed, output_valid_range); total_valid_range = input_valid_range[1] - input_valid_range[0]; total_real_range = real_range[1] - real_range[0]; if ((output_valid_range[1] - output_valid_range[0]) > total_valid_range) { /* Empirically, forcing the valid range to be the nearest power * of two greater than the existing valid range seems to improve * the behavior of the conversion. This is at least in part because * of the limited precision of the NIfTI-1 voxel scaling fields. */ double new_range = nearest_power_of_two(total_valid_range); if (new_range - 1.0 >= total_valid_range) { new_range -= 1.0; } if (output_valid_range[1] > total_valid_range) { output_valid_range[0] = 0; output_valid_range[1] = new_range; } else { output_valid_range[1] = output_valid_range[0] + new_range; } } else { /* The new range can't fully represent the input range. Use the * full available range, and warn the user that they may have a * problem. */ printf("WARNING: Range of input exceeds range of output format.\n"); } if (vflag) { printf("Real range: %f %f Input valid range: %f %f Output valid range: %f %f\n", real_range[0], real_range[1], input_valid_range[0], input_valid_range[1], output_valid_range[0], output_valid_range[1]); } /* If the output type is not floating point, we may need to scale the * voxel values. */ if (mnc_type != NC_FLOAT && mnc_type != NC_DOUBLE) { /* Figure out how to map pixel values into the range of the * output datatype. */ nifti_slope = ((real_range[1] - real_range[0]) / (output_valid_range[1] - output_valid_range[0])); if (nifti_slope == 0.0) { nifti_slope = 1.0; } nifti_inter = real_range[0] - (output_valid_range[0] * nifti_slope); /* One problem with NIfTI-1 is the limited precision of the * scl_slope and scl_inter fields (they are just 32-bits). So * we look for possible issues and warn about that here. */ if (nifti_inter != (float) nifti_inter || nifti_slope != (float) nifti_slope) { double epsilon_i = nifti_inter - (float) nifti_inter; double epsilon_s = nifti_slope - (float) nifti_slope; /* If the loss in precision is more than one part per thousand * of the real range, flag this as a problem! */ if ((epsilon_i > total_real_range / 1.0e3) || (epsilon_s > total_real_range / 1.0e3)) { fprintf(stderr, "ERROR: Slope and intercept cannot be represented in the NIfTI-1 header.\n"); fprintf(stderr, " slope %f (%f), intercept %f (%f)\n", nifti_slope, (float) nifti_slope, nifti_inter, (float) nifti_inter); return (-1); } } } else { nifti_slope = 0.0; } nii_ptr->scl_slope = nifti_slope; nii_ptr->scl_inter = nifti_inter; nii_ptr->nvox = 1; /* Initial value for voxel count */ /* Find all of the dimensions of the MINC file, in the order they * will be listed in the NIfTI-1/Analyze file. We use this to build * a map for restructuring the data according to the normal rules * of NIfTI-1. */ nii_ndims = 0; for (i = 0; i < MAX_NII_DIMS; i++) { if (dimnames[i] == NULL) { nii_dimids[nii_ndims] = -1; continue; } nii_dimids[nii_ndims] = ncdimid(mnc_fd, dimnames[i]); if (nii_dimids[nii_ndims] == -1) { continue; } /* Make sure the dimension is actually used to define the image. */ for (j = 0; j < mnc_ndims; j++) { if (nii_dimids[nii_ndims] == mnc_dimids[j]) { nii_map[nii_ndims] = j; break; } } if (j < mnc_ndims) { mnc_dlen = 1; mnc_dstep = 0; ncdiminq(mnc_fd, nii_dimids[nii_ndims], NULL, &mnc_dlen); ncattget(mnc_fd, ncvarid(mnc_fd, dimnames[i]), MIstep, &mnc_dstep); if (mnc_dstep < 0) { nii_dir[nii_ndims] = -1; mnc_dstep = -mnc_dstep; } else { nii_dir[nii_ndims] = 1; } nii_lens[nii_ndims] = mnc_dlen; nii_ndims++; } nii_ptr->dim[dimmap[i]] = (int) mnc_dlen; nii_ptr->nvox *= mnc_dlen; nii_ptr->pixdim[dimmap[i]] = (float) mnc_dstep; } /* Here we do some "post-processing" of the results. Make certain that * the nt value is never zero, and make certain that ndim is set to * 4 if there is a time dimension and 5 if there is a vector dimension */ if (nii_ptr->dim[3] > 1 && nii_ndims < 4) { nii_ndims = 4; } if (nii_ptr->dim[4] > 1) { nii_ptr->intent_code = NIFTI_INTENT_VECTOR; nii_ndims = 5; } nii_ptr->ndim = nii_ndims; /* Total number of dimensions in file */ nii_ptr->nx = nii_ptr->dim[0]; nii_ptr->ny = nii_ptr->dim[1]; nii_ptr->nz = nii_ptr->dim[2]; nii_ptr->nt = nii_ptr->dim[3]; nii_ptr->nu = nii_ptr->dim[4]; nii_ptr->dx = nii_ptr->pixdim[0]; nii_ptr->dy = nii_ptr->pixdim[1]; nii_ptr->dz = nii_ptr->pixdim[2]; nii_ptr->dt = nii_ptr->pixdim[3]; nii_ptr->du = 1; /* MINC files don't define a sample size for a vector_dimension */ nii_ptr->nifti_type = nifti_filetype; /* Load the direction_cosines and start values into the NIfTI-1 * sform structure. * */ for (i = 0; i < MAX_SPACE_DIMS; i++) { int id = ncvarid(mnc_fd, mnc_spatial_names[i]); double start; double step; double dircos[MAX_SPACE_DIMS]; int tmp; if (id < 0) { continue; } /* Set default values */ start = 0.0; step = 1.0; dircos[DIM_X] = dircos[DIM_Y] = dircos[DIM_Z] = 0.0; dircos[i] = 1.0; miattget(mnc_fd, id, MIstart, NC_DOUBLE, 1, &start, &tmp); miattget(mnc_fd, id, MIstep, NC_DOUBLE, 1, &step, &tmp); miattget(mnc_fd, id, MIdirection_cosines, NC_DOUBLE, MAX_SPACE_DIMS, dircos, &tmp); ncdiminq(mnc_fd, ncdimid(mnc_fd, mnc_spatial_names[i]), NULL, &mnc_dlen); if (step < 0) { step = -step; start = start - step * (mnc_dlen - 1); } nii_ptr->sto_xyz.m[0][i] = step * dircos[0]; nii_ptr->sto_xyz.m[1][i] = step * dircos[1]; nii_ptr->sto_xyz.m[2][i] = step * dircos[2]; nii_ptr->sto_xyz.m[0][3] += start * dircos[0]; nii_ptr->sto_xyz.m[1][3] += start * dircos[1]; nii_ptr->sto_xyz.m[2][3] += start * dircos[2]; miattgetstr(mnc_fd, id, MIspacetype, sizeof(att_str), att_str); /* Try to set the S-transform code correctly. */ if (!strcmp(att_str, MI_TALAIRACH)) { nii_ptr->sform_code = NIFTI_XFORM_TALAIRACH; } else if (!strcmp(att_str, MI_CALLOSAL)) { /* TODO: Not clear what do do here... */ nii_ptr->sform_code = NIFTI_XFORM_SCANNER_ANAT; } else { /* MI_NATIVE or unknown */ nii_ptr->sform_code = NIFTI_XFORM_SCANNER_ANAT; } } /* So the last row is right... */ nii_ptr->sto_xyz.m[3][0] = 0.0; nii_ptr->sto_xyz.m[3][1] = 0.0; nii_ptr->sto_xyz.m[3][2] = 0.0; nii_ptr->sto_xyz.m[3][3] = 1.0; nii_ptr->sto_ijk = nifti_mat44_inverse(nii_ptr->sto_xyz); nifti_datatype_sizes(nii_ptr->datatype, &nii_ptr->nbyper, &nii_ptr->swapsize); if (vflag) { nifti_image_infodump(nii_ptr); } /* Now load the actual MINC data. */ nii_ptr->data = malloc(nii_ptr->nbyper * nii_ptr->nvox); if (nii_ptr->data == NULL) { fprintf(stderr, "Out of memory.\n"); return (-1); } mnc_icv = miicv_create(); miicv_setint(mnc_icv, MI_ICV_TYPE, mnc_type); miicv_setstr(mnc_icv, MI_ICV_SIGN, (mnc_signed) ? MI_SIGNED : MI_UNSIGNED); miicv_setdbl(mnc_icv, MI_ICV_VALID_MAX, output_valid_range[1]); miicv_setdbl(mnc_icv, MI_ICV_VALID_MIN, output_valid_range[0]); miicv_setdbl(mnc_icv, MI_ICV_IMAGE_MAX, real_range[1]); miicv_setdbl(mnc_icv, MI_ICV_IMAGE_MIN, real_range[0]); miicv_setdbl(mnc_icv, MI_ICV_DO_NORM, TRUE); miicv_setdbl(mnc_icv, MI_ICV_USER_NORM, TRUE); miicv_attach(mnc_icv, mnc_fd, mnc_vid); /* Read in the entire hyperslab from the file. */ for (i = 0; i < mnc_ndims; i++) { ncdiminq(mnc_fd, mnc_dimids[i], NULL, &mnc_count[i]); mnc_start[i] = 0; } r = miicv_get(mnc_icv, mnc_start, mnc_count, nii_ptr->data); if (r < 0) { fprintf(stderr, "Read error\n"); return (-1); } /* Shut down the MINC stuff now that it has done its work. */ miicv_detach(mnc_icv); miicv_free(mnc_icv); miclose(mnc_fd); if (vflag) { /* Debugging stuff - just to check the contents of these arrays. */ for (i = 0; i < nii_ndims; i++) { printf("%d: %ld %d %d\n", i, nii_lens[i], nii_map[i], nii_dir[i]); } printf("bytes per voxel %d\n", nii_ptr->nbyper); printf("# of voxels %ld\n", nii_ptr->nvox); } /* Rearrange the data to correspond to the NIfTI dimension ordering. */ restructure_array(nii_ndims, nii_ptr->data, nii_lens, nii_ptr->nbyper, nii_map, nii_dir); if (vflag) { /* More debugging stuff - check coordinate transform. */ test_xform(nii_ptr->sto_xyz, 0, 0, 0); test_xform(nii_ptr->sto_xyz, 10, 0, 0); test_xform(nii_ptr->sto_xyz, 0, 10, 0); test_xform(nii_ptr->sto_xyz, 0, 0, 10); test_xform(nii_ptr->sto_xyz, 10, 10, 10); } if (vflag) { fprintf(stdout, "Writing NIfTI-1 file..."); } nifti_image_write(nii_ptr); if (vflag) { fprintf(stdout, "done.\n"); } return (0); }
int main(int argc, char *argv[]) { int r; const char **file_list = NULL; /* List of file names */ struct vff_attrs vffattrs; struct mnc_vars mnc2; char out_str[1024]; /* Big string for filename */ midimhandle_t hdim[MAX_VFF_DIMS]; mihandle_t hvol; double mnc_vrange[2]; /* MINC valid min/max */ int num_file_args; /* Number of files on command line */ string_t out_dir; /* Output directory */ int length; struct stat st; int ifile; int num_files; /* Total number of files */ int is_file=0; int is_list=0; int ival; char *extension; mnc2.mnc_srange[0]= -1; mnc2.mnc_srange[1]= -1; G.pname = argv[0]; /* get program name */ G.dirname = NULL; G.little_endian = 1; /*default is little endian unless otherwise*/ G.minc_history = time_stamp(argc, argv); /* Create minc history string */ if (ParseArgv(&argc, argv, argTable, 0) || argc < 2) { usage(); exit(EXIT_FAILURE); } if (G.dirname != NULL) { #if HAVE_DIRENT_H if (stat(G.dirname, &st) != 0 || !S_ISDIR(st.st_mode)) { fprintf(stderr,"Option -addattrs requires directory as argument!!!\n"); exit(EXIT_FAILURE); } #endif } if (G.List) { num_file_args = argc - 1; } else { strcpy(out_str, argv[1]); extension = strrchr(out_str, '.'); if (extension != NULL ) { extension++; if (strcmp(extension, "mnc") !=0) { usage(); exit(EXIT_FAILURE); } } if (argc == 3) { /* check if last argument is dir */ num_file_args = argc - 2; strcpy(out_dir, argv[argc - 1]); /* make sure path ends with slash */ length = strlen(out_dir); if (out_dir[length - 1] != '/') { out_dir[length++] = '/'; out_dir[length++] = '\0'; } if (stat(out_dir, &st) != 0 || !S_ISDIR(st.st_mode)) {/* assume filename */ is_file =1; } } else { //list of 2d files must check! num_file_args = argc - 2; is_list = 1; } } if (!is_file || G.List) { /* Get space for file lists */ /* Allocate the array of pointers used to implement the * list of filenames. */ file_list = malloc(1 * sizeof(char *)); CHKMEM(file_list); /* Go through the list of files, expanding directories where they * are encountered... */ num_files = 0; for (ifile = 1 ; ifile <= num_file_args; ifile++) { #if HAVE_DIRENT_H if (stat(argv[ifile + 1], &st) == 0 && S_ISDIR(st.st_mode)) { DIR *dp; struct dirent *np; char *tmp_str; length = strlen(argv[ifile + 1]); dp = opendir(argv[ifile + 1]); if (dp != NULL) { while ((np = readdir(dp)) != NULL) { /* Generate the full path to the file. */ tmp_str = malloc(length + strlen(np->d_name) + 2); strcpy(tmp_str, argv[ifile + 1]); if (tmp_str[length-1] != '/') { tmp_str[length] = '/'; tmp_str[length+1] = '\0'; } strcat(&tmp_str[length], np->d_name); if (stat(tmp_str, &st) == 0 && S_ISREG(st.st_mode)) { file_list = realloc(file_list, (num_files + 1) * sizeof(char *)); file_list[num_files++] = tmp_str; } else { free(tmp_str); } } closedir(dp); } else { fprintf(stderr, "Error opening directory '%s'\n", argv[ifile + 1]); } } else { file_list = realloc(file_list, (num_files + 1) * sizeof(char *)); file_list[num_files++] = strdup(argv[ifile + 1]); } #else file_list = realloc(file_list, (num_files + 1) * sizeof(char *)); file_list[num_files++] = strdup(argv[ifile + 1]); #endif } } if (G.List) { exit(EXIT_SUCCESS); } if (is_file) { read_3Dvff_file_header(argv[2],&mnc2,&vffattrs); } else { read_2Dvff_files_header(file_list,num_files,&mnc2,&vffattrs); } /* ok starting to create minc2.0 file assuming 3D must take care of 2D*/ r = micreate_dimension("zspace", MI_DIMCLASS_SPATIAL, MI_DIMATTR_REGULARLY_SAMPLED, mnc2.mnc_count[2], &hdim[0]); if (r != 0) { TESTRPT("failed create_dimension zspace", r); return (1); } r = micreate_dimension("yspace", MI_DIMCLASS_SPATIAL, MI_DIMATTR_REGULARLY_SAMPLED, mnc2.mnc_count[1], &hdim[1]); if (r != 0) { TESTRPT("failed create_dimension yspace", r); return (1); } r = micreate_dimension("xspace", MI_DIMCLASS_SPATIAL, MI_DIMATTR_REGULARLY_SAMPLED, mnc2.mnc_count[0], &hdim[2]); if (r != 0) { TESTRPT("failed create_dimension xspace", r); return (1); } r = miset_dimension_start(hdim[0], mnc2.mnc_starts[2]); if (r < 0) { TESTRPT("failed dimension start xspace", r); return (1); } r = miset_dimension_start(hdim[1], mnc2.mnc_starts[1]); if (r < 0) { TESTRPT("failed dimension start yspace", r); return (1); } /* create negative start for xspace to correct orientation */ r = miset_dimension_start(hdim[2], mnc2.mnc_starts[0] * -1); if (r < 0) { TESTRPT("failed dimension start zspace", r); return (1); } /* create negative spacing for zspace to correct orientation */ r = miset_dimension_separation(hdim[0], mnc2.mnc_steps[2] * -1); if (r < 0) { TESTRPT("failed dimension separation xspace", r); return (1); } /* create negative spacing for yspace to correct orientation */ r = miset_dimension_separation(hdim[1], mnc2.mnc_steps[1] * -1); if (r < 0) { TESTRPT("failed dimension separation yspace", r); return (1); } r = miset_dimension_separation(hdim[2], mnc2.mnc_steps[0]); if (r < 0) { TESTRPT("failed dimension separation zspace", r); return (1); } r = micreate_volume(out_str,MAX_VFF_DIMS, hdim, mnc2.mnc_type, MI_CLASS_REAL, NULL, &hvol); if (r != 0) { TESTRPT("error creating volume", r); return (1); } r = micreate_volume_image(hvol); if (r != 0) { TESTRPT("error creating volume", r); return (1); } // read image slice by slice if (is_file) { read_3Dvff_file_image(hvol, argv[2], mnc2, vffattrs, mnc_vrange); } else { read_2Dvff_files_image(hvol,file_list,num_files, mnc2, vffattrs, mnc_vrange); } miset_volume_valid_range(hvol,mnc_vrange[1], mnc_vrange[0]); if (mnc2.mnc_srange[0] == -1 || mnc2.mnc_srange[1] == -1) { /* min and max are not specified in the file voxel range is set same as real range */ mnc2.mnc_srange[0] = mnc_vrange[0]; mnc2.mnc_srange[1] = mnc_vrange[1]; } miset_volume_range(hvol,mnc2.mnc_srange[1], mnc2.mnc_srange[0]); if (is_file) { /* create minc history 3D */ strcat(vffattrs.cmd_line,G.minc_history); G.minc_history = vffattrs.cmd_line; /* attributes from vff file itself 3D case*/ add_vff_attribute_to_file(hvol,&vffattrs); } if (G.dirname != NULL) { /* attributes from external files 3D case*/ add_attributes_from_files(hvol); } else if (!is_file) { /* just afew attributes from 2D case */ ival = vffattrs.year; r = miset_attr_values(hvol, MI_TYPE_INT, "study", MIstart_year,1 , &ival); if (r < 0) { TESTRPT("failed to add date:year attribute", r); } ival = vffattrs.month; r = miset_attr_values(hvol, MI_TYPE_INT, "study", MIstart_month,1 , &ival); if (r < 0) { TESTRPT("failed to add date:month attribute", r); } ival = vffattrs.day; r = miset_attr_values(hvol, MI_TYPE_INT, "study", MIstart_day,1 , &ival); if (r < 0) { TESTRPT("failed to add date:day attribute", r); } } /* add history attribute */ r = miadd_history_attr(hvol,strlen(G.minc_history), G.minc_history); if (r < 0) { TESTRPT("error creating history", r); return (1); } if (file_list != NULL) { free_list(num_files, file_list); free(file_list); } miclose_volume(hvol); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { char **infiles; int n_infiles; char *out_fn; char *history; VIO_progress_struct progress; VIO_Volume totals, weights; int i, j, k, v; double min, max; double w_min, w_max; long num_missed; double weight, value; double initial_weight; VIO_Real dummy[3]; int sizes[MAX_VAR_DIMS]; double starts[MAX_VAR_DIMS]; double steps[MAX_VAR_DIMS]; long t = 0; /* start the time counter */ current_realtime_seconds(); /* get the history string */ history = time_stamp(argc, argv); /* get args */ if(ParseArgv(&argc, argv, argTable, 0) || (argc < 3)){ fprintf(stderr, "\nUsage: %s [options] <in1.mnc> [<in2.mnc> [...]] <out.mnc>\n", argv[0]); fprintf(stderr, " %s [options] -arb_path pth.conf <infile.raw> <out.mnc>\n", argv[0]); fprintf(stderr, " %s -help\n\n", argv[0]); exit(EXIT_FAILURE); } /* get file names */ n_infiles = argc - 2; infiles = (char **)malloc(sizeof(char *) * n_infiles); for(i = 0; i < n_infiles; i++){ infiles[i] = argv[i + 1]; } out_fn = argv[argc - 1]; /* check for infiles and outfile */ for(i = 0; i < n_infiles; i++){ if(!file_exists(infiles[i])){ fprintf(stderr, "%s: Couldn't find input file %s.\n\n", argv[0], infiles[i]); exit(EXIT_FAILURE); } } if(!clobber && file_exists(out_fn)){ fprintf(stderr, "%s: %s exists, -clobber to overwrite.\n\n", argv[0], out_fn); exit(EXIT_FAILURE); } /* check for weights_fn if required */ if(weights_fn != NULL){ if(!clobber && file_exists(weights_fn)){ fprintf(stderr, "%s: %s exists, -clobber to overwrite.\n\n", argv[0], weights_fn); exit(EXIT_FAILURE); } } /* set up parameters for reconstruction */ if(out_dtype == NC_UNSPECIFIED){ out_dtype = in_dtype; } if(out_is_signed == DEF_BOOL){ out_is_signed = in_is_signed; } /* check vector dimension size */ if(vect_size < 1){ fprintf(stderr, "%s: -vector (%d) must be 1 or greater.\n\n", argv[0], vect_size); exit(EXIT_FAILURE); } /* check sigma */ if(regrid_sigma[0] <= 0 || regrid_sigma[1] <= 0 || regrid_sigma[2] <= 0 ){ fprintf(stderr, "%s: -sigma must be greater than 0\n\n", argv[0]); exit(EXIT_FAILURE); } /* read in the output file config from a file is specified */ if(out_config_fn != NULL){ int ext_args_c; char *ext_args[32]; /* max possible is 32 arguments */ ext_args_c = read_config_file(out_config_fn, ext_args); if(ParseArgv(&ext_args_c, ext_args, argTable, ARGV_DONT_SKIP_FIRST_ARG | ARGV_NO_LEFTOVERS | ARGV_NO_DEFAULTS)){ fprintf(stderr, "\nError in parameters in %s\n", out_config_fn); exit(EXIT_FAILURE); } } if(verbose){ fprintf_vol_def(stdout, &out_inf); } /* transpose the geometry arrays */ /* out_inf.*[] are in world xyz order, perm[] is the permutation array to map world xyz to the right voxel order in the volume */ for(i = 0; i < WORLD_NDIMS; i++){ sizes[i] = out_inf.nelem[perm[i]]; /* sizes, starts, steps are in voxel volume order. */ starts[i] = out_inf.start[perm[i]]; steps[i] = out_inf.step[perm[i]]; } sizes[WORLD_NDIMS] = vect_size; /* create the totals volume */ totals = create_volume((vect_size > 1) ? 4 : 3, (vect_size > 1) ? std_dimorder_v : std_dimorder, out_dtype, out_is_signed, 0.0, 0.0); set_volume_sizes(totals, sizes); set_volume_starts(totals, starts); set_volume_separations(totals, steps); for(i = 0; i < WORLD_NDIMS; i++){ /* out_inf.dircos is in world x,y,z order, we have to use the perm array to map each direction to the right voxel axis. */ set_volume_direction_cosine(totals, i, out_inf.dircos[perm[i]]); } alloc_volume_data(totals); /* create the "weights" volume */ weights = create_volume(3, std_dimorder, out_dtype, out_is_signed, 0.0, 0.0); set_volume_sizes(weights, sizes); set_volume_starts(weights, starts); set_volume_separations(weights, steps); for(i = 0; i < WORLD_NDIMS; i++){ set_volume_direction_cosine(weights, i, out_inf.dircos[perm[i]]); } alloc_volume_data(weights); /* down below in regrid_loop, Andrew makes a nasty direct reference to the voxel_to_world transformation in the volume. This transformation is not necessarily up to date, particularly when non-default direction cosines are used. In volume_io, the direction cosines are set and a FLAG is also set to indicate that the voxel-to-world xform is not up to date. If the stanrd volume_io general transform code is used, it checks internally to see if the matrix is up to date, and if not it is recomputed. So here, we'll (LC + MK) force an update by calling a general transform. */ // convert_world_to_voxel(weights, (Real) 0, (Real) 0, (Real) 0, dummy); // convert_world_to_voxel(totals, (Real) 0, (Real) 0, (Real) 0, dummy); fprintf(stderr, "2Sizes: [%d:%d:%d] \n", sizes[perm[0]], sizes[perm[1]], sizes[perm[2]]); /* initialize weights to be arbitray large value if using NEAREST */ /* volume interpolation else initialize all to zero */ if(regrid_type == NEAREST_FUNC && ap_coord_fn == NULL){ initial_weight = LARGE_INITIAL_WEIGHT; } else{ initial_weight = 0.0; } /* initialize weights and totals */ for(k = sizes[Z_IDX]; k--;){ for(j = sizes[Y_IDX]; j--;){ for(i = sizes[X_IDX]; i--;){ set_volume_real_value(weights, k, j, i, 0, 0, initial_weight); for(v = vect_size; v--;){ set_volume_real_value(totals, k, j, i, v, 0, 0.0); } } } } /* if regridding via an arbitrary path */ if(ap_coord_fn != NULL){ if(n_infiles > 1){ fprintf(stderr, "%s: arb_path only works for one input file (so far).\n\n", argv[0]); exit(EXIT_FAILURE); } /* print some pretty output */ if(verbose){ fprintf(stdout, " | Input data: %s\n", infiles[0]); fprintf(stdout, " | Arb path: %s\n", ap_coord_fn); fprintf(stdout, " | Output range: [%g:%g]\n", out_range[0], out_range[1]); fprintf(stdout, " | Output file: %s\n", out_fn); } regrid_arb_path(ap_coord_fn, infiles[0], max_buffer_size_in_kb, &totals, &weights, vect_size, regrid_range[0], regrid_range[1]); } /* else if regridding via a series of input minc file(s) */ else { for(i = 0; i < n_infiles; i++){ if(verbose){ fprintf(stdout, " | Input file: %s\n", infiles[i]); } regrid_minc(infiles[i], max_buffer_size_in_kb, &totals, &weights, vect_size, regrid_range[0], regrid_range[1]); } } /* initialise min and max counters and divide totals/weights */ num_missed = 0; min = get_volume_real_value(totals, 0, 0, 0, 0, 0); max = get_volume_real_value(totals, 0, 0, 0, 0, 0); w_min = get_volume_real_value(weights, 0, 0, 0, 0, 0); w_max = get_volume_real_value(weights, 0, 0, 0, 0, 0); initialize_progress_report(&progress, FALSE, out_inf.nelem[Z_IDX], "Dividing through"); for(i = sizes[perm[0]]; i--;){ for(j = sizes[perm[1]]; j--;){ for(k = sizes[perm[2]]; k--;){ weight = get_volume_real_value(weights, k, j, i, 0, 0); if(weight < w_min){ w_min = weight; } else if(weight > w_max){ w_max = weight; } if(weight != 0){ for(v = vect_size; v--;){ value = get_volume_real_value(totals, k, j, i, v, 0) / weight; if(value < min){ min = value; } else if(value > max){ max = value; } set_volume_real_value(totals, k, j, i, v, 0, value); } } else { num_missed++; } } } update_progress_report(&progress, k + 1); } terminate_progress_report(&progress); /* set the volumes range */ if(verbose){ fprintf(stdout, " + data range: [%g:%g]\n", min, max); fprintf(stdout, " + weight range: [%g:%g]\n", w_min, w_max); } set_volume_real_range(totals, min, max); set_volume_real_range(weights, w_min, w_max); if(num_missed > 0 && verbose){ int nvox; nvox = out_inf.nelem[X_IDX] * out_inf.nelem[Y_IDX] * out_inf.nelem[Z_IDX]; fprintf(stdout, "\n-regrid_radius possibly too small, no data in %ld/%d[%2.2f%%] voxels\n\n", num_missed, nvox, ((float)num_missed / nvox * 100)); } /* rescale data if required */ if(out_range[0] != -DBL_MAX && out_range[1] != DBL_MAX){ double o_min, o_max; /* get the existing range */ get_volume_real_range(totals, &o_min, &o_max); /* rescale it */ scale_volume(&totals, o_min, o_max, out_range[0], out_range[1]); } /* output the result */ if(verbose){ fprintf(stdout, " | Outputting %s...\n", out_fn); } if(output_volume(out_fn, out_dtype, out_is_signed, 0.0, 0.0, totals, history, NULL) != VIO_OK){ fprintf(stderr, "Problems outputing: %s\n\n", out_fn); } /* output weights volume if required */ if(weights_fn != NULL){ if(verbose){ fprintf(stdout, " | Outputting %s...\n", weights_fn); } if(output_volume(weights_fn, out_dtype, out_is_signed, 0.0, 0.0, weights, history, NULL) != VIO_OK){ fprintf(stderr, "Problems outputting: %s\n\n", weights_fn); } } delete_volume(totals); delete_volume(weights); t = current_realtime_seconds(); printf("Total reconstruction time: %ld hours %ld minutes %ld seconds\n", t/3600, (t/60)%60, t%60); return (EXIT_SUCCESS); }
/* Main program */ int main(int argc, char *argv[]){ char **infiles, **outfiles; int nfiles, nout; char *arg_string; Loop_Options *loop_options; char *pname; int i; ident_t ident; scalar_t scalar; /* Save time stamp and args */ arg_string = time_stamp(argc, argv); /* Get arguments */ pname = argv[0]; if (ParseArgv(&argc, argv, argTable, 0) || (argc < 2)) { (void) fprintf(stderr, "\nUsage: %s [options] [<in1.mnc> ...] <out.mnc>\n", pname); (void) fprintf(stderr, " %s -help\n\n", pname); exit(EXIT_FAILURE); } /* Get output file names */ nout = (Output_list == NULL ? 1 : Output_list_size); outfiles = malloc(nout * sizeof(*outfiles)); if (Output_list == NULL) { outfiles[0] = argv[argc-1]; } else { for (i=0; i < Output_list_size; i++) { outfiles[i] = Output_list[i].file; } } /* check for output files */ for (i=0; i < nout; i++){ if(access(outfiles[i], F_OK) == 0 && !clobber){ fprintf(stderr, "%s: %s exists, use -clobber to overwrite\n\n", argv[0], outfiles[i]); exit(EXIT_FAILURE); } } /* Get the list of input files either from the command line or from a file, or report an error if both are specified. Note that if -outfile is given then there is no output file name left on argv after option parsing. */ nfiles = argc - 2; if (Output_list != NULL) nfiles++; if (filelist == NULL) { infiles = &argv[1]; } else if (nfiles <= 0) { infiles = read_file_names(filelist, &nfiles); if (infiles == NULL) { (void) fprintf(stderr, "Error reading in file names from file \"%s\"\n", filelist); exit(EXIT_FAILURE); } } else { (void) fprintf(stderr, "Do not specify both -filelist and input file names\n"); exit(EXIT_FAILURE); } /* Make sure that we have something to process */ if (nfiles == 0) { (void) fprintf(stderr, "No input files specified\n"); exit(EXIT_FAILURE); } /* Get the expression from the file if needed */ if ((expression == NULL) && (expr_file == NULL)) { (void) fprintf(stderr, "An expression must be specified on the command line\n"); exit(EXIT_FAILURE); } else if (expression == NULL) { expression = read_expression_file(expr_file); } /* Parse expression argument */ if (debug) fprintf(stderr, "Feeding in expression %s\n", expression); lex_init(expression); if (debug) yydebug = 1; else yydebug = 0; yyparse(); lex_finalize(); /* Optimize the expression tree */ root = optimize(root); /* Setup the input vector from the input files */ A = new_vector(); for (i=0; i<nfiles; i++) { if (debug) fprintf(stderr,"Getting file[%d] %s\n", i, argv[i+1]); scalar = new_scalar(eval_width); vector_append(A, scalar); scalar_free(scalar); } /* Construct initial symbol table from the A vector. Since setting a symbol makes a copy, we have to get a handle to that copy. */ rootsym = sym_enter_scope(NULL); ident = new_ident("A"); sym_set_vector(eval_width, NULL, A, ident, rootsym); vector_free(A); A = sym_lookup_vector(ident, rootsym); if (A==NULL) { (void) fprintf(stderr, "Error initializing symbol table\n"); exit(EXIT_FAILURE); } vector_incr_ref(A); /* Add output symbols to the table */ if (Output_list == NULL) { Output_values = NULL; } else { Output_values = malloc(Output_list_size * sizeof(*Output_values)); for (i=0; i < Output_list_size; i++) { ident = ident_lookup(Output_list[i].symbol); scalar = new_scalar(eval_width); sym_set_scalar(eval_width, NULL, scalar, ident, rootsym); scalar_free(scalar); Output_values[i] = sym_lookup_scalar(ident, rootsym); } } /* Set default copy_all_header according to number of input files */ if (copy_all_header == DEFAULT_BOOL) copy_all_header = (nfiles == 1); if (value_for_illegal_operations == DEFAULT_DBL) { if (use_nan_for_illegal_values) value_for_illegal_operations = INVALID_DATA; else value_for_illegal_operations = 0.0; } /* Do math */ loop_options = create_loop_options(); set_loop_verbose(loop_options, verbose); set_loop_clobber(loop_options, clobber); #if MINC2 set_loop_v2format(loop_options, minc2_format); #endif /* MINC2 */ set_loop_datatype(loop_options, datatype, is_signed, valid_range[0], valid_range[1]); set_loop_copy_all_header(loop_options, copy_all_header); /* only set buffer size if specified */ if(max_buffer_size_in_kb != 0){ set_loop_buffer_size(loop_options, (long) 1024 * max_buffer_size_in_kb); } set_loop_check_dim_info(loop_options, check_dim_info); voxel_loop(nfiles, infiles, nout, outfiles, arg_string, loop_options, do_math, NULL); free_loop_options(loop_options); /* Clean up */ vector_free(A); sym_leave_scope(rootsym); if (expr_file != NULL) free(expression); free(outfiles); if (Output_list != NULL) free(Output_list); if (Output_values != NULL) free(Output_values); exit(EXIT_SUCCESS); }
int main(int argc, char** argv) { char *input_path = 0; char *output_path = 0; char *dictionary_path = 0; int force = 0; int quality = 11; int decompress = 0; int repeat = 1; int verbose = 0; int lgwin = 0; clock_t clock_start; int i; ParseArgv(argc, argv, &input_path, &output_path, &dictionary_path, &force, &quality, &decompress, &repeat, &verbose, &lgwin); clock_start = clock(); for (i = 0; i < repeat; ++i) { FILE* fin = OpenInputFile(input_path); FILE* fout = OpenOutputFile(output_path, force || repeat); int is_ok = 0; if (decompress) { is_ok = Decompress(fin, fout, dictionary_path); } else { is_ok = Compress(quality, lgwin, fin, fout, dictionary_path); } if (!is_ok) { unlink(output_path); exit(1); } if (fclose(fin) != 0) { perror("fclose"); exit(1); } if (fclose(fout) != 0) { perror("fclose"); exit(1); } } if (verbose) { clock_t clock_end = clock(); double duration = (double)(clock_end - clock_start) / CLOCKS_PER_SEC; int64_t uncompressed_size; double uncompressed_bytes_in_MB; if (duration < 1e-9) { duration = 1e-9; } uncompressed_size = FileSize(decompress ? output_path : input_path); if (uncompressed_size == -1) { fprintf(stderr, "failed to determine uncompressed file size\n"); exit(1); } uncompressed_bytes_in_MB = (double)(repeat * uncompressed_size) / (1024.0 * 1024.0); if (decompress) { printf("Brotli decompression speed: "); } else { printf("Brotli compression speed: "); } printf("%g MB/s\n", uncompressed_bytes_in_MB / duration); } return 0; }
int main(int argc, char *argv[]) { VIO_General_transform transform, *grid_transform_ptr, forward_transform; VIO_Volume target_vol, volume; volume_input_struct input_info; VIO_Real voxel[VIO_MAX_DIMENSIONS], steps[VIO_MAX_DIMENSIONS], start[VIO_N_DIMENSIONS], target_steps[VIO_MAX_DIMENSIONS], wx,wy,wz, inv_x, inv_y, inv_z, def_values[VIO_MAX_DIMENSIONS]; static int clobber_flag = FALSE, verbose = TRUE, debug = FALSE; static char *target_file; int parse_flag, prog_count, sizes[VIO_MAX_DIMENSIONS], target_sizes[VIO_MAX_DIMENSIONS], xyzv[VIO_MAX_DIMENSIONS], target_xyzv[VIO_MAX_DIMENSIONS], index[VIO_MAX_DIMENSIONS], i, trans_count; VIO_progress_struct progress; static ArgvInfo argTable[] = { {"-like", ARGV_STRING, (char *) 0, (char *) &target_file, "Specify target volume sampling information."}, {"-no_clobber", ARGV_CONSTANT, (char *) FALSE, (char *) &clobber_flag, "Do not overwrite output file (default)."}, {"-clobber", ARGV_CONSTANT, (char *) TRUE, (char *) &clobber_flag, "Overwrite output file."}, {"-verbose", ARGV_CONSTANT, (char *) TRUE, (char *) &verbose, "Write messages indicating progress (default)"}, {"-quiet", ARGV_CONSTANT, (char *) FALSE, (char *) &verbose, "Do not write log messages"}, {"-debug", ARGV_CONSTANT, (char *) TRUE, (char *) &debug, "Print out debug info."}, {NULL, ARGV_END, NULL, NULL, NULL} }; prog_name = argv[0]; target_file = malloc(1024); strcpy(target_file,""); /* Call ParseArgv to interpret all command line args (returns TRUE if error) */ parse_flag = ParseArgv(&argc, argv, argTable, 0); /* Check remaining arguments */ if (parse_flag || argc != 3) print_usage_and_exit(prog_name); /* Read in file that has a def field to invert */ if (input_transform_file(argv[1], &transform) != OK) { (void) fprintf(stderr, "%s: Error reading transform file %s\n", argv[0], argv[1]); exit(EXIT_FAILURE); } for(trans_count=0; trans_count<get_n_concated_transforms(&transform); trans_count++ ) { grid_transform_ptr = get_nth_general_transform(&transform, trans_count ); if (grid_transform_ptr->type == GRID_TRANSFORM) { copy_general_transform(grid_transform_ptr, &forward_transform); /* this is the call that should be made with the latest version of internal_libvolume_io invert_general_transform(&forward_transform); */ forward_transform.inverse_flag = !(forward_transform.inverse_flag); volume = grid_transform_ptr->displacement_volume; if (strlen(target_file)!=0) { if (debug) print ("Def field will be resampled like %s\n",target_file); if (!file_exists( target_file ) ) { (void) fprintf(stderr, "%s: Target file '%s' does not exist\n", prog_name,target_file); exit(EXIT_FAILURE); } start_volume_input(target_file, 3, (char **)NULL, NC_UNSPECIFIED, FALSE, 0.0, 0.0, TRUE, &target_vol, (minc_input_options *)NULL, &input_info); get_volume_XYZV_indices(volume, xyzv); get_volume_separations (volume, steps); get_volume_sizes (volume, sizes); get_volume_XYZV_indices(target_vol, target_xyzv); get_volume_separations (target_vol, target_steps); get_volume_sizes (target_vol, target_sizes); for(i=0; i<VIO_MAX_DIMENSIONS; i++) { index[i] = 0; voxel[i] = 0.0; } convert_voxel_to_world(target_vol, voxel, &start[VIO_X], &start[VIO_Y], &start[VIO_Z]); if( volume != (void *) NULL ){ free_volume_data( volume ); } for(i=VIO_X; i<=VIO_Z; i++) { steps[ xyzv[i] ] = target_steps[ target_xyzv[i] ] ; sizes[ xyzv[i] ] = target_sizes[ target_xyzv[i] ] ; } set_volume_separations(volume, steps); set_volume_sizes( volume, sizes); set_volume_starts(volume, start); alloc_volume_data( volume ); } get_volume_sizes(volume, sizes); get_volume_XYZV_indices(volume,xyzv); for(i=0; i<VIO_MAX_DIMENSIONS; i++){ index[i] = 0; } if (verbose){ initialize_progress_report(&progress, FALSE, sizes[xyzv[VIO_X]]*sizes[xyzv[VIO_Y]]*sizes[xyzv[VIO_Z]]+1, "Inverting def field"); } prog_count = 0; for(index[xyzv[VIO_X]]=0; index[xyzv[VIO_X]]<sizes[xyzv[VIO_X]]; index[xyzv[VIO_X]]++) for(index[xyzv[VIO_Y]]=0; index[xyzv[VIO_Y]]<sizes[xyzv[VIO_Y]]; index[xyzv[VIO_Y]]++) for(index[xyzv[VIO_Z]]=0; index[xyzv[VIO_Z]]<sizes[xyzv[VIO_Z]]; index[xyzv[VIO_Z]]++) { index[ xyzv[VIO_Z+1] ] = 0; for(i=0; i<VIO_MAX_DIMENSIONS; i++) voxel[i] = (VIO_Real)index[i]; convert_voxel_to_world(volume, voxel, &wx, &wy, &wz); if (sizes[ xyzv[VIO_Z] ] ==1) general_inverse_transform_point_in_trans_plane(&forward_transform, wx, wy, wz, &inv_x, &inv_y, &inv_z); else grid_inverse_transform_point(&forward_transform, wx, wy, wz, &inv_x, &inv_y, &inv_z); def_values[VIO_X] = inv_x - wx; def_values[VIO_Y] = inv_y - wy; def_values[VIO_Z] = inv_z - wz; for(index[xyzv[VIO_Z+1]]=0; index[xyzv[VIO_Z+1]]<3; index[xyzv[VIO_Z+1]]++) set_volume_real_value(volume, index[0],index[1],index[2],index[3],index[4], def_values[ index[ xyzv[VIO_Z+1] ]]); prog_count++; if (verbose) update_progress_report(&progress, prog_count); } if (verbose) terminate_progress_report(&progress); delete_general_transform(&forward_transform); grid_transform_ptr->inverse_flag = !(grid_transform_ptr->inverse_flag); } } /* Write out the transform */ if (output_transform_file(argv[2], NULL, &transform) != OK) { (void) fprintf(stderr, "%s: Error writing transform file %s\n", argv[0], argv[2]); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { char *infile, *outfile; char *arg_string; int inmincid; int input_vector_length; int ivalue; Loop_Options *loop_options; Program_Data program_data; /* Save time stamp and args */ arg_string = time_stamp(argc, argv); /* Get arguments */ if (ParseArgv(&argc, argv, argTable, 0) || (argc != 3)) { (void) fprintf(stderr, "\nUsage: %s [options] <in.mnc> <out.mnc>\n", argv[0]); (void) fprintf(stderr, " %s -help\n\n", argv[0]); exit(EXIT_FAILURE); } infile = argv[1]; outfile = argv[2]; /* Check for conflicting options */ if ((conversion_type != CONV_DEFAULT) && (linear_coefficients.numvalues > 0)) { (void) fprintf(stderr, "Do not specify -linear with other conversion options\n"); exit(EXIT_FAILURE); } /* Set up conversion information */ if (conversion_type == CONV_DEFAULT) conversion_type = CONV_MAGNITUDE; program_data.conversion_type = conversion_type; program_data.num_coefficients = 0; program_data.linear_coefficients = NULL; /* Check for coefficients for linear combination */ if (linear_coefficients.numvalues > 0) { conversion_type = CONV_LINEAR; program_data.conversion_type = conversion_type; program_data.num_coefficients = linear_coefficients.numvalues; program_data.linear_coefficients = malloc(linear_coefficients.numvalues * sizeof(*program_data.linear_coefficients)); for (ivalue=0; ivalue < linear_coefficients.numvalues; ivalue++) { program_data.linear_coefficients[ivalue] = linear_coefficients.values[ivalue]; } } /* Open the input file and get the vector length */ inmincid = miopen(infile, NC_NOWRITE); input_vector_length = get_vector_length(inmincid); if (input_vector_length < 0) { fprintf(stderr, str_wrong_dimension_order); exit(EXIT_FAILURE); } if (input_vector_length < 1) input_vector_length = 1; /* Check that this length is okay */ if ((conversion_type == CONV_GREY) && (input_vector_length != 3) && (input_vector_length > 1)) { (void) fprintf(stderr, "Input file does not contain RGB data\n"); exit(EXIT_FAILURE); } if ((conversion_type == CONV_LINEAR) && (input_vector_length != program_data.num_coefficients) && (input_vector_length > 1)) { (void) fprintf(stderr, "Input vector length does not match number of linear coefficients\n"); exit(EXIT_FAILURE); } /* Set up looping options */ loop_options = create_loop_options(); set_loop_clobber(loop_options, clobber); set_loop_verbose(loop_options, verbose); #if MINC2 set_loop_v2format(loop_options, v2format); #endif /* MINC2 */ set_loop_datatype(loop_options, datatype, is_signed, valid_range[0], valid_range[1]); set_loop_output_vector_size(loop_options, 1); set_loop_buffer_size(loop_options, (long) buffer_size * 1024); set_loop_first_input_mincid(loop_options, inmincid); /* Do loop */ voxel_loop(1, &infile, 1, &outfile, arg_string, loop_options, do_makescalar, (void *) &program_data); /* Free stuff */ if (program_data.linear_coefficients != NULL) { free(program_data.linear_coefficients); } if (linear_coefficients.values != NULL) { free(linear_coefficients.values); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int ifile; Acr_Group group_list; char **file_list; /* List of file names */ Data_Object_Info **file_info_list; int num_file_args; /* Number of files on command line */ int num_files; /* Total number of files */ string_t out_dir; /* Output directory */ string_t message; /* Generic message */ int num_files_ok; /* Actual number of DICOM/IMA files */ struct stat st; int length; int exit_status; G.mosaic_seq = MOSAIC_SEQ_UNKNOWN; /* Assume ascending by default. */ G.splitDynScan = FALSE; /* Don't split dynamic scans by default */ G.splitEcho = TRUE; /* Do split by echo by default */ G.use_stdin = FALSE; /* Do not read file list from stdin */ G.filename_format = NULL; G.dirname_format = NULL; G.minc_history = time_stamp(argc, argv); /* Create minc history string */ G.prefer_coords = FALSE; G.abort_on_error = FALSE; G.pname = argv[0]; /* get program name */ /* Get the input parameters and file names. */ if (ParseArgv(&argc, argv, argTable, 0)) { usage(); } if (argc < 2) { usage(); } if (G.List) { num_file_args = argc - 1; /* Assume no directory given. */ } else { num_file_args = argc - 2; /* Assume last arg is directory. */ strcpy(out_dir, argv[argc - 1]); /* make sure path ends with slash */ length = strlen(out_dir); if (out_dir[length - 1] != '/') { out_dir[length++] = '/'; out_dir[length++] = '\0'; } if (stat(out_dir, &st) != 0 || !S_ISDIR(st.st_mode)) { fprintf(stderr, "The final argument, '%s', is not a directory\n", out_dir); exit(EXIT_FAILURE); } } /* Get space for file lists */ /* Allocate the array of pointers used to implement the * list of filenames. */ file_list = malloc(1 * sizeof(char *)); CHKMEM(file_list); /* Go through the list of files, expanding directories where they * are encountered... */ num_files = 0; for (ifile = 0 ; ifile < num_file_args; ifile++) { #if HAVE_DIRENT_H if (stat(argv[ifile + 1], &st) == 0 && S_ISDIR(st.st_mode)) { DIR *dp; struct dirent *np; char *tmp_str; if (G.Debug) { printf("Expanding directory '%s'\n", argv[ifile + 1]); } length = strlen(argv[ifile + 1]); dp = opendir(argv[ifile + 1]); if (dp != NULL) { while ((np = readdir(dp)) != NULL) { /* Generate the full path to the file. */ tmp_str = malloc(length + strlen(np->d_name) + 2); strcpy(tmp_str, argv[ifile + 1]); if (tmp_str[length-1] != '/') { tmp_str[length] = '/'; tmp_str[length+1] = '\0'; } strcat(&tmp_str[length], np->d_name); if (stat(tmp_str, &st) == 0 && S_ISREG(st.st_mode)) { file_list = realloc(file_list, (num_files + 1) * sizeof(char *)); file_list[num_files++] = tmp_str; } else { free(tmp_str); } } closedir(dp); } else { fprintf(stderr, "Error opening directory '%s'\n", argv[ifile + 1]); } } else { file_list = realloc(file_list, (num_files + 1) * sizeof(char *)); file_list[num_files++] = strdup(argv[ifile + 1]); } #else file_list = realloc(file_list, (num_files + 1) * sizeof(char *)); file_list[num_files++] = strdup(argv[ifile + 1]); #endif } if (G.use_stdin) { char linebuf[1024]; char *p; while (fgets(linebuf, sizeof(linebuf), stdin) != NULL) { /* Strip off newline at end of string. */ for (p = linebuf; *p != '\0'; p++) { if (*p == '\n') { *p = '\0'; } } if (strlen(linebuf) != 0) { file_list = realloc(file_list, (num_files + 1) * sizeof(char *)); file_list[num_files++] = strdup(linebuf); } } } file_info_list = malloc(num_files * sizeof(*file_info_list)); CHKMEM(file_info_list); /* figure out what kind of files we have - * supported types are: * * IMA (Siemens .ima format - Numaris 3.5) * N4DCM (Siemens DICOM - Numaris 4) * * if not all same type, return an error * * we start by assuming N4DCM with no offset - we find that the * file is IMA or has an offset (the 128 byte + DICM offset seen * on Syngo CD's and exports) then the appropriate flag will be * set. */ printf("Checking file types...\n"); if (check_file_type_consistency(num_files, file_list) < 0) { exit(EXIT_FAILURE); } /* Now loop over all files, getting basic info on each */ num_files_ok = 0; for (ifile = 0; ifile < num_files; ifile++) { char *cur_fname_ptr = file_list[ifile]; if (!G.Debug) { sprintf(message, "Parsing %d files", num_files); progress(ifile, num_files, message); } if (G.file_type == IMA) { group_list = siemens_to_dicom(cur_fname_ptr, ACR_IMAGE_GID - 1); } else { /* read up to but not including pixel data */ group_list = read_numa4_dicom(cur_fname_ptr, ACR_IMAGE_GID - 1); } if (group_list == NULL) { /* This file appears to be invalid - it is probably a dicomdir * file or some other stray junk in the directory. */ printf("Skipping file %s, which is not in the expected format.\n", cur_fname_ptr); free(cur_fname_ptr); } else { /* Copy it back to the (possibly earlier) position in the real * file list. */ file_list[num_files_ok] = cur_fname_ptr; /* allocate space for the current entry to file_info_list */ file_info_list[num_files_ok] = malloc(sizeof(*file_info_list[0])); CHKMEM(file_info_list[num_files_ok]); file_info_list[num_files_ok]->file_index = num_files_ok; parse_dicom_groups(group_list, file_info_list[num_files_ok]); /* put the file name into the info list */ file_info_list[num_files_ok]->file_name = strdup(file_list[num_files_ok]); /* Delete the group list now that we're done with it */ acr_delete_group_list(group_list); num_files_ok++; } } /* end of loop over files to get basic info */ if (G.Debug) { printf("Using %d files\n", num_files_ok); } num_files = num_files_ok; printf("Sorting %d files... ", num_files); /* sort the files into series based on acquisition number */ qsort(file_info_list, num_files, sizeof(file_info_list[0]), dcm_sort_function); /* If DEBUG, print a list of all files. */ if (G.Debug) { printf("\n"); for (ifile = 0; ifile < num_files; ifile++) { Data_Object_Info *info = file_info_list[ifile]; char *fname; if ((ifile % 16) == 0) { printf("%-4s %-32.32s %-14s %-8s %-8s %-4s %-4s %-4s %-4s %-4s %-4s %-4s %-4s %-4s %-5s %-16s\n", "num", "filename", "studyid", "serialno", "acq", "nec", "iec", "ndy", "idy", "nsl", "isl", "acol", "rcol", "mrow", "img#", "seq"); } /* Print out info about file. Truncate the name if necessary. */ fname = info->file_name; if (strlen(fname) > 32) { fname += strlen(fname) - 32; } printf("%4d %-32.32s %14.6f %8d %8d %4d %4d %4d %4d %4d %4d %4d %4d %4d %5d %-16s\n", ifile, fname, info->study_id, info->scanner_serialno, info->acq_id, info->num_echoes, info->echo_number, info->num_dyn_scans, info->dyn_scan_number, info->num_slices_nominal, info->slice_number, info->acq_cols, info->rec_cols, info->num_mosaic_rows, info->global_image_number, info->sequence_name); } } printf("Done sorting files.\n"); /* Loop over files, processing by acquisition */ if (G.List) { printf("Listing files by series...\n"); } else { printf("Processing files, one series at a time...\n"); } exit_status = use_the_files(num_files, file_info_list, out_dir); if (G.List) { printf("Done listing files.\n"); } else { printf("Done processing files.\n"); } free_list(num_files, file_list, file_info_list); free(file_list); free(file_info_list); exit(exit_status); }
int main(int argc, char *argv[]) { char *pname; char *filename, *tempfile, *newfile; char string[1024]; char *variable_name, *attribute_name; int created_tempfile; int done_redef; int iatt; int mincid, varid; int variable_exists, attribute_exists; nc_type attribute_type, new_type; int attribute_length, new_length; void *new_value; int total_length, alloc_length, ival; char *zeros; int old_ncopts; /* Parse the command line */ pname=argv[0]; if (ParseArgv(&argc, argv, argTable, 0) || (argc != 2)) { (void) fprintf(stderr, "\nUsage: %s [<options>] <file.mnc>\n", pname); (void) fprintf(stderr, " %s [-help]\n\n", pname); exit(EXIT_FAILURE); } filename = argv[1]; /* Create temp file name. First try looking for minc extension, then a compression extension. Chop off the unwanted extension. */ (void) strncpy(string, filename, sizeof(string)-1); tempfile = strstr(string, MINC_EXTENSION); if (tempfile != NULL) { tempfile += strlen(MINC_EXTENSION); if (*tempfile == '\0') tempfile = NULL; } else { tempfile = strstr(string, GZIP_EXTENSION); if (tempfile == NULL) tempfile = strstr(string, BZIP_EXTENSION); if (tempfile == NULL) tempfile = strstr(string, BZIP2_EXTENSION); if (tempfile == NULL) tempfile = strstr(string, COMPRESS_EXTENSION); if (tempfile == NULL) tempfile = strstr(string, PACK_EXTENSION); if (tempfile == NULL) tempfile = strstr(string, ZIP_EXTENSION); } if (tempfile != NULL) { *tempfile = '\0'; tempfile = string; } /* If tempfile == NULL, then either we have a minc file or we don't know how to edit the file in place. Check that it is a minc file. */ if (tempfile == NULL) { newfile = miexpand_file(filename, tempfile, TRUE, &created_tempfile); if (created_tempfile) { if (newfile != NULL) { (void) remove(newfile); free(newfile); } (void) fprintf(stderr, "Cannot edit file \"%s\" in place.\n", filename); exit(EXIT_FAILURE); } } /* Expand the file. */ newfile = miexpand_file(filename, tempfile, FALSE, &created_tempfile); if (newfile == NULL) { (void) fprintf(stderr, "Error decompressing file \"%s\"\n", filename); exit(EXIT_FAILURE); } /* If a new file was created, get rid of the old one */ if (created_tempfile) { (void) remove(filename); } /* Open the file */ mincid = miopen(newfile, NC_WRITE); /* Loop through attribute list, modifying values */ done_redef = FALSE; ncopts = NC_VERBOSE; zeros = NULL; alloc_length = 0; for (iatt=0; iatt < attribute_list_size; iatt++) { /* Get variable and attribute name */ variable_name = attribute_list[iatt].variable; attribute_name = attribute_list[iatt].attribute; /* Check for attribute existence */ if (strlen(variable_name) == 0) { varid = NC_GLOBAL; variable_exists = TRUE; } else { old_ncopts = ncopts; ncopts = 0; varid = ncvarid(mincid, variable_name); ncopts = old_ncopts; variable_exists = (varid != MI_ERROR); } attribute_type = NC_CHAR; attribute_length = 0; if (variable_exists) { old_ncopts = ncopts; ncopts = 0; attribute_exists = (ncattinq(mincid, varid, attribute_name, &attribute_type, &attribute_length) != MI_ERROR); ncopts = old_ncopts; } else attribute_exists = FALSE; /* Are we inserting or deleting? */ switch (attribute_list[iatt].action) { case Insert_attribute: case Append_attribute: if (attribute_list[iatt].value != NULL) { new_type = NC_CHAR; new_length = strlen(attribute_list[iatt].value)+1; new_value = (void *) attribute_list[iatt].value; } else { new_type = NC_DOUBLE; new_length = attribute_list[iatt].num_doubles; new_value = (void *) attribute_list[iatt].double_values; } /* For append we have to copy the entire attribute, if it * already exists. */ if (attribute_list[iatt].action == Append_attribute && attribute_exists) { char *tmp_value; /* Verify that the existing type matches the newly * requested type. Don't allow a -dappend on a * string attribute, for example. */ if (new_type != attribute_type) { fprintf(stderr, "Can't append %s data to %s attribute %s:%s.\n", (new_type == NC_DOUBLE) ? "double" : "string", (attribute_type == NC_DOUBLE) ? "double" : "string", variable_name, attribute_name); exit(EXIT_FAILURE); } new_type = attribute_type; tmp_value = malloc((attribute_length + new_length) * nctypelen(new_type)); ncattget(mincid, varid, attribute_name, tmp_value); /* For string attributes, remove any trailing null * character before appending. */ if (new_type == NC_CHAR && tmp_value[attribute_length-1] == 0) { attribute_length--; } memcpy(tmp_value + attribute_length * nctypelen(new_type), new_value, new_length * nctypelen(new_type)); new_length += attribute_length; new_value = (void *) tmp_value; } total_length = attribute_length*nctypelen(attribute_type); if (!attribute_exists || (total_length < new_length*nctypelen(new_type))) { if (! done_redef) { done_redef = TRUE; (void) ncredef(mincid); } } else if (!done_redef && attribute_exists && (total_length > 0)) { if (total_length > alloc_length) { if (zeros != NULL) free(zeros); zeros = malloc(total_length); alloc_length = total_length; for (ival=0; ival < alloc_length; ival++) zeros[ival] = '\0'; } (void) ncattput(mincid, varid, attribute_name, NC_CHAR, total_length, zeros); (void) ncsync(mincid); } if (!variable_exists) { old_ncopts = ncopts; ncopts = 0; varid = micreate_group_variable(mincid, variable_name); ncopts = old_ncopts; if (varid == MI_ERROR) { varid = ncvardef(mincid, variable_name, NC_INT, 0, NULL); } variable_exists = (varid != MI_ERROR); } if (variable_exists) { (void) ncattput(mincid, varid, attribute_name, new_type, new_length, new_value); } break; case Delete_attribute: if (attribute_exists) { if (! done_redef) { done_redef = TRUE; (void) ncredef(mincid); } (void) ncattdel(mincid, varid, attribute_name); } break; default: (void) fprintf(stderr, "Program error: unknown action %d\n", (int) attribute_list[iatt].action); exit(EXIT_FAILURE); } } ncopts = NC_VERBOSE | NC_FATAL; /* Close the file */ (void) miclose(mincid); /* Free stuff */ free(newfile); if (zeros != NULL) free(zeros); exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { int c, i; Coord_list coord_buf; char *coord_fn; int buff_size = 2048; int prev_size; /* Get arguments */ if(ParseArgv(&argc, argv, argTable, 0)) { (void)fprintf(stderr, "\nUsage: %s [options] <coords.cfg>\n", argv[0]); (void)fprintf(stderr, " %s -help\n\n", argv[0]); exit(EXIT_FAILURE); } coord_fn = argv[1]; /* initialise the parser with the config file */ fprintf(stderr, "Opening coord-file %s\n", coord_fn); if(!init_arb_path(coord_fn, NULL)) { fprintf(stderr, "Failed to init arb_path, this isn't good\n"); } /* suck in all the co-ordinates (brough-ha ha ha!) */ coord_buf = get_some_arb_path_coords(buff_size); while (coord_buf->n_pts != 0) { /* allocate some memory */ prev_size = n_coords; n_coords += coord_buf->n_pts; x_coord = (double *)realloc(x_coord, n_coords * sizeof(double)); y_coord = (double *)realloc(y_coord, n_coords * sizeof(double)); z_coord = (double *)realloc(z_coord, n_coords * sizeof(double)); /* add the current list */ for(c = 0; c < coord_buf->n_pts; c++) { x_coord[prev_size + c] = coord_buf->pts[c].coord[0]; y_coord[prev_size + c] = coord_buf->pts[c].coord[1]; z_coord[prev_size + c] = coord_buf->pts[c].coord[2]; /* set min and max */ for(i = 3; i--;) { if(coord_buf->pts[c].coord[i] > max[i]) { max[i] = coord_buf->pts[c].coord[i]; } if(coord_buf->pts[c].coord[i] < min[i]) { min[i] = coord_buf->pts[c].coord[i]; } } } fprintf(stdout, "Got %d co-ords, realloced to %d points\n", coord_buf->n_pts, n_coords); /* get the next lot of co-ordinates */ coord_buf = get_some_arb_path_coords(buff_size); } fprintf(stdout, "Got %d coords\n", n_coords); fprintf(stdout, "Min [%g:%g:%g] Max [%g:%g:%g]\n", min[0], min[1], min[2], max[0], max[1], max[2]); /* init the quat */ trackball(curquat, 0.0, 0.0, 0.0, 0.0); /* GLUT stuff */ glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutCreateWindow("regrid viewer"); glutDisplayFunc(mainDisplay); glutReshapeFunc(mainReshape); glutVisibilityFunc(vis); glutMouseFunc(mouse); glutMotionFunc(motion); glutKeyboardFunc(KeyPressed); glutSpecialFunc(SpecialKey); glMatrixMode(GL_PROJECTION); gluPerspective( /* field of view in degree */ 40.0, /* aspect ratio */ 1.0, /* Z near */ 1.0, /* Z far */ 40.0); glMatrixMode(GL_MODELVIEW); gluLookAt(0.0, 0.0, 30.0, /* eye is at (0,0,30) */ 0.0, 0.0, 0.0, /* center is at (0,0,0) */ 0.0, 1.0, 0.); /* up is in positive Y direction */ glPushMatrix(); /* dummy push so we can pop on model recalc */ glutMainLoop(); return TRUE; }
int main(int argc, char *argv[]) { char *pname, *tagfile1, *tagfile2, *outtag, *history; Real **tags1, **tags2, **new_tags, *this_tag; int n_volumes1, n_volumes2, n_tag_points1, n_tag_points2; int ipoint1, ipoint2, icoord, near_tag; STRING *labels1, *labels2, *new_labels, this_label; double min_distsq, distsq, diff, maximum_distsq; size_t string_length; FILE *fp; char dist_string[64]; /* Save history */ history = time_stamp(argc, argv); /* Parse arguments */ pname = argv[0]; if (ParseArgv(&argc, argv, argTable, 0) || (argc != 4)) { (void) fprintf(stderr, "\nUsage: %s [<options>] infile1.tag file2.tag outfile2.tag\n\n", pname); exit(EXIT_FAILURE); } tagfile1 = argv[1]; tagfile2 = argv[2]; outtag = argv[3]; maximum_distsq = maximum_distance * maximum_distance; /* Read in first tag file */ if ((open_file_with_default_suffix(tagfile1, get_default_tag_file_suffix(), READ_FILE, ASCII_FORMAT, &fp) != OK) || (input_tag_points(fp, &n_volumes1, &n_tag_points1, &tags1, NULL, NULL, NULL, NULL, &labels1) != OK)) { (void) fprintf(stderr, "%s: Error reading tag file %s\n", pname, tagfile1); exit(EXIT_FAILURE); } (void) close_file(fp); /* Read in second tag file */ if ((open_file_with_default_suffix(tagfile2, get_default_tag_file_suffix(), READ_FILE, ASCII_FORMAT, &fp) != OK) || (input_tag_points(fp, &n_volumes2, &n_tag_points2, &tags2, NULL, NULL, NULL, NULL, &labels2) != OK)) { (void) fprintf(stderr, "%s: Error reading tag file %s\n", pname, tagfile2); exit(EXIT_FAILURE); } (void) close_file(fp); /* Allocate space for output tags */ new_tags = MALLOC(n_tag_points1 * sizeof(*new_tags)); new_labels = MALLOC(n_tag_points1 * sizeof(*new_labels)); /* Loop through tags in first file */ for (ipoint1=0; ipoint1 < n_tag_points1; ipoint1++) { /* Look for nearest tag in second file */ min_distsq = 0.0; for (ipoint2=0; ipoint2 < n_tag_points2; ipoint2++) { /* Calculate distance-squared */ distsq = 0; for (icoord=0; icoord < WORLD_NDIMS; icoord++) { diff = tags1[ipoint1][icoord] - tags2[ipoint2][icoord]; distsq += diff * diff; } /* Check if this is the minimum */ if ((ipoint2 == 0) || (min_distsq > distsq)) { near_tag = ipoint2; min_distsq = distsq; } } /* Save the nearest tag */ if (min_distsq <= maximum_distsq) { this_tag = tags2[near_tag]; this_label = labels2[near_tag]; } else { this_tag = tags1[ipoint1]; this_label = "not found"; } (void) sprintf(dist_string, " (%.2f mm)", sqrt(min_distsq)); new_tags[ipoint1] = this_tag; string_length = strlen(labels1[ipoint1]) + strlen(this_label) + strlen(SEP_STRING) + strlen(dist_string) + 1; new_labels[ipoint1] = MALLOC(string_length); (void) strcpy(new_labels[ipoint1], labels1[ipoint1]); (void) strcat(new_labels[ipoint1], SEP_STRING); (void) strcat(new_labels[ipoint1], this_label); (void) strcat(new_labels[ipoint1], dist_string); } if (output_tag_file(outtag, history, 2, n_tag_points1, tags1, new_tags, NULL, NULL, NULL, new_labels) != OK) { (void) fprintf(stderr, "Error writing out labels\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { char *filename; int mincid, imgid, icvid, ndims, dims[MAX_VAR_DIMS]; nc_type datatype; int is_signed; long start[MAX_VAR_DIMS], count[MAX_VAR_DIMS], end[MAX_VAR_DIMS]; long size; int idim; void *data; double temp; /* Check arguments */ if (ParseArgv(&argc, argv, argTable, 0) || (argc != 2)) { (void) fprintf(stderr, "\nUsage: %s [<options>] <mincfile>\n", argv[0]); (void) fprintf(stderr, " %s -help\n\n", argv[0]); exit(EXIT_FAILURE); } filename = argv[1]; /* Check that a normalization option was specified */ if (normalize_output == VIO_BOOL_DEFAULT) { (void) fprintf(stderr, "Please specify either -normalize or -nonormalize\n"); (void) fprintf(stderr, "Usually -normalize is most appropriate\n"); exit(EXIT_FAILURE); } /* Open the file */ mincid = miopen(filename, NC_NOWRITE); /* Inquire about the image variable */ imgid = ncvarid(mincid, MIimage); (void) ncvarinq(mincid, imgid, NULL, NULL, &ndims, dims, NULL); (void)miget_datatype(mincid, imgid, &datatype, &is_signed); /* Check if arguments set */ /* Get output data type */ if (output_datatype == INT_MAX) output_datatype = datatype; /* Get output sign */ if (output_signed == INT_MAX) { if (output_datatype == datatype) output_signed = is_signed; else output_signed = (output_datatype != NC_BYTE); } /* Get output range */ if (valid_range[0] == DBL_MAX) { if ((output_datatype == datatype) && (output_signed == is_signed)) { (void) miget_valid_range(mincid, imgid, valid_range); } else { (void) miget_default_range(output_datatype, output_signed, valid_range); } } if (valid_range[0] > valid_range[1]) { temp = valid_range[0]; valid_range[0] = valid_range[1]; valid_range[1] = temp; } /* Set up image conversion */ icvid = miicv_create(); (void) miicv_setint(icvid, MI_ICV_TYPE, output_datatype); (void) miicv_setstr(icvid, MI_ICV_SIGN, (output_signed ? MI_SIGNED : MI_UNSIGNED)); (void) miicv_setdbl(icvid, MI_ICV_VALID_MIN, valid_range[0]); (void) miicv_setdbl(icvid, MI_ICV_VALID_MAX, valid_range[1]); if ((output_datatype == NC_FLOAT) || (output_datatype == NC_DOUBLE)) { (void) miicv_setint(icvid, MI_ICV_DO_NORM, TRUE); (void) miicv_setint(icvid, MI_ICV_USER_NORM, TRUE); } else if (normalize_output) { (void) miicv_setint(icvid, MI_ICV_DO_NORM, TRUE); } (void) miicv_attach(icvid, mincid, imgid); /* Set input file start, count and end vectors for reading a slice at a time */ for (idim=0; idim < ndims; idim++) { (void) ncdiminq(mincid, dims[idim], NULL, &end[idim]); } (void) miset_coords(ndims, (long) 0, start); (void) miset_coords(ndims, (long) 1, count); size = nctypelen(output_datatype); for (idim=ndims-2; idim < ndims; idim++) { count[idim] = end[idim]; size *= count[idim]; } /* Allocate space */ data = malloc(size); /* Loop over input slices */ while (start[0] < end[0]) { /* Read in the slice */ (void) miicv_get(icvid, start, count, data); /* Write out the slice */ if (fwrite(data, sizeof(char), (size_t) size, stdout) != size) { (void) fprintf(stderr, "Error writing data.\n"); exit(EXIT_FAILURE); } /* Increment start counter */ idim = ndims-1; start[idim] += count[idim]; while ( (idim>0) && (start[idim] >= end[idim])) { start[idim] = 0; idim--; start[idim] += count[idim]; } } /* End loop over slices */ /* Clean up */ (void) miclose(mincid); (void) miicv_free(icvid); free(data); exit(EXIT_SUCCESS); }
int waste_main_start(int argc, char **argv) { SetProgramDirectory(argv[0]); g_log_level=ds_Console; //g_log_level=ds_Debug; _logfile=stderr; installsighandler(); log_printf(ds_Console,"%s starting up...",g_nameverstr); MYSRAND(); #ifdef _DEFINE_WXUI extern void ParseArgv (const char *, bool); int i; for (i = 1; i < argc; i++) { ParseArgv(argv[i], true); } extern int g_opt_forceProfileDlg; if (Prefs_SelectProfile(g_opt_forceProfileDlg)) return 1; strcat(g_config_prefix,g_profile_name); #else strcat(g_config_prefix,"default"); #endif if (!g_exit) //emergency break! { #ifdef _WIN32 WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 0), &wsaData)) { memset(&g_key,0,sizeof(g_key)); MessageBox(NULL,"Error initializing Winsock\n",APP_NAME " Error",0); return 1; } #endif UnifiedReadConfig(); InitialLoadDb(); PrepareDownloadDirectory(); int need_setup=0; #ifndef _DEFINE_SRV need_setup=g_config->ReadInt(CONFIG_valid,0)<5; if (need_setup) { #ifdef _DEFINE_WXUI ::wxMessageBox(_T("This is your first time running WASTE.\n" "Please open the 'Preferences' window and press\n" "'Generate a new private key...', so that you can\n" "join and use the WASTE network."), _T("Welcome to WASTE"), wxICON_HAND|wxOK); g_config->WriteInt(CONFIG_valid,5); g_config->Flush(); #else if (!DialogBox(hInstance,MAKEINTRESOURCE(IDD_SETUPWIZ),NULL,SetupWi zProc)) { delete g_config; memset(&g_key,0,sizeof(g_key)); return 1; }; g_config->WriteInt(CONFIG_valid,5); g_config->Flush(); #endif }; #endif /* _DEFINE_SRV */ if (!g_key.bits && !need_setup) { reloadKey( g_config->ReadInt(CONFIG_storepass,CONFIG_storepass_DEFAULT)? g_config->ReadString(CONFIG_keypass,CONFIG_keypass_DEFAULT): NULL ); }; InitializeNetworkparts(); #ifdef _DEFINE_WXUI int x; for (x = 0; x < SEARCHCACHE_NUMITEMS; x ++) g_searchcache[x]=new SearchCacheItem; #endif #ifndef _DEFINE_SRV extern char *g_opt_wasteOpen; if (g_opt_wasteOpen) { handleWasteURL(g_opt_wasteOpen); free(g_opt_wasteOpen); g_opt_wasteOpen = NULL; }; #endif /* _DEFINE_SRV */ } return (g_exit); }
int main(int argc, char *argv[]) { char **infiles, *outfiles[3]; int nfiles, nout; char *arg_string; Norm_Data norm_data; Average_Data average_data; Loop_Options *loop_options; double *vol_mean, vol_total, nvols, global_mean, total_weight; int ifile, iweight; int weights_specified; int first_mincid, dimid, varid, dim[MAX_VAR_DIMS]; int ndims; long start, count; int old_ncopts; int strlength; char dimname[MAX_NC_NAME]; /* Save time stamp and args */ arg_string = time_stamp(argc, argv); /* Get arguments */ if (ParseArgv(&argc, argv, argTable, 0) || (argc < 2)) { (void) fprintf(stderr, "\nUsage: %s [options] [<in1.mnc> ...] <out.mnc>\n", argv[0]); (void) fprintf(stderr, " %s -help\n\n", argv[0]); exit(EXIT_FAILURE); } outfiles[0] = outfiles[1] = outfiles[2] = NULL; outfiles[0] = argv[argc-1]; nout = 1; if( sdfile != NULL ) outfiles[nout++] = sdfile; if( weightfile != NULL ) outfiles[nout++] = weightfile; first_mincid = MI_ERROR; /* Get the list of input files either from the command line or from a file, or report an error if both are specified */ nfiles = argc - 2; if (filelist == NULL) { infiles = &argv[1]; } else if (nfiles <= 0) { infiles = read_file_names(filelist, &nfiles); if (infiles == NULL) { (void) fprintf(stderr, "Error reading in file names from file \"%s\"\n", filelist); exit(EXIT_FAILURE); } } else { (void) fprintf(stderr, "Do not specify both -filelist and input file names\n"); exit(EXIT_FAILURE); } /* Make sure that we have something to process */ if (nfiles == 0) { (void) fprintf(stderr, "No input files specified\n"); exit(EXIT_FAILURE); } /* Set default value of copy_all_header */ if (copy_all_header == DEFAULT_BOOLEAN) { copy_all_header = (nfiles <= 1); } /* Are we averaging over a dimension? */ average_data.averaging_over_dimension = (averaging_dimension != NULL); /* Check for weights and width-weighting */ weights_specified = weights.numvalues > 0; if (weights_specified && width_weighted) { (void) fprintf(stderr, "%s: Please do not specify weights and width-weighting.\n", argv[0]); exit(EXIT_FAILURE); } /* Default is no weighting */ average_data.num_weights = 0; average_data.weights = NULL; /* Check for weights */ if (weights_specified) { if (averaging_dimension == NULL) { if (weights.numvalues != nfiles) { (void) fprintf(stderr, "%s: Number of weights does not match number of files.\n", argv[0]); exit(EXIT_FAILURE); } } else { if (nfiles > 1) { (void) fprintf(stderr, "%s: Only one input file allowed with -weights and -avgdim.\n", argv[0]); exit(EXIT_FAILURE); } /* Check that the dimension size matches the number of weights */ first_mincid = miopen(infiles[0], NC_NOWRITE); dimid = ncdimid(first_mincid, averaging_dimension); (void) ncdiminq(first_mincid, dimid, NULL, &count); if (weights.numvalues != count) { (void) fprintf(stderr, "%s: Number of weights does not match size of dimension.\n", argv[0]); } } /* Save the weights */ average_data.num_weights = weights.numvalues; average_data.weights = malloc(sizeof(*average_data.weights) * average_data.num_weights); for (iweight=0; iweight < average_data.num_weights; iweight++) { average_data.weights[iweight] = weights.values[iweight]; } free(weights.values); } /* Check for width weighting */ if (width_weighted) { /* Check for errors */ if (averaging_dimension == NULL) { (void) fprintf(stderr, "%s: Please specify -avgdim with -width_weighted.\n", argv[0]); exit(EXIT_FAILURE); } if (nfiles > 1) { (void) fprintf(stderr, "%s: Use -width_weighted with only one input file.\n", argv[0]); exit(EXIT_FAILURE); } /* Open the file */ first_mincid = miopen(infiles[0], NC_NOWRITE); /* Get the dimension id */ dimid = ncdimid(first_mincid, averaging_dimension); /* Look for the width variable */ strlength = MAX_NC_NAME - strlen(WIDTH_SUFFIX) - 1; (void) strncpy(dimname, averaging_dimension, strlength); dimname[strlength] = '\0'; (void) strcat(dimname, WIDTH_SUFFIX); old_ncopts = ncopts; ncopts = 0; varid = ncvarid(first_mincid, dimname); (void) ncvarinq(first_mincid, varid, NULL, NULL, &ndims, dim, NULL); ncopts = old_ncopts; if (varid != MI_ERROR) { /* Check that things match up */ if ((ndims != 1) || (dim[0] != dimid)) { (void) fprintf(stderr, "%s: Dimension width variable does not match avgdim.\n", argv[0]); } /* Get the size of the dimension */ (void) ncdiminq(first_mincid, dim[0], NULL, &count); average_data.num_weights = count; average_data.weights = malloc(sizeof(*average_data.weights) * average_data.num_weights); /* Read in the widths */ start = 0; (void) mivarget(first_mincid, varid, &start, &count, NC_DOUBLE, NULL, average_data.weights); } } /* If width_weighted */ /* Check that weights sum to non-zero. We don't need to normalize them, since a running sum is done in the averaging. */ if (average_data.num_weights > 0) { total_weight = 0.0; for (iweight=0; iweight < average_data.num_weights; iweight++) { total_weight += average_data.weights[iweight]; } if (total_weight == 0.0) { (void) fprintf(stderr, "%s: Weights sum to zero.\n", argv[0]); exit(EXIT_FAILURE); } } /* If we don't have weights, each input will get a weight of 1 */ if (average_data.num_weights == 0) total_weight = nfiles; /* Check the cumulative weight thresholding */ if (weight_thresh > 0.0 && weight_thresh_fraction > 0.0){ (void) fprintf(stderr, "Do not specify both -min_weight -min_weight_fraction\n"); exit(EXIT_FAILURE); } else if( weight_thresh_fraction > 0.0 ){ weight_thresh = weight_thresh_fraction * total_weight; } average_data.weight_thresh = weight_thresh; /* Check for binarization */ if (binarize) { if (normalize == TRUE) { (void) fprintf(stderr, "%s: Normalization and binarization cannot both be specified\n", argv[0]); exit(EXIT_FAILURE); } normalize = FALSE; if (binvalue != -DBL_MAX) { binrange[0] = binvalue - 0.5; binrange[1] = binvalue + 0.5; } if (binrange[0] > binrange[1]) { (void) fprintf(stderr, "%s: Please specify a binarization range with min less than max\n", argv[0]); exit(EXIT_FAILURE); } average_data.binrange[0] = binrange[0]; average_data.binrange[1] = binrange[1]; } average_data.binarize = binarize; /* Store the ignore above/below values */ average_data.ignore_below = ignore_below; average_data.ignore_above = ignore_above; /* Check for no specification of normalization */ #ifdef NO_DEFAULT_NORM if (normalize == -1) { (void) fprintf(stderr, "\n%s: %s\n\n%s\n%s\n%s\n%s\n%s\n\n", argv[0], "Please specify either -norm or -nonorm.", "The default setting for normalization is being changed from \"-norm\" to", "\"-nonorm\". To prevent undetected problems with data, this program will ", "not work unless one of these flags is explicitly given on the command-line", "(ie. no default is permitted). The new default will come into effect some", "time in the future." ); exit(EXIT_FAILURE); } #endif /* Do normalization if needed */ average_data.norm_factor = malloc(sizeof(*average_data.norm_factor) * nfiles); if (normalize) { vol_mean = malloc(sizeof(*vol_mean) * nfiles); loop_options = create_loop_options(); set_loop_verbose(loop_options, FALSE); #if MINC2 set_loop_v2format(loop_options, minc2_format); #endif /* MINC2 */ set_loop_accumulate(loop_options, TRUE, 0, NULL, NULL); set_loop_buffer_size(loop_options, (long) 1024 * max_buffer_size_in_kb); set_loop_check_dim_info(loop_options, check_dimensions); vol_total = 0.0; nvols = 0; if (verbose) { (void) fprintf(stderr, "Normalizing:"); (void) fflush(stderr); } for (ifile=0; ifile < nfiles; ifile++) { norm_data.threshold_set = FALSE; norm_data.sum0 = 0.0; norm_data.sum1 = 0.0; if (verbose) { (void) fprintf(stderr, "."); (void) fflush(stderr); } if (first_mincid != MI_ERROR) { set_loop_first_input_mincid(loop_options, first_mincid); first_mincid = MI_ERROR; } voxel_loop(1, &infiles[ifile], 0, NULL, NULL, loop_options, do_normalization, (void *) &norm_data); if (norm_data.sum0 > 0.0) { vol_mean[ifile] = norm_data.sum1 / norm_data.sum0; vol_total += vol_mean[ifile]; nvols++; } else { vol_mean[ifile] = 0.0; } if (debug) { (void) fprintf(stderr, "Volume %d mean = %.15g\n", ifile, vol_mean[ifile]); } } free_loop_options(loop_options); if (verbose) { (void) fprintf(stderr, "Done\n"); (void) fflush(stderr); } if (nvols > 0) global_mean = vol_total / nvols; else global_mean = 0.0; for (ifile=0; ifile < nfiles; ifile++) { if (vol_mean[ifile] > 0.0) average_data.norm_factor[ifile] = global_mean / vol_mean[ifile]; else average_data.norm_factor[ifile] = 0.0; if (debug) { (void) fprintf(stderr, "Volume %d norm factor = %.15g\n", ifile, average_data.norm_factor[ifile]); } } free(vol_mean); } else { for (ifile=0; ifile < nfiles; ifile++) { average_data.norm_factor[ifile] = 1.0; } } /* Do averaging */ average_data.need_sd = (sdfile != NULL); average_data.need_weight = (weightfile != NULL); loop_options = create_loop_options(); if (first_mincid != MI_ERROR) { set_loop_first_input_mincid(loop_options, first_mincid); first_mincid = MI_ERROR; } set_loop_verbose(loop_options, verbose); set_loop_clobber(loop_options, clobber); set_loop_datatype(loop_options, datatype, is_signed, valid_range[0], valid_range[1]); set_loop_accumulate(loop_options, TRUE, 1, start_average, finish_average); set_loop_copy_all_header(loop_options, copy_all_header); set_loop_dimension(loop_options, averaging_dimension); set_loop_buffer_size(loop_options, (long) 1024 * max_buffer_size_in_kb); set_loop_check_dim_info(loop_options, check_dimensions); voxel_loop(nfiles, infiles, nout, outfiles, arg_string, loop_options, do_average, (void *) &average_data); free_loop_options(loop_options); /* Free stuff */ free(average_data.weights); free(average_data.norm_factor); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int v1, v2, v3, v4; int sizes[VIO_MAX_DIMENSIONS], grid_sizes[4]; int n_concat_transforms, i; VIO_STR arg_string; char *input_volume_name; char *input_xfm; VIO_STR outfile; VIO_Real w1, w2, w3; VIO_Real nw1, nw2, nw3; VIO_Real original[3], transformed[3]; VIO_Real value; VIO_Real cosine[3]; VIO_Real original_separation[3], grid_separation[4]; VIO_Real original_starts[3], grid_starts[4]; VIO_Volume eval_volume, new_grid; VIO_General_transform xfm, *voxel_to_world; VIO_STR *dimnames, dimnames_grid[4]; VIO_progress_struct progress; arg_string = time_stamp(argc, argv); /* Check arguments */ if(ParseArgv(&argc, argv, argTable, 0) || (argc != 4)){ fprintf(stderr, "\nUsage: %s [options] input.mnc input.xfm output_grid.mnc\n", argv[0]); fprintf(stderr, " %s -help\n\n", argv[0]); exit(EXIT_FAILURE); } input_volume_name = argv[1]; input_xfm = argv[2]; outfile = argv[3]; /* check for the infile and outfile */ if(access(input_volume_name, F_OK) != 0){ fprintf(stderr, "%s: Couldn't find %s\n\n", argv[0], input_volume_name); exit(EXIT_FAILURE); } if(access(input_xfm, F_OK) != 0) { fprintf(stderr, "%s: Couldn't find %s\n\n", argv[0], input_xfm); exit(EXIT_FAILURE); } if(access(outfile, F_OK) == 0 && !clobber){ fprintf(stderr, "%s: %s exists! (use -clobber to overwrite)\n\n", argv[0], outfile); exit(EXIT_FAILURE); } /*--- input the volume */ /* if( input_volume( input_volume_name, 3, NULL, MI_ORIGINAL_TYPE, FALSE, 0.0, 0.0, TRUE, &eval_volume,(minc_input_options *) NULL ) != OK ) return( 1 ); */ if (input_volume_header_only( input_volume_name, 3, NULL, &eval_volume,(minc_input_options *) NULL ) != VIO_OK ) { return( 1 ); } /* get information about the volume */ get_volume_sizes( eval_volume, sizes ); voxel_to_world = get_voxel_to_world_transform(eval_volume); dimnames = get_volume_dimension_names(eval_volume); get_volume_separations(eval_volume, original_separation); get_volume_starts(eval_volume, original_starts); /* create new 4D volume, last three dims same as other volume, first dimension being the vector dimension. */ for(i=1; i < 4; i++) { dimnames_grid[i] = dimnames[i-1]; grid_separation[i] = original_separation[i-1]; grid_sizes[i] = sizes[i-1]; grid_starts[i] = original_starts[i-1]; } dimnames_grid[0] = "vector_dimension"; grid_sizes[0] = 3; grid_separation[0] = 1; grid_starts[0] = 0; new_grid = create_volume(4, dimnames_grid, NC_SHORT, FALSE, 0.0, 0.0); //set_voxel_to_world_transform(new_grid, voxel_to_world); // initialize the new grid volume, otherwise the output will be // garbage... set_volume_real_range(new_grid, -100, 100); set_volume_sizes(new_grid, grid_sizes); set_volume_separations(new_grid, grid_separation); set_volume_starts(new_grid, grid_starts); /* for (i=0; i < 3; i++) { get_volume_direction_cosine(eval_volume, i, cosine); set_volume_direction_cosine(new_grid, i+1, cosine); } */ alloc_volume_data(new_grid); /* get the transforms */ if( input_transform_file( input_xfm, &xfm ) != VIO_OK ) return( 1 ); /* see how many transforms will be applied */ n_concat_transforms = get_n_concated_transforms( &xfm ); printf("Number of transforms to be applied: %d\n", n_concat_transforms); initialize_progress_report(&progress, FALSE, sizes[0], "Processing"); /* evaluate the transform at every voxel, keep the displacement in the three cardinal directions */ for( v1 = 0; v1 < sizes[0]; ++v1 ) { update_progress_report(&progress, v1 + 1); for( v2 = 0; v2 < sizes[1]; ++v2 ) { for( v3 = 0; v3 < sizes[2]; ++v3 ) { convert_3D_voxel_to_world(eval_volume, v1, v2, v3, &original[0], &original[1], &original[2]); general_transform_point(&xfm, original[0], original[1], original[2], &transformed[0], &transformed[1], &transformed[2]); for(i=0; i < 3; i++) { value = transformed[i] - original[i]; set_volume_real_value(new_grid, i, v1, v2, v3, 0, value); } } } } terminate_progress_report(&progress); printf("Outputting volume.\n"); output_volume(outfile, MI_ORIGINAL_TYPE, TRUE, 0.0, 0.0, new_grid, arg_string, NULL); return(0); }
int main(int argc, char **argv) { char *line_ptr; int i; char img_fname[1024]; char hdr_fname[1024]; char out_fname[1024]; int result; if (ParseArgv(&argc, argv, argTable, 0) || argc < 2) { usage(argv[0]); return (-1); } ncopts = 0; /* Set the dimension names. This is done here since the correct * arrangement depends on the value of _orient_flag */ _dimnames[DIM_T] = MItime; _dimnames[DIM_X] = MIxspace; _dimnames[DIM_Y] = MIyspace; _dimnames[DIM_Z] = MIzspace; _dimnames[DIM_W] = MIvector_dimension; if (_orient_flag == ORIENT_HEAD) { /* If using head orientation, exchange Y and Z. */ _dimnames[DIM_Y] = MIzspace; _dimnames[DIM_Z] = MIyspace; } /* Open the header and the associated binary file. */ for (i = 1; i < argc; i++) { /* Here we try to be flexible about allowing the user to specify * either the name of the .hdr file or the name of the .img file, * or just the base name of the two files. All three options * should work. */ strcpy(img_fname, argv[i]); strcpy(hdr_fname, argv[i]); /* Find the last extension. */ line_ptr = strrchr(argv[i], '.'); /* Did the user specify the .hdr file?? */ if (line_ptr != NULL && !strcmp(line_ptr, ".hdr")) { line_ptr = strrchr(img_fname, '.'); if (line_ptr != NULL) { *line_ptr = '\0'; } } /* Did the user specify the .img file?? */ else if (line_ptr != NULL && !strcmp(line_ptr, ".img")) { strcat(hdr_fname, ".hdr"); } /* Or perhaps just the base name?? */ else { strcat(img_fname, ".img"); strcat(hdr_fname, ".img.hdr"); } /* See if there is a filename following this one, and if so, does it * end with the ".mnc" extension. If so, take that names as the * output for this conversions. */ if (i < argc - 1 && (line_ptr = strrchr(argv[i+1], '.')) != NULL && !strcmp(line_ptr, ".mnc")) { strcpy(out_fname, argv[i+1]); i++; } else { strcpy(out_fname, img_fname); line_ptr = strrchr(out_fname, '.'); if (line_ptr != NULL) { strcpy(line_ptr, ".mnc"); } } /* Perform the conversion. */ message(MSG_INFO, "Starting conversion\n"); message(MSG_INFO, "- Input header: %s\n", hdr_fname); message(MSG_INFO, "- Input image: %s\n", img_fname); message(MSG_INFO, "- Output file: %s\n", out_fname); result = upet_to_minc(hdr_fname, img_fname, out_fname, argv[0]); if (result < 0) { message(MSG_ERROR, "Error creating %s\n", out_fname); } else { message(MSG_INFO, "Finished creating %s\n", out_fname); } } return 0; }