Example #1
0
void
bench(void)
{
	Chess chess;
	SearchData sd;
	S64 timer;
	int npos = 0;
	int nfen = (int)(sizeof(bench_fen) / sizeof(char*));
	
	double avg_bfactor;
	double t_elapsed;
	double hhit_rate;
	U64 nnodes_all;	/* num. of all nodes (main + qs) */
	int nps;	/* nodes (all types) per second */
	int i;
	
	init_chess(&chess);
	init_search_data(&sd);
	chess.max_depth = 8;
	chess.increment = 60000;

	printf("Running benchmark at search depth %d...\n", chess.max_depth);
	timer = get_ms();
	progressbar(nfen, 0);
	for (i = 0; i < nfen; i++) {
		const char *fen = bench_fen[i];
		if (strlen(fen) <= 1)
			continue;
		if (!fen_to_board(&chess.board, fen)) {
			id_search(&chess, NULLMOVE);
			if (chess.sd.cmd_type != CMDT_CONTINUE) {
				printf("Benchmark cancelled by user\n");
				return;
			}

			sd.nnodes += chess.sd.nnodes;
			sd.nqs_nodes += chess.sd.nqs_nodes;
			sd.nhash_probes += chess.sd.nhash_probes;
			sd.nhash_hits += chess.sd.nhash_hits;
			sd.bfactor += chess.sd.bfactor;
			npos++;
			progressbar(nfen, npos);
		} else
			printf("\nInvalid FEN string: %s\n", fen);
	}

	timer = get_ms() - timer;
	t_elapsed = timer / 1000.0;
	avg_bfactor = sd.bfactor / npos;
	hhit_rate = (sd.nhash_hits * 100.0) / sd.nhash_probes;
	nnodes_all = sd.nnodes + sd.nqs_nodes;
	nps = (double)nnodes_all / ((double)timer / 1000.0);
	printf("\n\nBenchmark finished in %.2f seconds.\n", t_elapsed);
	printf("Main nodes searched: %" PRIu64 "\n", sd.nnodes);
	printf("Quiescence nodes searched: %" PRIu64 "\n", sd.nqs_nodes);
	printf("Total nodes per second: %d\n", nps);
	printf("Average branching factor: %.2f\n", avg_bfactor);
	printf("Hash table hit rate: %.2f%%\n", hhit_rate);
}
Example #2
0
void TextProgressBar::update()
{
    ++iteration;

    if (maximum > 0) {
        // we know the maximum
        // draw a progress bar
        int percent = value * 100 / maximum;
        int hashes = percent / 2;

        QByteArray progressbar(hashes, '#');
        if (percent % 2)
            progressbar += '>';

        printf("\r[%-50s] %3d%% %s     ",
               progressbar.constData(),
               percent,
               qPrintable(message));
    } else {
        // we don't know the maximum, so we can't draw a progress bar
        int center = (iteration % 48) + 1; // 50 spaces, minus 2
        QByteArray before(qMax(center - 2, 0), ' ');
        QByteArray after(qMin(center + 2, 50), ' ');

        printf("\r[%s###%s]      %s      ",
               before.constData(), after.constData(), qPrintable(message));
    }
}
Example #3
0
void
predefinedLIMEGrid(inputPars *par, struct grid *g){
  FILE *fp;
  int i;
  double x,y,z,scale,abun;
	
  fp=fopen(par->pregridLIME,"r");
  par->ncell=par->pIntensity+par->sinkPoints;

  /* read in the grid file, which includes all the sink points so we don't need to generate them */
  for(i=0;i<par->ncell;i++){
    fscanf(fp,"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %d\n", &g[i].x[0], &g[i].x[1], &g[i].x[2], &g[i].dens[0], &g[i].t[0], &g[i].t[1], &g[i].abun[0], &g[i].vel[0], &g[i].vel[1], &g[i].vel[2], &g[i].dopb, &g[i].sink);
    g[i].id=i;
	g[i].nmol[0]=g[i].abun[0]*g[i].dens[0];

	// This next step needs to be done, even though it looks stupid
	g[i].dir=malloc(sizeof(point)*1);
	g[i].ds =malloc(sizeof(double)*1);
	g[i].neigh =malloc(sizeof(int)*1);
	if(!silent) progressbar((double) i/((double)par->ncell-1), 4);	
  }

  fclose(fp);

  qhull(par,g);
  distCalc(par,g);
//  getArea(par,g, ran);
//  getMass(par,g, ran);
  getVelosplines_lin(par,g);
  if(par->gridfile) write_VTK_unstructured_Points(par, g);
}
unsigned Aggregate::displayChunks() const {
    fancyprint(activeChunks() << "/" << totalChunks(),NOTIFY);

    int j = m_chunk.size();
    for(auto i=0;i<m_chunk.size();i++){
        uintmax_t lower = std::atoi(m_chunk[i]->file()->filename().c_str());
        uintmax_t down= m_chunk[i]->txn()->range().lb()+m_chunk[i]->txn()->bytesDone();
        uintmax_t higher = m_chunk[i]->txn()->range().ub();
        std::string myColor;

        if(m_chunk[i]->txn()->isComplete())
            myColor = SUCCESS;
        else if(m_chunk[i]->txn()->hasFailed())
            myColor = ERROR;
        else if(m_chunk[i]->txn()->isDownloading())
            myColor = WARNING;
        else
            myColor = NOTIFY;

        fancyprint(lower << ":" << down << ":"<< higher<< " ",myColor);
    }

    std::cout << progressbar(progress(),COLOR(0,CC::WHITE,CC::PURPLE),COLOR(0,CC::PURPLE,CC::WHITE));
    print( " " << round(progress(),2) << "%\t"
            << formatTime(timeRemaining()) << "\t"
            << formatByte(speed()) << "ps\t");

    return j+1;
}
Example #5
0
static void copyFromTo(FILE* fout, FILE* fin, int size, dlCallback cb)
{
	char aBuf[1024];
	int curSize = size;
	while (curSize)
	{
		int chunk = (curSize > sizeof(aBuf)) ? sizeof(aBuf) : curSize;
		progressbar(size - curSize, size);
		fread(aBuf, 1, chunk, fin);
		if (cb)
			cb(aBuf, chunk);
		fwrite(aBuf, 1, chunk, fout);
		curSize -= chunk;
	}
	//printf("Download complete              \n");
	progressbar(size, size);
	printf("\n\n");
}
Example #6
0
void ModuleList::run(SourceInterface *source, size_t count, bool recursive) {

#if _OPENMP
	std::cout << "crpropa::ModuleList: Number of Threads: " << omp_get_max_threads() << std::endl;
#endif

	ProgressBar progressbar(count);

	if (showProgress) {
		progressbar.start("Run ModuleList");
	}

	g_cancel_signal_flag = false;
	sighandler_t old_signal_handler = ::signal(SIGINT,
			g_cancel_signal_callback);

#pragma omp parallel for schedule(static, 1000)
	for (size_t i = 0; i < count; i++) {
		if (g_cancel_signal_flag)
			continue;

		ref_ptr<Candidate> candidate;

		try {
			candidate = source->getCandidate();
		} catch (std::exception &e) {
			std::cerr << "Exception in crpropa::ModuleList::run: source->getCandidate" << std::endl;
			std::cerr << e.what() << std::endl;
			g_cancel_signal_flag = true;
		}

		if (candidate.valid()) {
			try {
				run(candidate, recursive);
			} catch (std::exception &e) {
				std::cerr << "Exception in crpropa::ModuleList::run: " << std::endl;
				std::cerr << e.what() << std::endl;
				g_cancel_signal_flag = true;
			}
		}

		if (showProgress)
#pragma omp critical(progressbarUpdate)
			progressbar.update();
	}

	::signal(SIGINT, old_signal_handler);
}
Example #7
0
int main(int argc, char *argv[])
{
    int i,total=0;
    struct winsize w;
    ioctl(0, TIOCGWINSZ, &w);
    printf ("lines %d columns %d\n",w.ws_row, w.ws_col);



    total = 4*1024*1024;
    total = total + random()%total;
    for (i=0; i<total; i += random()%4096) {
        progressbar(i, total, total/10, 80, "%30s %d", "xsh...", i);
        usleep(500);
    }

    return 0;
}
Example #8
0
void ModuleList::run(candidate_vector_t &candidates, bool recursive) {
	size_t count = candidates.size();

#if _OPENMP
	std::cout << "crpropa::ModuleList: Number of Threads: " << omp_get_max_threads() << std::endl;
#endif

	ProgressBar progressbar(count);

	if (showProgress) {
		progressbar.start("Run ModuleList");
	}

	g_cancel_signal_flag = false;
	sighandler_t old_sigint_handler = ::signal(SIGINT,
			g_cancel_signal_callback);
	sighandler_t old_sigterm_handler = ::signal(SIGTERM,
			g_cancel_signal_callback);

#pragma omp parallel for schedule(static, 1000)
	for (size_t i = 0; i < count; i++) {
		if (g_cancel_signal_flag)
			continue;

		try {
			run(candidates[i], recursive);
		} catch (std::exception &e) {
			std::cerr << "Exception in crpropa::ModuleList::run: " << std::endl;
			std::cerr << e.what() << std::endl;
		}

		if (showProgress)
#pragma omp critical(progressbarUpdate)
			progressbar.update();
	}

	::signal(SIGINT, old_sigint_handler);
	::signal(SIGTERM, old_sigterm_handler);
}
Example #9
0
void
predefinedGrid(inputPars *par, struct grid *g){
  FILE *fp;
  int i;
  double x,y,z,scale;
  gsl_rng *ran = gsl_rng_alloc(gsl_rng_ranlxs2);
#ifdef TEST
  gsl_rng_set(ran,6611304);
#else
  gsl_rng_set(ran,time(0));
#endif
	
  fp=fopen(par->pregrid,"r");
  par->ncell=par->pIntensity+par->sinkPoints;

  for(i=0;i<par->pIntensity;i++){
    //    fscanf(fp,"%d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\n", &g[i].id, &g[i].x[0], &g[i].x[1], &g[i].x[2],  &g[i].dens[0], &g[i].t[0], &abun, &g[i].dopb, &g[i].vel[0], &g[i].vel[1], &g[i].vel[2]);
    //    fscanf(fp,"%d %lf %lf %lf %lf %lf %lf %lf\n", &g[i].id, &g[i].x[0], &g[i].x[1], &g[i].x[2],  &g[i].dens[0], &g[i].t[0], &abun, &g[i].dopb);
    int nRead = fscanf(fp,"%d %lf %lf %lf %lf %lf %lf %lf %lf\n", &g[i].id, &g[i].x[0], &g[i].x[1], &g[i].x[2],  &g[i].dens[0], &g[i].t[0], &g[i].vel[0], &g[i].vel[1], &g[i].vel[2]);
    if( nRead != 9 || g[i].id < 0 || g[i].id > par->ncell)
      {
        if(!silent) bail_out("Reading Grid File error");
        exit(0);
      }

    g[i].dopb=200;
    g[i].abun[0]=1e-9;


    g[i].sink=0;
	g[i].t[1]=g[i].t[0];
	g[i].nmol[0]=g[i].abun[0]*g[i].dens[0];
		
	/* This next step needs to be done, even though it looks stupid */
	g[i].dir=malloc(sizeof(point)*1);
	g[i].ds =malloc(sizeof(double)*1);
	g[i].neigh =malloc(sizeof(struct grid *)*1);
	if(!silent) progressbar((double) i/((double)par->pIntensity-1), 4);	
  }

  for(i=par->pIntensity;i<par->ncell;i++){
    x=2*gsl_rng_uniform(ran)-1.;
    y=2*gsl_rng_uniform(ran)-1.;
    z=2*gsl_rng_uniform(ran)-1.;
    if(x*x+y*y+z*z<1){
      scale=par->radius*sqrt(1/(x*x+y*y+z*z));
      g[i].id=i;
      g[i].x[0]=scale*x;
      g[i].x[1]=scale*y;
      g[i].x[2]=scale*z;
      g[i].sink=1;
      g[i].abun[0]=0;
      g[i].dens[0]=1e-30;
      g[i].t[0]=par->tcmb;
      g[i].t[1]=par->tcmb;
      g[i].dopb=0.;
    } else i--;
  }
  fclose(fp);

  qhull(par,g);
  distCalc(par,g);
  //  getArea(par,g, ran);
  //  getMass(par,g, ran);
  getVelosplines_lin(par,g);
  if(par->gridfile) write_VTK_unstructured_Points(par, g);
  gsl_rng_free(ran);
}
Example #10
0
/* Read a PGN file (a collection of one or more games in PGN format) and store
   the positions and their win/loss ratios in an AVL tree (**tree).
   The AVL tree can later be written in an opening book file (book.bin).
   
   Returns the number of new positions added to the tree, or -1 on error.  */
int
pgn_to_tree(const char *filename, AvlNode **tree)
{
	PgnResult result;
	int prev_progress;
	int npos = 0;
	long file_len;
	FILE *fp;
	Board board;

	ASSERT(1, filename != NULL);

	if ((fp = fopen(filename, "r")) == NULL) {
		my_perror("Can't open PGN file %s", filename);
		return -1;
	}

	if (settings.book_type != BOOK_MEM) {
		settings.book_type = BOOK_MEM;
		printf("Changed book mode to \"book in memory\"\n");
	}
	if (*tree == NULL && file_exists(settings.book_file)) {
		printf("Loading opening book to memory...\n");
		book_to_tree(settings.book_file, tree);
	} else if (*tree == NULL)
		printf("Creating a new opening book...\n");

	/* Find out how big the file is.  */
	fseek(fp, 0, SEEK_END);
	file_len = ftell(fp);
	rewind(fp);

	printf("Reading PGN file %s...\n", filename);
	prev_progress = 0;
	progressbar(50, 0);
	while ((result = get_pgn_result(fp)) != RESULT_ERROR) {
		int depth;
		int progress;
		int len;
		char san_move[MAX_BUF];

		/* Games with an unknown result are ignored.  */
		ASSERT(1, result != RESULT_ERROR);
		if (result == NO_RESULT || result == DRAWN_GAME)
			continue;

		depth = 0;
		fen_to_board(&board, START_FEN);

		while ((len = read_move(san_move, MAX_BUF, fp)) >= 0) {
			int points = 0;
			U32 move;

			/* break out of the loop when a new game begins */
			if (depth > 0 && san_move[0] == '[')
				break;
			if (len < 2)
				continue;

			move = san_to_move(&board, san_move);
			if (move == NULLMOVE) {
				#if DEBUG_LEVEL > 0
				update_log("Illegal move in %s: %s, line: %d\n",
				          filename, san_move, get_line_num(fp));
				#endif /* DEBUG_LEVEL > 0 */
				break;
			}

			if ((result == WHITE_WINS && board.color == WHITE)
			||  (result == BLACK_WINS && board.color == BLACK))
				points = 2;

			make_move(&board, move);
			if (save_book_pos(board.posp->key, points, tree))
				npos++;

			if (++depth >= MAX_BOOK_PLIES)
				break;
		}
		progress = (ftell(fp) * 50) / file_len;
		if (progress > prev_progress) {
			progressbar(50, progress);
			prev_progress = progress;
		}
	}
	progressbar(50, 50);
	my_close(fp, filename);
	printf("\n");

	return npos;
}
Example #11
0
/*
 * Dialog-box function for the main PuTTYgen dialog box.
 */
static int CALLBACK MainDlgProc(HWND hwnd, UINT msg,
				WPARAM wParam, LPARAM lParam)
{
    static const char generating_msg[] =
	"Please wait while a key is generated...";
    static const char entropy_msg[] =
	"Please generate some randomness by moving the mouse over the blank area.";
    struct MainDlgState *state;

    switch (msg) {
      case WM_INITDIALOG:
        if (help_path)
            SetWindowLong(hwnd, GWL_EXSTYLE,
                          GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_CONTEXTHELP);
        else {
            /*
             * If we add a Help button, this is where we destroy it
             * if the help file isn't present.
             */
        }
        requested_help = FALSE;
	SendMessage(hwnd, WM_SETICON, (WPARAM) ICON_BIG,
		    (LPARAM) LoadIcon(hinst, MAKEINTRESOURCE(200)));

	state = snew(struct MainDlgState);
	state->generation_thread_exists = FALSE;
	state->collecting_entropy = FALSE;
	state->entropy = NULL;
	state->key_exists = FALSE;
	SetWindowLong(hwnd, GWL_USERDATA, (LONG) state);
	{
	    HMENU menu, menu1;

	    menu = CreateMenu();

	    menu1 = CreateMenu();
	    AppendMenu(menu1, MF_ENABLED, IDC_LOAD, "&Load private key");
	    AppendMenu(menu1, MF_ENABLED, IDC_SAVEPUB, "Save p&ublic key");
	    AppendMenu(menu1, MF_ENABLED, IDC_SAVE, "&Save private key");
	    AppendMenu(menu1, MF_SEPARATOR, 0, 0);
	    AppendMenu(menu1, MF_ENABLED, IDC_QUIT, "E&xit");
	    AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1, "&File");
	    state->filemenu = menu1;

	    menu1 = CreateMenu();
	    AppendMenu(menu1, MF_ENABLED, IDC_GENERATE, "&Generate key pair");
	    AppendMenu(menu1, MF_SEPARATOR, 0, 0);
	    AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH1, "SSH&1 key (RSA)");
	    AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2RSA, "SSH2 &RSA key");
	    AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2DSA, "SSH2 &DSA key");
	    AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1, "&Key");
	    state->keymenu = menu1;

	    menu1 = CreateMenu();
	    AppendMenu(menu1, MF_ENABLED, IDC_IMPORT, "&Import key");
	    AppendMenu(menu1, MF_SEPARATOR, 0, 0);
	    AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_OPENSSH,
		       "Export &OpenSSH key");
	    AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_SSHCOM,
		       "Export &ssh.com key");
	    AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1,
		       "Con&versions");
	    state->cvtmenu = menu1;

	    menu1 = CreateMenu();
	    AppendMenu(menu1, MF_ENABLED, IDC_ABOUT, "&About");
	    if (help_path)
		AppendMenu(menu1, MF_ENABLED, IDC_GIVEHELP, "&Help");
	    AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1, "&Help");

	    SetMenu(hwnd, menu);
	}

	/*
	 * Centre the window.
	 */
	{			       /* centre the window */
	    RECT rs, rd;
	    HWND hw;

	    hw = GetDesktopWindow();
	    if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
		MoveWindow(hwnd,
			   (rs.right + rs.left + rd.left - rd.right) / 2,
			   (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
			   rd.right - rd.left, rd.bottom - rd.top, TRUE);
	}

	{
	    struct ctlpos cp, cp2;

	    /* Accelerators used: acglops1rbd */

	    ctlposinit(&cp, hwnd, 4, 4, 4);
	    beginbox(&cp, "Key", IDC_BOX_KEY);
	    cp2 = cp;
	    statictext(&cp2, "No key.", 1, IDC_NOKEY);
	    cp2 = cp;
	    statictext(&cp2, "", 1, IDC_GENERATING);
	    progressbar(&cp2, IDC_PROGRESS);
	    bigeditctrl(&cp,
			"&Public key for pasting into authorized_keys file:",
			IDC_PKSTATIC, IDC_KEYDISPLAY, 5);
	    SendDlgItemMessage(hwnd, IDC_KEYDISPLAY, EM_SETREADONLY, 1, 0);
	    staticedit(&cp, "Key f&ingerprint:", IDC_FPSTATIC,
		       IDC_FINGERPRINT, 75);
	    SendDlgItemMessage(hwnd, IDC_FINGERPRINT, EM_SETREADONLY, 1,
			       0);
	    staticedit(&cp, "Key &comment:", IDC_COMMENTSTATIC,
		       IDC_COMMENTEDIT, 75);
	    staticpassedit(&cp, "Key p&assphrase:", IDC_PASSPHRASE1STATIC,
			   IDC_PASSPHRASE1EDIT, 75);
	    staticpassedit(&cp, "C&onfirm passphrase:",
			   IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT, 75);
	    endbox(&cp);
	    beginbox(&cp, "Actions", IDC_BOX_ACTIONS);
	    staticbtn(&cp, "Generate a public/private key pair",
		      IDC_GENSTATIC, "&Generate", IDC_GENERATE);
	    staticbtn(&cp, "Load an existing private key file",
		      IDC_LOADSTATIC, "&Load", IDC_LOAD);
	    static2btn(&cp, "Save the generated key", IDC_SAVESTATIC,
		       "Save p&ublic key", IDC_SAVEPUB,
		       "&Save private key", IDC_SAVE);
	    endbox(&cp);
	    beginbox(&cp, "Parameters", IDC_BOX_PARAMS);
	    radioline(&cp, "Type of key to generate:", IDC_TYPESTATIC, 3,
		      "SSH&1 (RSA)", IDC_KEYSSH1,
		      "SSH2 &RSA", IDC_KEYSSH2RSA,
		      "SSH2 &DSA", IDC_KEYSSH2DSA, NULL);
	    staticedit(&cp, "Number of &bits in a generated key:",
		       IDC_BITSSTATIC, IDC_BITS, 20);
	    endbox(&cp);
	}
	CheckRadioButton(hwnd, IDC_KEYSSH1, IDC_KEYSSH2DSA, IDC_KEYSSH1);
	CheckMenuRadioItem(state->keymenu, IDC_KEYSSH1, IDC_KEYSSH2DSA,
			   IDC_KEYSSH1, MF_BYCOMMAND);
	SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEYSIZE, FALSE);

	/*
	 * Initially, hide the progress bar and the key display,
	 * and show the no-key display. Also disable the Save
	 * buttons, because with no key we obviously can't save
	 * anything.
	 */
	ui_set_state(hwnd, state, 0);

	/*
	 * Load a key file if one was provided on the command line.
	 */
	if (cmdline_keyfile)
	    load_key_file(hwnd, state, filename_from_str(cmdline_keyfile), 0);

	return 1;
      case WM_MOUSEMOVE:
	state = (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	if (state->collecting_entropy &&
	    state->entropy && state->entropy_got < state->entropy_required) {
	    state->entropy[state->entropy_got++] = lParam;
	    state->entropy[state->entropy_got++] = GetMessageTime();
	    SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS,
			       state->entropy_got, 0);
	    if (state->entropy_got >= state->entropy_required) {
		struct rsa_key_thread_params *params;
		DWORD threadid;

		/*
		 * Seed the entropy pool
		 */
		random_add_heavynoise(state->entropy, state->entropy_size);
		memset(state->entropy, 0, state->entropy_size);
		sfree(state->entropy);
		state->collecting_entropy = FALSE;

		SetDlgItemText(hwnd, IDC_GENERATING, generating_msg);
		SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
				   MAKELPARAM(0, PROGRESSRANGE));
		SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);

		params = snew(struct rsa_key_thread_params);
		params->progressbar = GetDlgItem(hwnd, IDC_PROGRESS);
		params->dialog = hwnd;
		params->keysize = state->keysize;
		params->is_dsa = state->is_dsa;
		params->key = &state->key;
		params->dsskey = &state->dsskey;

		if (!CreateThread(NULL, 0, generate_rsa_key_thread,
				  params, 0, &threadid)) {
		    MessageBox(hwnd, "Out of thread resources",
			       "Key generation error",
			       MB_OK | MB_ICONERROR);
		    sfree(params);
		} else {
		    state->generation_thread_exists = TRUE;
		}
	    }
	}
	break;
      case WM_COMMAND:
	switch (LOWORD(wParam)) {
	  case IDC_KEYSSH1:
	  case IDC_KEYSSH2RSA:
	  case IDC_KEYSSH2DSA:
	    {
		state = (struct MainDlgState *)
		    GetWindowLong(hwnd, GWL_USERDATA);
		if (!IsDlgButtonChecked(hwnd, LOWORD(wParam)))
		    CheckRadioButton(hwnd, IDC_KEYSSH1, IDC_KEYSSH2DSA,
				     LOWORD(wParam));
		CheckMenuRadioItem(state->keymenu, IDC_KEYSSH1, IDC_KEYSSH2DSA,
				   LOWORD(wParam), MF_BYCOMMAND);
	    }
	    break;
	  case IDC_QUIT:
	    PostMessage(hwnd, WM_CLOSE, 0, 0);
	    break;
	  case IDC_COMMENTEDIT:
	    if (HIWORD(wParam) == EN_CHANGE) {
		state = (struct MainDlgState *)
		    GetWindowLong(hwnd, GWL_USERDATA);
		if (state->key_exists) {
		    HWND editctl = GetDlgItem(hwnd, IDC_COMMENTEDIT);
		    int len = GetWindowTextLength(editctl);
		    if (*state->commentptr)
			sfree(*state->commentptr);
		    *state->commentptr = snewn(len + 1, char);
		    GetWindowText(editctl, *state->commentptr, len + 1);
		    if (state->ssh2) {
			setupbigedit2(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC,
				      &state->ssh2key);
		    } else {
			setupbigedit1(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC,
				      &state->key);
		    }
		}
	    }
Example #12
0
/* Based on Lloyds Algorithm (Lloyd, S. IEEE, 1982) */	
void
smooth(configInfo *par, struct grid *gp){
  double mindist;	/* Distance to closest neighbor				*/
  int k=0,j,i;		/* counters									*/
  int sg;		/* counter for smoothing the grid			*/
  int cn;
  double move[3];	/* Auxillary array for smoothing the grid	*/
  double dist;		/* Distance to a neighbor					*/
  struct cell *dc=NULL; /* Not used at present. */
  unsigned long numCells;

  for(sg=0;sg<N_SMOOTH_ITERS;sg++){
    delaunay(DIM, gp, (unsigned long)par->ncell, 0, 0, &dc, &numCells);
    distCalc(par, gp);

    for(i=0;i<par->pIntensity;i++){
      mindist=1e30;
      cn=-1;
      for(k=0;k<gp[i].numNeigh;k++){
        if(gp[i].neigh[k]->sink==0){
          if(gp[i].ds[k]<mindist){
            mindist=gp[i].ds[k];
            cn=k;
          }
        }
      }

      if(par->radius-sqrt(gp[i].x[0]*gp[i].x[0] + gp[i].x[1]*gp[i].x[1] + gp[i].x[2]*gp[i].x[2])<mindist) cn=-1;

      if(cn>-1) {
        for(k=0;k<DIM;k++){
          move[k] = gp[i].x[k] - gp[i].dir[cn].x[k]*0.20;
        }			  
        if((move[0]*move[0]+move[1]*move[1]+move[2]*move[2])<par->radiusSqu &&
           (move[0]*move[0]+move[1]*move[1]+move[2]*move[2])>par->minScaleSqu){
          for(k=0;k<DIM;k++) gp[i].x[k]=move[k];
        }
      }
    }
		
    for(i=par->pIntensity;i<par->ncell;i++){
      mindist=1e30;
      cn=-1;
      for(k=0;k<gp[i].numNeigh;k++){
        if(gp[i].neigh[k]->sink==1){
          if(gp[i].ds[k]<mindist){
            mindist=gp[i].ds[k];
            cn=k;
          }
        }
      }
      j=gp[i].neigh[cn]->id;
      for(k=0;k<DIM;k++){
        gp[i].x[k] = gp[i].x[k] - (gp[j].x[k]-gp[i].x[k]) * 0.15;
      }			
      dist=par->radius/sqrt(gp[i].x[0]*gp[i].x[0] + gp[i].x[1]*gp[i].x[1] + gp[i].x[2]*gp[i].x[2]);	
      for(k=0;k<DIM;k++){
        gp[i].x[k] *= dist;
      }	
    }
		
    if(!silent) progressbar((double)(sg+1)/(double)N_SMOOTH_ITERS, 5);	
    free(dc);
  }	
}
Example #13
0
/*
 * Dialog-box function for the main PuTTYgen dialog box.
 */
static int CALLBACK MainDlgProc(HWND hwnd, UINT msg,
				WPARAM wParam, LPARAM lParam)
{
    enum {
	controlidstart = 100,
	IDC_TITLE,
	IDC_BOX_KEY,
	IDC_NOKEY,
	IDC_GENERATING,
	IDC_PROGRESS,
	IDC_PKSTATIC, IDC_KEYDISPLAY,
	IDC_FPSTATIC, IDC_FINGERPRINT,
	IDC_COMMENTSTATIC, IDC_COMMENTEDIT,
	IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT,
	IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT,
	IDC_BOX_ACTIONS,
	IDC_GENSTATIC, IDC_GENERATE,
	IDC_LOADSTATIC, IDC_LOAD,
	IDC_SAVESTATIC, IDC_SAVE, IDC_SAVEPUB,
	IDC_BOX_PARAMS,
	IDC_TYPESTATIC, IDC_KEYSSH1, IDC_KEYSSH2RSA, IDC_KEYSSH2DSA,
	IDC_BITSSTATIC, IDC_BITS,
	IDC_ABOUT,
    };
    static const int nokey_ids[] = { IDC_NOKEY, 0 };
    static const int generating_ids[] =
	{ IDC_GENERATING, IDC_PROGRESS, 0 };
    static const int gotkey_ids[] = {
	IDC_PKSTATIC, IDC_KEYDISPLAY,
	IDC_FPSTATIC, IDC_FINGERPRINT,
	IDC_COMMENTSTATIC, IDC_COMMENTEDIT,
	IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT,
	IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT, 0
    };
    static const char generating_msg[] =
	"Please wait while a key is generated...";
    static const char entropy_msg[] =
	"Please generate some randomness by moving the mouse over the blank area.";
    struct MainDlgState *state;

    switch (msg) {
      case WM_INITDIALOG:
        if (help_path)
            SetWindowLong(hwnd, GWL_EXSTYLE,
                          GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_CONTEXTHELP);
        else {
            /*
             * If we add a Help button, this is where we destroy it
             * if the help file isn't present.
             */
        }
        requested_help = FALSE;

	/*
	 * Centre the window.
	 */
	{			       /* centre the window */
	    RECT rs, rd;
	    HWND hw;

	    hw = GetDesktopWindow();
	    if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
		MoveWindow(hwnd,
			   (rs.right + rs.left + rd.left - rd.right) / 2,
			   (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
			   rd.right - rd.left, rd.bottom - rd.top, TRUE);
	}

	state = smalloc(sizeof(*state));
	state->generation_thread_exists = FALSE;
	state->collecting_entropy = FALSE;
	state->entropy = NULL;
	state->key_exists = FALSE;
	SetWindowLong(hwnd, GWL_USERDATA, (LONG) state);
	{
	    struct ctlpos cp, cp2;

	    /* Accelerators used: acglops1rbd */

	    ctlposinit(&cp, hwnd, 4, 4, 4);
	    bartitle(&cp, "Public and private key generation for PuTTY",
		     IDC_TITLE);
	    beginbox(&cp, "Key", IDC_BOX_KEY);
	    cp2 = cp;
	    statictext(&cp2, "No key.", 1, IDC_NOKEY);
	    cp2 = cp;
	    statictext(&cp2, "", 1, IDC_GENERATING);
	    progressbar(&cp2, IDC_PROGRESS);
	    bigeditctrl(&cp,
			"&Public key for pasting into authorized_keys file:",
			IDC_PKSTATIC, IDC_KEYDISPLAY, 5);
	    SendDlgItemMessage(hwnd, IDC_KEYDISPLAY, EM_SETREADONLY, 1, 0);
	    staticedit(&cp, "Key fingerprint:", IDC_FPSTATIC,
		       IDC_FINGERPRINT, 75);
	    SendDlgItemMessage(hwnd, IDC_FINGERPRINT, EM_SETREADONLY, 1,
			       0);
	    staticedit(&cp, "Key &comment:", IDC_COMMENTSTATIC,
		       IDC_COMMENTEDIT, 75);
	    staticpassedit(&cp, "Key p&assphrase:", IDC_PASSPHRASE1STATIC,
			   IDC_PASSPHRASE1EDIT, 75);
	    staticpassedit(&cp, "C&onfirm passphrase:",
			   IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT, 75);
	    endbox(&cp);
	    beginbox(&cp, "Actions", IDC_BOX_ACTIONS);
	    staticbtn(&cp, "Generate a public/private key pair",
		      IDC_GENSTATIC, "&Generate", IDC_GENERATE);
	    staticbtn(&cp, "Load an existing private key file",
		      IDC_LOADSTATIC, "&Load", IDC_LOAD);
	    static2btn(&cp, "Save the generated key", IDC_SAVESTATIC,
		       "Save p&ublic key", IDC_SAVEPUB,
		       "&Save private key", IDC_SAVE);
	    endbox(&cp);
	    beginbox(&cp, "Parameters", IDC_BOX_PARAMS);
	    radioline(&cp, "Type of key to generate:", IDC_TYPESTATIC, 3,
		      "SSH&1 (RSA)", IDC_KEYSSH1,
		      "SSH2 &RSA", IDC_KEYSSH2RSA,
		      "SSH2 &DSA", IDC_KEYSSH2DSA, NULL);
	    staticedit(&cp, "Number of &bits in a generated key:",
		       IDC_BITSSTATIC, IDC_BITS, 20);
	    endbox(&cp);
	}
	CheckRadioButton(hwnd, IDC_KEYSSH1, IDC_KEYSSH2DSA, IDC_KEYSSH1);
	SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEYSIZE, FALSE);

	/*
	 * Initially, hide the progress bar and the key display,
	 * and show the no-key display. Also disable the Save
	 * buttons, because with no key we obviously can't save
	 * anything.
	 */
	hidemany(hwnd, nokey_ids, FALSE);
	hidemany(hwnd, generating_ids, TRUE);
	hidemany(hwnd, gotkey_ids, TRUE);
	EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
	EnableWindow(GetDlgItem(hwnd, IDC_SAVEPUB), 0);

	return 1;
      case WM_MOUSEMOVE:
	state = (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	if (state->collecting_entropy &&
	    state->entropy && state->entropy_got < state->entropy_required) {
	    state->entropy[state->entropy_got++] = lParam;
	    state->entropy[state->entropy_got++] = GetMessageTime();
	    SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS,
			       state->entropy_got, 0);
	    if (state->entropy_got >= state->entropy_required) {
		struct rsa_key_thread_params *params;
		DWORD threadid;

		/*
		 * Seed the entropy pool
		 */
		random_add_heavynoise(state->entropy, state->entropy_size);
		memset(state->entropy, 0, state->entropy_size);
		sfree(state->entropy);
		state->collecting_entropy = FALSE;

		SetDlgItemText(hwnd, IDC_GENERATING, generating_msg);
		SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
				   MAKELPARAM(0, PROGRESSRANGE));
		SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);

		params = smalloc(sizeof(*params));
		params->progressbar = GetDlgItem(hwnd, IDC_PROGRESS);
		params->dialog = hwnd;
		params->keysize = state->keysize;
		params->is_dsa = state->is_dsa;
		params->key = &state->key;
		params->dsskey = &state->dsskey;

		if (!CreateThread(NULL, 0, generate_rsa_key_thread,
				  params, 0, &threadid)) {
		    MessageBox(hwnd, "Out of thread resources",
			       "Key generation error",
			       MB_OK | MB_ICONERROR);
		    sfree(params);
		} else {
		    state->generation_thread_exists = TRUE;
		}
	    }
	}
	break;
      case WM_COMMAND:
	switch (LOWORD(wParam)) {
	  case IDC_COMMENTEDIT:
	    if (HIWORD(wParam) == EN_CHANGE) {
		state = (struct MainDlgState *)
		    GetWindowLong(hwnd, GWL_USERDATA);
		if (state->key_exists) {
		    HWND editctl = GetDlgItem(hwnd, IDC_COMMENTEDIT);
		    int len = GetWindowTextLength(editctl);
		    if (*state->commentptr)
			sfree(*state->commentptr);
		    *state->commentptr = smalloc(len + 1);
		    GetWindowText(editctl, *state->commentptr, len + 1);
		    if (state->ssh2) {
			setupbigedit2(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC,
				      &state->ssh2key);
		    } else {
			setupbigedit1(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC,
				      &state->key);
		    }
		}
	    }
	    break;
	  case IDC_ABOUT:
	    EnableWindow(hwnd, 0);
	    DialogBox(hinst, MAKEINTRESOURCE(213), NULL, AboutProc);
	    EnableWindow(hwnd, 1);
	    SetActiveWindow(hwnd);
	    return 0;
	  case IDC_GENERATE:
	    state =
		(struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	    if (!state->generation_thread_exists) {
		BOOL ok;
		state->keysize = GetDlgItemInt(hwnd, IDC_BITS, &ok, FALSE);
		if (!ok)
		    state->keysize = DEFAULT_KEYSIZE;
		/* If we ever introduce a new key type, check it here! */
		state->ssh2 = !IsDlgButtonChecked(hwnd, IDC_KEYSSH1);
		state->is_dsa = IsDlgButtonChecked(hwnd, IDC_KEYSSH2DSA);
		if (state->keysize < 256) {
		    int ret = MessageBox(hwnd,
					 "PuTTYgen will not generate a key"
					 " smaller than 256 bits.\n"
					 "Key length reset to 256. Continue?",
					 "PuTTYgen Warning",
					 MB_ICONWARNING | MB_OKCANCEL);
		    if (ret != IDOK)
			break;
		    state->keysize = 256;
		    SetDlgItemInt(hwnd, IDC_BITS, 256, FALSE);
		}
		hidemany(hwnd, nokey_ids, TRUE);
		hidemany(hwnd, generating_ids, FALSE);
		hidemany(hwnd, gotkey_ids, TRUE);
		EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 0);
		EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 0);
		EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
		EnableWindow(GetDlgItem(hwnd, IDC_SAVEPUB), 0);
		EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH1), 0);
		EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2RSA), 0);
		EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2DSA), 0);
		EnableWindow(GetDlgItem(hwnd, IDC_BITS), 0);
		state->key_exists = FALSE;
		SetDlgItemText(hwnd, IDC_GENERATING, entropy_msg);
		state->collecting_entropy = TRUE;

		/*
		 * My brief statistical tests on mouse movements
		 * suggest that there are about 2.5 bits of
		 * randomness in the x position, 2.5 in the y
		 * position, and 1.7 in the message time, making
		 * 5.7 bits of unpredictability per mouse movement.
		 * However, other people have told me it's far less
		 * than that, so I'm going to be stupidly cautious
		 * and knock that down to a nice round 2. With this
		 * method, we require two words per mouse movement,
		 * so with 2 bits per mouse movement we expect 2
		 * bits every 2 words.
		 */
		state->entropy_required = (state->keysize / 2) * 2;
		state->entropy_got = 0;
		state->entropy_size = (state->entropy_required *
				       sizeof(*state->entropy));
		state->entropy = smalloc(state->entropy_size);

		SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
				   MAKELPARAM(0, state->entropy_required));
		SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
	    }
	    break;
	  case IDC_SAVE:
	    state =
		(struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	    if (state->key_exists) {
		char filename[FILENAME_MAX];
		char passphrase[PASSPHRASE_MAXLEN];
		char passphrase2[PASSPHRASE_MAXLEN];
		GetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
			       passphrase, sizeof(passphrase));
		GetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
			       passphrase2, sizeof(passphrase2));
		if (strcmp(passphrase, passphrase2)) {
		    MessageBox(hwnd,
			       "The two passphrases given do not match.",
			       "PuTTYgen Error", MB_OK | MB_ICONERROR);
		    break;
		}
		if (!*passphrase) {
		    int ret;
		    ret = MessageBox(hwnd,
				     "Are you sure you want to save this key\n"
				     "without a passphrase to protect it?",
				     "PuTTYgen Warning",
				     MB_YESNO | MB_ICONWARNING);
		    if (ret != IDYES)
			break;
		}
		if (prompt_keyfile(hwnd, "Save private key as:",
				   filename, 1)) {
		    int ret;
		    FILE *fp = fopen(filename, "r");
		    if (fp) {
			char buffer[FILENAME_MAX + 80];
			fclose(fp);
			sprintf(buffer, "Overwrite existing file\n%.*s?",
				FILENAME_MAX, filename);
			ret = MessageBox(hwnd, buffer, "PuTTYgen Warning",
					 MB_YESNO | MB_ICONWARNING);
			if (ret != IDYES)
			    break;
		    }
		    if (state->ssh2) {
			ret = ssh2_save_userkey(filename, &state->ssh2key,
						*passphrase ? passphrase :
						NULL);
		    } else {
			ret = saversakey(filename, &state->key,
					 *passphrase ? passphrase : NULL);
		    }
		    if (ret <= 0) {
			MessageBox(hwnd, "Unable to save key file",
				   "PuTTYgen Error", MB_OK | MB_ICONERROR);
		    }
		}
	    }
	    break;
	  case IDC_SAVEPUB:
	    state =
		(struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	    if (state->key_exists) {
		char filename[FILENAME_MAX];
		if (prompt_keyfile(hwnd, "Save public key as:",
				   filename, 1)) {
		    int ret;
		    FILE *fp = fopen(filename, "r");
		    if (fp) {
			char buffer[FILENAME_MAX + 80];
			fclose(fp);
			sprintf(buffer, "Overwrite existing file\n%.*s?",
				FILENAME_MAX, filename);
			ret = MessageBox(hwnd, buffer, "PuTTYgen Warning",
					 MB_YESNO | MB_ICONWARNING);
			if (ret != IDYES)
			    break;
		    }
		    if (state->ssh2) {
			ret = save_ssh2_pubkey(filename, &state->ssh2key);
		    } else {
			ret = save_ssh1_pubkey(filename, &state->key);
		    }
		    if (ret <= 0) {
			MessageBox(hwnd, "Unable to save key file",
				   "PuTTYgen Error", MB_OK | MB_ICONERROR);
		    }
		}
	    }
	    break;
	  case IDC_LOAD:
	    state =
		(struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	    if (!state->generation_thread_exists) {
		char filename[FILENAME_MAX];
		if (prompt_keyfile(hwnd, "Load private key:", filename, 0)) {
		    char passphrase[PASSPHRASE_MAXLEN];
		    int needs_pass;
		    int ver;
		    int ret;
		    char *comment;
		    struct PassphraseProcStruct pps;
		    struct RSAKey newkey1;
		    struct ssh2_userkey *newkey2 = NULL;

		    ver = keyfile_version(filename);
		    if (ver == 0) {
			MessageBox(NULL, "Couldn't load private key.",
				   "PuTTYgen Error", MB_OK | MB_ICONERROR);
			break;
		    }

		    comment = NULL;
		    if (ver == 1)
			needs_pass = rsakey_encrypted(filename, &comment);
		    else
			needs_pass =
			    ssh2_userkey_encrypted(filename, &comment);
		    pps.passphrase = passphrase;
		    pps.comment = comment;
		    do {
			if (needs_pass) {
			    int dlgret;
			    dlgret = DialogBoxParam(hinst,
						    MAKEINTRESOURCE(210),
						    NULL, PassphraseProc,
						    (LPARAM) & pps);
			    if (!dlgret) {
				ret = -2;
				break;
			    }
			} else
			    *passphrase = '\0';
			if (ver == 1)
			    ret =
				loadrsakey(filename, &newkey1, passphrase);
			else {
			    newkey2 =
				ssh2_load_userkey(filename, passphrase);
			    if (newkey2 == SSH2_WRONG_PASSPHRASE)
				ret = -1;
			    else if (!newkey2)
				ret = 0;
			    else
				ret = 1;
			}
		    } while (ret == -1);
		    if (comment)
			sfree(comment);
		    if (ret == 0) {
			MessageBox(NULL, "Couldn't load private key.",
				   "PuTTYgen Error", MB_OK | MB_ICONERROR);
		    } else if (ret == 1) {
			EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
			EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
			EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
			EnableWindow(GetDlgItem(hwnd, IDC_SAVEPUB), 1);
			EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH1), 1);
			EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2RSA), 1);
			EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2DSA), 1);
			EnableWindow(GetDlgItem(hwnd, IDC_BITS), 1);
			/*
			 * Now update the key controls with all the
			 * key data.
			 */
			{
			    SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
					   passphrase);
			    SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
					   passphrase);
			    if (ver == 1) {
				char buf[128];
				char *savecomment;

				state->ssh2 = FALSE;
				state->commentptr = &state->key.comment;
				state->key = newkey1;

				/*
				 * Set the key fingerprint.
				 */
				savecomment = state->key.comment;
				state->key.comment = NULL;
				rsa_fingerprint(buf, sizeof(buf),
						&state->key);
				state->key.comment = savecomment;

				SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
				/*
				 * Construct a decimal representation
				 * of the key, for pasting into
				 * .ssh/authorized_keys on a Unix box.
				 */
				setupbigedit1(hwnd, IDC_KEYDISPLAY,
					      IDC_PKSTATIC, &state->key);
			    } else {
				char *fp;
				char *savecomment;

				state->ssh2 = TRUE;
				state->commentptr =
				    &state->ssh2key.comment;
				state->ssh2key = *newkey2;	/* structure copy */
				sfree(newkey2);

				savecomment = state->ssh2key.comment;
				state->ssh2key.comment = NULL;
				fp =
				    state->ssh2key.alg->
				    fingerprint(state->ssh2key.data);
				state->ssh2key.comment = savecomment;

				SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
				sfree(fp);

				setupbigedit2(hwnd, IDC_KEYDISPLAY,
					      IDC_PKSTATIC, &state->ssh2key);
			    }
			    SetDlgItemText(hwnd, IDC_COMMENTEDIT,
					   *state->commentptr);
			}
			/*
			 * Finally, hide the progress bar and show
			 * the key data.
			 */
			hidemany(hwnd, nokey_ids, TRUE);
			hidemany(hwnd, generating_ids, TRUE);
			hidemany(hwnd, gotkey_ids, FALSE);
			state->key_exists = TRUE;
		    }
		}
	    }
	    break;
	}
	return 0;
      case WM_DONEKEY:
	state = (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	state->generation_thread_exists = FALSE;
	state->key_exists = TRUE;
	SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
			   MAKELPARAM(0, PROGRESSRANGE));
	SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, PROGRESSRANGE, 0);
	EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
	EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
	EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
	EnableWindow(GetDlgItem(hwnd, IDC_SAVEPUB), 1);
	EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH1), 1);
	EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2RSA), 1);
	EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2DSA), 1);
	EnableWindow(GetDlgItem(hwnd, IDC_BITS), 1);
	if (state->ssh2) {
	    if (state->is_dsa) {
		state->ssh2key.data = &state->dsskey;
		state->ssh2key.alg = &ssh_dss;
	    } else {
		state->ssh2key.data = &state->key;
		state->ssh2key.alg = &ssh_rsa;
	    }
	    state->commentptr = &state->ssh2key.comment;
	} else {
	    state->commentptr = &state->key.comment;
	}
	/*
	 * Invent a comment for the key. We'll do this by including
	 * the date in it. This will be so horrifyingly ugly that
	 * the user will immediately want to change it, which is
	 * what we want :-)
	 */
	*state->commentptr = smalloc(30);
	{
	    time_t t;
	    struct tm *tm;
	    time(&t);
	    tm = localtime(&t);
	    if (state->is_dsa)
		strftime(*state->commentptr, 30, "dsa-key-%Y%m%d", tm);
	    else
		strftime(*state->commentptr, 30, "rsa-key-%Y%m%d", tm);
	}

	/*
	 * Now update the key controls with all the key data.
	 */
	{
	    char *savecomment;
	    /*
	     * Blank passphrase, initially. This isn't dangerous,
	     * because we will warn (Are You Sure?) before allowing
	     * the user to save an unprotected private key.
	     */
	    SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT, "");
	    SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT, "");
	    /*
	     * Set the comment.
	     */
	    SetDlgItemText(hwnd, IDC_COMMENTEDIT, *state->commentptr);
	    /*
	     * Set the key fingerprint.
	     */
	    savecomment = *state->commentptr;
	    *state->commentptr = NULL;
	    if (state->ssh2) {
		char *fp;
		fp = state->ssh2key.alg->fingerprint(state->ssh2key.data);
		SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
		sfree(fp);
	    } else {
		char buf[128];
		rsa_fingerprint(buf, sizeof(buf), &state->key);
		SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
	    }
	    *state->commentptr = savecomment;
	    /*
	     * Construct a decimal representation of the key, for
	     * pasting into .ssh/authorized_keys or
	     * .ssh/authorized_keys2 on a Unix box.
	     */
	    if (state->ssh2) {
		setupbigedit2(hwnd, IDC_KEYDISPLAY,
			      IDC_PKSTATIC, &state->ssh2key);
	    } else {
		setupbigedit1(hwnd, IDC_KEYDISPLAY,
			      IDC_PKSTATIC, &state->key);
	    }
	}
	/*
	 * Finally, hide the progress bar and show the key data.
	 */
	hidemany(hwnd, nokey_ids, TRUE);
	hidemany(hwnd, generating_ids, TRUE);
	hidemany(hwnd, gotkey_ids, FALSE);
	break;
      case WM_HELP:
        if (help_path) {
            int id = ((LPHELPINFO)lParam)->iCtrlId;
            char *cmd = NULL;
            switch (id) {
              case IDC_GENERATING:
              case IDC_PROGRESS:
              case IDC_GENSTATIC:
              case IDC_GENERATE:
                cmd = "JI(`',`puttygen.generate')"; break;
              case IDC_PKSTATIC:
              case IDC_KEYDISPLAY:
                cmd = "JI(`',`puttygen.pastekey')"; break;
              case IDC_FPSTATIC:
              case IDC_FINGERPRINT:
                cmd = "JI(`',`puttygen.fingerprint')"; break;
              case IDC_COMMENTSTATIC:
              case IDC_COMMENTEDIT:
                cmd = "JI(`',`puttygen.comment')"; break;
              case IDC_PASSPHRASE1STATIC:
              case IDC_PASSPHRASE1EDIT:
              case IDC_PASSPHRASE2STATIC:
              case IDC_PASSPHRASE2EDIT:
                cmd = "JI(`',`puttygen.passphrase')"; break;
              case IDC_LOADSTATIC:
              case IDC_LOAD:
                cmd = "JI(`',`puttygen.load')"; break;
              case IDC_SAVESTATIC:
              case IDC_SAVE:
                cmd = "JI(`',`puttygen.savepriv')"; break;
              case IDC_SAVEPUB:
                cmd = "JI(`',`puttygen.savepub')"; break;
              case IDC_TYPESTATIC:
              case IDC_KEYSSH1:
              case IDC_KEYSSH2RSA:
              case IDC_KEYSSH2DSA:
                cmd = "JI(`',`puttygen.keytype')"; break;
              case IDC_BITSSTATIC:
              case IDC_BITS:
                cmd = "JI(`',`puttygen.bits')"; break;
            }
            if (cmd) {
                WinHelp(hwnd, help_path, HELP_COMMAND, (DWORD)cmd);
                requested_help = TRUE;
            } else {
                MessageBeep(0);
            }
        }
        break;
      case WM_CLOSE:
	state = (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
	sfree(state);
        if (requested_help) {
            WinHelp(hwnd, help_path, HELP_QUIT, 0);
            requested_help = FALSE;
        }
	EndDialog(hwnd, 1);
	return 0;
    }
    return 0;
}
Example #14
0
int main(int argc,char* argv[]) {
    time_t timestamp, current;
    int i,j,k;
    int a,n;
    char *pc;

    FILE *input_file;
    FILE *output_file;
    FILE* log_file=stderr;

    bamFile bam_input;
    bam_header_t *header;
    bam1_t* b;
    bam1_core_t *c;


    char cps_file_name[MAXFILEBUFFLENGTH]="";
    char bam_file_name[MAXFILEBUFFLENGTH]="";
    char out_file_name[MAXFILEBUFFLENGTH]="";
    char log_file_name[MAXFILEBUFFLENGTH]="";

    char buff[MAXFILEBUFFLENGTH];
    char chr[MAXFILEBUFFLENGTH];
    int beg, beg_prev, end, pos, offset; 
    int ref_id, ref_id_prev, label;
    int s, side;
    int read_type, mapped_strand;
    char ch;

    int limit_counts = 0;

    int* contig_count[2];
    int* contig_index[2];
    splice_site** contig_sites[2];

    long int n_reads[N_READ_TYPES][2];

    long int n_total_reads = 0;
    long int n_skipped_reads = 0;

    int max_intron_length=0;
    int min_intron_length=0;
    int ignore_gene_labels = 0;
    int stranded = 1;
    int rev_compl[2] = {1,0};

    int other_end, the_end, donor_id, acceptor_id;

    int *cigar;
    int flagged = 0;
    int margin = 4;


    /** reading input from the command line **/

    timestamp = time(NULL);

    if(argc==1) {
	fprintf(stderr, "BAM2SSJ is the utility for fast counting reads covering splice junctions\nCommand line use:\n");
        fprintf(stderr, "%s -cps <cps_file> -bam <bam_file> [-out <out_file>] [-log <log_file>] [-maxlen <max_intron_length>] [-minlen <min_intron_length>] [-margin <length>] ",argv[0]);
	fprintf(stderr, "[-v suppress verbose output] [-read1 0/1] [-read2 0/1] [-g ignore gene labels] [-u unstranded] [-f count reads flagged 0x800 only]\ntype %s -h for more info\n",argv[0]);
        exit(1);
    }

    for(i=1;i<argc;i++) {
        pc = argv[i];
        if(*pc == '-') {
            if(strcmp(pc+1,"cps") == 0) sscanf(argv[++i], "%s", &cps_file_name[0]);
	    if(strcmp(pc+1,"bam") == 0) sscanf(argv[++i], "%s", &bam_file_name[0]);
	    if(strcmp(pc+1,"out") == 0) sscanf(argv[++i], "%s", &out_file_name[0]);
            if(strcmp(pc+1,"log") == 0) sscanf(argv[++i], "%s", &log_file_name[0]);

            if(strcmp(pc+1,"read1") == 0) sscanf(argv[++i], "%i", &rev_compl[0]);
            if(strcmp(pc+1,"read2") == 0) sscanf(argv[++i], "%i", &rev_compl[1]);

	    if(strcmp(pc+1,"lim") == 0) sscanf(argv[++i], "%i", &limit_counts);
	    if(strcmp(pc+1,"minlen") == 0) sscanf(argv[++i], "%i", &min_intron_length);
	    if(strcmp(pc+1,"maxlen") == 0) sscanf(argv[++i], "%i", &max_intron_length);
	    if(strcmp(pc+1,"margin") == 0) sscanf(argv[++i], "%i", &margin);

	    if(strcmp(pc+1,"v") == 0) verbose = 0;
	    if(strcmp(pc+1,"g") == 0) ignore_gene_labels = 1;
	    if(strcmp(pc+1,"u") == 0) stranded = 0;
	    if(strcmp(pc+1,"f") == 0) flagged = 1;

	    if(strcmp(pc+1,"h") ==0 ) {
		fprintf(stderr, "Input:  (1) sorted BAM file\n");
		fprintf(stderr, "\t(2) CPS (chromosome-position-strand) tab-delimited file sorted by position (chr1 100 + etc)\n\n");
        	fprintf(stderr, "\tIn order to get CPS file from gtf, use the utility gtf2cps.sh\n");
        	fprintf(stderr, "\tImportant: CPS must be sorted by position ONLY!\n\n");
        	fprintf(stderr, "\tIf the 4th column contains (a numeric) gene label then only splice junctions within the same gene will be considered (unless the '-g' option is active)\n");
		fprintf(stderr, "\tThe utility to generate CPS with gene labels is gtf2cps_with_gene_id.sh (or update the script accordingly if you are using genome other than human)\n\n");
		fprintf(stderr, "Options:\n");
        	fprintf(stderr, "\t-maxlen <upper limit on intron length>; 0 = no limit (default=%i)\n",max_intron_length);
		fprintf(stderr, "\t-minlen <lower limit on intron length>; 0 = no limit (default=%i)\n",min_intron_length);
		fprintf(stderr, "\t-margin <length> minimum number of flanking nucleotides in the read in order to support SJ or cover EB, (default=%i)\n",margin);
        	fprintf(stderr, "\t-read1 0/1, reverse complement read1 no/yes (default=%i)\n",rev_compl[0]);
        	fprintf(stderr, "\t-read2 0/1, reverse complement read2 no/yes (default=%i)\n",rev_compl[1]);
        	fprintf(stderr, "\t-g ignore gene labels (column 4 of cps), default=%s\n", ignore_gene_labels ? "ON" : "OFF");
        	fprintf(stderr, "\t-u ignore strand (all reads map to the correct strand), default=%s\n", stranded ? "OFF" : "ON");
		fprintf(stderr, "\t-f count only reads that are flagged 0x800 (uniquely mapped reads), default=%s\n", flagged ? "ON" : "OFF");
		fprintf(stderr, "Output: tab-delimited  (default=stdout)\n");
        	fprintf(stderr, "\tColumn 1 is splice_junction_id\n");
        	fprintf(stderr, "\tColumns 2-6 are counts of 53, 5X, X3, 50, and 03 reads for the correct (annotated) strand\n");
        	fprintf(stderr, "\tColumns 7-11 are similar counts for the incorrect (opposite to annotated) strand\n");
		fprintf(stderr, "Descriptive read statistics are reported to stderr\n");
		exit(1);
	    }
	}
    }

    if(log_file_name[0]==0) {
	log_file = stderr;
    }
    else {
	log_file = fopen(log_file_name,"w");
	if(log_file == NULL) log_file = stderr;
    }

    if(bam_file_name[0]==0) {
	fprintf(log_file,"Bam not specified, exiting\n");
	exit(1); 
    }

    if(cps_file_name[0]==0) {
        fprintf(log_file,"Input not specified, exiting\n");
        exit(1);
    }

    if(out_file_name[0]==0) {
	fprintf(log_file,"[Warning: output set to stdout]\n");
	output_file = stdout;
    }
    else {
	output_file = fopen(out_file_name,"w");
	if(output_file == NULL) {
	    fprintf(log_file,"[Warning: output set to stdout]\n");
            output_file = stdout;
	}
    }

    if(max_intron_length>0) {
	if(verbose) fprintf(log_file,"[Warning: set max intron length=%i]\n",max_intron_length);
    }

    if(ignore_gene_labels) {
	if(verbose) fprintf(log_file,"[Warning: ignoring gene labels (column 4)]\n");
    }

    if(flagged) {
	if(verbose) fprintf(log_file,"[Warning: only look at reads flagged 0x800]\n");
    }

    if(margin>0) {
	if(verbose) fprintf(log_file,"[Warning: read margin set to %i]\n", margin);
    }

    if(verbose) {
	for(s = 0; s < 2; s++) if(rev_compl[s]) fprintf(log_file,"[Warning: take reverse complement of read %i]\n", s+1);
	fprintf(log_file,"[Warning: stranded = %s]\n", stranded ? "TRUE" : "FALSE (always correct strand)");
	if(ignore_gene_labels) fprintf(log_file,"[Warning: ignore gene labels (column 4)]\n");
    }


    for(i = 0; i < N_READ_TYPES; i++) for(s = 0; s < 2; s++) n_reads[i][s] = 0;

    /** initatializing BAM and header **/
   
    bam_input = bam_open(bam_file_name, "r");
    header = bam_header_read(bam_input);

    if(bam_input == NULL || header == NULL) {
        fprintf(log_file,"BAM can't be opened or contains no header, exiting\n");
        exit(1);
    }

    /** reading input from CPS **/

    input_file = fopen(cps_file_name, "r");
    if(input_file == NULL) {
	fprintf(log_file,"CPS can't be opened, exiting\n");
        exit(1);
    }

    /** populating gene structure arrays **/

    for(s = 0; s < 2; s++) {
    	contig_count[s] = (int*) malloc(sizeof(int) * (header->n_targets + ARRAY_MARGIN));
    	contig_index[s] = (int*) malloc(sizeof(int) * (header->n_targets + ARRAY_MARGIN));
    	contig_sites[s] = (splice_site**) malloc(sizeof(splice_site*) * (header->n_targets + ARRAY_MARGIN));

    	if(contig_count[s] == NULL || contig_sites[s] == NULL || contig_index[s] == NULL) {
	    fprintf(log_file, "Not enought memory, exiting\n");
            exit(1);
    	}
    }

    for(s = 0; s < 2; s++)
        for(i=0; i < header->n_targets; i++) 
	    contig_count[s][i] = contig_index[s][i] = 0;

    if(verbose) fprintf(log_file, "Reading %s pass1", cps_file_name);
    while(fgets(buff, MAXFILEBUFFLENGTH, input_file)) {
	sscanf(buff, "%s %*i %c", &chr[0], &ch);
	bam_parse_region(header, chr, &i, &beg, &end);
	s = (ch == '+' ? 0 : 1);
	if(i < header->n_targets && i>=0) contig_count[s][i]++;
    }

    for(s = 0; s < 2; s++) {
    	for(i = 0;i < header->n_targets; i++) {
	    contig_sites[s][i] = (splice_site*) malloc(sizeof(splice_site) * (contig_count[s][i] + ARRAY_MARGIN));
	    if(contig_sites[s][i] == NULL) {
	    	fprintf(log_file, "Not enought memory, exiting\n");
            	exit(1);
	    }
	}
    }
    if(verbose) fprintf(log_file, "\n");

    if(verbose) fprintf(log_file, "Reading %s pass2",cps_file_name);
    fseek(input_file, 0, SEEK_SET);
    while(fgets(buff, MAXFILEBUFFLENGTH, input_file)) {
        sscanf(buff, "%s %i %c %i", &chr[0], &pos, &ch, &label);
	bam_parse_region(header, chr, &i, &beg, &end);
	s = (ch == '+' ? 0 : 1);
	if(i < header->n_targets && i>=0) {
	    if(contig_index[s][i]>0) {
		if(pos < contig_sites[s][i][contig_index[s][i]-1].pos) {
		    fprintf(log_file, "Splice sites weren't sorted, exiting\n");
		    exit(1);
		}
	    }
	    contig_sites[s][i][contig_index[s][i]].pos = pos;
	    contig_sites[s][i][contig_index[s][i]].label = ignore_gene_labels ? 0 : label;
	    for(side = 0; side < 2; side++) {
                contig_sites[s][i][contig_index[s][i]].count00[side] = 0;
                contig_sites[s][i][contig_index[s][i]].count5X[side] = 0;
                contig_sites[s][i][contig_index[s][i]].countX3[side] = 0;
		contig_sites[s][i][contig_index[s][i]].junctions = NULL;
	    }
	    contig_index[s][i]++;
	}
    }
    if(verbose) fprintf(log_file, "\n");

    for(s = 0; s < 2; s++)
    	for(i = 0;i < header->n_targets; i++) 
	    contig_index[s][i] = 0;

    /** analysis starts here **/

    b = bam_init1();
    k = 0;
    ref_id_prev = -1;
    beg_prev = -1;
    while(bam_read1(bam_input, b)>=0) {
        c   = &b->core;
	ref_id = c->tid;
	if(ref_id<0) continue;

	if(flagged && ((c->flag & 0x800) == 0)) {
	    n_skipped_reads++;
	    continue;
	}

        if(stranded && ((c->flag & BAM_FREAD1) && (c->flag & BAM_FREAD2) || !(c->flag & BAM_FREAD1) && !(c->flag & BAM_FREAD2))) {
            n_skipped_reads++;
            continue;
        }

        cigar = bam1_cigar(b);

	if(ref_id != ref_id_prev  && ref_id_prev >= 0) {
	    if(contig_index[0][ref_id_prev] + contig_index[1][ref_id_prev] < contig_count[0][ref_id_prev] + contig_count[1][ref_id_prev]) {
		if(log_file==stderr) progressbar(1, 1, header->target_name[ref_id_prev], verbose);
	    }
	    beg_prev = -1;
	}

	/*if(ref_id < ref_id_prev) {
	    fprintf(log_file,"BAM file wasn't sorted, exiting\n");
            exit(1);
	}*/

	ref_id_prev = ref_id;

	beg = c->pos + 1;
	if(beg < beg_prev) {
	    fprintf(log_file,"BAM file wasn't sorted, exiting\n");
	    exit(1);
	}
	beg_prev = beg;

	s = ((c->flag & BAM_FREVERSE)>0);
	mapped_strand = (c->flag & BAM_FREAD1) ? (s + rev_compl[0]) & 1 : (s + rev_compl[1]) & 1;

	the_end = bam_calend(c, cigar);

	for(s = 0; s < 1 + stranded; s++) {
            end = beg;
	    side = (s == mapped_strand) ? 0 : 1;
	    side *= stranded;

	    // keep reading until the currect site is on the same chromosome downstream of the read 

	    while(contig_sites[s][ref_id][contig_index[s][ref_id]].pos < beg && contig_index[s][ref_id] < contig_count[s][ref_id]) {
		contig_index[s][ref_id]++;
	    	if(log_file==stderr) progressbar(contig_index[0][ref_id]+contig_index[1][ref_id], contig_count[0][ref_id]+contig_count[1][ref_id], header->target_name[ref_id], verbose);
	    }

	    read_type = RT_OTHER;

            if(contig_index[s][ref_id]<contig_count[s][ref_id]) {
	    	// check if the read is a split read and find its other end
	    	read_type = RT_GENOME;
            	for(i = 0; i < c->n_cigar; i++) {
	    	    offset = cigar[i] >> 4;
	    	    switch(cigar[i] & 0x0F) {
		    	case BAM_CMATCH: 	end += offset;  // match to the reference
					 	break;
		    	case BAM_CINS:		end += 0;	// insertion to the reference, pointer stays unchanged
						break;
		    	case BAM_CDEL:		end += offset;	// deletion from the reference (technically the same as 'N') pointer moves
						break; 
		    	case BAM_CREF_SKIP:	other_end = end + offset;
						donor_id = acceptor_id = -INFTY;
						if(end - beg < margin) break;
						if(the_end - other_end < margin) break;
						for(j = contig_index[s][ref_id]; contig_sites[s][ref_id][j].pos <= other_end && j < contig_count[s][ref_id];j++) {
						    if(contig_sites[s][ref_id][j].pos - end < min_intron_length && min_intron_length > 0) continue;
						    if(contig_sites[s][ref_id][j].pos - end > max_intron_length && max_intron_length > 0) break;
					    	    if(contig_sites[s][ref_id][j].label == contig_sites[s][ref_id][contig_index[s][ref_id]].label) {
					    	    	if(contig_sites[s][ref_id][j].pos == end - 1)   donor_id = j;
					    	    	if(contig_sites[s][ref_id][j].pos == other_end) acceptor_id = j;
					    	    }
					    	}
						if(donor_id>0 && acceptor_id>0) {
					    	    update_count(&contig_sites[s][ref_id][donor_id].junctions, acceptor_id, side);
					    	    contig_sites[s][ref_id][donor_id].count5X[side]++;
                                            	    contig_sites[s][ref_id][acceptor_id].countX3[side]++;
					    	    read_type = RT_KJUNCT;
						}
						else {
					    	    read_type = RT_UJUNCT;
						}
						end = other_end;
				 		break;
		    	case BAM_CSOFT_CLIP:
		    	case BAM_CHARD_CLIP:
		    	case BAM_CPAD:		break;
		    	default:		read_type = RT_OTHER;
	    	    }
            	}

	    	if(read_type == RT_GENOME) {
	            for(j=contig_index[s][ref_id]; beg + margin <= contig_sites[s][ref_id][j].pos  && contig_sites[s][ref_id][j].pos < end - margin && j<contig_count[s][ref_id]; j++) {
		    	contig_sites[s][ref_id][j].count00[side]++;
		    	read_type = RT_OVRLAP;
		    	k++;
	    	    }
	    	}
	    }

	    n_reads[read_type][side]++;
	}
	n_total_reads++;

	if(k>limit_counts && limit_counts>0) break;

    }
Example #15
0
void
raytrace(int im, inputPars *par, struct grid *g, molData *m, image *img){
  int *counta, *countb,nlinetot,aa;
  int ichan,px,iline,tmptrans,i,threadI,nRaysDone;
  double size,minfreq,absDeltaFreq;
  double cutoff;
  const gsl_rng_type *ranNumGenType = gsl_rng_ranlxs2;

  gsl_rng *ran = gsl_rng_alloc(ranNumGenType);	/* Random number generator */
#ifdef TEST
  gsl_rng_set(ran,178490);
#else
  gsl_rng_set(ran,time(0));
#endif

  gsl_rng **threadRans;
  threadRans = malloc(sizeof(gsl_rng *)*par->nThreads);

  for (i=0;i<par->nThreads;i++){
    threadRans[i] = gsl_rng_alloc(ranNumGenType);
    gsl_rng_set(threadRans[i],(int)gsl_rng_uniform(ran)*1e6);
  }

  size=img[im].distance*img[im].imgres;

  /* Determine whether there are blended lines or not */
  lineCount(par->nSpecies, m, &counta, &countb, &nlinetot);
  if(img[im].doline==0) nlinetot=1;

  /* Fix the image parameters */
  if(img[im].freq < 0) img[im].freq=m[0].freq[img[im].trans];
  if(img[im].nchan == 0 && img[im].bandwidth>0){
    img[im].nchan=(int) (img[im].bandwidth/(img[im].velres/CLIGHT*img[im].freq));
  } else if (img[im].velres<0 && img[im].bandwidth>0){
    img[im].velres = img[im].bandwidth*CLIGHT/img[im].freq/img[im].nchan;
  } else img[im].bandwidth = img[im].nchan*img[im].velres/CLIGHT * img[im].freq;

  if(img[im].trans<0){
    iline=0;
    minfreq=fabs(img[im].freq-m[0].freq[iline]);
    tmptrans=iline;
    for(iline=1;iline<m[0].nline;iline++){
      absDeltaFreq=fabs(img[im].freq-m[0].freq[iline]);
      if(absDeltaFreq<minfreq){
        minfreq=absDeltaFreq;
        tmptrans=iline;
      }
    }
  } else tmptrans=img[im].trans;

  cutoff = par->minScale*1.0e-7;

  for(px=0;px<(img[im].pxls*img[im].pxls);px++){
    for(ichan=0;ichan<img[im].nchan;ichan++){
      img[im].pixel[px].intense[ichan]=0.0;
      img[im].pixel[px].tau[ichan]=0.0;
    }
  }

  nRaysDone=0;
  omp_set_dynamic(0);
  #pragma omp parallel private(px,aa,threadI) num_threads(par->nThreads)
  {
    threadI = omp_get_thread_num();

    /* Declaration of thread-private pointers */
    rayData ray;
    ray.intensity=malloc(sizeof(double) * img[im].nchan);
    ray.tau=malloc(sizeof(double) * img[im].nchan);

    #pragma omp for
    /* Main loop through pixel grid */
    for(px=0;px<(img[im].pxls*img[im].pxls);px++){
      #pragma omp atomic
      ++nRaysDone;

      for(aa=0;aa<par->antialias;aa++){
        ray.x = size*(gsl_rng_uniform(threadRans[threadI])+px%img[im].pxls)-size*img[im].pxls/2.;
        ray.y = size*(gsl_rng_uniform(threadRans[threadI])+px/img[im].pxls)-size*img[im].pxls/2.;

        traceray(ray, tmptrans, im, par, g, m, img, nlinetot, counta, countb, cutoff);

        #pragma omp critical
        {
          for(ichan=0;ichan<img[im].nchan;ichan++){
            img[im].pixel[px].intense[ichan] += ray.intensity[ichan]/(double) par->antialias;
            img[im].pixel[px].tau[ichan] += ray.tau[ichan]/(double) par->antialias;
          }
        }
      }
    }
    if (threadI == 0){ // i.e., is master thread
      if(!silent) progressbar((double)(nRaysDone)/(double)(img[im].pxls*img[im].pxls-1), 13);
    }

    free(ray.tau);
    free(ray.intensity);
  } // end of parallel block.

  img[im].trans=tmptrans;

  free(counta);
  free(countb);
  for (i=0;i<par->nThreads;i++){
    gsl_rng_free(threadRans[i]);
  }
  free(threadRans);
  gsl_rng_free(ran);
}
Example #16
0
int clientsocket(char * addrs, int portnum)
{
	SOCKET sockfd;
	ZeroMemory(&sockfd, sizeof(sockfd));
	WSADATA wsaData;
	ZeroMemory(&wsaData, sizeof(wsaData));
	struct sockaddr_in addr;
	ZeroMemory(&addr, sizeof(addr));
	
	int str_len = 0;

	FILE *fp = NULL; //์ด๋ฏธ์ง€๋ฅผ ํŒŒ์ผ๋กœ ์ €์žฅ.

	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR)
	{
		return 1;
	}

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
	{
		return 1;
	}

	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(addrs); //์„œ๋ฒ„ ์ฃผ์†Œ string์œผ๋กœ ์ž…๋ ฅ
	addr.sin_port = htons(portnum); //ํฌํŠธ๋ฒˆํ˜ธ ์ž…๋ ฅ

	int recvTimeout = 3000;  // 3์ดˆ.
	if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char*)&recvTimeout, sizeof(recvTimeout)) != 0)
		return -1;
	
	if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
	{
		cout << "์ฃผ์†Œ์ž…๋ ฅ์—๋Ÿฌ!" << endl;
		MessageBox(NULL, "์ฃผ์†Œ๋ฅผ ํ™•์ธํ•˜๊ณ  ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”!", "์ฃผ์†Œํ™•์ธ!", MB_ICONINFORMATION);
		return -1;
	}
	else {
		printf("์„œ๋ฒ„์™€ ์—ฐ๊ฒฐ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!!\n");
	}
	char *p_get = 0;
	if (cases == 0) {
		p_get = "GET / HTTP/1.1\r\n\r\n";
	}
	else if (cases == 1) {
		printf("CGI.... GO!!\n");
		if (temp_port2 == 8677)
			p_get = "GET / HTTP/1.1\r\n\r\n"; //ํšจ๊ทผ๋‹˜
		else if(temp_port2 == 8090)
			p_get = "GET /index2.html HTTP/1.1\r\n\r\n"; //์žฌ๋ฏผ๋‹˜
		else if(temp_port2 == 8979)
			p_get = "GET /pic.html HTTP/1.1\r\n\r\n"; //๊ฒฝ๋ฏธ๋‹˜

		//p_get = "GET /hello.html HTTP/1.1\r\n\r\n"; //ํšจ๋ฒ”๋‹˜
		//p_get = "GET /home/ismean21/webserver/webServer_singleThread/calendar.html HTTP/1.1\r\n\r\n"; //์œ ๋ฏผ๋‹˜
	}

	if (cases == 2) {//jpg request message
		//printf("query_jpg_real : %s \n", query_jpg_real);
		//p_get = "GET /cup.bmp HTTP/1.1\r\n\r\n";
		send(sockfd, query_jpg, strlen(query_jpg), 0); //์—ฌ๊ธฐ์„œ ๋ฉ”์‹œ์ง€ ์š”์ฒญํ•˜๊ณ 
		recv(sockfd, rbuf, MAXLEN, 0);
		//printf("%s", rbuf);
		/*๊ฒฝ๋ฏธ๋‹˜*/
		if (temp_port2 == 8979) {
			recv(sockfd, rbuf, 44, 0);
			printf("%s", rbuf);
		}

		printf("GET IMAGE.... GO!!\n");
		if(fp==NULL)
			fp = fopen(image_file_name, "wb"); //rb๋กœ ํ•ด์•ผํ•จ
	}
	else {
		send(sockfd, p_get, strlen(p_get), 0); //์—ฌ๊ธฐ์„œ ๋ฉ”์‹œ์ง€ ์š”์ฒญํ•˜๊ณ 
	}
	char temp[TEMP_SIZE]; //์ž„์‹œ๋กœ ๊ฐ’์„ ์ €์žฅํ•  ๋ฐฐ์—ด ํฐ ํฌ๊ธฐ ํ• ๋‹น.
	int Pos = 0;
	memset(temp, 0x00, TEMP_SIZE);
	//temp = (char*)malloc(MAXLEN*sizeof(char));
	while (1) { //์—ฌ๊ธฐ์„œ ๋ฐ›๋Š”๋‹ค.
		memset(rbuf, 0x00, MAXLEN);
		str_len = recv(sockfd, rbuf, MAXLEN, 0); //NULL์ด ์•„๋‹ ๋•Œ๊นŒ์ง€ ์—ฌ๊ธฐ์„œ ๊ณ„์† ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ๋ฉ”์‹œ์ง€ ์ผ๋‹จ ๋ฐ›์Œ
		Pos += 5;
		if(Pos<80) //์—ฌ๊ธฐ์„œ๋Š” ๋๊นŒ์ง€ ๋ณด์—ฌ์ฃผ์ง€ ์•Š์Œ 
			progressbar(Pos);
		bufsize += str_len;
		if (str_len <= 0)
			break;
		if (cases == 2) {
			fwrite(rbuf, str_len, 1, fp);
		}
		else {
			printf("%s\n", rbuf);
			strncat(temp,rbuf,str_len);
		}
		//temp = (char*)realloc(temp, bufsize + (bufsize*sizeof(char)));
		str_len = 0;
	}
	if (cases == 2) {
		if(fp!=NULL)
		fclose(fp); //ํŒŒ์ผ ๋‹ซ์•„์ฃผ๊ธฐ
		image_exist = 1; //์ด๋ฏธ์ง€๋ฅผ ๋ฐ›๊ณ  ์žˆ๋‹ค๊ณ  ํ‘œ์‹œํ•ด ์ค˜์•ผํ•จ(๋ˆ„๋ฅด๊ณ )
		printf("jpg case ๋ฉ”๋ชจ๋ฆฌ ํ•ด์ œ\n");
		//delete[]query_jpg_real;
		//delete []image_file_name;
		closesocket(sockfd);
		memset(temp, 0x00, TEMP_SIZE);
		printf("total bufsize : %d\n", bufsize);
		progressbar(100);
		bufsize = 0;
		cases = 0;
	}
	else {
		closesocket(sockfd);
		parser(temp);
		memset(temp, 0x00, TEMP_SIZE);
		printf("total bufsize : %d\n", bufsize);
		progressbar(100);
		bufsize = 0;
	}
	progressbar(0);
	return 0;
}
Example #17
0
int main(int argc, char* argv[]) {
    char alnfilename[MAXBUFFLENGTH];
    char cpsfilename[MAXBUFFLENGTH];
    char outfilename[MAXBUFFLENGTH]="";
 
    char c;

    char buff[MAXBUFFLENGTH];
    char aux[MAXBUFFLENGTH];

    int start1,end1,len1,start2,end2,len2;
    char strand1, strand2;

    int a,b,k,l,i,j,s,m,q;
    int d,dmin,lmin,score_max;
    int x,y;

    int qbest, kbest, jbest;
    int kprev;

    int *gene_idx;	//index
    int *gene_off;	//offset  
    int *gene_site;	//site number
    char *gene_styp;	//site type
    int *gene_pos;	//site position
    int *gene_chr;	//chromosome
    char *gene_str;	//strand

    int max_genes;
    int max_sites;

    int *site_idx;	//index
    int *site_off;	//offset
    int *site_chr;	//matching chromosome
    int *site_pos;	//matching pos
    int *site_str;	//matching strand
    int *site_score;	//--- optimal score
    int *site_lbest;    //--- where it came from
    int *site_qbest;    //--- where it came from

    int specific_site=0;

    double dthreshold = 0.50;
    int dlimit = 5000;
    int max_depth = 4;

    int pos, strand;

    if(argc==1) {
	fprintf(stderr,"Select best unique maping from the ALN file created by map_single\n");
        fprintf(stderr,"Last updated by Dmitri Pervouchine ([email protected]) on Jan 28, 2013\n");
	fprintf(stderr,"Keys:\n -in <cps file>\n -aln <aln file>\n -out <output file>\n");
 	//fprintf(stderr," -l length difference limit [%i]\n -t percentage difference threshold [%1.2lf] (ONE OR THE OTHER THRESHOLD IS USED)\n -h max_depth [%i]\n",dlimit, dthreshold,max_depth);
	//fprintf(stderr," -v suppress verbose output [NO]\n");
	exit(1);
    }

    timestamp_set();
    for(i=1;i<argc;i++) {
        if(strcmp(argv[i],"-in")==0) {
            sscanf(argv[++i], "%s", &cpsfilename[0]);
        }
        if(strcmp(argv[i],"-aln")==0) {
            sscanf(argv[++i], "%s", &alnfilename[0]);
        }
        if(strcmp(argv[i],"-out")==0) {
            sscanf(argv[++i], "%s", &outfilename[0]);
        }
        if(strcmp(argv[i],"-lendiff")==0) {
            sscanf(argv[++i], "%i", &dlimit);
        }
        if(strcmp(argv[i],"-threshold")==0) {
            sscanf(argv[++i], "%lf", &dthreshold);
        }
        if(strcmp(argv[i],"-maxdepth")==0) {
            sscanf(argv[++i], "%i", &max_depth);
        }
        if(strcmp(argv[i],"-quiet")==0) {
            verbose=0;
        }
        if(strcmp(argv[i],"-s")==0) {
            sscanf(argv[++i], "%i", &specific_site);
        }
    }

    if(outfilename[0]==0) {
        fprintf(stderr,"[WARNING: output file not specified, redirect to stdout]\n");
        outfile = stdout;
    }
    else {
        outfile = fopen(outfilename,"w");
        if(outfile == NULL) {
            fprintf(stderr,"[ERROR: output file (%s) cannot be opened, exiting]\n", outfilename);
            exit(1);
        }
    }

/*******************************************************************************************************/
    cpsfile= fopen(cpsfilename,"r");
    if(cpsfile==NULL) {
	fprintf(stderr,"Can't access CPS file. Exiting\n");
	exit(1);
    }

    if(verbose) fprintf(stderr,"[Reading CPS, pass 0");
    max_sites = max_genes = 0;
    while(fgets(buff,MAXBUFFLENGTH,cpsfile)) {
      	if(strlen(buff)<2) break;
        sscanf(buff,"%*s %*i %*i %i %i", &i, &j);
        if(i>max_genes) max_genes = i;
	if(j>max_sites) max_sites = j;
    }

    max_genes++;
    max_sites++;

    gene_idx = (int*)  malloc(sizeof(int)*(max_genes+1));
    gene_off = (int*)  malloc(sizeof(int)*(max_genes+1));
    gene_chr = (int*)  malloc(sizeof(int)*(max_genes+1));
    gene_str = (char*) malloc(sizeof(char)*(max_genes+1));

    for(i=0;i<max_genes;i++) gene_idx[i]=gene_off[i]=0;

    if(verbose) fprintf(stderr,", max_genes = %i, max_sites = %i]\n", max_genes, max_sites);

    if(verbose) fprintf(stderr,"[Reading CPS, pass 1");
    fseek (cpsfile, 0, SEEK_SET);
    while(fgets(buff,MAXBUFFLENGTH,cpsfile)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%s %*i %i %i %*i" , aux, &strand, &i);
        gene_idx[i]++;
	gene_chr[i] = assign_code(aux);
	gene_str[i] = strand;
    }

    for(s=i=0;i<max_genes;i++) {
        x = gene_idx[i];
        gene_idx[i] =s;
        s+=x;
    }
    gene_idx[i] = s;

    gene_site = (int*)  malloc(sizeof(int)*(s+1));
    gene_styp = (char*) malloc(sizeof(char)*(s+1));
    gene_pos  = (int*)  malloc(sizeof(int)*(s+1));

    if(verbose) fprintf(stderr,", records = %i]\n", s);

    if(verbose) fprintf(stderr,"[Reading CPS, pass 2");
    fseek (cpsfile, 0, SEEK_SET);
    while(fgets(buff,MAXBUFFLENGTH,cpsfile)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%*s %i %*i %i %i %c" , &x, &i, &j, &c);
	gene_site[gene_idx[i]+gene_off[i]]=j;
        gene_styp[gene_idx[i]+gene_off[i]]=c;
        gene_pos[gene_idx[i]+gene_off[i]]=x;
	gene_off[i]++;
    }
    fclose(cpsfile);
    if(verbose) fprintf(stderr,"]\n");
/**********************************************************************************************/

    alnfile = fopen(alnfilename,"r");
    if(alnfile == NULL) {
	fprintf(stderr, "Cant open alignment file, exiting\n");
	exit(1);
    }

    site_idx = (int*) malloc(sizeof(int)*(max_sites+1));
    site_off = (int*) malloc(sizeof(int)*(max_sites+1));

    for(i=0;i<max_sites;i++) {
        site_idx[i]=site_off[i]=0;
    }

    if(verbose) fprintf(stderr,"[Reading alignment file, pass 1");

    while(fgets(buff,MAXBUFFLENGTH,alnfile)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%*s %*i %*i %*s %*i %*i %*i %i %*c" , &i);
	site_idx[i]++;
    }

    for(s=i=0;i<max_sites;i++) {
        x = site_idx[i];
        site_idx[i] =s;
        s+=x;
    }
    site_idx[i] = s;

    site_chr   = (int*) malloc(sizeof(int)*(s+1));
    site_pos   = (int*) malloc(sizeof(int)*(s+1));
    site_str   = (int*) malloc(sizeof(int)*(s+1));
    site_score = (int*) malloc(sizeof(int)*(s+1));
    site_lbest = (int*) malloc(sizeof(int)*(s+1));
    site_qbest = (int*) malloc(sizeof(int)*(s+1));

    if(verbose) fprintf(stderr,", records = %i]\n",s);

    if(verbose) fprintf(stderr,"[Reading alignment file, pass 2");
    fseek (alnfile, 0, SEEK_SET);
    while(fgets(buff,MAXBUFFLENGTH,alnfile)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%*s %*i %*i %s %i %i %*i %i %*c" , &aux, &pos, &strand, &i);
	site_chr[site_idx[i]+site_off[i]] = assign_code(aux);
        site_pos[site_idx[i]+site_off[i]] = pos;
        site_str[site_idx[i]+site_off[i]] = strand;
	site_score[site_idx[i]+site_off[i]] = 0;
        site_lbest[site_idx[i]+site_off[i]] = -1;
        site_qbest[site_idx[i]+site_off[i]] = -1;
	site_off[i]++;
    }
    fclose(alnfile);
    if(verbose) fprintf(stderr,"]\n");

    for(i=0;i<max_genes;i++) {
	progressbar(i,max_genes-1, (char*)"Processing");
	score_max=0;
	kbest = -1;
	for(j=gene_idx[i];j<gene_idx[i+1];j++) {
	    x = gene_site[j];
	    for(k=site_idx[x];k<site_idx[x+1];k++) {
		site_score[k] = 0;
		site_lbest[k] = site_qbest[k] = -1;
	    }
	    for(q=1;q<=max_depth;q++) {
            	if(j-q>=gene_idx[i]) {
                    y = gene_site[j-q];
	   	    a = abs(gene_pos[j]-gene_pos[j-q]);
		    for(k=site_idx[x];k<site_idx[x+1];k++) {
			dmin = INFTY;
			lmin = -1;
			for(l=site_idx[y];l<site_idx[y+1];l++) {
			    if(site_chr[k] == site_chr[l] && site_str[k] == site_str[l]) {
			    	b = abs(site_pos[k]-site_pos[l]);
				d = abs(b-a);
				if(d<dmin) {
				    dmin = d;
				    lmin = l;
				}
				if(x==specific_site) fprintf(stderr,"[prev=%i curr=%i pos_p=%i pos_c=%i d=%i]\n",y,x,site_pos[l],site_pos[k],d);
			    }
			}
			m  = (lmin>=0 && (((double)dmin/a)<dthreshold || dmin<dlimit)) ? site_score[lmin] + a : 0;			
			if(m>site_score[k]) {
			    site_score[k] = m;
			    site_lbest[k] = lmin;
                            site_qbest[k] = q;
			}
			if(site_score[k]>score_max) {
			    score_max = site_score[k];
			    kbest = k; jbest = j;
			}
			if(x==specific_site) fprintf(stderr,"[curr=%i score=%i]\n",x,site_score[k]);
		    }
		}
	    }
	}
	j = jbest;
	k = kbest;
	if(k>=0 && site_score[k]>0) {
	    fprintf(outfile,"%s\t%i\t%i\t%s\t%i\t%i\t",get_chr_name(gene_chr[i]),gene_pos[j],gene_str[i],get_chr_name(site_chr[k]),site_pos[k],site_str[k]);
	    fprintf(outfile,"%i\t%i\t%c\t%i\t%i\n",i,gene_site[j],gene_styp[j],site_pos[site_lbest[k]],0);
	    while(site_score[k]>0 && site_lbest[k]>=0 && site_qbest[k]>=0) {
		kprev = k;
            	j = j - site_qbest[k];
                k = site_lbest[k];
 		fprintf(outfile,"%s\t%i\t%i\t%s\t%i\t%i\t",get_chr_name(gene_chr[i]),gene_pos[j],gene_str[i],get_chr_name(site_chr[k]),site_pos[k],site_str[k]);
		fprintf(outfile,"%i\t%i\t%c\t%i\t%i\n",i,gene_site[j],gene_styp[j],(site_lbest[k]>=0?site_pos[site_lbest[k]]:0),(kprev>=0?site_pos[kprev]:0));
	    }
 
	}
    }
    timestamp_report();
    exit(0);
}
int main(int argc, char **argv) {
    struct sysinfo info;
    struct sigaction mysig;
    int i,rv=0;
    float duration_f, loops_per_sec;
    unsigned long free_mem, mapsize;

    basename=strrchr(argv[0],'/');
    if (basename) basename++; else basename=argv[0];

    /* Calculate default values */
    /* Get processor count. */
    num_cpus = sysconf(_SC_NPROCESSORS_CONF);
    /* Ensure we have at least two threads per CPU */
    if (num_cpus*2 > default_threads)
        default_threads = num_cpus*2;
    /* Get memory info */
    if (sysinfo(&info) != 0) { perror("sysinfo"); return -1; }
    free_mem=(info.freeram+info.bufferram)*info.mem_unit;
    total_ram=info.totalram*info.mem_unit;
    /* default to using most of free_mem */
    default_memsize = free_mem * DEFAULT_MEMPCT; 
    
    /* Set configurable values to reasonable defaults */
    runtime = default_runtime;
    num_threads = default_threads;
    memsize = default_memsize;
    
    /* parse options */
    while ((i = getopt(argc,argv,"hvqpt:n:m:")) != -1) {
        switch (i) {
            case 'h':
                usage();
                return 0;
            case 'v':
                verbose=1;
                break;
            case 'q':
                quiet=1;
                break;
            case 'p':
                parallel=1;
                break;
            case 't':
                runtime=atoi(optarg);
                if (!runtime) {
                    printf("%s: error: bad runtime \"%s\"\n",basename,optarg);
                    return 1;
                }
                break;
            case 'n':
                num_threads=atoi(optarg);
                if (!num_threads) {
                    printf("%s: error: bad thread count \"%s\"\n",basename,optarg);
                    return 1;
                }
                break;
            case 'm':
                memsize=parse_memsize(optarg);
                if (!memsize) {
                    printf("%s: error: bad memory size \"%s\"\n",basename,optarg);
                    return 1;
                }
                break;
        }
    }

    /* calculate mapsize now that memsize/num_threads is set */
    mapsize = memsize/num_threads;
    /* sanity checks */
    if (num_threads < num_cpus)
        printf("Warning: num_threads < num_cpus. This isn't usually a good idea.\n");
    if (memsize > free_mem)
        printf("Warning: memsize > free_mem. You will probably hit swap.\n");
    /* A little information */
    if (verbose) {
        printf("Detected %u processors.\n",num_cpus);
        printf("RAM: %.1f%% free (%s/",
                100.0*(double)free_mem/(double)total_ram,
                human_memsize(free_mem));
        printf("%s)\n",human_memsize(total_ram));
    }

    printf("Testing %s RAM for %u seconds using %u threads:\n",
            human_memsize(memsize),runtime,num_threads);
    
    /* Allocate room for thread info */
    threads=(pthread_t *)malloc(num_threads*sizeof(pthread_t));
    mmap_regions=(char **)malloc(num_threads*sizeof(char *));
    loop_counters=(unsigned long *)malloc(num_threads*sizeof(unsigned long *));

    /* Create all our threads! */
    while (created_threads < num_threads) {
        pthread_mutex_lock(&mmap_mutex);
        mmap_done=0;
        if (pthread_create(&threads[created_threads],NULL,
                    mem_twiddler,(void*)&mapsize) != 0) {
            perror("pthread_create"); exit(1);
        }
        /* Wait for it to finish initializing */
        while (!mmap_done) { pthread_cond_wait(&mmap_cond,&mmap_mutex); }
        pthread_mutex_unlock(&mmap_mutex);
        if (!verbose && !quiet) 
            progressbar("Starting threads",created_threads,num_threads);
    }

    if (parallel) {
        /* Wait for the signal that everyone is finished initializing */        
        pthread_mutex_lock(&init_mutex);
        while (live_threads < num_threads) { pthread_cond_wait(&init_cond,&init_mutex); }
        pthread_mutex_unlock(&init_mutex);
    }
    
    /* Let the testing begin! */
    if (!verbose && !quiet) printf("\n");
    gettimeofday(&start,NULL);
    pthread_cond_broadcast(&test_start);

    /* catch ^C signal */
    mysig.sa_handler=int_handler;
    sigemptyset(&mysig.sa_mask);
    mysig.sa_flags=0;
    sigaction(SIGINT,&mysig,NULL);

    /* Wait for the allotted time */
    i=0;
    while (!done && (i<runtime)) {
        if (sleep(1) == 0) i++;
        if (!quiet) progressbar("Testing RAM",i,runtime);
    }
    if (i != runtime)
        rv=1;
    
    /* Signal completion and join all threads */
    done=1;
    while (live_threads) {
        pthread_join(threads[live_threads-1],NULL);
        live_threads--;
    }
    gettimeofday(&finish,NULL);
    if (!quiet) printf("\n");
    /* Test is officially complete. Calculate run speed. */
    timersub(&finish,&start,&duration);
    duration_f=(float)duration.tv_sec + (float)duration.tv_usec / 1000000.0;
    loops_per_sec=0;
    if (verbose) printf("Runtime was %.2fs\n",duration_f);
    for (i=0;i<num_threads;i++) {
        if (verbose) printf("thread %i: %lu loops\n",i,loop_counters[i]);
        loops_per_sec += (float)loop_counters[i]/duration_f;
    }
    printf("Total loops per second: %.2f\n",loops_per_sec);
    
    /* All done. Return success. */
    printf("Testing complete.\n");
    return rv;
}
Example #19
0
int main(int argc, char* argv[]) {
    char cps_file_name[MAXBUFFLENGTH];
    char chain_file_name[MAXBUFFLENGTH];
    char out_file_name[MAXBUFFLENGTH]="";
 
    int marginlength = 0;

    char buff[MAXBUFFLENGTH+1];
    char aux[MAXBUFFLENGTH+1];

    long score;
    int start1,end1,len1,start2,end2,len2;
    char strand1, strand2, chr1[MAXBUFFLENGTH], chr2[MAXBUFFLENGTH];

    int *size, *dq, *dt;
    int a,b,k,i,j,s,m,x;

    int *position;
    int *strand;
    int *idg;
    int *ids;
    char *type;
    char c;

    int chridx[MAXCHR+1];
    int chroff[MAXCHR+1];

    char resstr;
    int  rescrd;
    long chain_id;


    if(argc==1) {
        fprintf(stderr,"This utility does liftOver of coordinates (cps) by  using chain alignment\n");
        fprintf(stderr,"Gene information is included in the output\n");
        fprintf(stderr,"Last update by Dmitri Pervouchine ([email protected]) on Mar 22, 2013\n");
        fprintf(stderr,"Usage: %s -in <cps_file> -chain <chain_alignment_file> [-margin <length>] [-quiet]\n", argv[0]);
        fprintf(stderr," -in cps6, i.e. chr1/position1/strand1/gene/site/type tab-delimited file, strand is +/-\n");
        fprintf(stderr," -chain UCSC chain alignment file, species1=>2\n");
        fprintf(stderr," -out <output_file> [default=stdout]\n");
        fprintf(stderr," -margin margin length [default=0]\n -quiet suppress verbose output [default=NO]\n");
	fprintf(stderr,"NOTE: Input has to be sorted by position!\n");
        fprintf(stderr,"Output format cps3+cps6: chr1/position1/strand1/chr2/position2/strand2/gene/site/type/score\n");
        exit(1);
    }

    timestamp_set();
    for(i=1;i<argc;i++) {
	if(strcmp(argv[i],"-in")==0) {
	   sscanf(argv[++i], "%s", &cps_file_name[0]);
	}
	if(strcmp(argv[i],"-chain")==0) {
	   sscanf(argv[++i], "%s", &chain_file_name[0]);
	}
	if(strcmp(argv[i],"-out")==0) {
           sscanf(argv[++i], "%s", &out_file_name[0]);
        }
	if(strcmp(argv[i],"-margin")==0) {
           sscanf(argv[++i], "%i", &marginlength);
        }
	if(strcmp(argv[i],"-quiet")==0) {
	   verbose=0;
	} 
    }

    if(out_file_name[0]==0) {
	fprintf(stderr,"[WARNING: output file not specified, redirect to stdout]\n");
	out_file = stdout;
    }
    else {
    	out_file = fopen(out_file_name,"w");
    	if(out_file == NULL) {
	    fprintf(stderr,"[ERROR: output file %s cannot be opened for writing, exiting]\n", out_file_name);
	    exit(1);
	}
	if(verbose) fprintf(stderr,"[>%s]\n",out_file_name);
    }

    cps_file= fopen(cps_file_name,"r");
    if(cps_file==NULL) {
	fprintf(stderr,"[ERROR: cannot access %s, exiting]\n", cps_file_name);
	exit(1);
    }

    for(i=0;i<MAXCHR;i++) chridx[i] = chroff[i] = 0;

    if(verbose) fprintf(stderr,"[<%s, pass 1",cps_file_name);
    while(fgets(buff,MAXBUFFLENGTH,cps_file)) {
        if(strlen(buff)<2) break;
      	sscanf(buff,"%s" , aux);
      	chridx[assign_code(aux)]++;
    }
    if(verbose) fprintf(stderr,"]\n");

    for(s=i=0;i<MAXCHR;i++) {
        x = chridx[i];
	chridx[i] =s;
	s+=x;
    }
    chridx[i] = s;

    position   = (int*) malloc(sizeof(int)*(s + ARRAY_MARGIN));
    strand     = (int*) malloc(sizeof(int)*(s + ARRAY_MARGIN));
    ids        = (int*) malloc(sizeof(int)*(s + ARRAY_MARGIN));
    idg        = (int*) malloc(sizeof(int)*(s + ARRAY_MARGIN));
    type       = (char*) malloc(sizeof(char)*(s + ARRAY_MARGIN));

    if(position==NULL || strand==NULL || type==NULL || ids==NULL || idg==NULL) {
        fprintf(stderr,"[ERROR: failed to create index tables, exiting]\n");
        exit(1);
    }

    fseek (cps_file, 0, SEEK_SET);
    if(verbose) fprintf(stderr,"[<%s, pass 2", cps_file_name);
    while(fgets(buff,MAXBUFFLENGTH,cps_file)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%s" , aux);
        i = assign_code(aux);
        m = chridx[i]+chroff[i];
        sscanf(buff,"%*s %i %c %i %i %c" , &position[m], &c,&idg[m],&ids[m],&type[m]);
	strand[m] = strand_c2i(c);
        chroff[i]++;
    }
    fclose(cps_file);
    if(verbose) fprintf(stderr,"]\n");


    if(verbose) fprintf(stderr,"[Sort by position (if not done before)");
    for(i=0;i<MAXCHR;i++) {
        k=1;
        while(k) {
            k=0;
            for(j=chridx[i];j<chridx[i+1]-1;j++) {
                if(position[j]>position[j+1]) {
                    k=1;
                    swapi(position+j,position+j+1);
                    swapi(strand+j,strand+j+1);
		    swapi(idg+j,idg+j+1);
		    swapi(ids+j,ids+j+1);
		    swapc(type+j,type+j+1);
                }
            }
        }
    }
    if(verbose) fprintf(stderr,"]\n");


/**********************************************************************************************/
    size = (int*) malloc(sizeof(int)*(MAXALN + ARRAY_MARGIN));
    dq   = (int*) malloc(sizeof(int)*(MAXALN + ARRAY_MARGIN));
    dt   = (int*) malloc(sizeof(int)*(MAXALN + ARRAY_MARGIN));

    if(size ==0 || dq ==0 || dt==0) {
        fprintf(stderr,"[ERROR: not enough memory for chains, exiting]\n");
        exit(1);
    }


/**********************************************************************************************/

    chain_file = fopen(chain_file_name,"r");
    if(chain_file==NULL) {
	fprintf(stderr,"[ERROR: cannot access %s, exiting]\n", chain_file_name);
	exit(1);
    }

    fseek(chain_file, 0, SEEK_END);
    unsigned int last_pos = ftell(chain_file);
    fseek(chain_file, 0, SEEK_SET);

    while(fgets(buff,MAXBUFFLENGTH,chain_file)) {
        if(strlen(buff)<2) break;
     	buff[5]=0;
     	if(strcmp(buff,"chain")==0) {
       	    sscanf(buff+6,"%li %s %i %c %i %i %s %i %c %i %i %li",&score, &chr1[0], &len1, &strand1, &start1, &end1, &chr2[0], &len2, &strand2, &start2, &end2, &chain_id);
	    k=0;
	    while(fgets(buff,MAXBUFFLENGTH,chain_file)) {
		if(strlen(buff)<2) break;
		progressbar(ftell(chain_file), last_pos-1, (char*)"Processing ", verbose);
	    	sscanf(buff,"%i %i %i",size + k, dt + k, dq + k);
	    	k++;
	    	if(k>=MAXALN) {
		    fprintf(stderr,"[ERROR: chain too long, exiting]\n");
		    exit(1);
	    	}
	    }

	    x = get_chr_code(chr1);
	    if(x<0) continue;

            a=start1;b=start2;
            j=0;

	    for(i=chridx[x];i<chridx[x+1] && position[i]<start1;i++);
	    for(;i<chridx[x+1]&& position[i]<end1;i++) {
	    	while(position[i]>a+size[j]+dt[j] && j<k){
		    a+=size[j]+dt[j];
		    b+=size[j]+dq[j];
		    j++;
	    	}
	        if(j>=k) break;
	        if(position[i]-a > marginlength && a+size[j]-position[i] >= marginlength) {
                    if(strand1==strand2) {
                    	resstr = strand[i];
                    	rescrd = position[i] - a + b;
                    }
                    else {
                    	resstr = -strand[i];
                    	rescrd = len2 - (position[i] - a + b - 1) ;
                    }
                    fprintf(out_file,"%s\t%i\t%c\t%s\t%i\t%c\t%i\t%i\t%c\t%li\n",chr1, position[i], strand_i2c(strand[i]), chr2, rescrd, strand_i2c(resstr), idg[i], ids[i],type[i],score);
	    	}
	    }
     	}
    }
    fclose(chain_file);
    fclose(out_file);
    timestamp_report();

    free(size);
    free(dq);
    free(dt);

    free(position);
    free(strand);
    exit(0);
}
Example #20
0
//Creates a list of times which the aubio onset detector thinks are note onset times for the audio Denemo->si->recording
//Result is placed in Denemo->si->note_onsets
void
generate_note_onsets (void)
{
    DenemoRecording *audio = Denemo.project->movement->recording;
    gint channels = audio->channels;

    smpl_t threshold = 0.3;
    smpl_t silence = -90.;
    uint_t buffer_size = 1024;
    uint_t overlap_size = 512;

    uint_t samplerate = 44100;

    aubio_onset_t *o = new_aubio_onset("default",
                                       buffer_size, overlap_size, samplerate);
    fvec_t *ibuf = new_fvec (overlap_size);
    fvec_t *onset = new_fvec (2);

    unsigned int pos = 0;         /*frames%dspblocksize */
    unsigned int i;               /*channels */
    unsigned int j;               /*frames */

    busy_cursor (Denemo.notebook);
    gtk_window_set_modal (progressbar (_("Analysing Audio"), NULL), TRUE);

    rewind_audio ();
    if (audio->notes)
    {
        g_list_free_full (audio->notes, g_free);
        audio->notes = NULL;
    }
    for (j = 0; j < (unsigned) audio->nframes; j++)
    {
        sf_read_float (audio->sndfile, ibuf->data + pos, 2);   //g_debug("\t%f", ibuf->data[0][pos]);
        if (pos == overlap_size - 1)
        {
            /* block loop */
            gtk_main_iteration_do (FALSE);
            aubio_onset_do (o, ibuf, onset);
            while (gtk_events_pending ())
                gtk_main_iteration ();
            if(onset->data[0] != 0) {
                DenemoRecordedNote *note = g_malloc0(sizeof(DenemoRecordedNote));
                note->timing = aubio_onset_get_last(o);/* aubio_onset_get_delay_s(o) for seconds */
                audio->notes = g_list_append (audio->notes, note);
            }
            pos = -1;             /* so it will be zero next j loop */
        }                       /* end of if pos==overlap_size-1 */
        pos++;
    }

    del_aubio_onset (o);
    del_fvec (ibuf);
    del_fvec (onset);
    aubio_cleanup ();











    progressbar_stop ();
    normal_cursor (Denemo.notebook);
}
Example #21
0
int clientsocket(char * addrs, int portnum)
{
	SOCKET sockfd;
	ZeroMemory(&sockfd, sizeof(sockfd));
	WSADATA wsaData;
	ZeroMemory(&wsaData, sizeof(wsaData));
	struct sockaddr_in addr;
	ZeroMemory(&addr, sizeof(addr));
	
	int str_len = 0;

	FILE *fp_imagefile = NULL; //์ด๋ฏธ์ง€๋ฅผ ํŒŒ์ผ๋กœ ์ €์žฅ.
	FILE *fp_recvlog = NULL;

	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR)
	{
		return -1;
	}

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
	{
		return -1;
	}

	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(addrs); //์„œ๋ฒ„ ์ฃผ์†Œ string์œผ๋กœ ์ž…๋ ฅ
	addr.sin_port = htons(portnum); //ํฌํŠธ๋ฒˆํ˜ธ ์ž…๋ ฅ

	int recvTimeout =3000;  // 3์ดˆ.
	if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char*)&recvTimeout, sizeof(recvTimeout)) != 0)
		return -1;
	
	if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
	{
		wow = TEXT("์ ‘์† ์—๋Ÿฌ!\n ์„œ๋ฒ„๊ฐ€ ์‘๋‹ตํ•˜์ง€ ์•Š๊ฑฐ๋‚˜ ์—†๋Š” ์ฃผ์†Œ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ํ™•์ธํ•ด์ฃผ์„ธ์š”.");
		MessageBox(NULL, TEXT("์„œ๋ฒ„๊ฐ€ ์‘๋‹ตํ•˜์ง€ ์•Š๊ฑฐ๋‚˜ ์—†๋Š” ์ฃผ์†Œ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ํ™•์ธํ•ด์ฃผ์„ธ์š”."), TEXT("์ ‘์† ์—๋Ÿฌ!"), MB_ICONINFORMATION);
		cases = 0; //์ดˆ๊ธฐํ™” ํ•ด ์ฃผ์–ด์•ผ ํ•œ๋‹ค.
		return -1;
	}

	char *p_get = "GET / HTTP/1.1\r\n\r\n"; //๊ธฐ๋ณธ ๋„์ด์—ˆ๋˜ ๋ฌธ์ œ ์žˆ์—ˆ์Œ

	if (cases == 1) {
		wprintf(TEXT("CGI.... GO!!\n"));
		if (temp_port2 == 8677)
			p_get = "GET / HTTP/1.1\r\n\r\n"; //ํšจ๊ทผ๋‹˜
		else if(temp_port2 == 8090)
			p_get = "GET /index2.html HTTP/1.1\r\n\r\n"; //์žฌ๋ฏผ๋‹˜
		else if(temp_port2 == 8777)
			p_get ="GET /hello.html HTTP/1.1\r\n\r\n"; //ํšจ๋ฒ”๋‹˜
		//p_get = "GET /home/ismean21/webserver/webServer_singleThread/calendar.html HTTP/1.1\r\n\r\n"; //์œ ๋ฏผ๋‹˜
	}

	if (cases == 2) {//jpg request message
		send(sockfd, query_jpg, strlen(query_jpg), 0); //์—ฌ๊ธฐ์„œ ๋ฉ”์‹œ์ง€ ์š”์ฒญํ•˜๊ณ 
		recv(sockfd, rbuf, MAXLEN, 0);

		wprintf(TEXT("GET IMAGE.... GO!!\n"));
		if (fp_imagefile == NULL) {
			fp_imagefile = _wfopen(image_file_name, TEXT("wb")); //rb๋กœ ํ•ด์•ผํ•จ
		}
	}
	else {
		send(sockfd, p_get, strlen(p_get), 0); //์—ฌ๊ธฐ์„œ ๋ฉ”์‹œ์ง€ ์š”์ฒญํ•˜๊ณ 
	}
	char temp[TEMP_SIZE]; //์ž„์‹œ๋กœ ๊ฐ’์„ ์ €์žฅํ•  ๋ฐฐ์—ด ํฐ ํฌ๊ธฐ ํ• ๋‹น.
	int Pos = 0;
	memset(temp, 0x00, TEMP_SIZE);
	
	if (fp_recvlog == NULL) {
		fp_recvlog = fopen("recv_log.txt", "w");
	}

	while (1) { //์—ฌ๊ธฐ์„œ ๋ฐ›๋Š”๋‹ค.
		memset(rbuf, 0x00, MAXLEN);
		str_len = recv(sockfd, rbuf, MAXLEN, 0); //NULL์ด ์•„๋‹ ๋•Œ๊นŒ์ง€ ์—ฌ๊ธฐ์„œ ๊ณ„์† ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ๋ฉ”์‹œ์ง€ ์ผ๋‹จ ๋ฐ›์Œ
		//printf("%s\n", rbuf); ์†๋„์ €ํ•˜
		Pos += 5;
		if(Pos<80) //์—ฌ๊ธฐ์„œ๋Š” ๋๊นŒ์ง€ ๋ณด์—ฌ์ฃผ์ง€ ์•Š์Œ 
			progressbar(Pos);
		bufsize += str_len;
		if (str_len <= 0)
			break;
		if (cases == 2) { //์ด๋ฏธ์ง€ ํŒŒ์ผ์ธ ๊ฒฝ์šฐ
			fwrite(rbuf, str_len, 1, fp_imagefile);
		}
		else {
			strncat(temp, rbuf,str_len);
		}
		str_len = 0;
	}
	fwrite(temp, TEMP_SIZE, 1, fp_recvlog);
	
	yMax = bufsize / 6;
	SetScrollRange(Main_hWnd, SB_VERT, 0, yMax, TRUE);
	SetScrollPos(Main_hWnd, SB_VERT, 0, TRUE);


	if (cases == 2) {
		if (fp_imagefile != NULL)
			fclose(fp_imagefile); //ํŒŒ์ผ ๋‹ซ์•„์ฃผ๊ธฐ
		image_exist = 1; //์ด๋ฏธ์ง€๋ฅผ ๋ฐ›๊ณ  ์žˆ๋‹ค๊ณ  ํ‘œ์‹œํ•ด ์ค˜์•ผํ•จ(๋ˆ„๋ฅด๊ณ )
		closesocket(sockfd);
		memset(temp, 0x00, TEMP_SIZE);
		wprintf(TEXT("total bufsize : %d"), bufsize);
		progressbar(100);
		bufsize = 0;
		cases = 0;
	}
	else {
		is_hyper_clicked_possible = 0;
		closesocket(sockfd);
		wchar_t* temp2 = new wchar_t[TEMP_SIZE];
		if (strstr(temp, "UTF-8") || strstr(temp, "utf-8"))
			MultiByteToWideChar(CP_UTF8, 0, temp, -1, temp2, strlen(temp)*sizeof(TCHAR)); //if utf-8 
		else
			MultiByteToWideChar(CP_ACP, 0, temp, -1, temp2, strlen(temp)*sizeof(TCHAR)); //CP_ACP IS The system default Windows ANSI code page.
		parser(temp2);
		memset(temp, 0x00, TEMP_SIZE);
		delete[] temp2;
		wprintf(TEXT("total bufsize : %d"), bufsize);
		progressbar(100);
		bufsize = 0;
	}
	progressbar(0);
	return 0;
}
Example #22
0
int clientsocket(char * addrs, int portnum)
{
	int str_len = 0;

	FILE *fp = NULL; //์ด๋ฏธ์ง€๋ฅผ ํŒŒ์ผ๋กœ ์ €์žฅ.

	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR)
	{
		return 1;
	}

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
	{
		return 1;
	}

	memset((void *)&addr, 0x00, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(addrs); //์„œ๋ฒ„ ์ฃผ์†Œ string์œผ๋กœ ์ž…๋ ฅ
	addr.sin_port = htons(portnum); //ํฌํŠธ๋ฒˆํ˜ธ ์ž…๋ ฅ
	int recvTimeout = 3000;  // 3์ดˆ.
	if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char*)&recvTimeout, sizeof(recvTimeout)) != 0)
		return -1;
	
	if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
	{
		cout << "์ฃผ์†Œ์ž…๋ ฅ์—๋Ÿฌ!" << endl;
		MessageBox(NULL, "์ฃผ์†Œ๋ฅผ ํ™•์ธํ•˜๊ณ  ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”!", "์ฃผ์†Œํ™•์ธ!", MB_ICONINFORMATION);
		return -1;
	}
	else {
		printf("์„œ๋ฒ„์™€ ์—ฐ๊ฒฐ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!!\n");
	}
	char *p_get = 0;
	if (cases == 0) {
		p_get = "GET / HTTP/1.1\r\n\r\n";
	}
	else if (cases == 1) {
		printf("CGI.... GO!!\n");
		//p_get = "GET /index2.html HTTP/1.1\r\n\r\n"; //์žฌ๋ฏผ๋‹˜
		p_get = "GET / HTTP/1.1\r\n\r\n"; //ํšจ๊ทผ๋‹˜
		//p_get = "GET /hello.html HTTP/1.1\r\n\r\n"; //ํšจ๋ฒ”๋‹˜
		//p_get = "GET /pic.html HTTP/1.1\r\n\r\n"; //๊ฒฝ๋ฏธ๋‹˜
		//p_get = "GET /home/ismean21/webserver/webServer_singleThread/calendar.html HTTP/1.1\r\n\r\n"; //์œ ๋ฏผ๋‹˜
	}

	if (cases == 2) {//jpg request message
		printf("query_jpg_real : %s \n", query_jpg_real);
		//p_get = "GET /cup.bmp HTTP/1.1\r\n\r\n";
		send(sockfd, query_jpg_real, strlen(query_jpg_real) + 1, 0); //์—ฌ๊ธฐ์„œ ๋ฉ”์‹œ์ง€ ์š”์ฒญํ•˜๊ณ 
		recv(sockfd, rbuf, MAXLEN, 0);
		printf("%s", rbuf);
		/*๊ฒฝ๋ฏธ๋‹˜*/
		//recv(sockfd, rbuf, 44, 0);
		//printf("%s", rbuf);

		printf("GET IMAGE.... GO!!\n");
		fp = fopen(image_file_name, "wb"); //rb๋กœ ํ•ด์•ผํ•จ
	}
	else {
		send(sockfd, p_get, strlen(p_get) + 1, 0); //์—ฌ๊ธฐ์„œ ๋ฉ”์‹œ์ง€ ์š”์ฒญํ•˜๊ณ 
	}

	int Pos = 0;

	while (1) { //์—ฌ๊ธฐ์„œ ๋ฐ›๋Š”๋‹ค.
		memset(rbuf, 0x00, MAXLEN + 1);
		str_len = recv(sockfd, rbuf, MAXLEN, 0); //NULL์ด ์•„๋‹ ๋•Œ๊นŒ์ง€ ์—ฌ๊ธฐ์„œ ๊ณ„์† ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ๋ฉ”์‹œ์ง€ ์ผ๋‹จ ๋ฐ›์Œ
		Pos += 5;
		if(Pos<80) //์—ฌ๊ธฐ์„œ๋Š” ๋๊นŒ์ง€ ๋ณด์—ฌ์ฃผ์ง€ ์•Š์Œ 
			progressbar(Pos);
		bufsize += str_len;
		if (str_len <= 0)
			break;
		if (cases == 2) {
			fwrite(rbuf, str_len, 1, fp);
		}
		else {
			strcat_s(temp, rbuf);
		}
		str_len = 0;
	}
	if (cases == 2) {
		fclose(fp); //ํŒŒ์ผ ๋‹ซ์•„์ฃผ๊ธฐ
		printf("jpg case ๋ฉ”๋ชจ๋ฆฌ ํ•ด์ œ\n");
		//delete[]query_jpg_real;
		//delete []image_file_name;
		closesocket(sockfd);
		printf("total bufsize : %d\n", bufsize);
		progressbar(100);
		bufsize = 0;
		cases = 0;
	}
	else {
		closesocket(sockfd);
		parser(temp);
		memset(temp, 0x00, 1000000);
		printf("total bufsize : %d\n", bufsize);
		progressbar(100);
		bufsize = 0;
	}
	progressbar(0);
	return 0;
}
Example #23
0
int main(int argc, char* argv[]) {
    char aln_file_name[MAXBUFFLENGTH];
    char out_file_name[MAXBUFFLENGTH]="";
 
    char buff[MAXBUFFLENGTH];
    char chr1[MAXBUFFLENGTH];
    char chr2[MAXBUFFLENGTH];

    double dthreshold = 1.50;
    int dlimit = 100000;
    int max_depth = 4;

    int** chr_t;
    int** str_t;
    int** pos_t;

    int* chr_q;
    int* str_q;
    int* pos_q;

    int **score;
    int **jbest;
    int **lbest;

    int a,b,d,dmin,lmin,s;
    char c,c1,c2;

    int *count;
    int *ptr;

    int max_rec=0;

    int pos1, pos2, str1, str2;
    int i, j, k, l, n;

    int s_max, k_max;

    if(argc==1) {
	fprintf(stderr,"This utility takes a non-unique mapping in cps3+cps3 format and does ad-hoc filtering of the projected coordinates by maximum synteny\n");
        fprintf(stderr,"Last update by Dmitri Pervouchine ([email protected]) on Mar 26, 2013\n");
        fprintf(stderr,"Usage: %s -in <aln_file> -out <output_file> [-maxdepth <int>] [-threshold <double>] [-lendiff <diff>] [-quiet]\n",argv[0]);
	fprintf(stderr," -in cps3+cps3 file, remember to sort by position in ascending order\n");
	fprintf(stderr," -out <output_file> [default=stdout]\n");
	fprintf(stderr," -maxdepth <integer> how many preceding positions can be skipped [default=%i]\n", max_depth);
	fprintf(stderr," -threshold <double> max change of segment length, in percent [default=%2.2lf]\n", dthreshold);
	fprintf(stderr," -lendiff <integer>, [default=%i]\n",dlimit);
	fprintf(stderr," -quiet suppress verbose output [default=NO]\n");
	fprintf(stderr,"Note: the mapping [x,x+dx] -> [y,y+dy] is OK if |dy-dx|/dx<threshold OR |dy-dx|<dlimit\n");
	exit(1);
    }

    timestamp_set();
    for(i=1;i<argc;i++) {
        if(strcmp(argv[i],"-in")==0) {
            sscanf(argv[++i], "%s", &aln_file_name[0]);
        }
        if(strcmp(argv[i],"-out")==0) {
            sscanf(argv[++i], "%s", &out_file_name[0]);
        }
        if(strcmp(argv[i],"-lendiff")==0) {
            sscanf(argv[++i], "%i", &dlimit);
        }
        if(strcmp(argv[i],"-threshold")==0) {
            sscanf(argv[++i], "%lf", &dthreshold);
        }
        if(strcmp(argv[i],"-maxdepth")==0) {
            sscanf(argv[++i], "%i", &max_depth);
        }
        if(strcmp(argv[i],"-quiet")==0) {
            verbose=0;
        }
    }

    if(out_file_name[0]==0) {
        fprintf(stderr,"[WARNING: output file not specified, redirect to stdout]\n");
        out_file = stdout;
    }
    else {
        out_file = fopen(out_file_name,"w");
        if(out_file == NULL) {
            fprintf(stderr,"[ERROR: output file (%s) cannot be opened, exiting]\n", out_file_name);
            exit(1);
        }
	if(verbose) fprintf(stderr,"[>%s]\n",out_file_name);
    }

/*******************************************************************************************************/
    aln_file= fopen(aln_file_name,"r");
    if(aln_file==NULL) {
        fprintf(stderr,"[ERROR: cannot access %s, exiting]\n", aln_file_name);
	exit(1);
    }

    if(verbose) fprintf(stderr,"[<%s, pass 1", aln_file_name);
    while(fgets(buff, MAXBUFFLENGTH, aln_file)) {
	if(strlen(buff)<2) break;
	max_rec++;
    }
    if(verbose) fprintf(stderr,"]\n");

    chr_q = (int*)malloc(sizeof(int)*(max_rec + ARRAY_MARGIN));
    str_q = (int*)malloc(sizeof(int)*(max_rec + ARRAY_MARGIN));
    pos_q = (int*)malloc(sizeof(int)*(max_rec + ARRAY_MARGIN));

    chr_t = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));
    str_t = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));
    pos_t = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));

    score = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));
    lbest = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));
    jbest = (int**)malloc(sizeof(int*)*(max_rec + ARRAY_MARGIN));

    count = (int*)malloc(sizeof(int)*(max_rec + ARRAY_MARGIN));
    ptr   = (int*)malloc(sizeof(int)*(max_rec + ARRAY_MARGIN));

    if(chr_q == NULL || str_q == NULL || pos_q == NULL || count == NULL || ptr == NULL || chr_t == NULL || str_t == NULL || pos_t == NULL) {
	fprintf(stderr,"[ERROR: not enough memory, exiting]\n");
	exit(1);
    }

    for(i=0;i<max_rec;i++) count[i] = ptr[i] = 0;

    if(verbose) fprintf(stderr,"[<%s, pass 2", aln_file_name);
    fseek (aln_file, 0, SEEK_SET);
    n=0;
    while(fgets(buff, MAXBUFFLENGTH, aln_file)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%s %i %c" , &chr1[0], &pos1, &c);
	str1 = strand_c2i(c);
	if(assign_code(chr1) != chr_q[n] || str1 != str_q[n] || pos1 != pos_q[n]) {
	    n++;
	    chr_q[n] = assign_code(chr1);
            str_q[n] = str1;
            pos_q[n] = pos1;
	}
	count[n]++;
    }
    if(verbose) fprintf(stderr,"]\n");

    for(i=1; i<=n; i++) {
        chr_t[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));
	pos_t[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));
        str_t[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));

	score[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));
	lbest[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));
        jbest[i] = (int*)malloc(sizeof(int)*(count[i] + ARRAY_MARGIN));

	if(chr_t[i] == NULL || str_t[i] == NULL || pos_t[i] == NULL) {
	    fprintf(stderr,"[ERROR: not enough memory, exiting]\n");
	    exit(1);
	}
    }

    if(verbose) fprintf(stderr,"[<%s, pass 3", aln_file_name);
    fseek (aln_file, 0, SEEK_SET);
    n=0;
    while(fgets(buff, MAXBUFFLENGTH, aln_file)) {
        if(strlen(buff)<2) break;
        sscanf(buff,"%s %i %c %s %i %c" , &chr1[0], &pos1, &c1, &chr2[0], &pos2, &c2);
	str1 = strand_c2i(c1);
	str2 = strand_c2i(c2);
	if(assign_code(chr1) != chr_q[n] || str1 != str_q[n] || pos1 != pos_q[n]) n++;
	chr_t[n][ptr[n]] = assign_code(chr2);
	pos_t[n][ptr[n]] = pos2;
	str_t[n][ptr[n]] = str2;
	ptr[n]++;
    }
    if(verbose) fprintf(stderr,"]\n");

    for(i=1; i<=n; i++) {
	progressbar(i, n, (char*)"Filtering ", verbose);
	for(k=0; k<count[i]; k++) {
	    score[i][k] = 0;
	    lbest[i][k] = -1;
	    jbest[i][k] = -1;
	    for(j=i-1; j>0 && i-j<=max_depth; j--) {
		a = abs(pos_q[i] - pos_q[j]);
                dmin = INFTY;
                lmin = -1;
		for(l=0; l<count[j]; l++) {
		    if(chr_t[i][k] == chr_t[j][l] && str_t[i][k]*str_t[j][l] == str_q[i]*str_q[j]) {
			b = abs(pos_t[i][k] - pos_t[j][l]);
                        d = abs(b-a);
                        if(d<dmin) {
                            dmin = d;
                            lmin = l;
                        }
                    }
                }
		s = (lmin>=0 && (((double)dmin/a) < dthreshold || dmin < dlimit)) ? score[j][lmin] + a : 0;
		if(s > score[i][k]) {
		    score[i][k] = s;
		    jbest[i][k] = j;
		    lbest[i][k] = lmin;
		} 
	    }
	}
    }
    
    for(i=n;i>0;i--) {
	s_max = 0;
	k_max = -1;
	for(k=0; k<count[i]; k++) {
	    if(score[i][k]>s_max) {
		s_max = score[i][k];
		k_max = k;
	    }
	}
	if(k_max>=0) {
	    k = k_max; 
	    while(jbest[i][k]>=0 && lbest[i][k]>=0) {
		fprintf(out_file,"%s\t%i\t%c\t", get_chr_name(chr_q[i]), pos_q[i], strand_i2c(str_q[i]));
		fprintf(out_file,"%s\t%i\t%c\n", get_chr_name(chr_t[i][k]), pos_t[i][k], strand_i2c(str_t[i][k]));
		j = jbest[i][k];
		l = lbest[i][k];
		i = j;
		k = l;
	    }
	}

    }
    timestamp_report();
    exit(0);
}
Example #24
0
int
main(int argc, const char * const argv[])
{
  int fd, fdout;
  size_t read_size, block_size;
  unsigned int i, begin_index;
  unsigned char *start, *end, *addr;
  size_t size;
  int page_size;
  off_t offset;
  const char *file_format;
  const char *dir_format;
  int c;

  read_size = 128 * 1024 * 1024;
  block_size = 512;
  begin_index = 0;
  file_format = "image%05d.jpg";
  dir_format = NULL;

  while ((c = getopt(argc, (char * const *) argv, "b:d:f:hi:m:qr:s:vV")) != -1) {
    switch (c) {
    case 'b':
      block_size = atol_suffix(optarg);
      break;
    case 'd':
      dir_format = optarg;
      break;
    case 'f':
      file_format = optarg;
      break;
    case 'i':
      begin_index = atoi(optarg);
      break;
    case 'm':
      max_size = atol_suffix(optarg);
      break;
    case 'q':
      quiet = 1;
      break;
    case 'r':
      read_size = atol_suffix(optarg);
      break;
    case 's':
      ignore_size = atol_suffix(optarg) - 1;
      break;
    case 'v':
      verbose = 1;
      break;
    case 'V':
      display_version_and_exit("recoverjpeg");
    default:
      usage(c == 'h');
    }
  }

  argc -= optind;
  argv += optind;

  if (argc != 1) {
    usage(0);
  }

  fd = open(argv[0], O_RDONLY);
  if (fd < 0) {
    fprintf(stderr,
	    "recoverjpeg: unable to open %s for reading (%s)\n",
	    argv[argc - 1], strerror(errno));
    exit(1);
  }

  page_size = getpagesize();
  if (read_size % page_size || read_size < max_size) {
    if (read_size < max_size) {
      read_size = max_size;
    }
    read_size = (read_size + page_size - 1) / page_size * page_size;
    if (!quiet) {
      fprintf(stderr, "Adjusted read size to %ld bytes\n", (long) read_size);
    }
  }

  start = end = (unsigned char *) malloc(read_size);
  if (start == 0) {
    fprintf(stderr,
	    "recoverjpeg: cannot allocate necessary memory (%s)\n",
	    strerror(errno));
    exit(1);
  }

  for (i = 0, offset = 0, addr = NULL; addr < end;) {

    if (progressbar()) {
      display_progressbar(offset, i);
    }

    if (addr == NULL || (size_t) (start + read_size - addr) < max_size) {
      off_t base_offset;
      long n;

      base_offset = offset / page_size * page_size;

      lseek(fd, base_offset, SEEK_SET);
      n = read(fd, start, read_size);
      if (n < 0) {
	fprintf(stderr, "recoverjpeg: unable to read data (%s)\n",
		strerror(errno));
	exit(1);
      }
      end = start + n;
      addr = start + (offset - base_offset);
    }

    size = jpeg_size(addr);
    if (size > ignore_size) {
      size_t n;

      const char *buffer = file_name(dir_format, file_format, begin_index + i);
      i++;
      if (verbose) {
	printf("%s %ld bytes\n", buffer, (long) size);
      }
      fdout = open(buffer, O_WRONLY | O_CREAT, 0666);
      if (fdout < 0) {
	fprintf(stderr, "Unable to open %s for writing\n", buffer);
	exit(1);
      }
      if ((size_t) write(fdout, addr, size) != size) {
	fprintf(stderr, "Unable to write %ld bytes to %s\n",
		(long) size, buffer);
	exit(1);
      }
      close(fdout);

      n = ((size + block_size - 1) / block_size) * block_size;
      addr += n;
      offset += n;
    }
    else {
      addr += block_size;
      offset += block_size;
    }
  }

  if (progressbar()) {
    cleanup_progressbar();
  }

  if (!quiet) {
    printf("Restored %d picture%s\n", i, i > 1 ? "s" : "");
  }

  /* Free allocated memory to keep valgrind happy */
  free(start);

  exit(0);
}
Example #25
0
int main(int argc, char *argv[])
{
  double        fps, k;
  int           i, width, height, len;
  CvCapture     *in;
  CvVideoWriter *out;
  IplImage      *bufimg;

  if (argc != 3)
    {
      ERROR("Usage: interpolation source destination");
      return EXIT_FAILURE;
    }

  in = cvCaptureFromFile(argv[1]);
  if (!in)
    {
      ERROR("Failed to open for reading '%s'", argv[1]);
      return EXIT_FAILURE;
    }

  fps = cvGetCaptureProperty(in, CV_CAP_PROP_FPS);
  if (fps > TARGET)
    {
      ERROR("Video already has a framerate of %.2f (target was %.2f)",
            fps, TARGET);
      return EXIT_FAILURE;
    }

  width = cvGetCaptureProperty(in, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(in, CV_CAP_PROP_FRAME_HEIGHT);
  len = cvGetCaptureProperty(in, CV_CAP_PROP_FRAME_COUNT);

  out = cvCreateVideoWriter(TMPFILE, CODEC, TARGET, cvSize(width, height), 1);
  if (!out)
    {
      ERROR("Failed to open for writing '%s'", TMPFILE);
      return EXIT_FAILURE;
    }

  k = TARGET / fps;
  bufimg = cvQueryFrame(in);
  for (i = 1; i < len; ++i)
    {
      IplImage *img;

      img = cvCloneImage(bufimg);
      bufimg = cvQueryFrame(in);
      progressbar(100 * i / len);

      if (interpolate(k, out, img, bufimg))
        return EXIT_FAILURE;

      cvReleaseImage(&img);
    }
  cvWriteFrame(out, bufimg);
  progressbar(0);

  cvReleaseVideoWriter(&out);
  cvReleaseCapture(&in);

  if (add_audio(argv[1], argv[2]))
    return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
Example #26
0
File: search.c Project: 111X/radare
static void search_alarm() {
	progressbar(nhit, config.seek, config.size);
#if __UNIX__
	go_alarm(search_alarm);
#endif
}
Example #27
0
s32 Wad_Install(FILE *fp)
{
	//////start the gui shit
	GuiWindow promptWindow(472,320);
	promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	promptWindow.SetPosition(0, -10);

	GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume);
	// because destroy GuiSound must wait while sound playing is finished, we use a global sound
	if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);
	//	GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);

	char imgPath[100];
	snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path);
	GuiImageData btnOutline(imgPath, button_dialogue_box_png);
	snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path);
	GuiImageData dialogBox(imgPath, dialogue_box_png);
	GuiTrigger trigA;
	trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);

	GuiImage dialogBoxImg(&dialogBox);
	if (Settings.wsprompt == yes){
	dialogBoxImg.SetWidescreen(CFG.widescreen);}

	GuiText btn1Txt(tr("OK"), 22, THEME.prompttext);
	GuiImage btn1Img(&btnOutline);
	if (Settings.wsprompt == yes){
	btn1Txt.SetWidescreen(CFG.widescreen);
	btn1Img.SetWidescreen(CFG.widescreen);}
	GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -35, &trigA, &btnSoundOver, btnClick2,1);
	btn1.SetLabel(&btn1Txt);
	btn1.SetState(STATE_SELECTED);

	snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", CFG.theme_path);
	GuiImageData progressbarOutline(imgPath, progressbar_outline_png);
	GuiImage progressbarOutlineImg(&progressbarOutline);
	if (Settings.wsprompt == yes){
	progressbarOutlineImg.SetWidescreen(CFG.widescreen);}
	progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
	progressbarOutlineImg.SetPosition(25, 50);

	snprintf(imgPath, sizeof(imgPath), "%sprogressbar_empty.png", CFG.theme_path);
	GuiImageData progressbarEmpty(imgPath, progressbar_empty_png);
	GuiImage progressbarEmptyImg(&progressbarEmpty);
	progressbarEmptyImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
	progressbarEmptyImg.SetPosition(25, 50);
	progressbarEmptyImg.SetTile(100);

	snprintf(imgPath, sizeof(imgPath), "%sprogressbar.png", CFG.theme_path);
	GuiImageData progressbar(imgPath, progressbar_png);
	GuiImage progressbarImg(&progressbar);
	progressbarImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
	progressbarImg.SetPosition(25, 50);

    char title[50];
   sprintf(title, "%s", tr("Installing wad"));
	GuiText titleTxt(title, 26, THEME.prompttext);
	titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
	titleTxt.SetPosition(0,40);
    char msg[50];
    sprintf(msg, " ");
	// sprintf(msg, "%s", tr("Initializing Network"));
	GuiText msg1Txt(NULL, 20, THEME.prompttext);
	msg1Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP);
	msg1Txt.SetPosition(50,75);
//	char msg2[50] = " ";
	GuiText msg2Txt(NULL, 20, THEME.prompttext);
	msg2Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP);
	msg2Txt.SetPosition(50, 98);

	GuiText msg3Txt(NULL, 20, THEME.prompttext);
	msg3Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP);
	msg3Txt.SetPosition(50, 121);

	GuiText msg4Txt(NULL, 20, THEME.prompttext);
	msg4Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP);
	msg4Txt.SetPosition(50, 144);

	GuiText msg5Txt(NULL, 20, THEME.prompttext);
	msg5Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP);
	msg5Txt.SetPosition(50, 167);

	GuiText prTxt(NULL, 26, THEME.prompttext);
	prTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	prTxt.SetPosition(0, 50);


	if ((Settings.wsprompt == yes) && (CFG.widescreen)){/////////////adjust for widescreen
		progressbarOutlineImg.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
		progressbarOutlineImg.SetPosition(0, 50);
		progressbarEmptyImg.SetPosition(80,50);
		progressbarEmptyImg.SetTile(78);
		progressbarImg.SetPosition(80, 50);

		msg1Txt.SetPosition(90,75);
		msg2Txt.SetPosition(90, 98);
		msg3Txt.SetPosition(90, 121);
		msg4Txt.SetPosition(90, 144);
		msg5Txt.SetPosition(90, 167);

	}
	promptWindow.Append(&dialogBoxImg);
	promptWindow.Append(&titleTxt);
	promptWindow.Append(&msg5Txt);
	promptWindow.Append(&msg4Txt);
	promptWindow.Append(&msg3Txt);
	promptWindow.Append(&msg1Txt);
	promptWindow.Append(&msg2Txt);

   //promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50);

	HaltGui();
	mainWindow->SetState(STATE_DISABLED);
	mainWindow->Append(&promptWindow);
	mainWindow->ChangeFocus(&promptWindow);
	//sleep(1);


	///start the wad shit
	bool fail = false;
	wadHeader   *header  = NULL;
	void		*pvoid;
	signed_blob *p_certs = NULL, *p_crl = NULL, *p_tik = NULL, *p_tmd = NULL;

	tmd *tmd_data  = NULL;

	u32 cnt, offset = 0;
	s32 ret = 666;


	ResumeGui();
	msg1Txt.SetText(tr(">> Reading WAD data..."));
	HaltGui();
#define SetPointer(a, p) a=(typeof(a))p
	// WAD header
	//ret = __Wad_ReadAlloc(fp, (void *)header, offset, sizeof(wadHeader));
	ret = __Wad_ReadAlloc(fp, &pvoid, offset, sizeof(wadHeader));

	if (ret < 0)
		goto err;
	SetPointer(header, pvoid);
	offset += round_up(header->header_len, 64);

	// WAD certificates
	//ret = __Wad_ReadAlloc(fp, (void *)&p_certs, offset, header->certs_len);
	ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->certs_len);
	if (ret < 0)
		goto err;
	SetPointer(p_certs, pvoid);
	offset += round_up(header->certs_len, 64);

	// WAD crl

	if (header->crl_len) {
		//ret = __Wad_ReadAlloc(fp, (void *)&p_crl, offset, header->crl_len);
		ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->crl_len);
		if (ret < 0)
			goto err;
		SetPointer(p_crl, pvoid);
		offset += round_up(header->crl_len, 64);
	}

	// WAD ticket
	//ret = __Wad_ReadAlloc(fp, (void *)&p_tik, offset, header->tik_len);
	ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->tik_len);
	if (ret < 0)
		goto err;
	SetPointer(p_tik, pvoid);
	offset += round_up(header->tik_len, 64);

	// WAD TMD
	//ret = __Wad_ReadAlloc(fp, (void *)&p_tmd, offset, header->tmd_len);
	ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->tmd_len);
	if (ret < 0)
		goto err;
	SetPointer(p_tmd, pvoid);
	offset += round_up(header->tmd_len, 64);

	ResumeGui();
	msg1Txt.SetText(tr("Reading WAD data... Ok!"));
	msg2Txt.SetText(tr(">> Installing ticket..."));
	HaltGui();
	// Install ticket
	ret = ES_AddTicket(p_tik, header->tik_len, p_certs, header->certs_len, p_crl, header->crl_len);
	if (ret < 0)
		goto err;

	ResumeGui();
	msg2Txt.SetText(tr("Installing ticket... Ok!"));
	msg3Txt.SetText(tr(">> Installing title..."));
	//WindowPrompt(">> Installing title...",0,0,0,0,0,200);
	HaltGui();
	// Install title
	ret = ES_AddTitleStart(p_tmd, header->tmd_len, p_certs, header->certs_len, p_crl, header->crl_len);
	if (ret < 0)
		goto err;

	// Get TMD info
	tmd_data = (tmd *)SIGNATURE_PAYLOAD(p_tmd);

	// Install contents
	//ResumeGui();
	//HaltGui();
	promptWindow.Append(&progressbarEmptyImg);
   promptWindow.Append(&progressbarImg);
   promptWindow.Append(&progressbarOutlineImg);
   promptWindow.Append(&prTxt);
	ResumeGui();
	msg3Txt.SetText(tr("Installing title... Ok!"));
	for (cnt = 0; cnt < tmd_data->num_contents; cnt++) {

		tmd_content *content = &tmd_data->contents[cnt];

		u32 idx = 0, len;
		s32 cfd;
		ResumeGui();

		//printf("\r\t\t>> Installing content #%02d...", content->cid);
		// Encrypted content size
		len = round_up(content->size, 64);

		// Install content
		cfd = ES_AddContentStart(tmd_data->title_id, content->cid);
		if (cfd < 0) {
			ret = cfd;
			goto err;
		}
		snprintf(imgPath, sizeof(imgPath), "%s%d...",tr(">> Installing content #"),content->cid);
		msg4Txt.SetText(imgPath);
		// Install content data
		while (idx < len) {

            //VIDEO_WaitVSync ();

			u32 size;

			// Data length
			size = (len - idx);
			if (size > BLOCK_SIZE)
				size = BLOCK_SIZE;

			// Read data
			ret = __Wad_ReadFile(fp, &wadBuffer, offset, size);
			if (ret < 0)
				goto err;

			// Install data
			ret = ES_AddContentData(cfd, wadBuffer, size);
			if (ret < 0)
				goto err;

			// Increase variables
			idx    += size;
			offset += size;
		
		//snprintf(imgPath, sizeof(imgPath), "%s%d (%d)...",tr(">> Installing content #"),content->cid,idx);

		//msg4Txt.SetText(imgPath);

		prTxt.SetTextf("%i%%", 100*(cnt*len+idx)/(tmd_data->num_contents*len));
      if ((Settings.wsprompt == yes) && (CFG.widescreen)) {
         progressbarImg.SetTile(78*(cnt*len+idx)/(tmd_data->num_contents*len));
      } else {
         progressbarImg.SetTile(100*(cnt*len+idx)/(tmd_data->num_contents*len));
      }

		}

		// Finish content installation
		ret = ES_AddContentFinish(cfd);
		if (ret < 0)
			goto err;
	}

	msg4Txt.SetText(tr("Installing content... Ok!"));
	msg5Txt.SetText(tr(">> Finishing installation..."));



	// Finish title install
	ret = ES_AddTitleFinish();
	if (ret >= 0) {
//		printf(" OK!\n");
		goto out;
	}

err:
	//char titties[100];
	ResumeGui();
	prTxt.SetTextf("%s%d", tr("Error..."),ret);
	promptWindow.Append(&prTxt);
	fail = true;
  	//snprintf(titties, sizeof(titties), "%d", ret);
	//printf(" ERROR! (ret = %d)\n", ret);
	//WindowPrompt("ERROR!",titties,"Back",0,0);
	// Cancel install
	ES_AddTitleCancel();
	goto exit;
	//return ret;

out:
	// Free memory
	if (header)
		free(header);
	if (p_certs)
		free(p_certs);
	if (p_crl)
		free(p_crl);
	if (p_tik)
		free(p_tik);
	if (p_tmd)
		free(p_tmd);
	goto exit;


exit:
	if (!fail)msg5Txt.SetText(tr("Finishing installation... Ok!"));
	promptWindow.Append(&btn1);
	while(btn1.GetState() != STATE_CLICKED){
	}


	HaltGui();
	mainWindow->Remove(&promptWindow);
	mainWindow->SetState(STATE_DEFAULT);
	ResumeGui();

	return ret;
}