Example #1
1
int main()
{
	int i;
	struct picture_t pic;
	struct encoded_pic_t encoded_pic;
	errno = 0;
	if(!camera_init(&pic))
		goto error_cam;
	if(!encoder_init(&pic)){
		fprintf(stderr,"failed to initialize encoder\n");
		goto error_encoder;
	}
	if(!preview_init(&pic))
		goto error_preview;
	if(!output_init(&pic))
		goto error_output;
	if(!encoder_encode_headers(&encoded_pic))
		goto error_output;
	if(!output_write_headers(&encoded_pic))
		goto error_output;
	if(!camera_on())
		goto error_cam_on;
	if(signal(SIGINT, stop_recording) == SIG_ERR){
		fprintf(stderr,"signal() failed\n");
		goto error_signal;
	}
	printf("Press ctrl-c to stop recording...\n");
	recording = 1;
	for(i=0; recording; i++){
		if(!camera_get_frame(&pic))
			break;
		gen_osd_info();
		osd_print(&pic, osd_string);
		if((i&7)==0) // i%8==0
			preview_display(&pic);
		if(!encoder_encode_frame(&pic, &encoded_pic))
			break;
		applog_flush();
		if(!output_write_frame(&encoded_pic))
			break;
	}
	printf("\nrecorded %d frames\n", i);

error_signal:
	camera_off();
error_cam_on:
	output_close();
error_output:
	preview_close();
error_preview:
	encoder_close();
error_encoder:
	camera_close();
error_cam:
	return 0;
}
Example #2
1
void *cam_thread()  
{  	
	int number,FileSize;
	number=0;
	FileSize =0; 
	fd_set fds;  
    struct timeval tv;  
    int r;
    printf ("cam_thread : I'm thread 1\n");
	while (!g_s32Quit) 
		{		
			/* Timeout. */  
			tv.tv_sec = 0;  
			tv.tv_usec = 33333;  
			nanosleep(&tv,NULL);
			if(!camera_get_frame(&pic)){
				printf("error1\r\n");
				break;
			}	
			gen_osd_info();
			osd_print(&pic, osd_string);
			if(!encoder_encode_frame(&pic, &encoded_pic))
				break;
			FileSize+=encoded_pic.length;
			if(g_s32DoPlay>0)
				ringput(encoded_pic.buffer,encoded_pic.length,encoded_pic.frame_type);
			if ((FileSize>MAX_SIZE) && (encoded_pic.frame_type ==FRAME_TYPE_I)) {
				output_close();	
				get_filename();
				printf("file:%s\n",mkv_filename);
				if(!output_init(&pic,mkv_filename))
					break;
				if(!output_write_headers(&header_pic,&psp))
					break;
				FileSize=0;
				ResetTime(&pic,&encoded_pic);
				if(!output_write_frame(&encoded_pic))
					break;
				encoder_release(&encoded_pic);
			} else {
				if(!output_write_frame(&encoded_pic))
					break;
				encoder_release(&encoded_pic);
				}
		}

	printf("exit the enc_thread\n");
	g_s32Quit= 0;
    //pthread_exit(NULL);  
} 
Example #3
0
File: xcorr.c Project: rforge/muste
static int tulostus()
{
    int i,t;
    char x[LLENGTH];

    i=output_open(eout);
    if (i<0) return(1);
    if (autocorr) sprintf(x,"Autocorrelations of %s in data %s:",word[2],word[1]);
    else sprintf(x,"Auto- and crosscorrelations of %s and %s in data %s:",word[2],word[3],word[1]);
    print_line(x);

    if (autocorr) sprintf(x," Lag  %.8s",word[2]);
    else sprintf(x," Lag %8.8s   %8.8s       Cross+     Cross-",word[2],word[3]);
    print_line(x);
    t=accuracy-3;
    if (autocorr)
        sprintf(x,"%3d  %10.*f",0,t,1.0);
    else
        sprintf(x,"%3d  %10.*f %10.*f %10.*f %10.*f",0,t,1.0,t,1.0,t,corr,t,corr);

    print_line(x);
    for (i=0; i<maxlag; ++i)
    {
        if (autocorr)
            sprintf(x,"%3d  %10.*f",i+1,t,xx[i]);
        else
            sprintf(x,"%3d  %10.*f %10.*f %10.*f %10.*f",i+1,t,xx[i],t,yy[i],t,xy1[i],t,xy2[i]);
        print_line(x);
    }
    output_close(eout);
    return(1);
}
int main(int argc, char *argv[]) {
	LIBXML_TEST_VERSION

	// xmlTextReaderPtr reader = xmlReaderForFile("/run/media/svartalf/storage/wikipedia/ruwiki-20140706-pages-meta-history1.xml", NULL, 0);
	xmlTextReaderPtr reader = xmlReaderForFile("/tmp/test.xml", NULL, 0);

	FILE *output = fopen("/tmp/output.bin", "w");
	output_write_header(output);

	Revision *rev = revision_create();

	int result = xmlTextReaderRead(reader);
	while (result == 1) {
		processNode(reader, rev);
		result = xmlTextReaderRead(reader);

		if (revision_filled(rev)) {
			output_write_row(output, rev);
			revision_clear(rev);
		}

	}

	output_close(output);

	xmlFreeTextReader(reader);
	if (result != 0) {
		fprintf(stderr, "failed to parse: %d\n", result);
	}
	xmlCleanupParser();

	return 0;

}
Example #5
0
File: sally.c Project: yangke/sally
/**
 * Exit Sally tool. Close open files and free memory.
 */
static void sally_exit()
{
    int ehash;
    const char *cfg_str, *hash_file;

    info_msg(1, "Flushing. Closing input and output.");
    input_close();
    output_close();

    config_lookup_string(&cfg, "features.vect_embed", &cfg_str);
    if (!strcasecmp(cfg_str, "tfidf"))
        idf_destroy(input);

    config_lookup_string(&cfg, "input.stopword_file", &cfg_str);
    if (strlen(cfg_str) > 0)
        stopwords_destroy();

    config_lookup_string(&cfg, "features.hash_file", &hash_file);
    if (strlen(hash_file) > 0) {
        info_msg(1, "Saving explicit hash table to '%s'.", hash_file);    
        gzFile z = gzopen(hash_file, "w9");
        if (!z)
            error("Could not open hash file '%s'", hash_file);
        fhash_write(z);
        gzclose(z);
    }
    
    config_lookup_int(&cfg, "features.explicit_hash", &ehash);
    if (ehash || strlen(hash_file) > 0)
        fhash_destroy();

    /* Destroy configuration */
    config_destroy(&cfg);

}
Example #6
0
static int printout()
        {
        output_open(eout);
        disp0();
        tab_disp();
        output_close(eout);
        return(1);
        }
Example #7
0
void destruct(MyInstance* my)
{
    if (my->drv != 0)
    {
        output_close(my->driver_name->text,
                     my->server_name->text);
    }

    string_deleteInstance(my->server_name);
    string_deleteInstance(my->driver_name);
    free(my);
}
Example #8
0
static int m_printout()
        {
        int i,k,h;
        char line[LLENGTH];
        char mean[32];
        char stddev[32];

        output_open(eout);
        print_line(" Means, std.devs and frequency distributions of variables");
        sprintf(line," in %s N=%d",
                          word[1],n);
        if (weight_variable>=0)
            {
            strcat(line," Weight="); strncat(line,d.varname[weight_variable],8);
            }
        print_line(line);
        strcpy(line,"                                           Frequencies");
        print_line(line);
        h=sprintf(line," Variable     Mean     Std.dev. N(missing)");
        for (k=0; k<n_class; ++k) h+=sprintf(line+h,"%4d ",k+1);
        print_line(line);
        for (i=0; i<d.m_act; ++i)
            {
            if (d.v[i]==weight_variable) continue;
            if (w[i]==0.0)
                sprintf(line," %-8.8s         -          -  %6d",d.varname[d.v[i]],
                         (int)(n-f[i]));
            else
                {
                fnconv(sum[i]/w[i],accuracy+2,mean);
                if (w[i]>1.0)
                   fnconv(sqrt((sum2[i]-sum[i]*sum[i]/w[i])/(w[i]-1)),accuracy+2,stddev);
                else
                   { strncpy(stddev,space,accuracy+2); stddev[accuracy+2]=EOS;
                     stddev[accuracy+1]='-';
                   }

                h=sprintf(line," %-8.8s %s  %s  %6d    ",d.varname[d.v[i]],
                             mean,stddev,(int)(n-f[i]));
                for (k=0; k<n_class; ++k)
                    h+=sprintf(line+h,"%4ld ",f2[k+i*n_class]);
                }
            print_line(line);
            }
        output_close(eout);
        return(1);
        }
Example #9
0
/**
 *
 * @brief Perform all selected benchmarks
 *
 * @return N/A
 */
void main(void)
{
	int	    continuously = 0;
	int	    test_result;

	init_output(&continuously);
	bench_test_init();

	do {
		fprintf(output_file, sz_module_title_fmt,
			"Nanokernel API test");
		fprintf(output_file, sz_kernel_ver_fmt,
			sys_kernel_version_get());
		fprintf(output_file,
			"\n\nEach test below is repeated %d times;\n"
			"average time for one iteration is displayed.",
			NUMBER_OF_LOOPS);

		test_result = 0;

		test_result += sema_test();
		test_result += lifo_test();
		test_result += fifo_test();
		test_result += stack_test();

		if (test_result) {
			/* sema/lifo/fifo/stack account for 12 tests in total */
			if (test_result == 12) {
				fprintf(output_file, sz_module_result_fmt,
					sz_success);
			} else {
				fprintf(output_file, sz_module_result_fmt,
					sz_partial);
			}
		} else {
			fprintf(output_file, sz_module_result_fmt, sz_fail);
		}
		TC_PRINT_RUNID;

	} while (continuously && !kbhit());

	output_close();
}
Example #10
0
/* Adds file descriptors to the child structure to support output_sync; one
   for stdout and one for stderr as long as they are open.  If stdout and
   stderr share a device they can share a temp file too.
   Will reset output_sync on error.  */
static void
setup_tmpfile (struct output *out)
{
  /* Is make's stdout going to the same place as stderr?  */
  static int combined_output = -1;

  if (combined_output < 0)
    combined_output = sync_init ();

  if (STREAM_OK (stdout))
    {
      int fd = output_tmpfd ();
      if (fd < 0)
        goto error;
      CLOSE_ON_EXEC (fd);
      out->out = fd;
    }

  if (STREAM_OK (stderr))
    {
      if (out->out != OUTPUT_NONE && combined_output)
        out->err = out->out;
      else
        {
          int fd = output_tmpfd ();
          if (fd < 0)
            goto error;
          CLOSE_ON_EXEC (fd);
          out->err = fd;
        }
    }

  return;

  /* If we failed to create a temp file, disable output sync going forward.  */
 error:
  output_close (out);
  output_sync = 0;
}
Example #11
0
/**
 *
 * @brief Perform all selected benchmarks
 * see config.h to select or to unselect
 *
 * @return N/A
 */
void BenchTask(void)
{
	int autorun = 0, continuously = 0;

	init_output(&continuously, &autorun);
	bench_test_init();

	PRINT_STRING(newline, output_file);
	do {
		PRINT_STRING(dashline, output_file);
		PRINT_STRING("|          S I M P L E   S E R V I C E    "
					 "M E A S U R E M E N T S  |  nsec    |\n",
					 output_file);
		PRINT_STRING(dashline, output_file);
		task_start(RECVTASK);
		call_test();
		queue_test();
		sema_test();
		mutex_test();
		memorymap_test();
		mempool_test();
		event_test();
		mailbox_test();
		pipe_test();
		PRINT_STRING("|         END OF TESTS                     "
					 "                                   |\n",
					 output_file);
		PRINT_STRING(dashline, output_file);
		PRINT_STRING("PROJECT EXECUTION SUCCESSFUL\n",output_file);
	} while (continuously && !kbhit());

	WAIT_FOR_USER();

	if (autorun) {
		task_sleep(SECONDS(2));
	}

	output_close();
}
Example #12
0
static int hfmodem_close(struct inode *inode, struct file *file)
{
    struct hfmodem_state *dev = &hfmodem_state[0];

    if (!dev->active)
        return -EPERM;
    dev->active = 0;
    dev->scops->stop(dev);
    free_irq(dev->io.irq, dev);
    disable_dma(dev->io.dma);
    free_dma(dev->io.dma);
    release_region(dev->io.base_addr, dev->scops->extent);
    kfree_s(dev->dma.buf, HFMODEM_FRAGSIZE * (HFMODEM_NUMFRAGS+HFMODEM_EXCESSFRAGS));
    hfmodem_clear_rq(dev);
    if (dev->sbuf.kbuf) {
        kfree_s(dev->sbuf.kbuf, dev->sbuf.size);
        dev->sbuf.kbuf = dev->sbuf.kptr = NULL;
        dev->sbuf.size = dev->sbuf.rem = 0;
    }
    output_close(dev);
    MOD_DEC_USE_COUNT;
    return 0;
}
Example #13
0
File: facta.c Project: rforge/muste
/****************
main(argc,argv)
int argc; char *argv[];
*******************/
void muste_facta(char *argv)
        {
        int i,j,h;
        unsigned int ui;
        double da,db;
        char x[LLENGTH];
        double sumlogsii;
//      extern double cdf_chi2();
        char acc[32];

//      if (argc==1) return;
        s_init(argv);

        if (g<3)
            {
            init_remarks();
            rem_pr("Usage: FACTA <corr.matrix>,k,L                ");
            rem_pr("       k=number of factors                    ");
            rem_pr("       L=first line for the results           ");
            rem_pr(" Factor matrix saved as FACT.M                ");
            rem_pr("                                              ");
            rem_pr(" METHOD=ULS Unweighted Least Squares          ");
            rem_pr(" METHOD=GLS Generalized Least Squares         ");
            rem_pr(" METHOD=ML  Maximum Likelihood (default)      ");
            rem_pr(" Test statistics by N=<number of observations>");
            rem_pr("More information by FACTA?                    ");

            wait_remarks(2);
            s_end(argv);
            return;
            }
        results_line=0;
        if (g>3)
            {
            results_line=edline2(word[3],1);
            if (results_line==0) return;
            }
        i=sp_init(r1+r-1); if (i<0) return;
        i=matrix_load(word[1],&E,&p,&n,&rlab,&clab,&lr,&lc,&type,expr);
        if (i<0) { s_end(argv); return; } // RS CHA argv[1]

        if (p!=n)
            {
            sprintf(sbuf,"\n%s not a square matrix!",word[1]); sur_print(sbuf); WAIT; return;
            }
        k=atoi(word[2]);
        if (k<1 || k>p-1)
            {
            sprintf(sbuf,"Incorrect number (%d) of factors!",k);
            if (etu==2)
                {
                sprintf(tut_info,"___@6@FACTA@%s@",sbuf); s_end(argv); // RS CHA argv[1]
                return;
                }
            sur_print("\n"); sur_print(sbuf); WAIT; return;
            }

        *mess=EOS;
        i=spfind("FEPS");
        if (i>=0)
            {
            double eps;

            eps=1.0-atof(spb[i]);
            for (i=0; i<p; ++i)
            for (j=0; j<p; ++j) { if (i==j) continue; E[i+j*p]*=eps; }

            }
        ind=3; i=spfind("METHOD");
        if (i>=0)
            {
            if (muste_strcmpi(spb[i],"ULS")==0) ind=1;
            if (muste_strcmpi(spb[i],"GLS")==0) ind=2;
            }

        for (i=0; i<p; ++i)
            {
            if (E[i*(p+1)]!=0.0) continue;
            sprintf(sbuf,"Variable %.*s is a constant!",lr,rlab+i*lr);
            if (etu==2)
                {
                sprintf(tut_info,"___@1@FACTA@%s@",sbuf); s_end(argv); // RS CHA argv[1]
                return;
                }
            sur_print("\n"); sur_print(sbuf); WAIT; return;
            }

/*
        if (ind==1)
            {
            for (i=0; i<p; ++i)
                {
                if (fabs(E[i*(p+1)]-1.0)<0.0001) continue;
                Rprintf("\n%s is not a correlation matrix as supposed in ULS!",
                                word[1]); WAIT; return;
                }
            }
*/

        i=varaa_tilat(); if (i<0) return;
        for (ui=0; ui<p*p; ++ui) S[ui]=E[ui];
        sumlogsii=0.0; for (i=0; i<p; ++i) sumlogsii+=log(S[i*(p+1)]);

        i=nwtrap();
        if (i<0)
            {
            if (etu!=2)
                { sur_print("\nSolution not found!"); WAIT; return; }
            s_end(argv); // RS CHA argv[1]
            return;
            }
        h=output_open(eout); if (h<0) return;
        strcpy(x,"Factor analysis: ");
        switch (ind)
            {
          case 1: strcat(x,"Unweighted Least Squares (ULS) solution"); break;
          case 2: strcat(x,"Generalized Least Squares (GLS) solution"); break;
          case 3: strcat(x,"Maximum Likelihood (ML) solution"); break;
            }
        print_line(x);
        if (*mess)
            {
            strcpy(x,"                 "); strcat(x,mess);
            print_line(x);
            if (etu!=2) { WAIT; }
            }
        i=spfind("N");
        if (i>=0)
            {
            if (ind>1)
                {
                double n1,c0,chi20,d0,m0,ck,chi2k,dk,mk,rho,pr;
                char *q;

                n1=atof(spb[i]);
                if (n1<(double)k) { sur_print("\nIncorrect N!"); WAIT; return; }
                c0=n1-1.0-(2.0*p+5.0)/6.0;
                chi20=c0*(sumlogsii-log(det));
                d0=p*(p-1.0)/2.0;
                m0=chi20/d0;
                ck=c0-2.0*k/3.0;
                chi2k=ck*f0;
                dk=((p-k)*(p-k)-p-k)/2.0;
                mk=chi2k/dk;
                rho=(m0-mk)/(m0-1.0);
//              pr=cdf_chi2(chi2k,dk,1e-10);
                pr=0.0;

                sprintf(x,"factors=%d Chi^2=%g df=%d P=%5.3f reliability=%g",
                            k,chi2k,(int)dk,pr,rho);
                if (rho>1.0) { q=strstr(x,"rel"); *q=EOS; } /* 3.6.1995 */

                print_line(x);
                }
            else
                {
                double n1,uu,dk,pr;

                n1=atof(spb[i]);
                if (n1<(double)k) { sur_print("\nIncorrect N!"); WAIT; return; }
                for (i=0; i<p; ++i) for (j=0; j<i; ++j)
                    {
                    da=0.0;
                    for (h=0; h<k; ++h) da+=L[i+p*h]*L[j+p*h];
                    S[i+p*j]=da; S[j+p*i]=da;
                    }  /* Huom. S-diagonaali säilytetään */
                mat_dcholinv(S,p,&uu);
                uu=(n1-1.0)*log(uu/det);
                dk=((p-k)*(p-k)+p-k)/2.0;   /* ei sama kuin yllä! */
//              pr=cdf_chi2(uu,dk,1e-10);
          pr=0.0;
                sprintf(x,"factors=%d Chi^2=%g df=%d P=%5.3f",
                            k,uu,(int)dk,pr);
                print_line(x);
                }
            }
        output_close(eout);

        f_orientation(L,p,k);
        text_labels(clab,k,lc,"F");
        matrix_save("FACT.M",L,p,k,rlab,clab,lr,lc,0,"F",0,0);
        strncpy(clab+k*lc,"h^2     ",8);
        for (i=0; i<p; ++i)
            {
            da=0.0;
            for (j=0; j<k; ++j)
                {
                db=L[i+p*j];
                S[i+p*j]=db;
                da+=db*db;
                }
            S[i+p*k]=da;
            }
        strcpy(acc,"12.1234567890123456");
        acc[accuracy-1]=EOS;
        matrix_print(S,p,k+1,rlab,clab,lr,lc,p,k+1,NULL,NULL,acc,c3,
                        results_line,eout,"Factor matrix");
        s_end(argv);
        }
Example #14
0
void update(void* instance)
{
    InstancePtr inst      = (InstancePtr) instance;
    MyInstancePtr my      = inst->my;
    int    options        = trim_int(inst->in_options->number, 0, INT_MAX);
    int    on_top         = options & 1;
    int    frame          = options & 2;
    int    mirrorx        = options & 4;
    int    mirrory        = options & 8;
    int    invert         = options & 16;
    int    monitor        = trim_int(inst->in_monitor->number, 0, 3);
    int    win_xsize      = trim_int(inst->in_xsize->number, 0, 2048);
    int    win_ysize      = trim_int(inst->in_ysize->number, 0, 2048);
    double brightness     = trim_double(inst->in_brightness->number, 0, 1);
    double contrast       = trim_double(inst->in_contrast->number, 0, 4);
    double gamma          = trim_double(inst->in_gamma->number, 0.01, 4);
    int    fb_xsize       = inst->in_in->xsize;
    int    fb_ysize       = inst->in_in->ysize;

    int result;
    char buffer[TEMP_BUF_SIZE] = "";
    const char* driver_name = inst->in_driver->text;
    const char* server_name = inst->in_server->text;

    if (strcmp(driver_name, my->driver_name->text) != 0 ||
            strcmp(server_name, my->server_name->text) != 0 ||
            my->drv == 0)
    {
        if (my->drv != 0)
        {
            get_drv_window_pos(my->drv, &my->win_xpos,&my->win_ypos);

            output_close(my->driver_name->text, my->server_name->text);
            my->drv = 0;
        }

        string_assign(my->driver_name, inst->in_driver);
        string_assign(my->server_name, inst->in_server);

        my->drv = output_open(driver_name, server_name);
        if (my->drv == 0)
            return;
    }

    assert(my->drv != 0);

    if (my->drv->inst == 0)
    {
        /** initialize the driver **/
        my->drv->inst = my->drv->new_instance(server_name,
                                              my->win_xpos, my->win_ypos,
                                              my->width, my->height,
                                              s_mmx_supported,
                                              buffer, sizeof(buffer));

        if (my->drv->inst == 0)
        {
            s_log(0, buffer);
            output_close(driver_name, server_name);

            my->drv = 0;
            return;
        }

        // reset parameters to make sure they are initialized below
        my->frame   = -1;
        my->monitor = -1;
        my->on_top  = -1;
    }

    assert(my->drv != 0);
    assert(my->drv->inst != 0);

    if (on_top != my->on_top && my->drv->always_on_top)
    {
        int res = my->drv->always_on_top(my->drv->inst,
                                         on_top,
                                         buffer, sizeof(buffer));
        if (!res)
            s_log(0, buffer);

        my->on_top  = on_top;
    }

    if (monitor != my->monitor && my->drv->to_monitor)
    {
        int res = my->drv->to_monitor(my->drv->inst,
                                      monitor,
                                      buffer, sizeof(buffer));
        if (!res)
            s_log(0, buffer);

        my->monitor = monitor;
    }

    if (win_xsize == 0 || win_ysize == 0)
    {
        win_xsize = fb_xsize;
        win_ysize = fb_ysize;
    }

    //  if (win_xsize != my->width || win_ysize != my->height)
    {
        int res = my->drv->resize(my->drv->inst, win_xsize, win_ysize,
                                  buffer, sizeof(buffer));

        if (!res)
        {
            char msg[128];
            snprintf(msg, sizeof(msg), "Could not resize: %s", buffer);
            s_log(0, msg);
        }

        my->width   = win_xsize;
        my->height  = win_ysize;
    }

    if (frame != my->frame && my->drv->frame)
    {
        int res = my->drv->frame(my->drv->inst,
                                 frame,
                                 buffer, sizeof(buffer));

        if (!res)
            s_log(0, buffer);
        my->frame = frame;
    }

    {
        struct blit_params params;
        params.mirrorx    = mirrorx;
        params.mirrory    = mirrory;
        params.brightness = brightness;
        params.contrast   = contrast;
        params.gamma      = gamma;
        params.invert     = invert;

        result = my->drv->blit(my->drv->inst,
                               (const uint8_t*) inst->in_in->framebuffer,
                               inst->in_in->xsize,
                               inst->in_in->ysize,
                               &params,
                               buffer, sizeof(buffer));
    }

    if (!result)
    {
        s_log(0, buffer);
    }
}
int main(){
	int FileSize;
	FileSize =0;
	int WriteSize;
	long tstmp;
	value_readfile_init();
	serial_init();
	wiringPiSetup();
	softPwmCreate(0,0,20000);
	softPwmCreate(1,0,20000);
	softPwmCreate(2,0,20000);
	softPwmCreate(3,0,20000);
	softPwmCreate(4,0,20000);
	softPwmCreate(5,0,20000);
	//i2c_init();
	gettimeofday(&timestart,NULL);
	get_filename(replayFileName);

	if(!encoder_init(&pic,fps,brightness,bitrate))
		goto error_encoder;
	if(!output_init(&pic,mkv_filename))
		goto error_output;

	encoded_pic.buffer=malloc(1024*100);
	encoded_pic.length=0;
	if(!encoder_encode_headers(&encoded_pic))
		goto error_output;
		
	memcpy(&header_pic,&encoded_pic,sizeof(encoded_pic));
	header_pic.buffer=malloc(1024*100);//(encoded_pic.length);
	printf("header_pic len:%d\n",encoded_pic.length);
	memcpy(header_pic.buffer,encoded_pic.buffer,encoded_pic.length);
	if(!output_write_headers(&encoded_pic))
		goto error_output;

	if(signal(SIGINT, stop_running) == SIG_ERR){
		printf("signal() failed\n");
		goto error_signal;
	}

	if(pthread_create(&thread[0], NULL, client_thread, NULL) != 0)         
               printf("client_thread error!\n");  
        else  
                printf("client_thread ok\n"); 
	if(pthread_create(&thread[1],NULL,schedule_do,NULL) != 0)
				printf("schedule_do error!\n");  
        else  
               printf("schedule_do ok\n");
	
    if(pthread_create(&thread[2],NULL,aircraft_thread,NULL) != 0)
				printf("aircraft_thread error!\n");  
        else  
               printf("aircraft_thread ok\n");
 	
	while (!camera_Quit) 
	{	
		gettimeofday(&timeend,NULL);
		tstmp=(timeend.tv_sec-timestart.tv_sec)*1000000ll+timeend.tv_usec-timestart.tv_usec;
		if(tstmp<(1000000/fps)){
			usleep(tstmp);
		}else{
			timestart.tv_sec=timeend.tv_sec;
			timestart.tv_usec=timeend.tv_usec;
			/*
			if(copycoded.length>0){
				
			if ((FileSize>MAX_SIZE) && (sendcoded.frame_type ==FRAME_TYPE_I)) {
				output_close();
				printf("file full\n");	
				get_filename(replayFileName);
				printf("file:%s\n",mkv_filename);
				
				if(!output_init(&pic,mkv_filename)){
					printf("output_init error\r\n");
					break;
				}
				if(!output_write_headers(&header_pic)){
					printf("output_write_headers error\r\n");
					break;
				}
			
				FileSize=0;
				//ResetTime(&pic,&encoded_pic);
				
				if(!output_write_frame(&copycoded)){
					printf("output_write_frame1 error\r\n");
					break;
				}
				//encoder_release(&encoded_pic);
			} else {
			
				if(!output_write_frame(&copycoded)){
					printf("output_write_frame2 error\r\n");
					break;
				}
				//encoder_release(&encoded_pic);
			}
			copycoded.length=0;
			}
			*/
		}
	}	
	error_signal:
	
	printf("exit the cam_thread\n");
	encode_Quit =1;
	//=========add==========
	free(sendcoded.buffer);
	//=========add==========
	schedule_do_Quit = 1;
	g_s32Quit = 1;	
	control_thread_go=1;
	printf("The device quit!\n");

	pthread_cancel(thread[0]); 
	pthread_cancel(thread[1]); 
	pthread_cancel(thread[2]); 
	
	if(thread[0])
		pthread_join(thread[0],NULL);
	if(thread[1])
		pthread_join(thread[1],NULL);
	if(thread[2])
		pthread_join(thread[2],NULL);
	
	error_output:

	error_cam_on:
		output_close();

	error_encoder:

	error_cam:
		serial_close();
		//i2c_close();
		return 0;
}
Example #16
0
int main()
{
	int s32MainFd,temp;
	struct timespec ts = { 2, 0 };


//=================================================
	ringmalloc(640*480);
	errno = 0;
	if(!camera_init(&pic))
		goto error_cam;
	if(!encoder_init(&pic))
		goto error_encoder;
	if(!preview_init(&pic))
		goto error_preview;
	get_filename();
	printf("file:%s\n",mkv_filename);
	if(!output_init(&pic,mkv_filename))
		goto error_output;
	if(!encoder_encode_headers(&encoded_pic))
		goto error_output;
	memcpy(&header_pic,&encoded_pic,sizeof(encoded_pic));
	header_pic.buffer=malloc(encoded_pic.length);
	memcpy(header_pic.buffer,encoded_pic.buffer,encoded_pic.length);
	if(!output_write_headers(&encoded_pic,&psp))
		goto error_output;
	encoder_release(&encoded_pic);
	if(!camera_on())
		goto error_cam_on;
	
//================================================

	printf("RTSP server START\n");

	PrefsInit();
	printf("listen for client connecting...\n");

	signal(SIGINT, IntHandl);

	s32MainFd = tcp_listen(SERVER_RTSP_PORT_DEFAULT);

	/* 初始化schedule_list 队列,创建调度线程,参考 schedule.c */
	if (ScheduleInit(&pic,&encoded_pic) == ERR_FATAL)
	{
		fprintf(stderr,"Fatal: Can't start scheduler %s, %i \nServer is aborting.\n", __FILE__, __LINE__);
		return 0;
	}

	/* 将所有可用的RTP端口号放入到port_pool[MAX_SESSION] 中 */
	RTP_port_pool_init(RTP_DEFAULT_PORT);

	//循环等待
	if((temp = pthread_create(&thread[0], NULL, cam_thread, NULL)) != 0)         
                printf("cam_thread error!\n");  
        else  
                printf("cam_thread ok\n"); 
	pthread_mutex_init(&mut,NULL);
	while (!g_s32Quit)
	{
		nanosleep(&ts, NULL);

		/*查找收到的rtsp连接,
	    * 对每一个连接产生所有的信息放入到结构体rtsp_list中
	    */
//		trace_point();
		EventLoop(s32MainFd);
	}
	ringfree();
	printf("The Server quit!\n");


	camera_off();
error_cam_on:
	output_close();
error_output:
	preview_close();
error_preview:
	encoder_close();
error_encoder:
	camera_close();
error_cam:

	return NULL;
}
/**
 * \brief main function
 */
int	main(int argc, char *argv[]) {
	int	ierr;
	int	num_procs;
	int	tag = 1;
	double	h = 1;
	int	steps = 1;
	char	*basedir = NULL;

	udata_t	udata;
	udata.nx = 1;
	udata.ny = 1;
	udata.dimension = 16;
	udata.algorithm = 0;
	udata.picturesteps = 1;

	// initialize MPI
	ierr = MPI_Init(&argc, &argv);
	if (ierr) {
		fprintf(stderr, "cannot initialize MPI: %d\n", ierr);
		return EXIT_FAILURE;
	}

	// get MPI dimension parameters
	ierr = MPI_Comm_rank(MPI_COMM_WORLD, &udata.rank);
	ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
	char	rankprefix[10];
	snprintf(rankprefix, sizeof(rankprefix), "%d", udata.rank);

	if (debug) {
		fprintf(stderr, "%s:%d[%d]: process id %d\n",
			__FILE__, __LINE__, udata.rank, getpid());
	}

	// parse the command line
	int	c;
	while (EOF != (c = getopt(argc, argv, "b:dh:r:s:t:x:y:n:a:?")))
		switch (c) {
		case 'd':
			debug++;
			break;
		case 's':
			udata.picturesteps = atoi(optarg);
			break;
		case 't':
			udata.maxsteps = atof(optarg);
			break;
		case 'x':
			udata.nx = atoi(optarg);
			break;
		case 'y':
			udata.ny = atoi(optarg);
			break;
		case 'b':
			basedir = optarg;
			break;
		case 'n':
			udata.dimension = atoi(optarg);
			break;
		case 'a':
			udata.algorithm = atoi(optarg);
			break;
		case '?':
			usage(argv[0]);
			return EXIT_SUCCESS;
		}


	udata.maxsteps = udata.dimension + udata.dimension;
	udata.h = 1 / udata.dimension;

	// make sure the arguments are consistent
	if (num_procs != udata.nx * udata.ny) {
		fprintf(stderr, "number of processes does not match "
			"dimensions: %d != %d x %d\n", num_procs, udata.nx,
			udata.ny);
		usage(argv[0]);
		return EXIT_FAILURE;
	}

	// compute horizontal and vertical index of this rank
	udata.rh = udata.rank % udata.nx;
	udata.rv = udata.rank / udata.nx;
	if (debug) {
		fprintf(stderr, "%s:%d[%d]: rh = %d, rv = %d\n",
			__FILE__, __LINE__, udata.rank, udata.rh, udata.rv);
	}

	// next argument is image file name
	if (argc <= optind) {
		fprintf(stderr, "image file name argument missing\n");
		usage(argv[0]);
		return EXIT_FAILURE;
	}
	char	*imagefilename = argv[optind++];

	// next argument is output file name
	char	*netcdffilename = NULL;
	if (argc > optind) {
		netcdffilename = argv[optind++];
		if (debug) {
			fprintf(stderr, "%s:%d: netcdffilename: %s\n",
				__FILE__, __LINE__, netcdffilename);
		}
	}

	// image file and output file
	heatfile_t      *hf = NULL;
	image_t	*image = NULL;
	
	// process zero initializes and writes data
	if (udata.rank == 0) {
		// read the image file
		image = readimage(imagefilename);
		if (NULL == image) {
			fprintf(stderr, "cannot read image\n");
			return EXIT_FAILURE;
		}
		if (debug) {
			fprintf(stderr, "%s:%d[%d]: %d x %d image read\n",
				__FILE__, __LINE__, udata.rank,
				image->width, image->height);
		}

		// create the output file
		if (netcdffilename) {
			if (debug) {
				fprintf(stderr, "%s:%d: creating NetCDF %s\n",
					__FILE__, __LINE__, netcdffilename);
			}
			hf = output2_create(netcdffilename, h,
				steps * udata.ht, image->width, image->height);
			if (NULL == hf) {
				fprintf(stderr, "cannot create output file\n");
				return EXIT_FAILURE;
			}
		}
	}

	// write the first image
	if ((basedir) && (udata.rank == 0)) {
		char	outfilename[1024];
		snprintf(outfilename, sizeof(outfilename), "%s/00000.fits",
			basedir);
		writeimage(image, outfilename);
	}

	// index ranges for each rank
	udata.ranges = (int *)malloc(4 * num_procs * sizeof(int));
	if (udata.rank == 0) {
		partitiondomain(&udata, image);
	}

	// exchange range size information with all other ranks. The ranks
	// then pick the dimensions they need from the array, this is
	// the purpose of the range pointer
	MPI_Bcast(udata.ranges, 4 * num_procs, MPI_INT, 0, MPI_COMM_WORLD);
	int	*range = &udata.ranges[4 * udata.rank];
	if (debug) {
		fprintf(stderr, "%s:%d:[%d]: [%d,%d) x [%d,%d)\n",
			__FILE__, __LINE__, udata.rank,
			range[0], range[1], range[2], range[3]);
	}

	// allocate memory for the area we are responsible for
	udata.width = range[1] - range[0];
	udata.height = range[3] - range[2];
	allocate_u(&udata);
	double	*unew = (double *)malloc(udata.length * sizeof(double));
	if (debug) {
		fprintf(stderr, "%s:%d[%d]: arrays allocated, %d x %d\n",
			__FILE__, __LINE__,
			udata.rank, udata.width, udata.height);
	}

	// write initial data to the output file
	if ((hf) && (udata.rank == 0)) {
		output2_add(hf, 0, image->data);
	}

	// measure start time (after all allocations are done)
	double	start = gettime();

	// process 0 has to send the data to all the other processes
	if (udata.rank == 0) {
		for (int r = 1; r < num_procs; r++) {
			sendimagerange(&udata, image, r, tag);
		}
		copyfromimage(&udata, image);
	} else {
		// receive my part of the matrix
		receiverange(&udata, tag);
	}
	tag++;

	// make sure dimension is correct
	if (udata.dimension != udata.height + udata.width) {
		fprintf(stderr, "dimension does not match\n");
		return EXIT_FAILURE;
	}

	// start the solver algorithm
	int	stepcounter = 0;	// counter for time steps
	while (stepcounter < udata.maxsteps) {
		stepcounter++;

		// copy everything to unew as the initial approximation
		for (int i = 0; i < udata.length; i++) {
			unew[i] = udata.u[i];
		}

		// now perform <picturesteps> iterations
		for (int k = 0; k < udata.picturesteps; k++) {
			// synchronize current values of boundary with neighbors
			tag++;
			exchange_boundaries(&udata, tag);

			// perform iteration step
			iterate_u(unew, &udata);

			// copy the new u to the old u / only used for Jacobi
			if (udata.algorithm == 0) {
				for (int i = 0; i < udata.length; i++) {
					udata.u[i] = unew[i];
				}
			}
		}

		// decide whether we have to output something
		if (0) {
			// time value for this data output
			int	stepvalue = stepcounter / udata.picturesteps;

			// output needed, so we synchronize image data
			tag++;
			synchronize_image(&udata, image, tag);

			// write an image
			if ((basedir) && (udata.rank == 0)) {
				char	outfilename[1024];
				snprintf(outfilename, sizeof(outfilename),
					"%s/%05d.fits", basedir, stepvalue);
				writeimage(image, outfilename);
			}

			// write solution data
			if ((hf) && (udata.rank == 0)) {
				output2_add(hf, stepvalue, image->data);
			}
		}
	}

	// measure end time
	double	end = gettime();

	// we are now done, rank 0 displays the result
	if (udata.rank == 0) {
		printf("%.6f",end - start);
	}

	// close the netcdf file
	if ((udata.rank == 0) && (hf)) {
		output_close(hf);
	}

	// cleanup MPI
	MPI_Finalize();

	// cleanup the memory we have allocated
	free(udata.ranges); udata.ranges = NULL;
	free_u(&udata);

	return EXIT_SUCCESS;
}
Example #18
0
static int rnd_printout()
        {
        int i,k;
        double a,a1,a2,a3,sumx,sumx2,sumy,sumy2,df;
        double mean,stddev,amax;
        char s1[LLENGTH],s2[LLENGTH],s3[LLENGTH];


        if (n<3L) { sprintf(sbuf,"\nOnly %d active observations!",n);
                    sur_print(sbuf); WAIT; return(-1);
                  }
        output_open(eout);
        mean=sum1/(double)n;
        stddev=sqrt((sum2-sum1*sum1/(double)n)/(double)(n-1));
        sprintf(sbuf,"Testing randomness of %s in data %s",word[2],word[1]);
        print_line(sbuf);
        fnconv2(mean,accuracy+2,s1); fnconv2(stddev,accuracy+2,s2);
        fnconv2(stddev/sqrt((double)n),accuracy+2,s3);
        sprintf(sbuf,"N=%d mean=%s stddev=%s SE[mean]=%s",n,s1,s2,s3); print_line(sbuf);
        if (stddev<1e-15) { sprintf(sbuf,"\nVariable %s is constant=%g",
                            word[2],mean); sur_print(sbuf); WAIT; return(-1);
                           }
        if (n_sub) sub_results();
        if (fr_n) fr_results();
        for (imax=MAXRUN-1; imax>=0; --imax)
            {
            if (runs_up[imax]+runs_down[imax]>0) break;
            }
        runs_hald();
        runtest2();

        if (maxlag)
            {
            amax=0.0;
            a=sum1*sum1/(double)n;
            a1=sum2-a;
            print_line(" ");
            print_line("   Lag    Autocorrelation");
            sumx=sumy=sum1; sumx2=sumy2=sum2;
            for (i=0; i<maxlag; ++i)
                {
                a=first_x[i];
                sumx-=a; sumx2-=a*a;
                a=lagv[lagpos];
                sumy-=a; sumy2-=a*a;
                if (lagpos>0) --lagpos; else lagpos=maxlag-1;
                df=n-(int)(i+1);
                a=lagvv[i]-sumx*sumy/df;
                a1=sumx2-sumx*sumx/df; a2=sumy2-sumy*sumy/df;
                a2=a/sqrt(a1*a2);
                if (fabs(a2)>amax) amax=fabs(a2);
                a3=2*muste_cdf_std(-fabs(a2)*sqrt((double)n));
                fnconv(a2,accuracy,s1);
/*  Rprintf("\nlag=%d sumx=%g sumx2=%g sumy=%g sumy2=%g S=%g",
                i+1,sumx,sumx2,sumy,sumy2,lagvv[i]); getch();
*/
                k=sprintf(sbuf,"%6d    %s",i+1,s1);
                if (a3<0.1)
                    {
                    k+=sprintf(sbuf+k," P=%g",a3);
                    }
                if (i==maxlag-1) { fnconv2(amax,accuracy,s1); k+=sprintf(sbuf+k,"  max.autocorr.=%s",s1); }
                print_line(sbuf);
                }
            }
        if (maxgap) gap_results();
        if (permlen) perm_results();
        if (poklen) poker_results();
        if (couplen) coup_results();
        output_close(eout);
        return(1);
        }
Example #19
0
static int goodness_of_fit_test(FREQ *f,int m,int n)
    {
    int i,j;
    double a,x2;

    if (n!=2)
        {
        sprintf(sbuf,"\nTable must have 2 columns (expected and observed) frquencies!");
        sur_print(sbuf); WAIT; return(-1);
        }
    if (m<2)
        {
        sprintf(sbuf,"\nTable must have at least two rows!");
        sur_print(sbuf); WAIT; return(-1);
        }

    e=(double *)muste_malloc(m*sizeof(double));
    ecum=(double *)muste_malloc(m*sizeof(double));
    o=(int *)muste_malloc(m*sizeof(int));
    n2=0; for (i=0; i<m; ++i) { o[i]=f[i]; n2+=o[i]; }
    n1=0; for (i=0; i<m; ++i) n1+=f[i+m];
    a=(double)n2/(double)n1;

    for (i=0; i<m; ++i) e[i]=a*f[i+m];
    a=0.0; for (i=0; i<m; ++i) { a+=e[i]; ecum[i]=a; }
    for (i=0; i<m; ++i) ecum[i]/=ecum[m-1];

    g_print=&sur_print;

    x2=chi_square(m);
// Rprintf("\nx2=%g n2=%d",x2,n2); getch();

    maxcount=1000000L;
    i=spfind("SIMUMAX");
    if (i>=0) maxcount=atol(spb[i]);
    i=rand_init(); if (i<0) return(-1);

    conf_level=0.95;
    i=spfind("CONF");
    if (i>=0) conf_level=atof(spb[i]);
    if (conf_level<0.8 || conf_level>=1.0)
        {
        sur_print("\nError in CONF=p! Confidence level p must be 0.8<p<1");
        WAIT; return(-1);
        }
    conf_coeff=muste_inv_std(1.0-(1.0-conf_level)/2);

    disp0fit(m,n,x2);

    dn=10000L;
    i=spfind("GAP");
    if (i>=0) dn=atol(spb[i]);
    count=0L; pcount=0L; dcount=0L; ecount=0L;

    while (1)
        {
        ++count; ++dcount;
        for (i=0; i<m; ++i) o[i]=0;
        for (j=0; j<n2; ++j)
            {
            a=(*rand1)();
            i=0;
            while (a>ecum[i]) ++i;
            ++o[i];
            }
// Rprintf("\no: "); for (i=0; i<m; ++i) Rprintf("%d ",o[i]);
// a=chi_square(m); Rprintf("\na=%g",a);
        if (chi_square(m)>=x2) ++pcount;

        if (dcount>=dn)
            {
            tab_disp();
            if (count>=maxcount) break;
            if (sur_kbhit()) { sur_getch(); break; }           
            WAIT;
            dcount=0;
            }

        }
// Rprintf("\np=%g",(double)pcount/(double)count); getch();
    g_print=&print_line;

    output_open(eout);
    disp0fit(m,n,x2);
    tab_disp();
    output_close(eout);

    return(1);
    }
Example #20
0
int main(int argc, char** argv) 
{
	char *record;
	char *block;									//endiamesos xwros mnhmhs ston opoio ekxwroun ta block oi reducers//
	int i,j,fd;
	char buffer[56];								//pinakas ston opoion sxhmatizoume to katallhlo format gia ta pipenames//
	pid_t pid;
	int status;
	fd_set read_set, active_set;							//ta set me tous file descriptors pou xrhsimopoiei h select//
	BUFFERS *buffers;								//deikths sthn arxh twn buffers//
	
	struct sigaction sig_act;

	if (argc!=3)									//onoma ektelesimou, #Mappers, #Reducers//
	{
		printf("Usage:%s  #Mappers  #Reducers\n",argv[0]);
		return -1;
	}
	
	sig_act.sa_handler=handler1;     		    				//Signal Handler1 gia ton patera//
	sig_act.sa_flags=0;
											//prosthetw ta simata sto set tou patera.
	if ((sigemptyset(&sig_act.sa_mask ) == -1) || (sigaction(SIGINT,&sig_act,NULL) == -1 ) 
	|| (sigaction(SIGQUIT,&sig_act,NULL) == -1 ) || (sigaction(SIGTERM,&sig_act,NULL) == -1 ))
	{
	      perror("FAIL TO INSTAL  SIGNAL HANDLER FOR SIGUSR1");
	      return -1;
	}
	Mappers=atoi(argv[1]);
	Reducers=atoi(argv[2]);
	for(i=0;i<Mappers;i++)								//dhmiourgia twn pipes prin dhmiourgh8oun ta paidia//
	{
		for (j=0;j<Reducers;j++)
		{
			buffer[0]='\0';
			sprintf(buffer,".pipe.%d.%d",i+1,j+1);				
			if ( mkfifo(buffer,0666 )==-1)	
       			{
                        	perror("mkfifo");
				removepipes(Mappers,Reducers);
                        	return -1;
                	}
		}
	}
	mkdir("./output_folder",0700);					//dhmiourgoume ton output folder//
	for(i=0;i<Mappers+Reducers;i++)							//kanena paidi den exei dhmiourgh8ei akoma//							
		pids[i]=0;
	for(i=0;i<Mappers+Reducers;i++)
	{
 		pids[i]=pid=fork();
		if (pid<0)								//periptwsh apotyxias fork()//
        	{									//epeidh den 3eroume posa paidia exoun gennh8ei epityxws,ara posa prepei na//
        		perror("fork failed\n");					//skotwsoume,o pateras stelnei ena SIGINT ston eauto tou kai o handler tou patera//
               		kill(getpid(),SIGINT);						//eidopoiei ta gennhmena paidia na termatisoun//
			removepipes(Mappers,Reducers);
                        return -1;
        	}
		else if ( pid==0 )							//to paidi vgainei apo to loop ka8ws mono h Initial prepei na kanei fork()//
			break;
	}
	if (pid==0)									//an eimaste sto paidi//
	{
		sigset_t ign_signals;
		
		//prosthetw sta 3 simata sto set twn paidiwn kai meta ta mplokarw//
		if ( (sigemptyset(&ign_signals ) == -1) || (sigaddset(&ign_signals,SIGINT) == -1 ) || (sigaddset(&ign_signals,SIGQUIT) == -1 ) 
				|| (sigaddset(&ign_signals,SIGTERM) == -1 ))
		{
	      		kill(getppid(),SIGINT);
		}
		else
			sigprocmask(SIG_BLOCK,&ign_signals,NULL);

 		
		sig_act.sa_handler=handler2;     		    			 //Signal Handler2-o handler twn paidiwn//
		sig_act.sa_flags=0;
		//orizw ton handler na antistoixei sto SIGUSR1, pou stelnei o parent//
		if ((sigemptyset(&sig_act.sa_mask ) == -1) || (sigaction(SIGUSR1,&sig_act,NULL) == -1 ))
	      		kill(getppid(),SIGINT);
		for(i=0;i<Mappers+Reducers;i++)						//anazhtw ston pinaka me ta pids to 10 mhdeniko,pou ypodeiknyei th seira gennhshs//
			if (pids[i]==0)
				break;
		i++;									//auti einai i thesi mou, gia na 3exwrizw an eimai maper i reducer//
		if (i<=Mappers)								//kwdikas tou mapper//
		{
			MRIFILE* fp;
			buffers=calloc(Reducers,sizeof(struct BUFFERS));		//desmeuoume mnhmh gia tosous buffers osoi einai kai oi reducers//	
			for (j=0;j<Reducers && !error ;j++)
			{
				buffer[0]='\0';
				sprintf(buffer,".pipe.%d.%d",i,j+1);			//dinoume onoma sta pipe//
				if ( (fd=open(buffer,O_WRONLY))<0 ) 			//anoigei to pipe gia grapsimo//
       		                {
					if ( errno != EINTR )				//an yparxei la8os k den einai apo shma//
        	                        	kill(getppid(),SIGINT);			//steile to shma //
	       	                	perror("Mapper::open");				//alliws ginetai allo la8os sthn open//
					free(buffers);					//kai apodesmevoume tous porous tou mapper//
					return -1;
        	                }
				initialize(buffers, j, fd);				//arxikopoioume tous buffers//
			}
			DIR             *dip;
			struct dirent   *dit;
			if ( (dip = opendir("input_folder")) == NULL)			//anoigoume ton inputfolder//
       			{
				if ( errno != EINTR )                           	//an yparxei la8os k den einai apo shma//
                                	kill(getppid(),SIGINT);                 	//steile to shma //
                                perror("Mapper::opendir");                         	//alliws ginetai allo la8os sthn open//
        		}
			while ((dit = readdir(dip)) != NULL  &&  !error)		//oso exoume files gia diavasma//
        		{
                		if ( strncmp(dit->d_name,"file_",5) == 0)		//an oi prwtoi 5 xarakthres twn 2 autwn string einai idioi,dhladh an einai file_//
				{
					int filenumber;					//ari8mos arxeiou input//
					
					sscanf(dit->d_name,"file_%d",&filenumber);	//kanw retrieve ton ari8mo tou trexodos arxeiou//
					if ( filenumber%Mappers+1==i)			//apofasizoume me katakermatismo poios mapper 8a diavazei apo ka8e file//
					{	
						char filename[50];
						sprintf(filename,"./input_folder/%s",dit->d_name);
						fp=input_open(filename);			//anoigoume to file//
						while ( (record=input_next(fp))!= NULL )	//kai oso uparxoun eggrafes gia diavasma//
						{						//kaleitai h addrecord gia pros8hkh eggrafwn stous buffers//
							addrecord(buffers,record,partition(map(record).key,Reducers));	
						}
						input_close(fp);			//kleinoume to file//
					}
				}
			}
			closedir(dip);							//kleinoume kai ton katalogo//
			for (j=0; j<Reducers && error==0; j++)				
			{
				if ( buffers[j].curbyte != 4 ){
					if ( my_write(buffers[j].pipedesc,buffers[j].block)!= BLKSIZE )	//grafoume sto pipe oses eggrafes exoun 3emeinei//
        	                       		printf("error here\n");
				}
			}
			for (j=0;j<Reducers;j++)
                       	{
				close(buffers[j].pipedesc);				//kleinoume ta pipe afou exoume diavasei//
			}
			free(buffers);							//afou teleiwnoume me to diavasma apodesmevoume taous buffers//
		}
		else									//kwdikas tou reducer//
		{
			char **keys;
			char **values;
			char *tempkey;							//deikths sthn prwth 8esh tou pinaka twn keys//
			char **tempval;							//deikths sthn prwth 8esh tou pinaka twn values//
			int counter;
			int total_records=0;
			int memsize=100;
			int whoami;							//8esh mias diergasias ston pinaka twn paidiwn//
			whoami=i;
			char buffer[40];
			MROFILE *fp;

			sprintf(buffer,"./output_folder/file_%d",whoami-Mappers);	//ka8orismos twn files sto output folder gia ton ka8e reducer
                        fp=output_open(buffer);

			if (  (keys=calloc(memsize,sizeof(char*))) == NULL		//an exoume provlhma me th desmeush tou pinaka gia ta keys,h' ta values// 
			|| (values=calloc(memsize,sizeof(char*)))==NULL 		//h' to block ,tote//
			|| (block=calloc(BLKSIZE,sizeof(char)))==NULL )
			{
			 	kill(getppid(),SIGINT);					//stelnoume shma ston patera//
			}
			FD_ZERO(&read_set);						//mhdenizoume to set twn file descriptors twn pipe//
			for (j=0;j<Mappers;j++)
			{
				buffer[0]='\0';
				sprintf(buffer,".pipe.%d.%d",j+1,i-Mappers);	
				if ( (fd=open(buffer,O_RDONLY))<0 ) 			//anoigoume to pipe gia diavasma//
       		                {
					if ( errno != EINTR )				//an yparxei la8os kai den einai apo shma//
						kill(getppid(),SIGINT);			//tote stelnoume to shma//
        	                	perror("Reducer::open");
					break;
        	                }
				FD_SET(fd,&read_set);					//pros8etoume ton fd sto readset//
			}
			active_set=read_set;
			int closed=0;							//arxikopoioume to plh8os twn diavasmenwn fds//
			while ( error==0 && closed != Mappers)				//oso uparxoun fds sto active set kai den lavei shma//
			{
				read_set=active_set;
				int chosen;
				if ( (chosen=select(FD_SETSIZE,&read_set,NULL,NULL,NULL)) < 0) 		
				{
					if ( errno != EINTR ){
                                                kill(getppid(),SIGINT);
						error=1;
					}
					perror("select");				//alliws yparxei provlhma sth select//
					break;
				}
				else							//h select epistrefei ton katallhlo fd//
				{
					for (i = 0; i < FD_SETSIZE; i++)		//gia olous tous fds pou yparxoun mesa sto set//
					{
             					if (FD_ISSET (i, &read_set))		//an o i fd einai melos tou read set otan epistrepsei h select//
						{
							if ( (chosen=my_read(i,block))<0 )		//diavase apo ton i fd//
							{
								if ( errno != EINTR )
								{
                                         			       	kill(getppid(),SIGINT);
                                                			error=1;
                                        			}
								perror("read");
								break;
							}
							else if ( chosen==0 )			
							{
								FD_CLR (i, &active_set); 	//afairei ton i fd apo to active set//
								closed++;			//au3anetai kata ena o ari8mos twn fds pou diavasthkan//
								close(i);			//kleinei o i fd//
								if ( closed == Mappers )
									break;
							}
							else
								retrieve_records(block,&keys,&values,&total_records,&memsize);
						}
					}
				}
			}
			printf("%s\n",keys[10000]);
			printf("%d\n",total_records);
			if ( error==0 )								//an den exoume lavei shma//
			{
				sort(keys, values, total_records,compare);						
        	                tempkey=keys[0];						//o deikths tempkey deixnei sthn 1h 8esh tou pinaka twn keys//
                	        tempval=values;
                        	counter=1;
                	        for ( i=1; i<total_records; i++)
                        	{
                               		if ( compare(tempkey,keys[i]) == 0 )			//an ta kleidia se dyo diadoxikes 8eseis tou pinaka einai idia//
                                	        counter++;					//au3anetai kata 1 to plh8os twn eggrafwn me to idio kleidi//	
                       		        else							//an ta kleidia se dyo diadoxikes 8eseis tou pinaka einai diaforetika//
                                	{
						output_next(fp,reduce(tempkey,tempval,counter));//kaleitai h reduce kai grafoume to apotelesma sto output file.//
                         	                counter=1;					//epilegoume neo kleidi//
                                	        tempkey=keys[i];				//h kainouria 8esh tou tempkey//
                                        	tempval=values+i;				//h kainouria 8esh tou tempval//
                                	}
        	                }
			}
			output_close(fp);							//kleinoume to output file tou kathe reducer//
			if ( block != NULL )							//apodesmeush twn porwn tou reducer//
				free(block);
			if ( keys != NULL && values!= NULL )					//an den exei ginei la8os kata th desmeush//
			{									//apodesmeuoume olh th dunamika desmeumenh mnhmh//
				for(i=0;i<memsize;i++)						
				{
					if ( keys[i]!=NULL && values[i]!=NULL )
					{
						free(keys[i]);
						free(values[i]);
					}
				}
				free(keys);
				free(values);
			}
			for (i = 0; i < FD_SETSIZE; i++)					//kleinoume olous tous file descriptors pou vriskodai sto active set//
                              if (FD_ISSET (i, &active_set))   
					close(i);
		}	
	}
	else											//alliws an eisai ston patera,Initial process//
	{
		while ( (pid=r_wait(NULL))>0 )							//perimenei ta paidia tou na teleiwsoun// 
		{	
			fprintf(stderr,"Child %d finished\n",pid);
		}	
		removepipes(Mappers,Reducers);							//svhsimo twn pipes//
	}
	return 0;
	
}
Example #21
0
void muste_t2test(char *argv)
        {
        int i,k;
        int l,l2;

//      if (argc==1) return(1);
        s_init(argv);
        if (g<3)
            {
            sur_print("\nUsage: T2TEST <data1>,<data2>,<output_line>");
            WAIT; return;
            }
        tulosrivi=0;
        if (g>3)
            {
            tulosrivi=edline2(word[3],1,1);
            if (tulosrivi==0) return;
            }

        simumax=10000;
        i=spec_init(r1+r-1); if (i<0) return;
        if ((i=spfind("RESULTS"))>=0) results=atoi(spb[i]);

    x=NULL;
    v=NULL;
    xx=NULL;
    ind=NULL;
    s=NULL;
    s2=NULL;
    ss[0]=NULL;
    ss2[0]=NULL;
    ss[1]=NULL;
    ss2[1]=NULL;
    ss_inv=NULL;
    ss_apu=NULL;
    ss_apu2=NULL;
    ero=NULL;

        i=hae_apu("prind",sbuf); if (i) prind=atoi(sbuf);
        if ((i=spfind("PRIND"))>=0) prind=atoi(spb[i]);

        if ((i=spfind("SIMUMAX"))>=0) simumax=atol(spb[i]);

        method=1;
        if ((i=spfind("METHOD"))>=0) method=atoi(spb[i]);

        fixed=0;
        if ((i=spfind("FIXED"))>=0) fixed=atoi(spb[i]);
        orig_samples=1;
        spec_rnd();
        strcpy(tempname,etmpd); strcat(tempname,"SURVOHOT.TMP");
        tempfile=muste_fopen(tempname,"wb");
        if (tempfile==NULL)
            {
            sprintf(sbuf,"\nCannot open temporary file %s!",tempname);
            sur_print(sbuf); WAIT; return;
            }

        strcpy(aineisto[0],word[1]);
        i=data_read_open(aineisto[0],&d); if (i<0) return;
        i=mask(&d); if (i<0) return;
        m=d.m_act;
        if (m==0)
            {
            sur_print("\nNo active variables!");
            WAIT; return;
            }

        x=(double *)muste_malloc(m*sizeof(double));
        if (x==NULL) { not_enough_memory(); return; }
        v=(int *)muste_malloc(m*sizeof(int));
        if (v==NULL) { not_enough_memory(); return; }

        for (i=0; i<m; ++i) v[i]=d.v[i];

        sur_print("\n");
        talleta(1);   /* data 1 */
        data_close(&d);

        strcpy(aineisto[1],word[2]);
        i=data_read_open(aineisto[1],&d); if (i<0) return;
        i=mask(&d); if (i<0) return;

        if (d.m_act!=m) { data_error(); return; }
        for (i=0; i<m; ++i)
            {
            if (v[i]!=d.v[i]) {data_error(); return; }
            }

        talleta(2);   /* data 2 */
        data_close(&d);
        muste_fclose(tempfile);
        n[0]=n[1]+n[2];

        tempfile=muste_fopen(tempname,"rb");

        xx=(double *)muste_malloc(n[0]*m*sizeof(double));
        if (xx==NULL) { not_enough_memory(); return; }

        fread(xx,sizeof(double),n[0]*(int)m,tempfile);
        muste_fclose(tempfile);

        ind=muste_malloc(n[0]);
        if (ind==NULL) { not_enough_memory(); return; }
        s=muste_malloc(m*sizeof(double));
        if (s==NULL) { not_enough_memory(); return; }
        s2=muste_malloc(m*m*sizeof(double));
        if (s2==NULL) { not_enough_memory(); return; }


        for (l=0; l<n[0]; ++l) ind[l]='1';
        laske_summat(s,s2);
// Rprintf("s: %g %g\n",s[0],s[1]); getch();

        ss[0]=muste_malloc(m*sizeof(double));
        if (ss[0]==NULL) { not_enough_memory(); return; }
        ss2[0]=muste_malloc(m*m*sizeof(double));
        if (ss2[0]==NULL) { not_enough_memory(); return; }

        ss[1]=muste_malloc(m*sizeof(double));
        if (ss[1]==NULL) { not_enough_memory(); return; }
        ss2[1]=muste_malloc(m*m*sizeof(double));
        if (ss2[1]==NULL) { not_enough_memory(); return; }

        ss_inv=muste_malloc(m*m*sizeof(double));
        if (ss_inv==NULL) { not_enough_memory(); return; }
        ss_apu=muste_malloc(m*m*sizeof(double));
        if (ss_apu==NULL) { not_enough_memory(); return; }
        ss_apu2=muste_malloc(m*m*sizeof(double));
        if (ss_apu2==NULL) { not_enough_memory(); return; }
        ero=muste_malloc(m*sizeof(double));
        if (ero==NULL) { not_enough_memory(); return; }



// Todelliset otokset
        for (l=0; l<n[0]; ++l) ind[l]='0';
        for (l=0; l<n[1]; ++l) ind[l]='1';

        t2_0=T2();
        p_hot=1.0-muste_cdf_f((double)(n[0]-m-1)/(n[0]-2)/(double)m*t2_0,
                        (double)m,(double)(n[1]+n[2]-m-1),1e-15);

        if (method==2)
            {
            t2_BF0=T2_BF();
            yao_test();
            print_t2_yao();
            }
// Rprintf("\nt2: %g %g",t2_0,t2_BF0); getch();
        else
            print_t2_hot();

        if (fixed) orig_samples=0;

        ++scroll_line;
        nn1=0L; k=0;
        if (simumax) sur_print("\nInterrupt by '.'");

        for (nn=1; nn<=simumax; ++nn)
            {
// Rprintf("\nnn=%d",nn);
            for (l=0; l<n[0]; ++l) ind[l]='0';
            for (l=0; l<n[1]; ++l)
                {
                while (1)
                    {
                    l2=n[0]*uniform_dev();
                    if (ind[l2]=='1') continue;
                    ind[l2]='1'; break;
                    }
                }

            if (method==1)
                {
                t2_1=T2();
// Rprintf("t2: %g %g\n",t2_1,t2_0); getch();
                if (t2_1>t2_0) ++nn1;
                }
            else
                {
                t2_1=T2_BF();
// Rprintf("t2: %g %g\n",t2_1,t2_BF0); getch();
                if (t2_1>t2_BF0) ++nn1;
                }

            ++k;
// Rprintf("t2=%g\n",t2_1); i=getch(); if (i=='.') break;
/**********************************
            if (sur_kbhit())
                {
                i=sur_getch(); if (i=='.') break;
                prind=1-prind;
                }
***********************************/
            if (k>=1000 && prind)
                {
                sprintf(sbuf,"\n%d %g  ",nn,(double)nn1/(double)nn);
                sur_print(sbuf);
                k=0;
                }
            }
// Rprintf("4"); sur_getch();
        output_open(eout);
        --nn;
    if (method==1)
        {
        eoutput("Hotelling's two-sample test for equality of mean vectors:");
        sprintf(sbuf,"T2=%g p=%d n1=%d n2=%d P1=%g",
                    t2_0,m,n[1],n[2],p_hot);
        }
    else
        {
        eoutput("Yao's two-sample test for equality of mean vectors:");
        sprintf(sbuf,"T2=%g P1=%g (assuming nonequal cov.matrices)",
                    t2_BF0,p_yao);
        }
        eoutput(sbuf);
        if (simumax>0L)
            {
            eoutput("Randomization test:");
            p_sim=(double)nn1/(double)nn;
            sprintf(sbuf,"N=%d P=%g (s.e. %g) %s",
                nn,p_sim,sqrt(p_sim*(1-p_sim)/nn),method_text[method-1]);
            eoutput(sbuf);
            }
        output_close(eout);
        s_end(argv);
        return;
        }
Example #22
0
void muste_covtest(char *argv)
        {
        int i,k,h,kk;
        int l,l2,li;

     // if (argc==1) return(1);
        s_init(argv[1]);
        if (g<2)
            {
            sur_print("\nUsage: COVTEST <output_line>");
            sur_print("\n       SAMPLES=<data(1),...,<data(m)>");
            WAIT; return;
            }
        tulosrivi=0;
        if (g>1)
            {
            tulosrivi=edline2(word[1],1,1);
            if (tulosrivi==0) return;
            }
        i=spec_init(r1+r-1); if (i<0) return;
        if ((i=spfind("RESULTS"))>=0) results=atoi(spb[i]);
        i=hae_apu("prind",sbuf); if (i) prind=atoi(sbuf);
        if ((i=spfind("PRIND"))>=0) prind=atoi(spb[i]);

        simumax=10000;
        if ((i=spfind("SIMUMAX"))>=0) simumax=atol(spb[i]);

        spec_rnd();

        strcpy(tempname,etmpd); strcat(tempname,"SURVOCOV.TMP");
        tempfile=fopen(tempname,"wb");
        if (tempfile==NULL)
            {
            sprintf(sbuf,"\nCannot open temporary file %s!",tempname);
            sur_print(sbuf); WAIT; return;
            }

        i=spfind("SAMPLES");
        if (i<0)
            {
            sur_print("SAMPLES=<data(1),...,<data(m)> missing!");
            WAIT; return;
            }

        strcpy(y,spb[i]);
        ns=split(y,otos,S_MAX);
        if (ns<2)
            {
            sur_print("At least 2 samples must be given by SAMPLES!");
            WAIT; return;
            }

    x=NULL;
    v=NULL;
    xx=NULL;
    ind=NULL;

        nt=0L;
        for (k=0; k<ns; ++k)
            {
            strcpy(aineisto,otos[k]);
            i=data_read_open(aineisto,&d); if (i<0) return;
            i=mask(&d); if (i<0) return;
            if (d.m_act==0)
                {
                sur_print("\nNo active variables!");
                WAIT; return;
                }

            if (k==0)
                {
                m=d.m_act;
                x=(double *)muste_malloc(m*sizeof(double));
                if (x==NULL) { not_enough_memory(); return; }
                v=(int *)muste_malloc(m*sizeof(int));
                if (v==NULL) { not_enough_memory(); return; }
                for (i=0; i<m; ++i) v[i]=d.v[i];
                }

            if (k!=0)
                {
                if (d.m_act!=m) { data_error(k); return; }
                for (i=0; i<m; ++i)
                    {
                    if (v[i]!=d.v[i]) { data_error(k); return; }
                    }
                }
            sur_print("\n");
            talleta(k);   /* data k */
            data_close(&d);
            }

        muste_fclose(tempfile);


        tempfile=fopen(tempname,"rb");

        xx=(double *)muste_malloc(nt*m*sizeof(double));
        if (xx==NULL) { not_enough_memory(); return; }

        fread(xx,sizeof(double),nt*(int)m,tempfile);
        muste_fclose(tempfile);

        ind=muste_malloc(sizeof(short)*nt);
        if (ind==NULL) { not_enough_memory(); return; }

        for (k=0; k<ns+1; ++k)
            {
            s[k]=NULL;
            s[k]=muste_malloc(m*sizeof(double));
            if (s[k]==NULL) { not_enough_memory(); return; }
            s2[k]=NULL;
            s2[k]=muste_malloc(m*m*sizeof(double));
            if (s2[k]==NULL) { not_enough_memory(); return; }
            }

        l=0;
        for (k=0; k<ns; ++k)
            for (li=0L; li<n[k]; ++li) ind[l++]=k;

        laske_summat();
        l=0;
        for (k=0; k<ns; ++k)
            for (li=0; li<n[k]; ++li)
                {
                for (h=0; h<m; ++h)
                    xx[l+h]-=s[k][h]/n[k];
                l+=m;
                }

        t0=testi();
        os1=(double)(nt-ns)*m/2*log((double)(nt-ns));
        nim2=0.0; a=0.0;
        for (k=0; k<ns; ++k)
            {
            nim2+=(n[k]-1)*muste_log((double)(n[k]-1));
            a+=1.0/(n[k]-1);
            }
        x2=t0/2+os1-(double)m/2*nim2;
        a=1-(a-1.0/(nt-ns))*(2*m*m+3*m-1)/6.0/(m+1)/(k-1);
        x2*=-2*a;
// Rprintf("x2=%g\n",x2); getch();
        df=(double)m/2*(m+1)*(ns-1);
        pr_x2=1.0-muste_cdf_chi2(x2,df,1e-7);

/*****************************************************
os1=n*p/2*log(n)
os1=10326.054776478
os2=0.5*(n1*log(det1)+n2*log(det2)+n3*log(det3))
os2=8299.3933358899
nim1=n/2*log(det)
nim1=9932.2525957076
nim2=p/2*(n1*log(n1)+n2*log(n2)+n3*log(n3))
nim2=8697.69129334

logL=os1+os2-nim1-nim2
logL=-4.4957766798343

a=1-(1/n1+1/n2+1/n3-1/n)*(2*p*p+3*p-1)/6/(p+1)/(k-1)

X2=-2*a*logL
X2=8.9516537694752
df=p/2*(p+1)*(k-1)
********************************************************/

        print_t0(x2,df,pr_x2);
        ++scroll_line;
        nn1=0L; kk=0;
        for (nn=1; nn<=simumax; ++nn)
            {
            for (l=0; l<nt; ++l) ind[l]=0;
            for (k=1; k<ns; ++k)
                {
                for (l=0L; l<n[k]; ++l)
                    {
                    while (1)
                        {
                        l2=nt*uniform_dev();
                        if (ind[l2]!=(short)0) continue;
                        ind[l2]=k; break;
                        }
                    }
                }

            t1=testi();
            if (t1<t0) ++nn1;

            ++kk;
/*************************
            if (kbhit())
                {
                i=getch(); if (i=='.') break;
                prind=1-prind;
                }
******************************/
            if (kk==1000)
                {
                if (prind)
                     {
                     sprintf(sbuf,"\n%d %g  ",nn,(double)nn1/(double)nn);
                     sur_print(sbuf);
                     }
                kk=0;
                }
            }

        output_open(eout);
        --nn;
        eoutput("Comparing covariance matrices:");
        sprintf(sbuf,"Asymptotic X^2 test: X2=%g df=%g P=%g",x2,df,pr_x2);
        eoutput(sbuf);
        p_sim=(double)nn1/(double)nn;
        sprintf(sbuf,"Randomization test: N=%d P=%g (s.e. %g)",
            nn,p_sim,sqrt(p_sim*(1-p_sim)/nn));
        eoutput(sbuf);
        output_close(eout);

        s_end(argv);

        return;
        }
Example #23
0
static int tulosta()
        {
        int i,k,imin,h;
        int j,jj;
        int gr;
        int n_used;
        double min;
        char rivi[LLENGTH];
        char x[LLENGTH];

        hav=muste_fopen(tempfile,"r+b");
        output_open(eout);

        sprintf(rivi,"Stepwise cluster analysis by Wilks' Lambda criterion");
        eoutput(rivi);
        sprintf(rivi,"Data %s  N=%d",aineisto,n); eoutput(rivi);

        k=sprintf(rivi,"Variables: ");
        for (i=0; i<m; ++i)
            {
            strcpy(x,d.varname[d.v[i]]);
            h=strlen(x); while (h && x[h-1]==' ') x[--h]=EOS;
            k+=sprintf(rivi+k,"%s",x);
            if (i<m-1) k+=sprintf(rivi+k,", ");
            if (k>c3-10) { eoutput(rivi); k=0; }
            }
        if (k) eoutput(rivi);

        n_used=0;
        for (i=0; i<n_saved; ++i)
            {
            if (freq[i]==0) break;
            ++n_used;
            }

        if (it==1)
            {
            sprintf(rivi," Lambda=%g  Clustering saved in %s",f2,d.varname[gvar]);
            eoutput(rivi);
            }
        if (it>1)
            {
            sprintf(rivi,"Best clusterings found in %d trials are saved as follows:",it);
            eoutput(rivi);
            eoutput(" Lambda          freq  Grouping var");
            imin=0;
            for (i=0; i<n_used; ++i)
                {
                min=1e100;
                for (k=0; k<n_used; ++k)
                    {
                    if (lambda2[k]<min) { imin=k; min=lambda2[k]; }
                    }
                lambda2[imin]+=1000.0; ii[i]=imin;
                         /* ennen 7.11.89 =1e100 */
                sprintf(rivi,"%10.10f %6d   %s",min,freq[imin],d.varname[gvar2[i]]);
                eoutput(rivi);
                }
            }

        sur_print("\nSaving clusterings...");
        for (jj=0L; jj<n; ++jj)
            {
            if (sur_kbhit())
                {
                i=sur_getch(); prind=1-prind;
                }
            if (prind) { sprintf(sbuf," %d",jj+1); sur_print(sbuf); }
            hav_read2(jj,&j);
            if (it==1)
                {
                hav_read1(jj,&gr);
                data_save(&d,j,gvar,(double)gr);
                }
            else
                {
                for (i=0; i<n_used; ++i)
                    {
                    hav_read4(jj,ii[i],&gr);
                    data_save(&d,j,gvar2[i],(double)gr);
                    }
                }
            }


        if (it==1)
            {
            sprintf(x,"clustering in %d groups: Lambda=%g",ng,f2);
            kirjoita_lauseke(gvar,x);
            }
        else
            {
            for (i=0; i<n_used; ++i)
                {
                sprintf(x,"clustering %d in %d groups: Lambda=%g",i+1,ng,lambda2[ii[i]]-1000.0);
                kirjoita_lauseke(gvar2[i],x);
                }
            }       /* 7.11.89 */


        output_close(eout);
        muste_fclose(hav);
        return(1);
        }
Example #24
0
File: main.c Project: MarcelHB/c37
int main(int argc, char *argv[]){
	Spawn *player;
	InterfaceData idata = {0, NULL, -1, NULL, 1};
	SDL_Event event;
	int num_tiles = OUTPUT_IN_GLYPHS_X * OUTPUT_IN_GLYPHS_Y, i;
	
	/*SDL anmachen*/
    if(SDL_Init(SDL_INIT_VIDEO))
        return EXIT_FAILURE;
    SDL_EnableKeyRepeat(200, 50);
    
    /*Karte laden*/
    if(argc==2)
        map=load_map(argv[1]);
    else{
        fprintf(stderr,"Kartennamen angeben\n");
        return EXIT_FAILURE;
    }
    if(map == NULL) {
        fprintf(stderr,"Fehler beim Laden der Karte\n");
        return EXIT_FAILURE;
    }
    
    player = get_player_spawn(map);
    if(player==NULL){
        fprintf(stderr, "Kein Spieler auf der Karte\n");
        return EXIT_FAILURE;
    }
    
    /*Map zeichnen*/
    
    /* Ausgabepuffer initialisieren */
    buf = (BufferTile*)ex_malloc(sizeof(BufferTile) * num_tiles);
    for(i = 0; i < num_tiles; ++i) {
        BufferTile bt = {' ', 0x00000000};
        buf[i] = bt;
    }
    
    output_init(OUTPUT_IN_GLYPHS_X, OUTPUT_IN_GLYPHS_Y, map->name);
    
    explore_area(player, map);
    create_output_buffer(map, buf, num_tiles);
    get_interface_data(map, &idata);
    output_draw(buf, num_tiles, &idata);
    
    /*Eingabeloop*/
    int quit=0;
    KeyAction current_action = INVALID;
    while(SDL_WaitEvent(&event)){
        if(event.type == SDL_KEYDOWN) {
            current_action = get_action(event.key.keysym.sym);
            /*bei Escape beenden*/
            if(event.key.keysym.sym == SDLK_ESCAPE){
                quit=1;
                break;
            }
            if(current_action != INVALID) {
                process_event(current_action, map);
            }
            create_output_buffer(map, buf, num_tiles);
            get_interface_data(map, &idata);
            output_draw(buf, num_tiles, &idata);
        } else if(event.type == SDL_QUIT) {
            quit=1;
            break;
        }
        SDL_Delay(1);
        /*Affe tot => Klappe zu*/
        if(player->hp<=0){
            game_over(0);
            break;
        }
        /* Ende erreicht */
        if(map->finished) {
            game_over(1);
            break;
        }
    }
    if(!quit){
        while(SDL_WaitEvent(&event)){
            /*bei Escape beenden*/
            if(event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) {
                break;
            }
            SDL_Delay(1);
        }
    }
    free(buf);
    flush_map(map);
    free(idata.message); free(idata.item_name);
    
    output_close();
    SDL_Quit();
    return EXIT_SUCCESS;
}