Exemplo n.º 1
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"<input:string>", NULL};
  Process_Arguments(argc, argv, Spec, 1);


  String_Workspace *sw = New_String_Workspace();
  FILE *fp = fopen(Get_String_Arg("input"), "r");
  char *line;
  int start = 10000;
  int end = 0;

  while((line = Read_Line(fp, sw)) != NULL) {
    int value = String_First_Integer(line);
    if (value < start) {
      start = value;
    }
    if (value > end) {
      end = value;
    }
  }
  fclose(fp);

  printf("%d %d\n", start, end);

  return 0;
}
Exemplo n.º 2
0
int Swc_Node_Fscan(FILE *fp, Swc_Node *cell)
{
  String_Workspace *sw = New_String_Workspace();

  char *line = Read_Line(fp, sw);
  int succ = 1;

  if (line != NULL) {
    strtrim(line);
    
    if (line[0] == '#') {
      succ = 0;
    } else {
      if (sscanf(line, "%d %d %lf %lf %lf %lf %d", &(cell->id), &(cell->type),
		 &(cell->x), &(cell->y), &(cell->z), &(cell->d),
		 &(cell->parent_id)) != 7) {
	succ = 0;
      }
    }
  } else {
    succ = 0;
  }

  Kill_String_Workspace(sw);

  return succ;
}
Exemplo n.º 3
0
main() {
	int i;
	char buf[1024];
	STD_TERM *term;

	term = Init_Terminal();

	Write_Char('-', 50);
	WRITE_STR("\r\n");

#ifdef WIN32
	test(term, "text\010\010st\n"); //bs bs
	test(term, "test\001xxxx\n"); // home
	test(term, "test\001\005xxxx\n"); // home
	test(term, "\033[A\n"); // up arrow
#endif

	do {
		WRITE_STR(">> ");
		i = Read_Line(term, buf, 1000);
		printf("len: %d %s\r\n", i, term->out);
	} while (i > 0);

	Quit_Terminal(term);
}
Exemplo n.º 4
0
int main(int argc, char **argv) {
	char commandBuf[BUFSIZE + 1];
	struct Process proc;
	char path[BUFSIZE + 1] = DEFAULT_PATH;
	char *command;
	int detached;

	/* Set attribute to gray on black. */
	Print("\x1B[37m");

	while (true) {
		/* Print shell prompt (bright cyan on black background) */
		Print("\x1B[1;36m$\x1B[37m ");

		/* Read a line of input */
		Read_Line(commandBuf, sizeof(commandBuf));
		command = Strip_Leading_Whitespace(commandBuf);
		Trim_Newline(command);
		detached = isDetached(command);

		/*
		 * Handle some special commands
		 */
		if (strcmp(command, "exit") == 0) {
			/* Exit the shell */
			break;
		} else if (strcmp(command, "pid") == 0) {
			/* Print the pid of this process */
			Print("%d\n", Get_PID());
			continue;
		} else if (strcmp(command, "exitCodes") == 0) {
			/* Print exit codes of spawned processes. */
			exitCodes = 1;
			continue;
		} else if (strncmp(command, "path=", 5) == 0) {
			/* Set the executable search path */
			strcpy(path, command + 5);
			continue;
		} else if (strcmp(command, "") == 0) {
			/* Blank line. */
			continue;
		}

		proc.command = Strip_Leading_Whitespace(command);
		if (!Copy_Token(proc.program, proc.command)) {
			Print("Error: invalid command\n");
			continue;
		}

		Spawn_Single_Command(&proc, path, detached);
		if (detached && proc.pid > 0)
			Print("[%d]\n", proc.pid);

	}

	Print_String("DONE!\n");
	return 0;
}
Exemplo n.º 5
0
int main(int argc, char **argv)
{
    int nproc;
    char commandBuf[BUFSIZE+1];
    struct Process procList[MAXPROC];
    char path[BUFSIZE+1] = DEFAULT_PATH;
    char *command;

    /* Set attribute to gray on black. */
    Print("\x1B[37m");

    while (true) {
	/* Print shell prompt (bright cyan on black background) */
	Print("\x1B[1;36m$\x1B[37m ");

	/* Read a line of input */
	Read_Line(commandBuf, sizeof(commandBuf));
	command = Strip_Leading_Whitespace(commandBuf);
	Trim_Newline(command);

	/*
	 * Handle some special commands
	 */
	if (strcmp(command, "exit") == 0) {
	    /* Exit the shell */
	    break;
	} else if (strcmp(command, "pid") == 0) {
	    /* Print the pid of this process */
	    Print("%d\n", Get_PID());
	    continue;
	} else if (strcmp(command, "exitCodes") == 0) {
	    /* Print exit codes of spawned processes. */
	    exitCodes = 1;
	    continue;
	} else if (strncmp(command, "path=", 5) == 0) {
	    /* Set the executable search path */
	    strcpy(path, command + 5);
	    continue;
	} else if (strcmp(command, "") == 0) {
	    /* Blank line. */
	    continue;
	}

	/*
	 * Parse the command string and build array of
	 * Process structs representing a pipeline of commands.
	 */
	nproc = Build_Pipeline(command, procList);
	if (nproc <= 0)
	    continue;

	Spawn_Pipeline(procList, nproc, path);
    }

    Print_String("DONE!\n");
    return 0;
}
Exemplo n.º 6
0
void TPPlusRoute::Execute (void)
{
	int old_routes, old_nodes;

	//---- read the network ----

	Network_Service::Execute ();

	//---- check the input route numbers ----

	if (input_flag) {
		Route_Data *route_ptr = route_data.Last_Key ();

		if (route_ptr != NULL) {
			if (route_id <= route_ptr->Route ()) {
				route_id = ((route_ptr->Route () / 100) + 1) * 100;
			}
		}
		old_routes = route_data.Num_Records ();
		old_nodes = route_data.Num_Nodes ();
	} else {
		old_routes = old_nodes = 0;
	}

	//---- read the tpplus node map file ----

	if (map_flag) {
		Read_Node_Map ();
	}

	//---- read the tpplus line files ----

	Read_Line ();

	//---- write the route header and nodes ----

	Write_Route ();

	//---- print the results ----

	Break_Check (4);
	Write (2, "Number of Route Header Records = %d", nroute);
	if (old_routes > 0) Write (0, " (%d new)", (nroute - old_routes));

	Write (1, "Number of Route Nodes Records = %d", nnodes);
	if (old_nodes > 0) Write (0, " (%d new)", (nnodes - old_nodes));

	if (num_match > 0) Write (1, "Number of Matched Routes = %d", num_match);

	Exit_Stat (DONE);
}
Exemplo n.º 7
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"<input:string> -o <string> -tile_number <int> [-upsample <string>]", NULL};
  Process_Arguments(argc, argv, Spec, 1);

  char filepath[500];
  int i;
  int n = Get_Int_Arg("-tile_number");
  for (i = 0; i < n; i++) {
    sprintf(filepath, "%s/%03d", Get_String_Arg("input"), i+1);
    int n = dir_fnum(filepath, "tif");
    sprintf(filepath, "%s/%03d.xml", Get_String_Arg("-o"), i+1);
    FILE *fp = GUARDED_FOPEN(filepath, "w");
    fprintf(fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    fprintf(fp, "<trace>\n");
    fprintf(fp, "<data>\n");
    fprintf(fp, "<image type=\"bundle\">\n");
    fprintf(fp, "<prefix>%s/%03d/</prefix>\n", Get_String_Arg("input"), i+1);
    fprintf(fp, "<suffix>.tif</suffix>\n");
    if (n > 100) {
      fprintf(fp, "<num_width>3</num_width>\n");
    } else {
      fprintf(fp, "<num_width>2</num_width>\n");
    }
    fprintf(fp, "<first_num>1</first_num>\n");
    fprintf(fp, "</image>\n");
    fprintf(fp, "<resolution><x>0.0375</x><y>0.0375</y><z>0.2</z></resolution>\n");
    fprintf(fp, "</data>\n");
    fprintf(fp, "</trace>\n");
    fclose(fp);
    printf("%s created\n", filepath);
  }

  if (Is_Arg_Matched("-upsample")) {
    if (fexist(Get_String_Arg("-upsample"))) {
      FILE *fp = fopen(Get_String_Arg("-upsample"), "r");
      String_Workspace *sw = New_String_Workspace();
      char *line = NULL;
      int n;
      line = Read_Line(fp, sw);
      int *array = String_To_Integer_Array(line, NULL, &n);
      int i;
      for (i = 0; i < n; i++) {
	upsample(Get_String_Arg("-o"), array[i]);
      }
      fclose(fp);
    }
  }

  return 0;
}
Exemplo n.º 8
0
static Geo3d_Scalar_Field* read_node_file(char *file_path)
{
  FILE *fp = fopen(file_path, "r");
  int n = 0;
  double value[4];

  String_Workspace *sw = New_String_Workspace();

  while (Read_Line(fp, sw)) {
    n++;
  }

  rewind(fp);

  Geo3d_Scalar_Field *field = Make_Geo3d_Scalar_Field(n);
  field->size = 0;

  char *line = NULL;
  while ((line = Read_Line(fp, sw)) != NULL) {
    String_To_Double_Array(line, value, &n);
    if (n == 4) {
      field->points[field->size][0] = value[0];
      field->points[field->size][1] = value[1];
      field->points[field->size][2] = value[2];
      field->values[field->size++] = value[3];
    } else if (n == 3) {
      field->points[field->size][0] = value[0];
      field->points[field->size][1] = value[1];
      field->points[field->size][2] = value[2];
      field->values[field->size++] = 1;
    }
  }

  fclose(fp);

  return field;
}
Exemplo n.º 9
0
*/	DEVICE_CMD Read_IO(REBREQ *req)
/*
**		Low level "raw" standard input function.
**
**		The request buffer must be long enough to hold result.
**
**		Result is NOT terminated (the actual field has length.)
**
***********************************************************************/
{
	long total = 0;
	int len = req->length;

	if (GET_FLAG(req->modes, RDM_NULL)) {
		req->common.data[0] = 0;
		return DR_DONE;
	}

	req->actual = 0;

	if (Std_Inp >= 0) {

		interrupted = 0;
		// Perform a processed read or a raw read?
#ifndef HAS_SMART_CONSOLE
		if (Term_IO)
			total = Read_Line(Term_IO, s_cast(req->common.data), len);
		else
#endif
			total = read(Std_Inp, req->common.data, len); /* will be restarted in case of signal */

		if (total < 0) {
			req->error = errno;
			return DR_ERROR;
		}
		if (interrupted) {
			char noop[] = "does[]\n";
			APPEND_BYTES_LIMIT(req->common.data, cb_cast(noop), len);
			total += sizeof(noop);
		}

		req->actual = total;
	}

	return DR_DONE;
}
Exemplo n.º 10
0
*/	DEVICE_CMD Read_IO(REBREQ *req)
/*
**		Low level "raw" standard input function.
**
**		The request buffer must be long enough to hold result.
**
**		Result is NOT terminated (the actual field has length.)
**
***********************************************************************/
{
	long total = 0;
	int len = req->length;

	if (GET_FLAG(req->modes, RDM_NULL)) {
		req->data[0] = 0;
		return DR_DONE;
	}

	req->actual = 0;

	if (Std_Inp >= 0) {

		// Perform a processed read or a raw read?
#ifndef HAS_SMART_CONSOLE
		if (Term_IO)
			total = Read_Line(Term_IO, req->data, len);
		else
#endif
			total = read(Std_Inp, req->data, len);

		if (total < 0) {
			req->error = errno;
			return DR_ERROR;
		}

		req->actual = total;
	}

	return DR_DONE;
}
Exemplo n.º 11
0
// exe infilename MT M I SigmaExp outputfilename
// MT model type 0 for plane, 1 for line, 2 for vanishing point
// M number of MSS
// I inlier threshold
// SigmaExp
int main(int argc, const char* argv[])
{
	if(argc<7) {
		std::cout<<argv[0]<<" infilename Modeltype Mss InlierThreshold SigmaExp outfilename"<<std::endl;
		return 1;
	}

	int MT=atoi(argv[2]);
	int M =atoi(argv[3]);
	double I=atof(argv[4]);
	double SigmaExp=atof(argv[5]);

	std::ifstream ifile(argv[1]);
	Read_Line(ifile);

	std::vector<unsigned int> Lables;
	std::vector<unsigned int> LableCount;

	std::vector<std::vector<float> *> *mModels = 
		JlnkSample::run(&pts, M, MT, 0, 3/*, SigmaExp*/);
	unsigned int num = JlnkCluster::run(Lables, LableCount, &pts, mModels, I, MT);

	std::ofstream ofile(argv[6]);
	unsigned int len = (unsigned int)Lables.size();
	for(unsigned int i=0; i<len; ++i) {
		ofile<<(*pts[i])[0]<<" "<<(*pts[i])[1]<<" "
			<<(*pts[i])[2]<<" "<<(*pts[i])[3]<<" "<<Lables.at(i)<<std::endl;
	}
	ofile.close();

	for(unsigned int i=0; i<pts.size(); i++)
		delete pts[i];

	for(unsigned int i=0; i < mModels->size(); i++)
		delete (*mModels)[i];
	delete mModels;

	return 0;
}
Exemplo n.º 12
0
//
//  Read_IO: C
//
// Low level "raw" standard input function.
//
// The request buffer must be long enough to hold result.
//
// Result is NOT terminated (the actual field has length.)
//
DEVICE_CMD Read_IO(REBREQ *req)
{
    long total = 0;
    int len = req->length;

    if (GET_FLAG(req->modes, RDM_NULL)) {
        req->common.data[0] = 0;
        return DR_DONE;
    }

    req->actual = 0;

    if (Std_Inp >= 0) {

        interrupted = 0;
        // Perform a processed read or a raw read?
#ifndef HAS_SMART_CONSOLE
        if (Term_IO)
            total = Read_Line(Term_IO, s_cast(req->common.data), len);
        else
#endif
            total = read(Std_Inp, req->common.data, len); /* will be restarted in case of signal */

        if (total < 0) {
            req->error = errno;
            return DR_ERROR;
        }
        if (interrupted) {
            char noop[] = "does[]\n";
            APPEND_BYTES_LIMIT(req->common.data, cb_cast(noop), len);
            total += sizeof(noop);
        }

        req->actual = total;
    }

    return DR_DONE;
}
Exemplo n.º 13
0
// exe infilename outputfilename
int main(int argc, const char* argv[])
{
	if(argc<3) {
		std::cout<<argv[0]<<" infilename outfilename"<<std::endl;
		return 1;
	}

	std::ifstream ifile(argv[1]);
	Read_Line(ifile);

	std::vector<unsigned int> Lables;
	std::vector<unsigned int> LableCount;
	{//2. VP cluster
		std::vector<std::vector<float> *> *mModels = 
			VPSample::run(&pts, 5000, 2, 0, 3);
		int classNum = VPCluster::run(Lables, LableCount, &pts, mModels, 2, 2);
		std::cout<<"vpdetection found "<<classNum<<" classes!"<<std::endl;

		//2.1. release other resource
		for(unsigned int i=0; i < mModels->size(); ++i)
			delete (*mModels)[i];
		delete mModels;
	}

	std::ofstream ofile(argv[2]);
	unsigned int len = (unsigned int)Lables.size();
	for(unsigned int i=0; i<len; ++i) {
		ofile<<(*pts[i])[0]<<" "<<(*pts[i])[1]<<" "
			<<(*pts[i])[2]<<" "<<(*pts[i])[3]<<" "<<Lables.at(i)<<std::endl;
	}
	ofile.close();

	for(unsigned int i=0; i<pts.size(); i++)
		delete pts[i];

	return 0;
}
Exemplo n.º 14
0
int Main (int argc , char ** argv)
{
  int i;
  int ret;
  int done;
  int eoln;
  int debug;
  char *curr;
  char *dest;
  char line[256];
  int infd, outfd;
  char tempName[2];
  char strName[20];
  int numCommand;
  int   count ;         /* child process's argc */
  char command[256];

  done = 0;
  while (!done) {
     Printf("shell %% ");

     eoln = 0;
     count = 0;

     Read_Line( line, sizeof(line) );

     line[strlen(line)-1] = '\0';

     /* blank line */
     if (!strcmp(line, "")) continue;

     if (!strcmp(line, "exit")) {
         return 0;
     } else if (!strcmp(line, "debug")) {
	 debug = 1;
	 continue;
     } else if (!strcmp(line, "nodebug")) {
	 debug = 0;
	 continue;
     }

    split(line, &numCommand);
    infd = 0;
    outfd = 1;

    for (i=0; i < numCommand-1; i++) {
        if (commands[i].outFile) {
	    Printf("Error: file redirection for command other than last one in pipeline\n");
	    break;
	}
    }
    if (i != numCommand-1) continue;

    if (debug) {
	for (i=0; i < numCommand; i++) {
	    Printf("command %d = %s\n", i, commands[i].command);
	}
    }

    for (i=0; i < numCommand; i++) {
 	 if (outfd != 1) infd = outfd;

         if (i == numCommand-1)  {
	     if (commands[i].outFile) {
		 /* last one goes to a file */
		 outfd = Open(commands[i].outFile, O_WRITE|O_CREATE);
		 if (outfd < 0) {
		     Printf("Error opening %s\n", commands[i].outFile);
		 }
	     } else {
		 /* last one goes to stdout */
		 outfd = 1;
	     }
	 } else {
             strcpy(strName, "/dev/pipe");
	     tempName[0] = count + '0';
	     count++;
	     tempName[1] = '\0';
	     strcat(strName, tempName);
 	     outfd = MessageQueueCreate(strName);
	     if (outfd < 0) {
	         Printf("pipe failed\n");
		 continue;
	     }
	 }

         /* now run it */
	 memset(command, '\0', sizeof(command));
         if (commands[i].command[0] != '/') {
	     //	add implict path to /c for programs
	     strcpy(command, "/c/");
             for (curr=commands[i].command, dest=&command[3]; *curr; curr++) {
                if (*curr == ' ') break;
                *(dest++) = *curr;
             }
             strcat(command, ".exe");
             strcat(command, curr);
             // Printf("command is %s\n", command);
         } else {
             strcpy(command, commands[i].command);
         }

         commands[i].pid = Spawn_Program ( command , infd, outfd);
         if ( commands[i].pid <= 0 )  {  /* Unable to proc_start */
            Printf ( "%s: Command not found\n", commands[i].command) ;
            continue;
         } else {
	    if (debug) Printf("spawned pid %d, command = %s\n", 
		commands[i].pid, commands[i].command);
   	    if (infd != 0) Close(infd);
	 }
    }

    /* now wait for them all to finish */
    for (i=0; i < numCommand; i++) {
	if (commands[i].pid > 0) {
	    ret = Wait(commands[i].pid);
	    if (debug) Printf("process %d exited\n", commands[i].pid);
	}
    }
    if (debug) Printf("all processes exited\n");
  }

  return 0;
}
Exemplo n.º 15
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"[-root_id <int>] [<input:string>]",
    "[-a <string>] [-b <string>]", 
    "[-stitch_script] [-exclude <string>] [-tile_number <int>]",
    NULL};
  Process_Arguments(argc, argv, Spec, 1);

  int *excluded = NULL;
  int nexc = 0;
  int *excluded_pair = NULL;
  int nexcpair = 0;
  if (Is_Arg_Matched("-exclude")) {
    String_Workspace *sw = New_String_Workspace();
    FILE *fp = fopen(Get_String_Arg("-exclude"), "r");
    char *line = Read_Line(fp, sw);
    excluded = String_To_Integer_Array(line, NULL, &nexc);
    line = Read_Line(fp, sw);
    if (line != NULL) {
      excluded_pair = String_To_Integer_Array(line, NULL, &nexcpair);
      nexcpair /= 2;
    }
    Kill_String_Workspace(sw);
    fclose(fp);
  }

  int n = 0;
  Graph *graph = Make_Graph(n + 1, n, TRUE);
  char filepath1[100];
  char filepath2[100];
  int i, j;
  Stack *stack1 = NULL;
  FILE *fp = NULL;
  if (Is_Arg_Matched("-stitch_script")) {
    Cuboid_I *boxes = read_tile_array(Get_String_Arg("-a"), &n);
    for (i = 0; i < n; i++) {
      for (j = i + 1; j < n; j++) {      
	BOOL is_excluded = FALSE;
	int k;
	for (k = 0; k < nexc; k++) {
	  if ((i == excluded[k] - 1) || (j == excluded[k] - 1)) {
	    is_excluded = TRUE;
	    break;
	  }
	}
	for (k = 0; k < nexcpair; k++) {
	  if (((i == excluded_pair[k*2]) && (j == excluded_pair[k*2+1])) ||
	      ((j == excluded_pair[k*2]) && (i == excluded_pair[k*2+1]))) {
	    is_excluded = TRUE;
	    break;
	  }
	}
	/*
	if ((i != 103) && (j != 103) && (i != 115) && (j != 115) && (i != 59) &&
	    (j != 59) && !(i == 116 && j == 116)) {
	    */
	if (is_excluded == FALSE) {
	  Cuboid_I_Overlap_Volume(boxes + i, boxes + j);
	  Cuboid_I ibox;
	  Cuboid_I_Intersect(boxes + i, boxes + j, &ibox);
	  int width, height, depth;
	  Cuboid_I_Size(&ibox, &width, &height, &depth);

	  if ((imax2(width, height) > 1024 / 3) && (imin2(width, height) > 0)) {
	    sprintf(filepath1, "%s/stack/%03d.xml", 
		Get_String_Arg("input"), i + 1);
	    sprintf(filepath2, "%s/stack/%03d.xml", 
		Get_String_Arg("input"), j + 1);
	    if (stack1 == NULL) {
	      stack1 = Read_Stack_U(filepath1);
	    }
	    Stack *stack2 = Read_Stack_U(filepath2);

	    Stack *substack1= Crop_Stack(stack1, ibox.cb[0] - boxes[i].cb[0], 
		ibox.cb[1] - boxes[i].cb[1], 0,
		width, height, stack1->depth, NULL);
	    Stack *substack2 = Crop_Stack(stack2, ibox.cb[0] - boxes[j].cb[0], 
		ibox.cb[1] - boxes[j].cb[1], 0,
		width, height, stack2->depth, NULL);

	    Image *img1 = Proj_Stack_Zmax(substack1);	
	    Image *img2 = Proj_Stack_Zmax(substack2);
	    double w = u16array_corrcoef((uint16_t*) img1->array, 
		(uint16_t*) img2->array, 
		img1->width * img1->height);

	    Kill_Stack(stack2);
	    Kill_Stack(substack1);
	    Kill_Stack(substack2);
	    Kill_Image(img1);
	    Kill_Image(img2);
	    printf("%d, %d : %g\n", i + 1, j + 1, w);
	    Graph_Add_Weighted_Edge(graph, i + 1, j + 1, 1000.0 / (w + 1.0));
	  }
	}
	if (stack1 != NULL) {
	  Kill_Stack(stack1);
	  stack1 = NULL;
	}
      }
    }

    Graph_Workspace *gw = New_Graph_Workspace();
    Graph_To_Mst2(graph, gw);

    Arrayqueue q = Graph_Traverse_B(graph, Get_Int_Arg("-root_id"), gw);

    Print_Arrayqueue(&q);

    int *grown = iarray_malloc(graph->nvertex);
    for (i = 0; i < graph->nvertex; i++) {
      grown[i] = 0;
    }

    int index  = Arrayqueue_Dequeue(&q);
    grown[index] = 1;

    char stitch_p_file[5][500];
    FILE *pfp[5];
    for (i = 0; i < 5; i++) {
      sprintf(stitch_p_file[i], "%s/stitch/stitch_%d.sh", Get_String_Arg("input"), i);
      pfp[i] = fopen(stitch_p_file[i], "w");
    }

    sprintf(filepath1, "%s/stitch/stitch_all.sh", Get_String_Arg("input"));

    fp = GUARDED_FOPEN(filepath1, "w");
    fprintf(fp, "#!/bin/bash\n");

    int count = 0;
    while ((index = Arrayqueue_Dequeue(&q)) > 0) {
      for (i = 0; i < graph->nedge; i++) {
	int index2 = -1;
	if (index == graph->edges[i][0]) {
	  index2 = graph->edges[i][1];
	} else if (index == graph->edges[i][1]) {
	  index2 = graph->edges[i][0];
	}

	if (index2 > 0) {
	  if (grown[index2] == 1) {
	    char cmd[500];
	    sprintf(filepath2, "%s/stitch/%03d_%03d_pos.txt",
		Get_String_Arg("input"), index2, index);
	    sprintf(cmd, 
		"%s/stitchstack %s/stack/%03d.xml %s/stack/%03d.xml -o %s", 
		Get_String_Arg("-b"), Get_String_Arg("input"),
		index2, Get_String_Arg("input"), index, filepath2);
	    fprintf(fp, "%s\n", cmd);
	    count++;
	    fprintf(pfp[count%5], "%s\n", cmd);
	    /*
	    if (!fexist(filepath2)) {
	      system(cmd);
	    }
	    */
	    grown[index] = 1;
	    break;
	  }
	}
      }
    }

    fclose(fp);  
    for (i = 0; i < 5; i++) {
      fprintf(pfp[i], "touch %s/stitch/stitch_%d_done\n", 
	  Get_String_Arg("input"), i);
      fclose(pfp[i]);
    }
    return 0;
  }
  
  sprintf(filepath1, "%s/stitch/stitch_all.sh", Get_String_Arg("input"));
  fp = GUARDED_FOPEN(filepath1, "r");

//#define MAX_TILE_INDEX 153
  int tile_number = Get_Int_Arg("-tile_number");
  int max_tile_index = tile_number + 1;

  char *line = NULL;
  String_Workspace *sw = New_String_Workspace();
  int id[2];
  char filepath[100];
  int offset[max_tile_index][3];
  int relative_offset[max_tile_index][3];
  int array[max_tile_index];

  for (i = 0; i < max_tile_index; i++) {
    array[i] = -1;
    offset[i][0] = 0;
    offset[i][1] = 0;
    offset[i][2] = 0;
    relative_offset[i][0] = 0;
    relative_offset[i][1] = 0;
    relative_offset[i][2] = 0;
  }

  while ((line = Read_Line(fp, sw)) != NULL) {
    char *remain = strsplit(line, ' ', 1);
    if (String_Ends_With(line, "stitchstack")) {
      String_To_Integer_Array(remain, id, &n);
      id[0] = id[1];
      id[1] = id[3];
      array[id[1]] = id[0];

      sprintf(filepath, "%s/stitch/%03d_%03d_pos.txt", Get_String_Arg("input"),
	      id[0], id[1]);
      if (!fexist(filepath)) {
	fprintf(stderr, "file %s does not exist\n", filepath);
	return 1;
      }
      FILE *fp2 = GUARDED_FOPEN(filepath, "r");
      line = Read_Line(fp2, sw);
      line = Read_Line(fp2, sw);
      int tmpoffset[8];
      String_To_Integer_Array(line, tmpoffset, &n);
      relative_offset[id[1]][0] = tmpoffset[2];
      relative_offset[id[1]][1] = tmpoffset[3];
      relative_offset[id[1]][2] = tmpoffset[4];

      fclose(fp2);
    }
  }
  
  for (i = 1; i < max_tile_index; i++) {
    BOOL is_excluded = FALSE;
    int k;
    for (k = 0; k < nexc; k++) {
      if (i == excluded[k]) {
	is_excluded = TRUE;
	break;
      }
    }
    /*if ((i == 104) || (i == 116) || (i == 60) || (i == 152)) {*/
    if (is_excluded) {
      printf("%d: (0, 0, 10000)\n", i);
    } else {
      int index = i;
      while (index >= 0) {
	offset[i][0] += relative_offset[index][0];
	offset[i][1] += relative_offset[index][1];
	offset[i][2] += relative_offset[index][2];
	index = array[index];
      }
      printf("%d: (%d, %d, %d)\n", i, offset[i][0], offset[i][1], offset[i][2]);
    }
  }

  fclose(fp);

  return 0;
}
Exemplo n.º 16
0
Apo_Node* Read_Apo_File(char *file_path, int *napo)
{
  FILE *fp = GUARDED_FOPEN(file_path, "r");

  String_Workspace *sw = New_String_Workspace();

  int n = 0;
  while (Read_Line(fp, sw) != NULL) {
    n++;
  }

  Apo_Node *apos = (Apo_Node*)malloc(sizeof(Apo_Node)*n);
  *napo = 0;

  fseek(fp, 0, SEEK_SET);

  char *line = NULL;
  while ((line = Read_Line(fp, sw)) != NULL) {
    apos[*napo].no = atoi(line);

    char *head1 = strsplit(line, ',', 2);
    if (head1 == NULL) {
      continue;
    }

    char *head2 = strsplit(head1, ',', 1);
    if (head2 == NULL) {
      continue;
    }

    char *token = strsplit(head2, ',', 1);
    if (token != NULL) {
      strcpy(apos[*napo].name, head1);
      strcpy(apos[*napo].comment, head2);
      apos[*napo].z = atof(token);
    } else {
      continue;
    }

    token = strsplit(token, ',', 1);
    if (token != NULL) {
      apos[*napo].x = atof(token);
    } else {
      continue;
    }

    token = strsplit(token, ',', 1);
    if (token != NULL) {
      apos[*napo].y = atof(token);
    } else {
      continue;
    }

    token = strsplit(token, ',', 1);
    if (token != NULL) {
      apos[*napo].maxintensity = atof(token);
    } else {
      continue;
    }

    token = strsplit(token, ',', 1);
    if (token != NULL) {
      apos[*napo].intensity = atof(token);
    } else {
      continue;
    }

    token = strsplit(token, ',', 1);
    if (token != NULL) {
      apos[*napo].sdev = atof(token);
    } else {
      continue;
    }

    token = strsplit(token, ',', 1);
    if (token != NULL) {
      apos[*napo].volsize = atof(token);
    } else {
      continue;
    }

    token = strsplit(token, ',', 1);
    if (token != NULL) {
      apos[*napo].mass = atof(token);
    } else {
      continue;
    }

    token = strsplit(token, ',', 1);
    token = strsplit(token, ',', 1);
    token = strsplit(token, ',', 1);
    token = strsplit(token, ',', 1);
    if (token == NULL) {
      apos[*napo].r = Cube_Root(0.75 / TZ_PI * apos[*napo].volsize);

      ++(*napo);
      continue;
    }

    head1 = strsplit(token, ',', 1);
    if (head1 == NULL) {
      continue;
    }

    head2 = strsplit(head1, ',', 1);
    if (head2 == NULL)
      continue;
    else {
      strcpy(apos[*napo].colorr, token);
      strcpy(apos[*napo].colorg, head1);
      strcpy(apos[*napo].colorb, head2);
    }

    // token = strsplit(token, ',', 1);
    // if (token != NULL) {
    //   strcpy(apos[*napo].colorb, token);
    // } else {
    //   continue;
    // }

    apos[*napo].r = Cube_Root(0.75 / TZ_PI * apos[*napo].volsize);

    ++(*napo);
  }

  Kill_String_Workspace(sw);

  fclose(fp);

  return apos;
}
Exemplo n.º 17
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"[-t]", NULL};
  Process_Arguments(argc, argv, Spec, 1);

  if (Is_Arg_Matched("-t")) {
    /* Example test */
    Stack *stack = Make_Stack(GREY, 7, 7, 1);
    One_Stack(stack);
    Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
    ws->conn = 26;
    ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			  Stack_Depth(stack));
    Zero_Stack(ws->mask);

    /* set seeds */
    Set_Stack_Pixel(ws->mask, 1, 1, 0, 0, 1.0);
    Set_Stack_Pixel(ws->mask, 1, 5, 0, 0, 2.0);
    Set_Stack_Pixel(ws->mask, 3, 3, 0, 0, 3.0);
    Set_Stack_Pixel(ws->mask, 5, 1, 0, 0, 4.0);
    Set_Stack_Pixel(ws->mask, 5, 5, 0, 0, 5.0);

    /* set stack values */
    Set_Stack_Pixel(stack, 1, 1, 0, 0, 3.0);
    Set_Stack_Pixel(stack, 1, 5, 0, 0, 3.0);
    Set_Stack_Pixel(stack, 3, 3, 0, 0, 3.0);
    Set_Stack_Pixel(stack, 5, 1, 0, 0, 3.0);
    Set_Stack_Pixel(stack, 5, 5, 0, 0, 3.0);
    
    Stack *out = Stack_Watershed(stack, ws);

    //Write_Stack("../data/test/watershed/golden/watershed1.tif", out);

    char *golden_file = "../data/test/watershed/golden/watershed1.tif";
    if (fexist(golden_file)) {
      Stack *golden = Read_Stack(golden_file);
      if (Stack_Identical(out, golden) == FALSE) {
	Print_Stack_Value(stack);
	Print_Stack_Value(out);
	Print_Stack_Value(golden);
	PRINT_EXCEPTION("Bug?", "Conflict with golden.");
	return 1;
      }

      Kill_Stack(stack);
      Kill_Stack(out);
      Kill_Stack(golden);
      Kill_Stack_Watershed_Workspace(ws);
    } else {
      printf("%s cannot be found.\n", golden_file);
    }

    char *test_file = "../data/benchmark/rice_label.tif";
    if (fexist(test_file)) {
      stack = Read_Stack_U(test_file);

      ws = Make_Stack_Watershed_Workspace(stack);
      ws->mask = Copy_Stack(stack);
      ws->conn = 26;
      One_Stack(stack);

      out = Stack_Watershed(stack, ws);

      //Write_Stack("../data/test/watershed/golden/watershed2.tif", out);

      Stack *golden = Read_Stack("../data/test/watershed/golden/watershed2.tif");
      if (Stack_Identical(out, golden) == FALSE) {
	PRINT_EXCEPTION("Bug?", "Conflict with golden.");
	return 1;
      }
    } else {
      printf("%s cannot be found.\n", test_file);
    }

    printf(":) Testing passed.\n");

    return 0;
  }

#if 0
  /* Initialize */
  Watershed_3d *watershed = New_Watershed_3d();
  Watershed_3d_Workspace *ws = New_Watershed_3d_Workspace();
  ws->conn = 26;

  /* Initialize stack */
  Stack *stack = Read_Stack("../data/fly_neuron/dist.tif");
  int nvoxel = Stack_Voxel_Number(stack);
  int i;
  uint16 *array16 = (uint16 *)stack->array;
  for (i = 0; i < nvoxel; i++) {
    array16[i] = 0xFFFF - array16[i];
  }
  
  /* Add mask to ignore dark voxels  */
  ws->mask = Copy_Stack(stack); 
  

  //Translate_Stack(stack, GREY, 1);

  //stack->array = stack->array + stack->width * stack->height * 100;
  //stack->depth = 1;
  // ws->mask = Copy_Stack(stack);
  //Stack_Binarize(ws->mask);
  // ws->mask = NULL;

  //Write_Stack("../data/dist.tif", stack);


  //Stack *stack2 = Copy_Stack(stack);


#  if 0
  Build_3D_Watershed(stack, watershed, ws);
  Write_Stack("../data/test.tif", watershed->labels);
#  endif

#  if 0
  
  Image_View iv = Image_View_Stack(stack2);
  Watershed_Test *watershed2 = Build_2D_Watershed_Test(&(iv.image), 0);
  Write_Image("../data/test2.tif", watershed2->labels);
#  endif
#endif

#if 0
  Image *image = Read_Image("../data/Ring15.tif_Sub1200_Original_inv.tif");
  Watershed_2D *ws = Build_2D_Watershed(image, 0);
  Image *result = Color_Watersheds(ws, image);
  Write_Image("../data/test.tif", result);
  Kill_Image(image);
#endif

#if 0
  Stack *stack = Make_Stack(GREY, 7, 7, 1);
  One_Stack(stack);
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->conn = 26;
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			Stack_Depth(stack));
  Zero_Stack(ws->mask);
  Set_Stack_Pixel(ws->mask, 1, 1, 0, 0, 1.0);
  Set_Stack_Pixel(ws->mask, 1, 5, 0, 0, 2.0);
  Set_Stack_Pixel(ws->mask, 3, 3, 0, 0, 3.0);
  Set_Stack_Pixel(ws->mask, 5, 1, 0, 0, 4.0);
  Set_Stack_Pixel(ws->mask, 5, 5, 0, 0, 5.0);

  Set_Stack_Pixel(stack, 1, 1, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 1, 5, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 3, 3, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 5, 1, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 5, 5, 0, 0, 3.0);
  
  Stack *out = Stack_Watershed(stack, ws);

  Print_Stack_Value(out);
#endif

#if 0
  Stack *stack = Make_Stack(GREY, 3, 3, 1);
  One_Stack(stack);
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->conn = 26;
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			Stack_Depth(stack));
  Zero_Stack(ws->mask);

  Set_Stack_Pixel(ws->mask, 0, 0, 0, 0, 1.0);
  Set_Stack_Pixel(ws->mask, 2, 2, 0, 0, 2.0);

  Set_Stack_Pixel(stack, 0, 0, 0, 0, 5.0);
  Set_Stack_Pixel(stack, 2, 2, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 0, 2, 0, 0, 2.0);
  //Set_Stack_Pixel(stack, 1, 1, 0, 0, 2.0);
  Set_Stack_Pixel(stack, 1, 2, 0, 0, 2.0);
  Set_Stack_Pixel(stack, 2, 0, 0, 0, 2.0);
  Set_Stack_Pixel(stack, 2, 1, 0, 0, 2.0);

  Print_Stack_Value(stack);

  ws->start_level = 6;

  Stack *out = Stack_Watershed(stack, ws);

  Print_Stack_Value(out);
#endif
 
#if 0
  Stack *stack = Read_Stack_U("../data/benchmark/rice_label.tif");

  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->mask = Copy_Stack(stack);
  ws->conn = 26;
  One_Stack(stack);

  tic();
  Stack *out = Stack_Watershed(stack, ws);
  printf("%lld\n", toc());

  Write_Stack("../data/test.tif", out); 
#endif

#if 0
  Stack *stack = Read_Stack_U("../data/diadem_d1_147.xml");
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			Stack_Depth(stack));
  Zero_Stack(ws->mask);
  ws->conn = 26;

  const int *dx = Stack_Neighbor_X_Offset(ws->conn);
  const int *dy = Stack_Neighbor_X_Offset(ws->conn);
  const int *dz = Stack_Neighbor_X_Offset(ws->conn);
  
  int seed[3];
  String_Workspace *sw = New_String_Workspace();
  char *line = NULL;
  FILE *fp = fopen("../data/diadem_d1_root_z.txt", "r");
  int k = 1;
    
  while ((line = Read_Line(fp, sw)) != NULL) {
    int n;
    String_To_Integer_Array(line, seed, &n);
    double maxv = -1;
    if (n == 3) {
      maxv = Get_Stack_Pixel(stack, seed[0], seed[1], seed[2], 0);
      printf("%g\n", maxv);
      int i;
      for (i = 0; i < ws->conn; i++) {
	if (maxv < Get_Stack_Pixel(stack, seed[0] + dx[i], seed[1] + dy[i], 
				   seed[2] + dz[i], 0)) {
	  maxv = Get_Stack_Pixel(stack, seed[0] + dx[i], seed[1] + dy[i], 
				 seed[2] + dz[i], 0);
	}
      }

      //Set_Stack_Pixel(stack, seed[0], seed[1], seed[2], 0, maxv);
      Set_Stack_Pixel(ws->mask, seed[0], seed[1], seed[2], 0, k);
      for (i = 0; i < ws->conn; i++) {
	//Set_Stack_Pixel(stack, seed[0] + dx[i], seed[1] + dy[i], 
	//		seed[2] + dz[i], 0, maxv);
	Set_Stack_Pixel(ws->mask, seed[0] + dx[i], seed[1] + dy[i], 
			seed[2] + dz[i], 0, k);	
      }
      k++;
    }
  }
  fclose(fp);
  Kill_String_Workspace(sw);
  
  /*
  Set_Stack_Pixel(ws->mask, 19, 605, 112, 0, 1.0);
  Set_Stack_Pixel(ws->mask, 28, 565, 112, 0, 1.0);
  */
  Stack_Watershed_Infer_Parameter(stack, ws);

  tic();
  Stack *out = Stack_Watershed(stack, ws);
  printf("%lld\n", toc());

  Write_Stack("../data/diadem_d1_147_label.tif", out);

  static const uint8 Color_Map[][3] = { 
    {0, 0, 0},
    {0, 224, 64}, {32, 64, 128}, {64, 64, 0}, {64, 128, 64},
    {96, 64, 128}, {64, 0, 0}, {128, 200, 64}, {160, 128, 128},
    {192, 0, 0}, {192, 160, 64}, {224, 64, 128}, {224, 224, 192}};
  
  Translate_Stack(out, COLOR, 1);
  size_t nvoxel = Stack_Voxel_Number(out);
  size_t i;
  color_t *arrayc = (color_t*) out->array;
  for (i = 0; i < nvoxel; i++) {
    arrayc[i][2] = Color_Map[arrayc[i][0]][2];
    arrayc[i][1] = Color_Map[arrayc[i][0]][1];
    arrayc[i][0] = Color_Map[arrayc[i][0]][0];
  }

  Write_Stack("../data/diadem_d1_147_paint.tif", out);
#endif

#if 0
  Stack *stack = Read_Stack_U("../data/diadem_d1_146.xml");
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  Stack *mask = Read_Stack("../data/test3.tif");
  ws->mask = Crop_Stack(mask, 252, -937, 2, 1024, 1024, 63, NULL);
  ws->conn = 26;

  Stack_Watershed_Infer_Parameter(stack, ws);

  tic();
  Stack *out = Stack_Watershed(stack, ws);
  printf("%lld\n", toc());
  
  Write_Stack("../data/test2.tif", out);
#endif

#if 0
  Stack *stack = Make_Stack(GREY, 7, 7, 1);
  One_Stack(stack);
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->conn = 26;
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			Stack_Depth(stack));
  Zero_Stack(ws->mask);
  Set_Stack_Pixel(ws->mask, 1, 1, 0, 0, 1.0);
  Set_Stack_Pixel(ws->mask, 1, 5, 0, 0, 2.0);
  Set_Stack_Pixel(ws->mask, 3, 3, 0, 0, 3.0);
  Set_Stack_Pixel(ws->mask, 5, 1, 0, 0, 4.0);
  Set_Stack_Pixel(ws->mask, 5, 5, 0, 0, 5.0);

  Set_Stack_Pixel(stack, 1, 1, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 1, 5, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 3, 3, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 5, 1, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 5, 5, 0, 0, 3.0);
  
  Stack *out = Stack_Watershed(stack, ws);
  Print_Stack_Value(out);

  Stack *out2 = Stack_Region_Border_Shrink(out, ws);
  
  Print_Stack_Value(out2);

#endif

#if 0
  Stack *stack = Read_Stack("../data/diadem_d1_013_label.tif");
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  //ws->conn = 26;

  Stack *out = Stack_Region_Border_Shrink(stack, ws);
  Write_Stack("../data/test.tif", out);
#endif

#if 0
  Stack *stack = Make_Stack(GREY, 1, 1, 19);
  One_Stack(stack);
  
  stack->array[3] = 5;
  stack->array[4] = 5;
  stack->array[7] = 5;
  stack->array[8] = 5;
  stack->array[10] = 4;
  stack->array[11] = 5;
  stack->array[12] = 5;
  stack->array[13] = 4;
  stack->array[16] = 5;
  stack->array[17] = 5;

  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->conn = 26;
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			Stack_Depth(stack));
  Zero_Stack(ws->mask);

  
  Print_Stack_Value(stack);
  Stack_Watershed_Zgap_Barrier(stack, ws->mask);
  Print_Stack_Value(ws->mask);
#endif

#if 0
  Stack *stack = Read_Stack("../data/diadem_d1_047_label.tif");
  Stack_Binarize(stack);

  Stack *stack2 = Stack_Bwdist_L_U16(stack, NULL, 0);
  Write_Stack("../data/test.tif", stack2);  
#endif

#if 0
  char stack_path[100];
  char mask_path[100];

  strcpy(stack_path, "../data/diadem_d1_064.xml");

  strcpy(mask_path, stack_path);
  strsplit(mask_path, '.', -1);
  sprintf(mask_path, "%s_label.tif", mask_path);

  if (!fexist(stack_path)) {
    fprintf(stderr, "Cannot find %s\n", stack_path);
    return 1;
  }
  
  printf("Processing %s\n", stack_path);
  Stack *stack = Read_Stack_U(stack_path);
  Stack *mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			   Stack_Depth(stack));
  Zero_Stack(mask);

  int conn = 26;
  const int *dx = Stack_Neighbor_X_Offset(conn);
  const int *dy = Stack_Neighbor_X_Offset(conn);
  const int *dz = Stack_Neighbor_X_Offset(conn);
  
  int seed[3];
  String_Workspace *sw = New_String_Workspace();
  char *line = NULL;
  FILE *fp = fopen("../data/064.seeds.txt", "r");
  int k = 1;

  /* label seeds */
  while ((line = Read_Line(fp, sw)) != NULL) {
    int n;
    String_To_Integer_Array(line, seed, &n);
    double maxv = -1;
    if (n == 3) {
      maxv = Get_Stack_Pixel(stack, seed[0], seed[1], seed[2], 0);
      int i;
      for (i = 0; i < conn; i++) {
	if (maxv < Get_Stack_Pixel(stack, seed[0] + dx[i], seed[1] + dy[i], 
				   seed[2] + dz[i], 0)) {
	  maxv = Get_Stack_Pixel(stack, seed[0] + dx[i], seed[1] + dy[i], 
				 seed[2] + dz[i], 0);
	}
      }
      
      Set_Stack_Pixel(mask, seed[0], seed[1], seed[2], 0, k);
      for (i = 0; i < conn; i++) {
	Set_Stack_Pixel(mask, seed[0] + dx[i], seed[1] + dy[i], 
			seed[2] + dz[i], 0, k);	
      }
      k++;
    }
  }
  fclose(fp);
  Kill_String_Workspace(sw);

  Stack_Running_Median(stack, 0, stack);
  Stack_Running_Median(stack, 1, stack);
    
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->mask = mask;
    
  Filter_3d *filter = Gaussian_Filter_3d(2.0, 2.0, 1.5);
  Stack *filtered_stack  = Filter_Stack(stack, filter);
  Stack_Watershed_Zgap_Barrier(filtered_stack, ws->mask);
  Stack_Running_Max(ws->mask, 0, ws->mask);
  Stack_Running_Max(ws->mask, 1, ws->mask);
  //Write_Stack("../data/test.tif", ws->mask);
    
  Kill_Stack(filtered_stack);
  filtered_stack = NULL;

    
  FMatrix *dm = Mexihat_3D1_F(2.0, NULL, 2);
  //FMatrix *dm = Mexihat_3D_F(2.0, NULL);
  FMatrix_Negative(dm);

  filtered_stack = Filter_Stack(stack, dm);
  
  Stack_Threshold_Common(filtered_stack, 0, 65535);
  Stack_Binarize(filtered_stack);
  Translate_Stack(filtered_stack, GREY, 1);
    
    
  {
    int i, j, k;
    int offset = 0;
    uint16 *array = (uint16*) stack->array;
    for (k = 0; k < stack->depth; k++) {
      for (j = 0; j < stack->height; j++) {
	for (i = 0; i < stack->width; i++) {
	  if (filtered_stack != NULL) {
	    if (filtered_stack->array[offset] == 1) {
	      ws->mask->array[offset] = STACK_WATERSHED_BARRIER;
	    }
	  }
	  array[offset++] += k * 2;
	}
      }
    }
  }

  Kill_Stack(filtered_stack);
  
  Stack_Watershed_Infer_Parameter(stack, ws);
  ws->conn = 6;

  double weights[26] = {0.5, 0.5, 1.0, 1.0, 0.2, 0.2, 0.75, 0.75, 0.75, 0.75,
			0.35, 0.35, 0.35, 0.35, 0.6, 0.6, 0.6, 0.6, 
			0.45, 0.45, 0.45, 0.45,
			0.45, 0.45, 0.45, 0.45};

  ws->weights = weights;
  ws->weights = NULL;
  
  if (ws->weights != NULL) {
    ws->min_level /= 3;
  }
    
  Stack_Running_Median(stack, 0, stack);
  Stack_Running_Median(stack, 1, stack);
  
  Stack *out = Stack_Watershed(stack, ws);
  
  strcpy(mask_path, stack_path);
  strsplit(mask_path, '.', -1);
  sprintf(mask_path, "%s_label.tif", mask_path);
  
  Write_Stack("../data/test.tif", out);

#endif

#if 0
  Stack *stack = Read_Stack("../data/test/soma2.tif");

  int thre = Stack_Find_Threshold_A(stack, THRESHOLD_LOCMAX_TRIANGLE);
  Filter_3d *filter = Gaussian_Filter_3d(1.0, 1.0, 0.5);
  Stack *out = Filter_Stack(stack, filter);
  stack = Copy_Stack(out);
  Stack_Threshold_Binarize(out, thre);
  Stack *out2 = Stack_Bwdist_L_U16P(out, NULL, 0);
  int nvoxel = Stack_Voxel_Number(out);
  uint16_t *dist_array = (uint16_t*) out2->array;
  int i;
  for (i = 0; i < nvoxel; i++) {
    dist_array[i] = sqrt(dist_array[i]);
  }

  Write_Stack("../data/labmeeting13/distp.tif", out2);
#endif

#if 0
  //Stack *stack = Read_Stack("../data/test/soma2.tif");

  Stack *stack = Read_Stack("/Users/zhaot/Data/jinny/slice7_2to34ds_soma_c2.tif");
  int thre = Stack_Find_Threshold_A(stack, THRESHOLD_LOCMAX_TRIANGLE);
  Filter_3d *filter = Gaussian_Filter_3d(1.0, 1.0, 0.5);
  Stack *out = Filter_Stack(stack, filter);
  stack = Copy_Stack(out);
  Stack_Threshold_Binarize(out, thre);
  Stack *out2 = Stack_Bwdist_L_U16P(out, NULL, 0);

  /*
  out = Stack_Locmax_Region(out2, 26);
  */
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
      Stack_Depth(stack));
  Zero_Stack(ws->mask);
  size_t nvoxel = Stack_Voxel_Number(stack);
  size_t offset;
  uint16_t *dist_array = (uint16_t*) out2->array;
  for (offset = 0; offset < nvoxel; offset++) {
    if (/*(out->array[offset] == 1) && */(dist_array[offset] > 1000)) {
      ws->mask->array[offset] = 1;
    }
  }

  //Objlabel_Workspace *ow = New_Objlabel_Workspace();
  //Stack_Label_Large_Objects_W(ws->mask, 1, 2, 10, ow);
  //Stack_Label_Objects_N(ws->mask, NULL, 1, 2, 26);
  Object_3d_List *objs = Stack_Find_Object(ws->mask, 1, 100);
  Zero_Stack(ws->mask);
  Stack_Draw_Objects_Bw(ws->mask, objs, -255);
  printf("%g\n", Stack_Max(ws->mask, NULL));

  /*
  Write_Stack("../data/test.tif", ws->mask);
  return 1;
*/

  ws->min_level = thre;
  ws->start_level = 65535;

  Stack *out3 = Stack_Watershed(stack, ws);
  /*
  Write_Stack("../data/labmeeting13/watershed.tif", out3);
  return 1;
*/
  for (offset = 0; offset < nvoxel; offset++) {
    if (dist_array[offset] < 300) {
      out3->array[offset] = 0;
    }
  }

  int nregion = Stack_Max(out3, NULL);

  Kill_Stack(out2);
  Stack *filtered = Copy_Stack(stack);
  Kill_Stack(stack);
  
  ws->conn = 8;
  stack = Stack_Region_Border_Shrink(out3, ws);
  out2 = Stack_Region_Expand(stack, 4, 30, NULL);

  for (offset = 0; offset < nvoxel; offset++) {
    if (out->array[offset] == 0) {
      out2->array[offset] = 0;
    }
  }

  Write_Stack("../data/test2.tif", out2);

  Kill_Stack(stack);
  //stack = Read_Stack("../data/test/soma2.tif");
  stack = Read_Stack("/Users/zhaot/Data/jinny/slice7_2to34ds_soma_c2.tif");
  Translate_Stack(stack, COLOR, 1);
  int i;
  double h = 0.0;
  double s = 1.0;
  for (i = 0; i < nregion; i++) {
    Stack_Label_Color_L(stack, out2, i+1, h+=0.35, s, filtered);
    /*
    Rgb_Color color;
    Set_Color_Jet(&color, i*3);
    Stack_Label_Level(stack, out2, i+1, color);
    */
  }
  Write_Stack("../data/test.tif", stack);
#endif

#if 0
  Stack *stack = Read_Stack("../data/leaktest/leak3.tif");
  Stack *distmap = Stack_Bwdist_L_U16P(stack, NULL, 0);

  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->mask = Copy_Stack(distmap);
  Stack_Threshold_Binarize(ws->mask, 10);
  Translate_Stack(ws->mask, GREY, 1);
  Object_3d_List *objs = Stack_Find_Object(ws->mask, 1, 100);
  Zero_Stack(ws->mask);
  Stack_Draw_Objects_Bw(ws->mask, objs, -255);

  ws->min_level = 1;
  ws->start_level = 65535;
  Stack *out3 = Stack_Watershed(distmap, ws);
  Write_Stack("../data/test.tif", out3);

#endif

#if 0
  Stack *stack = Read_Stack("../data/benchmark/two_disk.tif");
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->conn = 26;
  Stack *out = Stack_Watershed(stack, ws);

  Write_Stack("../data/test.tif", out);
#endif
  return 0;
}