Ejemplo n.º 1
0
int main(int argc, char *argv[]) {
  assert(("Usage: ./3sat_seq [output path] [record_time file]") && argc == 3);
  openfiles(argv[1], argv[2]);
  
  int nClauses;
  int nVar;

  scanf("%d %d", &nClauses, &nVar);

  short **clauses = readClauses(nClauses, nVar);
  double st = omp_get_wtime();
  long solution = solveClauses(clauses, nClauses, nVar);
  double ed = omp_get_wtime();
  int i;
	
  if (solution >= 0) {
    printf("Solution found [%ld]: ", solution);
    fprintf(fout, "Solution found [%ld]: ", solution);
    for (i = 0; i < nVar; i++) {
      printf("%d ", (int) ((solution & (long) exp2(i)) / exp2(i)));
      fprintf(fout, "%d ", (int) ((solution & (long) exp2(i)) / exp2(i)));
    }
    printf("\n");
  } else {
    printf("Solution not found.\n");
    fprintf(fout, "Solution not found.\n");
  }
  printf("take %.4lfs\n", ed - st);
  fprintf(ftime, "%.4lf\n", ed - st);

  closefiles();
	
  return EXIT_SUCCESS;
}
Ejemplo n.º 2
0
int main(int argc, char **argv)
{
	uctran_off = 0;
	optimize =1;
	exceptions=1;
//	printf("c64 starting...\r\n");
	while(--argc) {
        if( **++argv == '-')
            options(*argv);
		else {
			if (PreProcessFile(*argv) == -1)
				break;
			if( openfiles(*argv)) {
				lineno = 0;
				initsym();
				memset(gsyms,0,sizeof(gsyms));
				memset(&defsyms,0,sizeof(defsyms));
				memset(&tagtable,0,sizeof(tagtable));
				getch();
				lstackptr = 0;
				lastst = 0;
				NextToken();
				compile();
				summary();
				ReleaseGlobalMemory();
				closefiles();
			}
        }
    }
	//getchar();
	return 0;
}
Ejemplo n.º 3
0
Archivo: err.cpp Proyecto: BigEd/Cores
void fatal(char *str)
{
	printf(str);
	closefiles();
	getchar();
	exit(2);
}
Ejemplo n.º 4
0
static void removefps(struct fp_stream * fps){
	if(!fp_streams) return;
	pthread_mutex_lock(&file_mutex);
	if(fp_streams == fps)fp_streams = fps->next;
	else {
		struct fp_stream *fps2;

		for(fps2 = fp_streams; fps2->next; fps2 = fps2->next){
			if(fps2->next == fps){
				fps2->next = fps->next;
				break;
			}
		}
		
	}
	pthread_mutex_unlock(&file_mutex);
	if(fps->callbacks){
		freecallback(fps, fps->callbacks);
		fps->callbacks = 0;
	}
	closefiles(fps);
	if(fps->buf) {
		free(fps->buf);
		fps->buf = NULL;
	}
	fps->state = 0;
}
Ejemplo n.º 5
0
int main(int argc, char **argv)
{
	opt_nopeep = FALSE;
	uctran_off = 0;
	optimize =1;
	exceptions=1;
//	printf("c64 starting...\r\n");
	while(--argc) {
    if( **++argv == '-')
      options(*argv);
		else {
			if (PreProcessFile(*argv) == -1)
				break;
			if( openfiles(*argv)) {
				lineno = 0;
				initsym();
	compiler.compile();
//				compile();
				summary();
				MBlk::ReleaseAll();
//				ReleaseGlobalMemory();
				closefiles();
			}
    }
    dfs.printf("Next on command line (%d).\n", argc);
  }
	//getchar();
	dfs.printf("Exiting\n");
	dfs.close();
 	exit(0);
	return (0);
}
Ejemplo n.º 6
0
int main(int argc, char* argv[]) {

	long int i, *r;

	openfiles();

	fscanf(fin, "%ld", &N);
	strings = (char*) malloc(N * LENGTH);
	if (strings == NULL) {
		perror("malloc strings");
		exit(EXIT_FAILURE);
	}

	for (i = 0; i < N; i++)
		fscanf(fin, "%s", strings + (i * LENGTH));

	fflush(stdout);

	r = bucket_sort(strings, LENGTH, N);

	fflush(stdout);

	for (i = 0; i < N; i++)
		fprintf(fout, "%s\n", strings + (r[i] * LENGTH));

	free(r);
	free(strings);
	closefiles();

	return EXIT_SUCCESS;
}
Ejemplo n.º 7
0
loadmix(char *fnames[], int nscores, double *weights) {
	if(nscores<2 || nscores>NSCORES) error("Bad number of files\n");
	
	double xty[NSCORES+1];
	if(weights) {
		int j;
		for(j=0;j<=nscores;j++)
			xty[j]=weights[j];
	} else
		computemix(fnames, nscores, xty);
	lg("Mixing coeeficients\n");
	int f;
	for(f=0;f<=nscores;f++)
		lg("-lew %f ",xty[f]);
	lg("\n");
		
	FILE *fp[NSCORES];
	openfiles(fp,fnames,nscores);
	int i;
	for(i=0; i<NENTRIES; i++) {
		PROGRESS(i,NENTRIES);
		int r=(userent[i]>>USER_LMOVIEMASK)&7;
		float s[NSCORES];
		readfiles(fp,s,nscores);
		float stotal=0.;
		int j;
		for(j=0;j<nscores;j++)
			stotal+=xty[j]*(r-s[j]);
		stotal+=xty[nscores];
		err[i]=r-stotal;
	}
	closefiles(fp,nscores);
}
Ejemplo n.º 8
0
static int main_cleanup(short code)
{
	closefiles();
	if (code != AC_Success)
		exit(code);
	
	return 0;
	}
Ejemplo n.º 9
0
//
// error - print error information
//
void error(int n)
{
	if (numerrs < 80) {
		my_errno[numerrs++] = n;
		++total_errors;
	}
	else {
		closefiles();
		exit(1);
	}
}
Ejemplo n.º 10
0
void getaddress(void)
{
 size_t ppos;
 fread(addarray,3,1,patchfile);
 ppos = ftell(patchfile);
 if (patchsize == ppos &&
     (addarray[0]=='E')&&
     (addarray[1]=='O')&&
     (addarray[2]=='F'))    closefiles();
 totalchunks++;
 address=addarray[2]+(addarray[1]*256UL)+(addarray[0]*65536UL);
}
Ejemplo n.º 11
0
/*
 * NAME:	cpo->raw()
 * DESCRIPTION:	copy the data fork of an HFS file to a UNIX file
 */
int cpo_raw(hfsvol *vol, const char *srcname, const char *dstname)
{
  hfsfile *ifile;
  int ofile, result = 0;

  if (openfiles(vol, srcname, dstname, 0, &ifile, &ofile) == -1)
    return -1;

  result = do_raw(ifile, ofile);

  closefiles(ifile, ofile, &result);

  return result;
}
Ejemplo n.º 12
0
static FILTER_ACTION fp_request(void *fc, struct clientparam * param, unsigned char ** buf_p, int * bufsize_p, int offset, int * length_p){
	if(fc && (param->service == S_PROXY)){
		if(FC->state) {
			closefiles(FC);
			FC->state = 0;
		}
		processcallbacks(FC, FP_CALLONREQUEST, *buf_p + offset, *length_p - offset);
		if(FC->what &FP_REJECT) return REJECT;
		FC->state = GOT_HTTP_REQUEST;
		genpaths(FC);
		if(FC->what & FP_CLIHEADER) initclientfile(FC);

	}	
	return CONTINUE;
}
Ejemplo n.º 13
0
void getnumbytes(void)
{
 unsigned long b1,b2;

 fread(bytesarray,2,1,patchfile);
 b1=bytesarray[0];
 b2=bytesarray[1];
 numbytes=b2+(b1*256UL);
 if (!numbytes) getrle();
 if (numbytes>MAXARRAYSIZE)
 {
  printf ("Debug: numbytes=%lu\n",numbytes);
  overload=1;
  closefiles();
 }
}
Ejemplo n.º 14
0
/*
 * NAME:	cpo->text()
 * DESCRIPTION:	copy an HFS file to a UNIX file using text translation
 */
int cpo_text(hfsvol *vol, const char *srcname, const char *dstname)
{
  const char *ext = 0;
  hfsfile *ifile;
  int ofile, result = 0;

  if (strchr(srcname, '.') == 0)
    ext = ".txt";

  if (openfiles(vol, srcname, dstname, ext, &ifile, &ofile) == -1)
    return -1;

  result = do_text(ifile, ofile);

  closefiles(ifile, ofile, &result);

  return result;
}
Ejemplo n.º 15
0
int
main(int argc, char *argv[])
{
	int i;

	openfiles();

	if (argc > 1) {
		for (i=1; i<argc; i++) {
			readfile(argv[i]);
		}
	}
	else {
		readfile(NULL);
	}

	dumpdata();

	closefiles();
	return 0;
}
Ejemplo n.º 16
0
/*
 * The function to execute a RA.
 */
static int
execra(const char * rsc_id, const char * rsc_type, const char * provider,
       const char * op_type, const int timeout, GHashTable * params)
{
	char ra_pathname[RA_MAX_NAME_LENGTH];
	GHashTable * tmp_for_setenv;
	GString * params_gstring;
	char * inherit_debuglevel = NULL;
	int save_errno;

	get_ra_pathname(RA_PATH, rsc_type, provider, ra_pathname);

	/* Setup environment correctly */
	tmp_for_setenv = g_hash_table_new(g_str_hash, g_str_equal);
	add_OCF_prefix(params, tmp_for_setenv);
	add_OCF_env_vars(tmp_for_setenv, rsc_id, rsc_type, provider);
	raexec_setenv(tmp_for_setenv);
	g_hash_table_foreach_remove(tmp_for_setenv, let_remove_eachitem, NULL);
	g_hash_table_destroy(tmp_for_setenv);

	/* let this log show only high loglevel. */
	inherit_debuglevel = getenv(HADEBUGVAL);
	if ((inherit_debuglevel != NULL) && (atoi(inherit_debuglevel) > 1)) {
		params_gstring = g_string_new("");
		hash_to_str(params, params_gstring);
		cl_log(LOG_DEBUG, "RA instance %s executing: OCF::%s %s. Parameters: "
			"{%s}", rsc_id, rsc_type, op_type, params_gstring->str);
		g_string_free(params_gstring, TRUE);
	}

	closefiles(); /* don't leak open files */
	/* execute the RA */
	execl(ra_pathname, ra_pathname, op_type, (const char *)NULL);
	/* oops, exec failed */
	save_errno = errno; /* cl_perror may change errno */
	cl_perror("(%s:%s:%d) execl failed for %s" 
		  , __FILE__, __FUNCTION__, __LINE__, ra_pathname);
	errno = save_errno;
	exit(get_failed_exec_rc());
}
Ejemplo n.º 17
0
static int linclose(Aflinst *t)
{
	t->info.optimized = 1;

	afprintv(t->rq->verbose, 4, "Writing database information");
	if (afwriteinfo(t->f.info, &(t->info)) < 0)
		return -1;

	afprintv(t->rq->verbose, 4, "Closing database files");
	if (closefiles(&(t->f)) < 0)
		return -1;
	
	afprintv(t->rq->verbose, 4, "Truncating unlinearized files");
	if (truncufiles(t->rq->db) < 0)
		return -1;

	afprintv(t->rq->verbose, 4, "Unlocking database");
	if (freelock(t->rq->db) < 0)
		return -1;

	return 0;
}
Ejemplo n.º 18
0
Archivo: xec.c Proyecto: deadpixi/sam
bool
D_cmd(File *f, Cmd *cp)
{
    closefiles(f, cp->ctext);
    return true;
}
Ejemplo n.º 19
0
Archivo: dna.c Proyecto: oshogun/dna-se
int main(int argc, char *argv[]) {

	if (argc != 3) {
		printf("Insufficient number of input files!\nUsage: %s <database file> <query file>\n\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	struct timeval start_computation, end_computation;
	struct timeval start_total, end_total;
	unsigned long int time_computation = 0, time_total;

	gettimeofday(&start_total, NULL);

	openfiles(argv[1], argv[2]);

	char *base = (char*) malloc(sizeof(char) * 1000001);
	if (base == NULL) {
		perror("malloc");
		exit(EXIT_FAILURE);
	}
	char *str = (char*) malloc(sizeof(char) * 1000001);
	if (str == NULL) {
		perror("malloc str");
		exit(EXIT_FAILURE);
	}

	char desc_dna[100], desc_query[100];
	int found, result;



	while (get_next_query_descripton(desc_query)) {
		fprintf(fout, "%s\n", desc_query);

		get_next_query_string(str);

		// read database and search
		found = 0;
		fseek(fdatabase, 0, SEEK_SET);
		while (get_next_base_description(desc_dna)) {

			get_next_base_string(base);

   		gettimeofday(&start_computation, NULL);
			result = bmhs(base, strlen(base), str, strlen(str));
			gettimeofday(&end_computation, NULL);
			time_computation += (end_computation.tv_sec - start_computation.tv_sec) * 1000000 + end_computation.tv_usec - start_computation.tv_usec;

			if (result > 0) {
				fprintf(fout, "%s\n%d\n", desc_dna, result);
				found++;
			}
		}

		if (!found)
			fprintf(fout, "NOT FOUND\n");
	}

	closefiles();

	free(str);
	free(base);

	gettimeofday(&end_total, NULL);
	time_total = (end_total.tv_sec - start_total.tv_sec) * 1000000 + end_total.tv_usec - start_total.tv_usec;

	printf("Elapsed computing time: %ld microseconds.\nI/O time: %ld microseconds\n", time_computation, time_total - time_computation);

	return EXIT_SUCCESS;
}
int main(int argc, char *argv[]) {
  printf("Initializing ... \n");
  initialize();
  if (ictype==2) {
    fcfilename=argv[1];
    FILE *fcfid;
    if ((fcfid=fopen(fcfilename,"rb"))==NULL) {
      printf("Unable to open %s ... \n",fcfilename);
      exit(1);}
    readbrfc();  
  }
  if (stimnum>0) {
    printf("Building stimulus matrix ... \n");
    buildptstim();  
  }
  printf("Opening files ... \n");
  openfiles();
  step=0;
  printf("Writing initial conditions ... \n");
  output();
  printf("Entering time loop ... \n");
  double cpu_start=rtclock();

  while (derivarr[0]<=tfinal && step<=Nsteps + 1 && stable){
    step=step+1;
    derivarr[0]+=dt;        // update time (msec) 
	if (blocktimenum>0)                
    {
      int i,m,n;
	  for (i=0;i<blocktimenum;++i){
	    if ((derivarr[0]>=blocktimes[i][0])&&(blocktimes[i][1]==0.0)){
//	      printf("Changing block conditions: %4.3f msec \n",derivarr[0]);
	      blocktimes[i][1]=1.0;
	      for (m=1;m<Nx+1;++m){
	        for (n=1;n<Ny+1;++n){
	    	  if (block[m][n]==0) block[m][n]=1;
			}
      	  }
    	}
  	  }
    } // blockonoff

    if (step % 2 == 1) {
        brgates_currents_1();
    }
    else {
        brgates_currents_2();
    }

	{
	  int ii;
	  double R0, R1;
	  R0=(D[1][0]/D[0][0])*(dx/dy);
	  R1=(D[1][0]/D[1][1])*(dy/dx);
	  if (BC==1){   // Slab
	    /* First set Vm at ghost nodes */
	    datarr[step%2][0][0][1]=datarr[step%2][0][2][1];
	    datarr[step%2][0][0][0]=datarr[step%2][0][2][2];
	    datarr[step%2][0][1][0]=datarr[step%2][0][1][2];
	    datarr[step%2][0][Nx][0]=datarr[step%2][0][Nx][2];
	    datarr[step%2][0][Nx+1][0]=datarr[step%2][0][Nx-1][2];
	    datarr[step%2][0][Nx+1][1]=datarr[step%2][0][Nx-1][1];
	    datarr[step%2][0][Nx+1][Ny]=datarr[step%2][0][Nx-1][Ny];
	    datarr[step%2][0][Nx+1][Ny+1]=datarr[step%2][0][Nx-1][Ny-1];
	    datarr[step%2][0][Nx][Ny+1]=datarr[step%2][0][Nx][Ny-1];
	    datarr[step%2][0][1][Ny+1]=datarr[step%2][0][1][Ny-1];
	    datarr[step%2][0][0][Ny+1]=datarr[step%2][0][2][Ny-1];
	    datarr[step%2][0][0][Ny]=datarr[step%2][0][2][Ny];  
	    for (ii=2;ii<Nx;++ii){            /* decouple these loops b/c Nx might not equal Ny */
	      datarr[step%2][0][ii][Ny+1]=datarr[step%2][0][ii][Ny-1]+R1*(datarr[step%2][0][ii-1][Ny]-datarr[step%2][0][ii+1][Ny]);  /* Eq 3 in notes */
	      datarr[step%2][0][ii][0]=datarr[step%2][0][ii][2]-R1*(datarr[step%2][0][ii-1][1]-datarr[step%2][0][ii+1][1]);          /* Eq 2 in notes */
	    }
	    for (ii=2;ii<Ny;++ii){           /* decouple these loops b/c Nx might not equal Ny */
	      datarr[step%2][0][0][ii]=datarr[step%2][0][2][ii]-R0*(datarr[step%2][0][1][ii-1]-datarr[step%2][0][1][ii+1]);           /* Eq 1 in notes */
	      datarr[step%2][0][Nx+1][ii]=datarr[step%2][0][Nx-1][ii]+R0*(datarr[step%2][0][Nx][ii-1]-datarr[step%2][0][Nx][ii+1]);   /* Eq 4 in notes */
	    }
	  }
	}


{ 
  if (step % 2 == 1) {
    vmdiff_1();
  }
  else {
    vmdiff_2();
  }
}


    if (step%rpN==0) {          // update user
      printf("%4.4e msec, Vm(%d,%d): %3.2f mV\n",derivarr[0],mNx,mNy,datarr[step%2][0][mNx][mNy]); 
      fflush(stdout);
    } 
    if (step%wN==0) output();   // write data to files
  }  // end time loop
  double cpu_end = rtclock();
  printf("total time is %.2lf\n",(double)(cpu_end-cpu_start));
  if (stable){
    printf("\nSimulation Finished!\n");
  }
  else {
    printf("\nSimulation Aborted!\n");
  }
  printf("Saving final conditions...\n\n");
  brfc();
  printf("         tfinal: %5.3f msec\n",tfinal);
  printf("     Final time: %5.3f msec\n",derivarr[0]);
  printf("         Nsteps: %10.2f\n",Nsteps);
  printf("Number of steps: %d\n",step);
  printf("             Nx: %d\n",Nx);
  printf("             Ny: %d\n",Ny);
  closefiles();
}
Ejemplo n.º 21
0
int main(int argc, char **argv)
{
    long i;
    int band, rows, cols;
    CELL *rowbuffer[3];
    struct Option *opt_hue, *opt_red;
    struct Option *opt_inten, *opt_green;
    struct Option *opt_sat, *opt_blue;
    struct GModule *module;
    int fd_input[3];
    int fd_output[3];

    /* Initialize GIS engine */
    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    module->keywords = _("imagery, color transformation, RGB, HIS");
    module->description =
	_("Transforms raster maps from RGB (Red-Green-Blue) color space to "
	  "HIS (Hue-Intensity-Saturation) color space.");

    /* Define the different options */
    opt_red = G_define_standard_option(G_OPT_R_INPUT);
    opt_red->key = "red_input";
    opt_red->description = _("Name of input raster map (red)");

    opt_green = G_define_standard_option(G_OPT_R_INPUT);
    opt_green->key = "green_input";
    opt_green->description = _("Name of input raster map (green)");

    opt_blue = G_define_standard_option(G_OPT_R_INPUT);
    opt_blue->key = "blue_input";
    opt_blue->description = _("Name of input raster map (blue)");

    opt_hue = G_define_standard_option(G_OPT_R_OUTPUT);
    opt_hue->key = "hue_output";
    opt_hue->description = _("Name for output raster map (hue)");

    opt_inten = G_define_standard_option(G_OPT_R_OUTPUT);
    opt_inten->key = "intensity_output";
    opt_inten->description = _("Name for output raster map (intensity)");

    opt_sat = G_define_standard_option(G_OPT_R_OUTPUT);
    opt_sat->key = "saturation_output";
    opt_sat->description = _("Name for output raster map (saturation)");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* get dimension of the image */
    rows = G_window_rows();
    cols = G_window_cols();

    openfiles(opt_red->answer, opt_green->answer, opt_blue->answer,
	      opt_hue->answer, opt_inten->answer, opt_sat->answer,
	      fd_input, fd_output, rowbuffer);

    for (i = 0; i < rows; i++) {
	/* read in a row from each cell map */
	G_percent(i, rows, 2);

	for (band = 0; band < 3; band++)
	    if (G_get_map_row(fd_input[band], rowbuffer[band], i) < 0)
		G_fatal_error(_("Unable to read raster map row %ld"), i);

	/* process this row of the map */
	rgb2his(rowbuffer, cols);

	/* write out the new row for each cell map */
	for (band = 0; band < 3; band++)
	    if (G_put_raster_row(fd_output[band], rowbuffer[band], CELL_TYPE)
		< 0)
		G_fatal_error(_("Failed writing raster map row %ld"), i);
    }
    G_percent(i, rows, 2);

    closefiles(opt_hue->answer, opt_inten->answer, opt_sat->answer,
	       fd_output, rowbuffer);


    exit(EXIT_SUCCESS);
}
Ejemplo n.º 22
0
static int copyfdtosock(struct fp_stream * fps, DIRECTION which, long len){
	int res;
	long toread;
	int state;
#ifdef _WIN32
	HANDLE h;
#else
	int fd;
#endif
	SOCKET sock;
	long offset;
	int sendchunk = 0;

	state = fps->state;
	fps->state = FLUSH_DATA;
	if(!fps->buf){
		fps->buf = malloc(2048);
		if(!fps->buf) return -2;
		fps->bufsize = 2048;
	}
	if(which == SERVER){
		offset = fps->clientsent;
		fps->clientsent += len;
#ifdef _WIN32
		h = fps->fpd.h_cli;
#else
		fd = fps->fpd.fd_cli;
#endif
		sock = fps->fpd.cp->remsock;
	}
	else {
		if(fps->fpd.cp->chunked){ 
			if(fps->serversent < fps->srvhdrwritten && (fps->serversent + len) > fps->srvhdrwritten){
				len -= fps->srvhdrwritten - fps->serversent;
				if ((res = copyfdtosock(fps, which, fps->srvhdrwritten - fps->serversent))) return res;
			}
			if(fps->serversent >= fps->srvhdrwritten){
				sprintf(fps->buf, "%lx\r\n", len);
				sendchunk = (int)strlen(fps->buf);
				if(pl->socksend(fps->fpd.cp->clisock, fps->buf, sendchunk, pl->conf->timeouts[STRING_S]) != sendchunk){
					return -4;
				}
			} 
		}
		offset = fps->serversent;
		fps->serversent += len;
#ifdef _WIN32
		h = fps->fpd.h_srv;
#else
		fd = fps->fpd.fd_srv;
#endif
		sock = fps->fpd.cp->clisock;
	}
#ifdef _WIN32
	if(SetFilePointer(h,offset,0,FILE_BEGIN)!=offset){
		return -1;
	}
#else
	if(lseek(fd, offset, SEEK_SET) < 0) {
		return -1;
	}
#endif


	while(len > 0){


/*
	Fixme: prevent client/server timeouts
*/
		toread = (len > fps->bufsize)? fps->bufsize:len;
#ifdef _WIN32
		if(!ReadFile(h, fps->buf, (DWORD)toread,(DWORD *)&res,NULL)) {
#else
		if((res = read(fd, fps->buf, toread)) <= 0) {
#endif
			return -3;
		}
		if(pl->socksend(sock, fps->buf, res, pl->conf->timeouts[STRING_S]) != res) {
			return -4;
		}
		len -= res;
	}
	if(sendchunk){
		if(pl->socksend(sock, "\r\n", 2, pl->conf->timeouts[STRING_S]) != 2)
			return -4;
	}
	fps->state = state;
	return 0;
}

static int WINAPI fp_poll(struct pollfd *fds, unsigned int nfds, int timeout){
 struct fp_stream *fps = NULL;
 int res;
 unsigned i;
 int to;

 for(i = 0; i<nfds; i++){
	res = searchsocket(fds[i].fd, &fps);
	if(res == 2 && fps->state == GOT_SMTP_DATA){
		if(fds[i].events & POLLOUT){
			fds[i].revents = POLLOUT;
			return 1;
		}
	}
	else if(res == 2 && (((fps->what & FP_CLIHEADER) && (fps->state == GOT_HTTP_REQUEST || fps->state == GOT_HTTP_CLI_HDR2)) || ((fps->what & FP_CLIDATA) && fps->state == GOT_HTTP_CLIDATA))){

		if(fds[i].events & POLLIN){
			processcallbacks(fps, (fps->state == GOT_HTTP_CLIDATA)?FP_CLIDATA:FP_CALLAFTERCLIHEADERS, NULL, 0);
			if(fps->clihdrwritten + fps->clientwritten > fps->clientsent) {
				if(copyfdtosock(fps, SERVER, (fps->clihdrwritten + fps->clientwritten) - fps->clientsent))
					return -2;
			}
			if(fps->state) {
				if(fps->what & FP_SRVHEADER) initserverfile(fps);
				fps->state =  GOT_HTTP_SRV_HDR;
			}
		}

		else if(fds[i].events & POLLOUT){
			fds[i].revents = POLLOUT;
			return 1;
		}

	}
	else if(res == 1 && (fps->state == GOT_HTTP_SRVDATA || fps->state == GOT_HTTP_SRV_HDR || fps->state == GOT_HTTP_SRV_HDR2)&& (fds[i].events & POLLIN)){
			processcallbacks(fps, (fps->state == GOT_HTTP_SRVDATA)? FP_SRVDATA:FP_CALLAFTERSRVHEADERS, NULL, 0);
			if(fps->srvhdrwritten + fps->serverwritten > fps->serversent) {
				if(copyfdtosock(fps, CLIENT, (fps->srvhdrwritten + fps->serverwritten) - fps->serversent))
					return -2;
			}
			closefiles(fps);
			fps->state = 0;
	}
	
 }
 return sso._poll(fds, nfds, timeout);
}

static int WINAPI fp_send(SOCKET s, const char *msg, fp_size_t len, int flags){
 struct fp_stream *fps = NULL;
 int res;
 res = searchsocket(s, &fps);
 if(res == 2){
	if(fps->state == GOT_SMTP_DATA) {
		if(fps->clihdrwritten + fps->clientwritten > fps->clientsent) {
			processcallbacks(fps, FP_CLIDATA, NULL, 0);
			if(copyfdtosock(fps, SERVER, (fps->clihdrwritten + fps->clientwritten) - fps->clientsent)) {
				return -1;
			}
			fps->state = 0;
		}
		closefiles(fps);
		fps->state = 0;
		return sso._send(s, msg, len, flags);
	}
	if((((fps->what & FP_CLIHEADER) && (fps->state == GOT_HTTP_REQUEST || fps->state == GOT_HTTP_CLI_HDR2)) || ((fps->what & FP_CLIDATA) && fps->state == GOT_HTTP_CLIDATA))){
#ifdef _WIN32
		if(SetFilePointer(fps->fpd.h_cli, fps->clientwritten + fps->clihdrwritten, 0, FILE_BEGIN) != (fps->clientwritten + fps->clihdrwritten)){
			return -1;
		}
		if(!WriteFile(fps->fpd.h_cli, msg, (DWORD)len,(DWORD *)&res,NULL) || res != len){
			return -1;
		}
#else
		if(lseek(fps->fpd.fd_cli, fps->clientwritten + fps->clihdrwritten, SEEK_SET) < 0) {
			return -1;
		}
		if((res = write(fps->fpd.fd_cli, msg, len) != len)) return -1;
#endif
		if(fps->state == GOT_HTTP_CLIDATA)fps->clientwritten += res;
		else fps->clihdrwritten += res;
		return res;
	}
 }
 if(res == 1){
	if(((fps->what & FP_SRVDATA) && (fps->state == GOT_HTTP_SRVDATA || fps->state == GOT_HTTP_SRV_HDR) && fps->fpd.cp->chunked && len < 16 )){
		int hasnonzero = 0, i;
		
		for(i=0; i < len; i++){
			char c = msg[i];

			if(c == '\r' || c == '\n') continue;
			if((c<'0'|| c>'9') && (c<'A' || c>'F') && (c<'a' || c>'f')) {
				return sso._send(s, msg, len, flags);
			}
			if(c != '0') hasnonzero = 1;
		}
		if(i>2 && !hasnonzero){

			if(fps->srvhdrwritten + fps->serverwritten > fps->serversent) {
				processcallbacks(fps, FP_SRVDATA, NULL, 0);
				if(copyfdtosock(fps, CLIENT, (fps->srvhdrwritten + fps->serverwritten) - fps->serversent)) {
					return -1;
				}
				fps->state = 0;
			}
			closefiles(fps);
			fps->state = 0;
			return sso._send(s, msg, len, flags);
		}
		return len;
	}
	if(((fps->what & FP_SRVHEADER) && (fps->state == GOT_HTTP_SRV_HDR || fps->state == GOT_HTTP_SRV_HDR2))){
#ifdef _WIN32
		if(SetFilePointer(fps->fpd.h_srv, fps->serverwritten + fps->srvhdrwritten, 0, FILE_BEGIN) != (fps->serverwritten + fps->srvhdrwritten)){
			return -1;
		}
		if(!WriteFile(fps->fpd.h_srv, msg, (DWORD)len,(DWORD *)&res,NULL) || res !=len){
			return -1;
		}
#else
		if(lseek(fps->fpd.fd_srv, fps->serverwritten + fps->srvhdrwritten, SEEK_SET) < 0) {
			return -1;
		}
		if((res = write(fps->fpd.fd_srv, msg, len) != len)) return -1;
#endif
		fps->srvhdrwritten += res;
		return res;
	}
 }
 return sso._send(s, msg, len, flags);
}
static int WINAPI fp_sendto(SOCKET s, const void *msg, int len, int flags, const struct sockaddr *to, fp_size_t tolen){
 struct fp_stream *fps = NULL;
 int res;
 res = searchsocket(s, &fps);
 if(res == 2) {
	switch(fps->state){
	case GOT_SMTP_REQ:
		if(!(fps->what & FP_CLIDATA)) break;
		fps->state = GOT_SMTP_DATA;
		initclientfile(fps);
	case GOT_FTP_REQ:
		if(fps->state == GOT_FTP_REQ){
			if(!(fps->what & FP_CLIDATA)) break;
			fps->state = GOT_FTP_CLIDATA;
			initclientfile(fps);
		}
	case GOT_HTTP_CLI_HDR2:
		if(fps->state == GOT_HTTP_CLI_HDR2){
			processcallbacks(fps, FP_CALLAFTERCLIHEADERS, NULL, 0);
			if ((fps->what & FP_REJECT)) return -1;
			if((fps->what & FP_CLIDATA) && !(fps->what & FP_CLIHEADER)) initclientfile(fps);
			else if(!(fps->what & FP_CLIDATA) && (fps->what & FP_CLIHEADER)){
				if(fps->clihdrwritten + fps->clientwritten > fps->clientsent) {
					if(copyfdtosock(fps, SERVER, (fps->clihdrwritten + fps->clientwritten) - fps->clientsent))
						return -2;
				}
			}
			fps->state = GOT_HTTP_CLIDATA;
		}
	case GOT_HTTP_REQUEST:
		if(fps->state == GOT_HTTP_REQUEST && !(fps->what & FP_CLIHEADER)) break;
	case GOT_SMTP_DATA:
	case GOT_FTP_CLIDATA:
	case GOT_FTP_SRVDATA:
	case GOT_HTTP_CLIDATA:
		if((!fps->what & FP_CLIDATA)) break;
#ifdef _WIN32
		if(SetFilePointer(fps->fpd.h_cli, fps->clientwritten + fps->clihdrwritten, 0, FILE_BEGIN) != (fps->clientwritten + fps->clihdrwritten)){
			return -1;
		}
		if(!WriteFile(fps->fpd.h_cli, msg, (DWORD)len,(DWORD *)&res,NULL) || res != len) {
			return -1;
		}
#else
		if(lseek(fps->fpd.fd_cli, fps->clientwritten + fps->clihdrwritten, SEEK_SET) < 0) {
			return -1;
		}
		if((res = write(fps->fpd.fd_cli, msg, len) != len)) return -1;
#endif
		if(fps->state == GOT_HTTP_REQUEST)fps->clihdrwritten += res;
		else fps->clientwritten += res;
		if(fps->preview_size && ((fps->clihdrwritten + fps->clientwritten) > (fps->clientsent + fps->preview_size))){
			if(!fps->clientsent){
				processcallbacks(fps, FP_PREVIEWCLI, NULL, 0);
				if ((fps->what & FP_REJECT)) return -1;
			}
			if(copyfdtosock(fps, SERVER, (fps->clihdrwritten + fps->clientwritten) - (fps->clientsent + fps->preview_size)))
				return -1;

		}
		return res;
	}
	
 }
 else if(res == 1){ 
	switch(fps->state){
	case GOT_HTTP_SRV_HDR2:
		processcallbacks(fps, FP_CALLAFTERSRVHEADERS, NULL, 0);
		if ((fps->what & FP_REJECT)) return REJECT;
		if((fps->what & FP_SRVDATA) && !(fps->what & FP_SRVHEADER)) initserverfile(fps);
		else if(!(fps->what & FP_SRVDATA) && (fps->what & FP_SRVHEADER)){
			if(fps->srvhdrwritten + fps->serverwritten > fps->serversent) {
				if(copyfdtosock(fps, CLIENT, (fps->srvhdrwritten + fps->serverwritten) - fps->serversent))
					return -2;
			}
		}
		fps->state = GOT_HTTP_SRVDATA;
	case GOT_FTP_REQ:
		if(fps->state == GOT_FTP_REQ){
			if(!(fps->what & FP_SRVDATA)) break;
			fps->state = GOT_FTP_SRVDATA;
			initserverfile(fps);
		}
	case GOT_HTTP_SRV_HDR:
		if(fps->state == GOT_HTTP_SRV_HDR && !(fps->what & FP_SRVHEADER)) break;
	case GOT_HTTP_SRVDATA:
	case GOT_FTP_SRVDATA:
	case GOT_FTP_CLIDATA:
		if(!(fps->what & FP_SRVDATA)) break;
#ifdef _WIN32
		if(SetFilePointer(fps->fpd.h_srv, fps->serverwritten + fps->srvhdrwritten, 0, FILE_BEGIN) != (fps->serverwritten + fps->srvhdrwritten)){
			return -1;
		}
		if(!WriteFile(fps->fpd.h_srv, msg, (DWORD)len,(DWORD *)&res,NULL) || res != len){
			return -1;
		}
#else
		if(lseek(fps->fpd.fd_srv, fps->serverwritten + fps->srvhdrwritten, SEEK_SET) < 0) {
			return -1;
		}
		if((res = write(fps->fpd.fd_srv, msg, len) != len)) return -1;
#endif
		if(fps->state == GOT_HTTP_SRV_HDR)fps->srvhdrwritten += res;
		else fps->serverwritten += res;
		if(fps->preview_size && ((fps->srvhdrwritten + fps->serverwritten) > (fps->serversent + fps->preview_size))){
			if(!fps->serversent){
				processcallbacks(fps, FP_PREVIEWSRV, NULL, 0);
				if ((fps->what & FP_REJECT)) return -1;
			}
			if(copyfdtosock(fps, CLIENT, (fps->srvhdrwritten + fps->serverwritten) - (fps->serversent + fps->preview_size)))
				return -1;

		}
		return res;
	}
 }
 return sso._sendto(s, msg, len, flags, to, tolen);
}
static int WINAPI fp_recv(SOCKET s, void *buf, fp_size_t len, int flags){
 return sso._recv(s, buf, len, flags);
}
static int WINAPI fp_recvfrom(SOCKET s, void * buf, fp_size_t len, int flags, struct sockaddr * from, fp_size_t * fromlen){
 return sso._recvfrom(s, buf, len, flags, from, fromlen);
}
static int WINAPI fp_shutdown(SOCKET s, int how){
 struct fp_stream *fps = NULL;

 int res;
 res = searchsocket(s, &fps);
 if(res){
	if(fps->state == GOT_HTTP_SRV_HDR || fps->state == GOT_HTTP_SRVDATA || fps->state == GOT_FTP_SRVDATA){
		if(fps->srvhdrwritten + fps->serverwritten > fps->serversent) {
			processcallbacks(fps, FP_SRVDATA, NULL, 0);
			copyfdtosock(fps, CLIENT, (fps->srvhdrwritten + fps->serverwritten) - fps->serversent);
		}
		closefiles(fps);
		fps->state = 0;
	}
	else if(fps->state == GOT_FTP_CLIDATA){
		if(fps->clihdrwritten + fps->clientwritten > fps->clientsent) {
			processcallbacks(fps, FP_CLIDATA, NULL, 0);
			copyfdtosock(fps, SERVER, (fps->clihdrwritten + fps->clientwritten) - fps->clientsent);
		}
		closefiles(fps);
		fps->state = 0;
	}
 }
 
 return sso._shutdown(s, how);
}
static int WINAPI fp_closesocket(SOCKET s){
 return sso._closesocket(s);
}



struct fp_stream * addfps(struct clientparam *cp){
 struct fp_stream *fps;

 for(fps = fp_streams; fps && fps->fpd.cp != cp; fps = fps->next);
 if(!fps) {
   fps = malloc(sizeof(struct fp_stream));
   if(!fps){
	return NULL;
   }
   memset(fps, 0, sizeof(struct fp_stream));
   fps->fpd.cp = cp;
   fps->next = fp_streams;
   fp_streams = fps;
#ifdef _WIN32
   fps->fpd.h_cli = fps->fpd.h_srv = INVALID_HANDLE_VALUE;
#else
   fps->fpd.fd_cli = fps->fpd.fd_srv = -1;
#endif
 }
 return fps;
}

static int fp_registercallback (int what, int max_size, int preview_size, struct clientparam *cp, FP_CALLBACK cb, void *data){
 struct fp_callback * fpc;
 struct fp_stream *fps;

 fpc = malloc(sizeof(struct fp_callback));
 if(!fpc) return 0;
 fpc->what = what;
 fpc->preview_size = preview_size;
 fpc->max_size = max_size;
 fpc->data = data;
 fpc->callback = cb;
 pthread_mutex_lock(&file_mutex);
 fps = addfps(cp);
 if(fps){
	 fpc->next = fps->callbacks;
	 fps->callbacks = fpc;
	 fps->what |= fpc->what;
	 if(preview_size > fps->preview_size) fps->preview_size = preview_size;
 }
 else free(fpc);
 pthread_mutex_unlock(&file_mutex);
 return fps?1:0;
}


static void * fp_open(void * idata, struct srvparam * param){
	return idata;
}


#define FC ((struct fp_stream *)fc)

static FILTER_ACTION fp_client(void *fo, struct clientparam * param, void** fc){

	pthread_mutex_lock(&file_mutex);
	(*fc) = (void *)addfps(param);
	pthread_mutex_unlock(&file_mutex);
	return CONTINUE;
}
Ejemplo n.º 23
0
/* Function for opening subprocesses. Returns 0 on success and -1 on failure.
   On failure, errmsg_out shall contain a '\0'-terminated error message. */
static int dopopen(const char *const *args,  /* program arguments with NULL sentinel */
                   const char *executable,   /* actual executable */
                   struct fdinfo fdinfo[3],  /* info for stdin/stdout/stderr */
                   int close_fds,            /* 1 to close all fds */
                   int binary,               /* 1 to use binary files */
                   const char *cwd,          /* working directory for program */
                   struct proc *proc,        /* populated on success! */
                   FILE *pipe_ends_out[3],   /* pipe ends are put here */
                   char errmsg_out[],        /* written to on failure */
                   size_t errmsg_len         /* length of errmsg_out (EXCLUDING sentinel) */
                  )
#if defined(OS_POSIX)
{
    int fds[3];
    int i;
    struct fdinfo *fdi;
    int piperw[2];
    int errpipe[2]; /* pipe for returning error status */
    int flags;
    int en; /* saved errno */
    int count;
    pid_t pid;

    errmsg_out[errmsg_len] = '\0';

    for (i=0; i<3; ++i)
        pipe_ends_out[i] = NULL;

    /* Manage stdin/stdout/stderr */
    for (i=0; i<3; ++i){
        fdi = &fdinfo[i];
        switch (fdi->mode){
            case FDMODE_INHERIT:
inherit:
                fds[i] = dup(i);
                if (fds[i] == -1){
fd_failure:
                    strncpy(errmsg_out, strerror(errno), errmsg_len + 1);
                    closefds(fds, i);
                    closefiles(pipe_ends_out, i);
                    return -1;
                }
                break;
            case FDMODE_FILENAME:
                if (i == STDIN_FILENO){
                    if ((fds[i] = open(fdi->info.filename, O_RDONLY)) == -1) goto fd_failure;
                } else {
                    if ((fds[i] = creat(fdi->info.filename, 0666)) == -1) goto fd_failure;
                }
                break;
            case FDMODE_FILEDES:
                if ((fds[i] = dup(fdi->info.filedes)) == -1) goto fd_failure;
                break;
            case FDMODE_FILEOBJ:
                if ((fds[i] = dup(fileno(fdi->info.fileobj))) == -1) goto fd_failure;
                break;
            case FDMODE_PIPE:
                if (pipe(piperw) == -1) goto fd_failure;
                if (i == STDIN_FILENO){
                    fds[i] = piperw[0]; /* give read end to process */
                    if ((pipe_ends_out[i] = fdopen(piperw[1], "w")) == NULL) goto fd_failure;
                } else {
                    fds[i] = piperw[1]; /* give write end to process */
                    if ((pipe_ends_out[i] = fdopen(piperw[0], "r")) == NULL) goto fd_failure;
                }
                break;
            case FDMODE_STDOUT:
                if (i == STDERR_FILENO){
                    if ((fds[STDERR_FILENO] = dup(fds[STDOUT_FILENO])) == -1) goto fd_failure;
                } else goto inherit;
                break;
        }
    }
    
    /* Find executable name */
    if (!executable){
        /* use first arg */
        executable = args[0];
    }
    assert(executable != NULL);

    /* Create a pipe for returning error status */
    if (pipe(errpipe) == -1){
        strncpy(errmsg_out, strerror(errno), errmsg_len + 1);
        closefds(fds, 3);
        closefiles(pipe_ends_out, 3);
        return -1;
    }
    /* Make write end close on exec */
    flags = fcntl(errpipe[1], F_GETFD);
    if (flags == -1){
pipe_failure:
        strncpy(errmsg_out, strerror(errno), errmsg_len + 1);
        closefds(errpipe, 2);
        closefds(fds, 3);
        closefiles(pipe_ends_out, 3);
        return -1;
    }
    if (fcntl(errpipe[1], F_SETFD, flags | FD_CLOEXEC) == -1) goto pipe_failure;

    /* Do the fork/exec (TODO: use vfork somehow?) */
    pid = fork();
    if (pid == -1) goto pipe_failure;
    else if (pid == 0){
        /* child */
        close(errpipe[0]);
        
        /* dup file descriptors */
        for (i=0; i<3; ++i){
            if (dup2(fds[i], i) == -1) goto child_failure;
        }

        /* close other fds */
        if (close_fds){
            for (i=3; i<sysconf(_SC_OPEN_MAX); ++i){
                if (i != errpipe[1])
                    close(i);
            }
        }

        /* change directory */
        if (cwd && chdir(cwd)) goto child_failure;

        /* exec! Farewell, subprocess.c! */
        execvp(executable, (char *const*) args); /* XXX: const cast */

        /* Oh dear, we're still here. */
child_failure:
        en = errno;
        write(errpipe[1], &en, sizeof en);
        _exit(1);
    }

    /* parent */
    /* close unneeded fds */
    closefds(fds, 3);
    close(errpipe[1]);
    
    /* read errno from child */
    while ((count = read(errpipe[0], &en, sizeof en)) == -1)
        if (errno != EAGAIN && errno != EINTR) break;
    if (count > 0){
        /* exec failed */
        close(errpipe[0]);
        strncpy(errmsg_out, strerror(en), errmsg_len + 1);
        return -1;
    }
    close(errpipe[0]);

    /* Child is now running */
    proc->done = 0;
    proc->pid = pid;
    return 0;
}
Ejemplo n.º 24
0
int main (int argc, char **argv)
{
 if (argc<3)
 {
  fprintf (stderr,"Universal IPS Patcher - Copyright 2003 Steve Nickolas\n");
  fprintf (stderr,"usage: uips source.ext patch.ips [outfile.ext]\n");
  return -1;
 }
 sourcefile=fopen(argv[1],"r+b");
 if (!sourcefile)
 {
  fprintf (stderr,"Source file ");
  perror(argv[1]);
  return -1;
 }
 if (argc>3)
 {
  f=fopen(argv[3],"wb");
 }
 if(f)
 {
  fcopy(sourcefile, f);
  fclose(f);
  fclose(sourcefile);
  sourcefile=fopen(argv[3],"r+b");
  strcpy(outname,argv[3]);
 }

 patchfile=fopen(argv[2],"rb");
 if (!patchfile)
 {
  fprintf (stderr,"Patch file ");
  perror(argv[2]);
  return -1;
 }

 fseek(patchfile, 0, SEEK_END);
 patchsize = (int) ftell(patchfile);
 fseek(patchfile, 0, SEEK_SET);
 chunkarray = (char*)malloc(patchsize);

 if(!chunkarray)
 {
  fprintf (stderr,"Cannot allocate memory.");
  return -1;
 }

 isitanips();

 printf ("Applying Patch '%s' to file '%s'...\n", argv[2], argv[1]);

 while (!feof(patchfile))
 {
  getaddress();
  getnumbytes();
  if (numbytes) getchunk();
  if (numbytes) applypatch(); else applyrle();
 }
 closefiles();

 /* avert warning */
 return 40;
}
Ejemplo n.º 25
0
int
D_cmd(File *f, Cmd *cp)
{
	closefiles(f, cp->ctext);
	return TRUE;
}
Ejemplo n.º 26
0
computemix(char *fnames[], int nscores, double *xty)
{
#ifdef HOLDOUT
	lg("With holdout\n");
#endif
	int ns2=nscores+2;
	int ns1=nscores+1;
	FILE *fp[NSCORES];
	openfiles(fp,fnames,nscores);

	double xtx[NSCORES+2][NSCORES+2];
	ZERO(xtx);
	
	int u;
	for(u=0; u<NUSERS; u++) {
		PROGRESS(u,NUSERS);
		int base=useridx[u][0];
#ifdef HOLDOUT
		if(aopt) error("cant do holdout with -a");
		int d0=UNTRAIN(u);
		int d1=UNALL(u)-d0;
#else
		int d0=0;
		int d1=UNTRAIN(u);
#endif
		seekfiles(fp,nscores, d0);
		base+=d0;
		int j;			
		for(j=0;j<d1;j++) {
			unsigned int dd=userent[base+j];
			int r = (dd>>USER_LMOVIEMASK)&7;
			float s[NSCORES+2];
			readfiles(fp,s,nscores);
			int f;
			for(f=0;f<nscores;f++)		
				s[f]=r-s[f];
			s[nscores]=1.;
			s[nscores+1]=r;

			int ff;
			for(f=0;f<ns2;f++) {
				for(ff=0;ff<ns2;ff++)
					xtx[f][ff] +=s[f]*s[ff];
			}
		}
		int d2=UNTOTAL(u)-(d1+d0);
		seekfiles(fp,nscores, d2);
	}
	closefiles(fp,nscores);
	int count=xtx[nscores][nscores];
	int j1,j2;
	for(j1=0;j1<nscores;j1++)
		lg("File %d RMSE %f\n",j1,sqrt((xtx[j1][j1]+xtx[ns1][ns1]-2*xtx[ns1][j1])/count));
	double avgs[NSCORES+2],std[NSCORES+2];
	for(j1=0;j1<ns2;j1++) {
		avgs[j1]=xtx[nscores][j1]/count;
		std[j1]=sqrt(xtx[j1][j1]/count-avgs[j1]*avgs[j1]);
	}
	for(j1=0;j1<ns2;j1++)
		lg("%f\t",avgs[j1]);
	lg("\n");
	for(j1=0;j1<ns2;j1++)
		lg("%f\t",std[j1]);
	lg("\n");
	lg("-------------------------------------------------\n");
	for(j1=0;j1<ns2;j1++) {
		for(j2=0;j2<ns2;j2++) {
			lg("%f\t",(xtx[j1][j2]/count-avgs[j1]*avgs[j2])/(std[j1]*std[j2]+1.e-6));
		}
		lg("\n");
	}
	lg("-------------------------------------------------\n");
	double eavgs[NSCORES],estd[NSCORES];
	for(j1=0;j1<nscores;j1++) {
		eavgs[j1]=avgs[ns1]-avgs[j1];
		estd[j1]=sqrt((xtx[ns1][ns1]+ xtx[j1][j1]-2*xtx[j1][ns1])/count);
	}
	for(j1=0;j1<nscores;j1++)
		lg("%f\t",eavgs[j1]);
	lg("\n");
	for(j1=0;j1<nscores;j1++)
		lg("%f\t",estd[j1]);
	lg("\n");
	lg("-------------------------------------------------\n");
	for(j1=0;j1<nscores;j1++) {
		for(j2=0;j2<nscores;j2++) {
			lg("%f\t",((xtx[j1][j2]+xtx[ns1][ns1]-xtx[ns1][j1]-xtx[ns1][j2])/count-eavgs[j1]*eavgs[j2])/(estd[j1]*estd[j2]+1.e-6));
		}
		lg("\n");
	}


	char TRANS='N';
	char UFLO='U';
	int M=ns1;
	int N=ns1;
	int NRHS=1;
	double A[NSCORES+1][NSCORES+1];
	int LDA=NSCORES+1;
	double B[NSCORES+1];
	int LDB=NSCORES+1;
	double S[NSCORES+1];
	double RCOND=0.00001; // singular values below this are treated as zero.
	int RANK;
	double WORK[1000];
	int LWORK=1000;
	int INFO;

	for(j1=0;j1<ns1;j1++) {
		B[j1]=xtx[ns1][j1];
		for(j2=0;j2<ns1;j2++)
			A[j1][j2]=xtx[j1][j2];
	}	
	for(j1=0;j1<ns1;j1++) A[j1][j1]+=LAMBDA;
	/*dgesv_(&N,&NRHS,A,&LDA,IPIV,B,&LDB,&INFO);*/
	/*dgels_(&TRANS,&M,&N,&NRHS,A,&LDA,B,&LDB,WORK,&LWORK,&INFO);*/
	/*dgelss_( &M, &N, &NRHS, A, &LDA, B, &LDB, S, &RCOND, &RANK, WORK, &LWORK, &INFO );*/
	dposv_(&UFLO,&N,&NRHS,A,&LDA,B,&LDB,&INFO);
	if(INFO) error("failed %d\n",INFO);
		
	for(j1=0;j1<=nscores;j1++)
		xty[j1]=B[j1];

	lg("Check that the matrix inversion worked:\n");
	for(j1=0;j1<=nscores;j1++) {
		double sum=LAMBDA*B[j1];
		for(j2=0;j2<=nscores;j2++)
			sum+=xtx[j1][j2]*B[j2];
		lg("%f\t%f\n",sum,xtx[nscores+1][j1]);
	}
}
int main(int argc, char *argv[]){
  printf("Initializing ... \n");
  initialize();
  if (ictype==2) {
    fcfilename=argv[1];
    FILE *fcfid;
    if ((fcfid=fopen(fcfilename,"rb"))==NULL){
      printf("Unable to open %s ... \n",fcfilename);
      exit(1);}
    readbrfc();  }
  if (stimnum>0) {
    printf("Building stimulus matrix ... \n");
    buildptstim();  }
  printf("Opening files ... \n");

  openfiles();

  step=0;

  printf("Writing initial conditions ... \n");

  output();

  printf("Entering time loop ... \n");

  time_t gpu_start = time(NULL);

  double cpu_start=rtclock();

#pragma acc data copyin(constarr,D,Dp,Afield) copy(datarr)

  while (derivarr[0]<=tfinal && step<=Nsteps + 1 && stable){

    step=step+1;
    derivarr[0]+=dt;        // update time (msec) 
	if (blocktimenum>0)                
      {
  	int i,m,n;
	  for (i=0;i<blocktimenum;++i){
	    if ((derivarr[0]>=blocktimes[i][0])&&(blocktimes[i][1]==0.0)){
//	      printf("Changing block conditions: %4.3f msec \n",derivarr[0]);
	      blocktimes[i][1]=1.0;
	      for (m=1;m<Nx+1;++m){
	        for (n=1;n<Ny+1;++n){
		  if (block[m][n]==0) block[m][n]=1;
			}
      		}
    		}
  		}
       

      } // blockonoff
//#pragma acc parallel num_workers(1) vector_length(128) copyin(block)
#pragma acc kernels copyin(block) 
{  // begin acc
#pragma acc loop independent vector(32) worker(2) gang(256)
    for(Xstep = 1;Xstep<Nx+1;Xstep++){  
#pragma acc loop independent vector(32) worker(2) gang(256)
    for (Ystep = 1; Ystep < Ny+1; Ystep++) {
//	if (stimnum>0)
//     {
//          int i;
//	  datarr[Xstep][Ystep][14][(step-1)%2]=0;
//	  for (i=0;i<stimnum;++i){
//	    if ((stimarr[Xstep-1][Ystep-1][i][0]!=0)&&(derivarr[0]>=stimarr[Xstep-1][Ystep-1][i][0])&&(derivarr[0]<=stimarr[Xstep-1][Ystep-1][i][0]+stimint)){
//	      if (stimarr[Xstep-1][Ystep-1][i][1]==0.0) {
//        //	printf("Applying Stimulus at %4.3f msec to node (%d,%d)\n",derivarr[0],Xstep,Ystep); 
//		stimarr[Xstep-1][Ystep-1][i][1]=1.0;
//	      } //end if
//	      datarr[Xstep][Ystep][14][(step-1)%2]=Istimamp; 
//	    }   //end if
//	  }     //end for
//
//     }  //stimulate
        /* Ix1 */
	double ax1,bx1,tx1,x1inf,dx1dt,x1;
	/* INa */
	double am,bm,tm,minf,ah,bh,th,hinf;
	/* Is */
	double ad,bd,td,dinf,af,bf,tf,finf,dddt,d,dfdt,f;
	/* Cai */
	double kCa,sigma;
        /* Vm */
       double Vm;
       /* IK1 */
       double IK1t1,IK1t2,IK1t3,IK1t4,gK1,IK1;
       /* Ix1 */
       double Ix1t1,Ix1t2,gx1,Ix1;
       /* INa */
       double gNa,ENa,INa,dmdt,m,dhdt,h, A;
       /* Cai */
       double dCaidt,Cai;
       /* Is */
       double Es,gs,Is;
       /* Other currents */
       double Isum,Istim;
       /* Vm */
       double Cm, dVmdt;
       /* Diffusion */
       double Diff;
	/* Need these from datarr to update derivatives in derivarr */

	/* datarr values are not altered here */

	/* these are initial conditions for step=1 */

  Vm=datarr[(step-1)%2][0][Xstep][Ystep];   /* mV */         

  x1=datarr[(step-1)%2][4][Xstep][Ystep];/* unitless */

  m=datarr[(step-1)%2][6][Xstep][Ystep];    /* unitless */

  h=datarr[(step-1)%2][7][Xstep][Ystep];    /* unitless */

  Is=datarr[(step-1)%2][8][Xstep][Ystep];   /* uA/cm^2 */

  d=datarr[(step-1)%2][9][Xstep][Ystep];   /* unitless */

  f=datarr[(step-1)%2][10][Xstep][Ystep];   /* unitless */

  Cai=datarr[(step-1)%2][11][Xstep][Ystep]; /* moles/L */

    /* Constants */

    kCa = constarr[6];      /* msec^-1 */

    sigma = constarr[11];   /* unitless */

    /* Ix1  */ 

    ax1 = abfun_0(Vm);

    bx1 = abfun_1(Vm);

    tx1 = 1 / (ax1+bx1);

    x1inf = ax1 * tx1;

    dx1dt = (x1inf - (x1)) / tx1;

    /* INa */

    am = abfun_2(Vm);

    bm = abfun_3(Vm);

    tm = 1 / (am+bm);

    minf = am * tm;

    dmdt = (minf - (m)) / tm;

    ah = abfun_4(Vm);

    bh = abfun_5(Vm);

    th = 1 / (ah + bh);

    hinf = ah * th;

    dhdt = (hinf - (h)) / th;

    /* Is */

    ad = abfun_8(Vm);

    bd = abfun_9(Vm);

    td = (1 / (ad+bd)) * (sigma);

    dinf = ad * td;

    dddt = (dinf - (d)) / td;

    af = abfun_10(Vm);

    bf = abfun_11(Vm);

    tf = (1 / (af+bf)) * (sigma);

    finf = af * tf;

    dfdt = (finf - (f)) / tf;


    /* Cai */

    dCaidt = (-1e-7)*(Is) + (kCa)*((1e-7)-(Cai));  /* mole/L */

    /* Constants */

    gK1 = constarr[0];            /* mmho/cm^2 */

    gNa = constarr[1];            /* mmho/cm^2 */

    ENa = constarr[2];            /* mV */

    gx1 = constarr[3];            /* mmho/cm^2 */

    gs = constarr[4];             /* mmho/cm^2 */

    Cm = constarr[5];             /* uF/cm^2 */

    //gNaC = &constarr[7];           /* mmho/cm^2 */

    A=Afield[Xstep-1][Ystep-1]; /* unitless */

    /* copy previous timestep data into current datarr */

    /* such that previous Vm is used to update next Vm */

  int jj;
//#pragma acc loop seq
  for (jj=0; jj<varnum-2; jj++)                                               /* varnum-1 b/c don't want to overwrite */
 {
    datarr[step%2][jj][Xstep][Ystep]=datarr[(step-1)%2][jj][Xstep][Ystep];    /* the stimulus and diffusion in last 2 elements of datarr */
 }

  Vm=datarr[step%2][0][Xstep][Ystep];        /* mV */

  dVmdt=datarr[step%2][1][Xstep][Ystep];     /* mV/msec */

  IK1=datarr[step%2][2][Xstep][Ystep];       /* uA/cm^2 */

  Ix1=datarr[step%2][3][Xstep][Ystep];       /* uA/cm^2 */

  x1=datarr[step%2][4][Xstep][Ystep];        /* unitless */

  INa=datarr[step%2][5][Xstep][Ystep];       /* uA/cm^2 */

  m=datarr[step%2][6][Xstep][Ystep];         /* unitless */

  h=datarr[step%2][7][Xstep][Ystep];         /* unitless */

  Is=datarr[step%2][8][Xstep][Ystep];        /* uA/cm^2 */

  d=datarr[step%2][9][Xstep][Ystep];        /* unitless */

  f=datarr[step%2][10][Xstep][Ystep];        /* unitless */

  Cai=datarr[step%2][11][Xstep][Ystep];      /* mole/L */

  Isum=datarr[step%2][12][Xstep][Ystep];    /* uA/cm^2 */

  Diff=datarr[step%2][13][Xstep][Ystep];     /* mV/msec */

  Istim=datarr[step%2][14][Xstep][Ystep];    /* uA/cm^2 */

    /* IK1 */

    IK1t1 = 4 * (exp(0.04*(Vm+85))-1);

    IK1t2 = exp(0.08*(Vm+53)) + exp(0.04*(Vm+53));

    IK1t3 = 0.2 * (Vm+23);

    IK1t4 = 1 - exp(-0.04*(Vm+23));

    /* uA/cm^2  09/07/2005 */

    IK1 = (A) * (gK1) * (IK1t1/IK1t2 + IK1t3/IK1t4);

    datarr[step%2][2][Xstep][Ystep]=IK1 ;       /* uA/cm^2 */	 

    /* Ix1 */

    x1 = x1 + dx1dt*dt;

    datarr[step%2][4][Xstep][Ystep]=x1;        /* unitless */

    Ix1t1 = exp(0.04*(Vm+77)) - 1;

    Ix1t2 = exp(0.04*(Vm+35));

    Ix1 = ((gx1*Ix1t1) / (Ix1t2)) * (x1);        /* uA/cm^2 */

    datarr[step%2][3][Xstep][Ystep]=Ix1;       /* uA/cm^2 */	 

    /* INa */

    m =  m+ dmdt * dt;

    datarr[step%2][6][Xstep][Ystep]=m;         /* unitless */

    h =  h+dhdt * dt;

    datarr[step%2][7][Xstep][Ystep]=h;         /* unitless */

    /* *INa=((gNa)*(pow((m),3.0))*(h)*(*j)+*gNaC)*(Vm-ENa); */

    /* uA/cm^2, BR Na current */

    /* uA/cm^2, no gNaC or j gate in BRDR Na current */

    INa = ((gNa) * block[Xstep][Ystep] * (pow((m),3.0))*(h))*(Vm-ENa); 

    datarr[step%2][5][Xstep][Ystep]=INa;       /* uA/cm^2 */        

    /* Cai */

    Cai = Cai + dCaidt * dt;              /* moles/L */

    datarr[step%2][11][Xstep][Ystep]=Cai;      /* mole/L */	 

    /* Is */

    d = d+dddt * dt;

    datarr[step%2][9][Xstep][Ystep]=d;        /* unitless */

    f = f+dfdt * dt;

    datarr[step%2][10][Xstep][Ystep]=f;        /* unitless */

    Es = -82.3 - 13.0287 * log(Cai);
    Is = (gs) * block[Xstep][Ystep] * (d) * (f) * (Vm-Es);  /* uA/cm^2 */

    datarr[step%2][8][Xstep][Ystep]=Is;        /* uA/cm^2 */	 

    /* Vm */

    Isum = (IK1 + Ix1 + INa + Is);                     /* uA/cm^2 */

    datarr[step%2][12][Xstep][Ystep]=Isum;    /* uA/cm^2 */

    dVmdt = (Diff) - (1/(Cm))*(Isum-Istim);        /* mV/msec */

    datarr[step%2][1][Xstep][Ystep]=dVmdt;     /* mV/msec */   	 

    Vm = Vm + ((dVmdt)*dt);     

    datarr[step%2][0][Xstep][Ystep]= Vm;                       /* mV */


    datarr[step%2][13][Xstep][Ystep]=0.0;   // zero used diffusion terms     

   }  // end Xstep loop
  }    // end Ystep loop
 } //end acc

//bcs();


	#pragma acc parallel vector_length(1) num_workers(1) num_gangs(1)
	{
	  int ii;
	  double R0, R1;
	  
	  R0=(D[1][0]/D[0][0])*(dx/dy);
	  R1=(D[1][0]/D[1][1])*(dy/dx);
	  
	  
	  if (BC==1){   // Slab
	    /* First set Vm at ghost nodes */
	    datarr[step%2][0][0][1]=datarr[step%2][0][2][1];
	    datarr[step%2][0][0][0]=datarr[step%2][0][2][2];
	    datarr[step%2][0][1][0]=datarr[step%2][0][1][2];
	    datarr[step%2][0][Nx][0]=datarr[step%2][0][Nx][2];
	    datarr[step%2][0][Nx+1][0]=datarr[step%2][0][Nx-1][2];
	    datarr[step%2][0][Nx+1][1]=datarr[step%2][0][Nx-1][1];
	    datarr[step%2][0][Nx+1][Ny]=datarr[step%2][0][Nx-1][Ny];
	    datarr[step%2][0][Nx+1][Ny+1]=datarr[step%2][0][Nx-1][Ny-1];
	    datarr[step%2][0][Nx][Ny+1]=datarr[step%2][0][Nx][Ny-1];
	    datarr[step%2][0][1][Ny+1]=datarr[step%2][0][1][Ny-1];
	    datarr[step%2][0][0][Ny+1]=datarr[step%2][0][2][Ny-1];
	    datarr[step%2][0][0][Ny]=datarr[step%2][0][2][Ny];  
	    for (ii=2;ii<Nx;++ii){            /* decouple these loops b/c Nx might not equal Ny */
	      datarr[step%2][0][ii][Ny+1]=datarr[step%2][0][ii][Ny-1]+R1*(datarr[step%2][0][ii-1][Ny]-datarr[step%2][0][ii+1][Ny]);  /* Eq 3 in notes */
	      datarr[step%2][0][ii][0]=datarr[step%2][0][ii][2]-R1*(datarr[step%2][0][ii-1][1]-datarr[step%2][0][ii+1][1]);          /* Eq 2 in notes */
	    }
	    for (ii=2;ii<Ny;++ii){           /* decouple these loops b/c Nx might not equal Ny */
	      datarr[step%2][0][0][ii]=datarr[step%2][0][2][ii]-R0*(datarr[step%2][0][1][ii-1]-datarr[step%2][0][1][ii+1]);           /* Eq 1 in notes */
	      datarr[step%2][0][Nx+1][ii]=datarr[step%2][0][Nx-1][ii]+R0*(datarr[step%2][0][Nx][ii-1]-datarr[step%2][0][Nx][ii+1]);   /* Eq 4 in notes */
	    }
	    
	  }
	}
	


#pragma acc kernels present(datarr, Dp)
{  //begin openacc
#pragma acc loop  independent vector(32) worker(2) gang(256)
    for (Xstep=1; Xstep<Nx+1; ++Xstep) {
#pragma acc loop independent vector(32) worker(2) gang(256)
        for (Ystep=1; Ystep<Ny+1; ++Ystep) {
//Response to MBEC Reviewer: Scattering To Collecting

/* Diffusion: Compute the new Vm's contribution to the next diffusion matrix */
/* (step-1)%2 for next timestep and step%2 for current timestep */
/* Dp stands for Dprime, the Laplacian multiplier form of the diffusion tensor D */
/* Remember: diffusion at ghost points doesn't matter  */

datarr[(step-1)%2][13][Xstep][Ystep] =
        datarr[(step-1)%2][13][Xstep][Ystep]
        - (2*Dp[0][0] + 2*Dp[1][1]) * datarr[step%2][0][Xstep][Ystep]
        - Dp[1][0] * datarr[step%2][0][Xstep-1][Ystep+1]
        + Dp[1][1] * datarr[step%2][0][Xstep][Ystep+1]
        + Dp[1][0] * datarr[step%2][0][Xstep+1][Ystep+1]
        + Dp[0][0] * datarr[step%2][0][Xstep+1][Ystep]
        - Dp[1][0] * datarr[step%2][0][Xstep+1][Ystep-1]
        + Dp[1][1] * datarr[step%2][0][Xstep][Ystep-1]
        + Dp[1][0] * datarr[step%2][0][Xstep-1][Ystep-1]
        + Dp[0][0] * datarr[step%2][0][Xstep-1][Ystep];
        }
    }
}  //end openacc

    if (step%rpN==0) {          // update user
	#pragma acc update host(datarr)
      printf("%4.4e msec, Vm(%d,%d): %3.2f mV\n",derivarr[0],mNx,mNy,datarr[step%2][0][mNx][mNy]); 

      fflush(stdout);

    } 

    if (step%wN==0) output();   // write data to files

  }  // end time loop

  double cpu_end = rtclock();

  time_t gpu_end = time(NULL);    

  printf("total time is %.2lf\n",(double)(cpu_end-cpu_start));

  if (stable){

    printf("\nSimulation Finished!\n");

  }

  else {

    printf("\nSimulation Aborted!\n");

  }

  printf("Saving final conditions...\n\n");

  brfc();

  printf("         tfinal: %5.3f msec\n",tfinal);

  printf("     Final time: %5.3f msec\n",derivarr[0]);

  printf("         Nsteps: %10.2f\n",Nsteps);

  printf("Number of steps: %d\n",step);

  printf("             Nx: %d\n",Nx);

  printf("             Ny: %d\n",Ny);

  closefiles();

}