예제 #1
0
/**
 * Agrega todos os valores a partir de uma localizacao num ficheiro
 * @param prefixo e a localizacao a partir do qual vao ser agregados os valores
 * @param nivel e o nivel de detalhe da agregacao
 * @param path e o nome do ficheiro onde deve ser colocada essa agregacao
 */
int agregar(char* prefixo[], int nivel, char* path){ // TEM DE BLOQUEAR ENQUANTO ESCREVE
    
    unlink(path);
    
    DistritoFluRecord *distrito = getByNameDist(prefixo[0]);
    ConcelhoFluRecord *tmpC = NULL;
    FreguesiaFluRecord *tmpF = NULL;
    char *tamanho=(char*)malloc(10);
    if(distrito == NULL){
        return E_AGRIMPOSSIVEL;} //retorna que a agregacao é impossivel
    int fdEscrita = open(path, O_CREAT| O_TRUNC | O_WRONLY, 0666);
    if(fdEscrita<0) return E_FICHEIRO;//mensagem_de_erro(E_FICHEIRO);
    switch (nivel) {
        case 0:
            write(fdEscrita, distrito->nome,strlen(distrito->nome));
            write(fdEscrita, ":", 1);
            clearbuffer(tamanho, 10);
            sprintf(tamanho,"%d",(distrito->aggregate));
            write(fdEscrita, tamanho, sizeof(tamanho)-1);
            write(fdEscrita, "\n", 1);
            break;
        case 1:
            for(tmpC = distrito->concelhos; tmpC!=NULL; tmpC=tmpC->next){
                write(fdEscrita, distrito->nome,strlen(distrito->nome));
                write(fdEscrita, ":", 1);
                write(fdEscrita, tmpC->nome,strlen(tmpC->nome));
                write(fdEscrita, ":", 1);
                clearbuffer(tamanho, 10);
                sprintf(tamanho,"%d",(tmpC->aggregate));
                write(fdEscrita, tamanho, numDigits(tmpC->aggregate));
                write(fdEscrita, "\n", 1);
            }
            break;
        case 2:
            for(tmpC = distrito->concelhos; tmpC!=NULL; tmpC=tmpC->next)
                for(tmpF = tmpC->freguesias; tmpF!=NULL; tmpF=tmpF->next){
                    write(fdEscrita, distrito->nome,strlen(distrito->nome));
                    write(fdEscrita, ":", 1);
                    write(fdEscrita, tmpC->nome,strlen(tmpC->nome));
                    write(fdEscrita, ":", 1);
                    write(fdEscrita, tmpF->nome, strlen(tmpF->nome));
                    write(fdEscrita, ":", 1);
                    clearbuffer(tamanho, 10);
                    sprintf(tamanho,"%d",(tmpF->aggregate));
                    write(fdEscrita, tamanho, numDigits(tmpF->aggregate));
                    write(fdEscrita, "\n", 1);
                }
        default:
            break;
    }
    if(fdEscrita>=0)
        close(fdEscrita);
    
    return 0;
}
예제 #2
0
void bw::ostreambin::write(const bool bit)
{
    bufferOut = (bufferOut << 1) | bit;
    bufferOutBitSize++;

    if (bufferOutBitSize == 8) clearbuffer();
}
예제 #3
0
static int open_sound (void) {
	if (!currprefs.produce_sound)
		return 0;
	config_changed = 1;

	clearbuffer();

    currprefs.sound_stereo = 1;
    //currprefs.sound_freq = fs_emu_get_audio_frequency();
    //changed_prefs.sound_freq = g_audio_frequency;

	//init_sound_table16 ();
	sample_handler = currprefs.sound_stereo ? sample16s_handler : sample16_handler;

	//obtainedfreq = currprefs.sound_freq;
	obtainedfreq = g_audio_frequency;

	have_sound = 1;
	sound_available = 1;
	update_sound (fake_vblank_hz, 1, currprefs.ntscmode);
	//paula_sndbufsize = spec.samples * 2 * spec.channels;
	//paula_sndbufsize = fs_emu_get_audio_buffer_size();
	paula_sndbufsize = g_audio_buffer_size;
	paula_sndbufpt = paula_sndbuffer;
#ifdef DRIVESOUND
	write_log("initialize drivesound\n");
	driveclick_init();
#endif
	write_log("open_sound returning 1\n");
	return 1;
}
예제 #4
0
파일: menu.c 프로젝트: max1325/uae-wii
void play_click(int sound)
{
	int snd_bf_pointer;
	uae_s16 gui_volume;
	
	if (!changed_prefs.gui_volume) return;
	if (changed_prefs.sound_stereo!=1) return; //Only stereo implemented
	
	gui_volume = 5-changed_prefs.gui_volume;
	
	if (gui_volume<0) gui_volume=0;
	if (gui_volume>5) gui_volume=5;
	
	audio_resume();
	
	for(snd_bf_pointer=0; snd_bf_pointer< (len_click_buffer[sound]-sndbufsize); snd_bf_pointer+=sndbufsize)
	{
		memcpy_volume((uae_s16 *)sndbuffer, (uae_s16 *)(click_buffer_pointer[sound]+snd_bf_pointer), sndbufsize, gui_volume);
		finish_sound_buffer();
	}
	
	memcpy(sndbuffer, click_buffer_pointer[sound] + snd_bf_pointer, len_click_buffer[sound] - snd_bf_pointer); //The last chunk
	memset((char *) sndbuffer + len_click_buffer[sound]-snd_bf_pointer,0, sndbufsize -(len_click_buffer[sound]- snd_bf_pointer));
	finish_sound_buffer();
	clearbuffer();
	
	audio_pause();
}
예제 #5
0
파일: audio.cpp 프로젝트: adurdin/fs-uae
static int open_sound (void)
{
    if (!currprefs.produce_sound) {
        return 0;
    }
    config_changed = 1;

    clearbuffer();

    currprefs.sound_stereo = 1;
    //currprefs.sound_freq = fs_emu_get_audio_frequency();
    //changed_prefs.sound_freq = sdp->obtainedfreq;

    //init_sound_table16 ();
    sample_handler = currprefs.sound_stereo ? sample16s_handler : sample16_handler;

    //obtainedfreq = currprefs.sound_freq;
    obtainedfreq = sdp->obtainedfreq;

    have_sound = 1;
    sound_available = 1;
    paula_sndbufsize = g_audio_buffer_size;
    paula_sndbufpt = paula_sndbuffer;
#ifdef DRIVESOUND
    driveclick_init();
#endif
    write_log("open_sound returning 1\n");
    return 1;
}
예제 #6
0
int reloadLocalization(char* file){
    int fdRead = open(file,O_RDONLY);
    int getmore=0;
    char *buffer=(char*)malloc(256);
    char *tmp=(char*)malloc(512);
    char *localidade=(char*)malloc(1);
    char *path=(char*)malloc(1);
    char *pipeResposta=(char*)malloc(1);
    
    int nOi=-1;
    int tamLido=-1;
    int tipo=-1;
    int numeroRetorno=0;
    char* toParse=(char*)malloc(1);
    char *posnl;
    
    Localidades *localidades;
    
    
    clearbuffer(buffer, 256);
    while((tamLido = read(fdRead, buffer, 256))>0){
        getmore=0;
        
        strcat(tmp,buffer);
        
        while(numeroRetorno<tamLido && !getmore){
            //printf("--nr: %d\n'%s'--\n",numeroRetorno,tmp);
            if((posnl = strstr(tmp,"\n"))!=NULL){
                numeroRetorno+=copiaStringAte(tmp,'\n',512,&toParse);
                tmp = (posnl+1);
                
                tipo = parsingMensagem(toParse, &localidade, &path, &nOi, &pipeResposta);
                
                if(tipo==_INCREMENTAR){
                    localidades = split(localidade, ",");
                    incrementar(localidades->localidades, nOi);
                }
            }
            else getmore=1;
            clearbuffer(toParse, 256);
        }
        clearbuffer(buffer,256);
    }
    
    return 0;
}
예제 #7
0
void resume_sound (void) {
    write_log("STUB: resume_sound\n");
	if (!have_sound)
		return;
	clearbuffer();
#if 0
	SDL_PauseAudio (0);
#endif
}
예제 #8
0
파일: io.c 프로젝트: DanielMyshkin/cifer
void initbuffer(int buffer_id)
{
  get_buffer(buffer_id)        = malloc_good( DEFAULT_BUFFER_SIZE + 1 );
  get_buffer_size(buffer_id)   = DEFAULT_BUFFER_SIZE;
  get_buffer_filter(buffer_id) = BUFFER_FILTER_NONE;

  clearbuffer(buffer_id);
  setbuffernull(buffer_id);
}
예제 #9
0
파일: io.c 프로젝트: DanielMyshkin/cifer
void resizebuffer(int buffer_id, int newsize)
{
  get_buffer(buffer_id) = realloc_good( get_buffer(buffer_id), newsize + 1 );
  get_buffer_size(buffer_id) = newsize;
  get_buffer_filter(buffer_id) = BUFFER_FILTER_NONE;

  clearbuffer(buffer_id);
  setbuffernull(buffer_id);
}
예제 #10
0
int retreiver::run() {
	LOG4CXX_INFO("Entering thread.");
	int count = 0;
	bool offline = false;
	bool duplicates = true;
	bool savecopy = true;

	m_itemindex = 0;
	m_batch = 1;
	time(&m_then);
	while(runable() == true) {
		if(offline == true) {
			if((m_msg = on_nextcopy()) != NULL) { // pull from buffer
				if(duplicates == true)
					insertitem(m_msg); // re-insert a new copy
				postmessage(PROC_RETR, EV_DATA, count++, (long int)m_msg);
				continue;
			}
			if(duplicates == true)
				insertitem(NULL); // insert an END
		} else {
			m_itemindex++;
			if((m_msg = on_nextrecord()) != NULL) { // pull from database
				if(savecopy == true)
					insertitem(m_msg); // insert copy into buffer
				postmessage(PROC_RETR, EV_DATA, count++, (long int)m_msg);
				continue;
			}
			insertitem(NULL); // insert an END
		}

		offline = true;
		if((m_batch%m_modpoint) == 0) {
			offline = false;
			clearbuffer();
			m_itemindex = 0;
		}

		if(m_singlestep == 1) // singlestep used for debugging
			break;

		ondelay(count, offline);
		if(queuewait(count) == true)
			time(&m_then);

		count = 0;
		if(m_batch++ > 999999) { // rollover
			m_batch = 0;
			m_overloaded = 1;
		}
	}
	LOG4CXX_INFO("Exiting thread.");
	return 0;
}
예제 #11
0
파일: audio.cpp 프로젝트: adurdin/fs-uae
void close_sound (void)
{
    config_changed = 1;
    gui_data.sndbuf = 0;
    gui_data.sndbuf_status = 3;
    if (!have_sound)
        return;

    // SDL_PauseAudio (1);
    clearbuffer();
    have_sound = 0;
}
예제 #12
0
파일: fbutils.c 프로젝트: noisegate/fbpy
int styledredraw()
{
    /*
     * this function redraws the canvas using 
     * the plot function, thus applying
     * pixelstyle
     */
    int x;
    int y;
    int xr;
    int yr;

    struct Color tempcolor;

    //store buffer in temp mem  
    memcpy(dummy_buf, tmp_buf, screensize); 
  
    tempcolor.r = currentcolor->r;
    tempcolor.g = currentcolor->g;
    tempcolor.b = currentcolor->b;
    tempcolor.a = currentcolor->a;
  
    //redraw buffer form temp mem
    //first clear it

    clearbuffer(tmp_buf);

    for (x=0; x<width;x++){
        for (y=0;y<height;y++){
            get_pixel(x, y, currentcolor, dummy_buf); 
            currentcolor->a = tempcolor.a; 
            xr = x;
            yr = y;  
            if ((currentcolor->r!=0) || (currentcolor->g!=0) || (currentcolor->b!=0)){
            //aint gonna tranform nonvisible pixels pixels. cmon.
                transform(&xr, &yr);
                if ((xr>0) && (xr<width)){
                    if ((yr>0)&&(yr<height)){
                        pPlot(xr,yr);
                    }
                }
            }
        }
    } 
    
    currentcolor->a = tempcolor.a;
    currentcolor->r = tempcolor.r;
    currentcolor->g = tempcolor.g;
    currentcolor->b = tempcolor.b;
    
    return 0;
}
예제 #13
0
/**
 * Atribui uma nova funcao ao sinal que recebe como argumento
 * @param sinal é o valor do sinal que sera alterado
 */
void alteraSinais(int sinal){
    int i=0, pidFilho=0, status=0;
    int para=0, posicao=-1;
    char* tmp=(char*)malloc(256);
    char* queueMsg=NULL;
    int posFilhoMorreu = -1;
    
    clearbuffer(tmp, 256);
    switch (sinal) {
        case SIGCHLD: //o SIGCHLD passa a ser responsavel por reiniciar o processo que morreu
            if((pidFilho=waitpid(-1, &status, WNOHANG)) != -1){ //descobrir o pid do filho que morreu
                for(i=0;i<numeroDistritos && !para;i++)
                    if(kill(distritos[i]->pidFilho,0)==-1){
                        posFilhoMorreu=i;
                        para=1;
                    }
                
                distritosAreiniciar+=1; //incrementar o numero de processos a reiniciar
                distritos[posFilhoMorreu]->estado=DEAD; //alterar o estado do processo que enviou o sinal
                pidFilho=fork();
                if(pidFilho==0){
                    workerFilho(distritos[posFilhoMorreu]); //iniciar o processo que tera a mesma funcao que o que morreu
                }
                else{
                    distritos[posFilhoMorreu]->pidFilho=pidFilho; //actualizar a informacao do pid do processo
                    strcat(tmp, "(B121) O filho de ");
                    strcat(tmp, distritos[posFilhoMorreu]->nome);
                    strcat(tmp, " esta a ser reiniciado\n");
                    write(1,tmp,strlen(tmp));
                }
            }
            break;
        case SIGUSR1: //o SIGUSR1 e o sinal enviado pelo filho que foi iniciado ou reiniciado para o pai avisar que esta activo
            for(i=0;i<numeroDistritos && distritosAreiniciar>0;i++){ //so entra caso nao seja um processo a iniciar
                if(distritos[i]->estado==DEAD){
                    distritosAreiniciar-=1;
                    distritos[i]->estado=ALIVE; //actualizar o estado do processo
                    while((queueMsg=dequeue(distritos[i]))!=NULL)
                        write(distritos[i]->pipe[1],queueMsg,strlen(queueMsg));
                    strcat(tmp, "(B121) O filho de ");
                    strcat(tmp, distritos[i]->nome);
                    strcat(tmp, " esta novamente activo\n");
                    write(1,tmp,strlen(tmp));
                }
            }
            break;
        default:
            break;
    }
}
예제 #14
0
파일: io.c 프로젝트: DanielMyshkin/cifer
void copybuffer(int buffer_id_1, int buffer_id_2)
{
  printf("copybuffer: copying %i to %i...\n", buffer_id_1, buffer_id_2);

  if (get_buffer_size(buffer_id_2) < get_buffer_real_size(buffer_id_1))
  {
    printf("copybuffer: must resize buffer %i to %i bytes\n", 
                            buffer_id_2, get_buffer_real_size(buffer_id_1));
    resizebuffer(buffer_id_2, get_buffer_real_size(buffer_id_1));
  }

  clearbuffer(buffer_id_2);
  memcpy(get_buffer(buffer_id_2), get_buffer(buffer_id_1),
                            get_buffer_real_size(buffer_id_1));

  *(get_buffer(buffer_id_2) + get_buffer_real_size(buffer_id_1)) = 0;
  setbuffernull(buffer_id_2);
}
예제 #15
0
void rs_kgdb_hook(int tty_no) {
	int t;
	struct serial_state *ser = &rs_table[tty_no];

	kdb_port_info.state = ser;
	kdb_port_info.magic = SERIAL_MAGIC;
	kdb_port_info.port = ser->port;
	kdb_port_info.flags = ser->flags;
	kdb_port_info.iomem_base = ser->iomem_base;
	kdb_port_info.iomem_reg_shift = ser->iomem_reg_shift;
	kdb_port_info.MCR = UART_MCR_DTR | UART_MCR_RTS;

	/*
	 * Clear all interrupts
	 */
	serial_in(&kdb_port_info, UART_LSR);
	serial_in(&kdb_port_info, UART_RX);
	serial_in(&kdb_port_info, UART_IIR);
	serial_in(&kdb_port_info, UART_MSR);

	/*
	 * Now, initialize the UART 
	 */
	serial_out(&kdb_port_info, UART_LCR, UART_LCR_WLEN8);	/* reset DLAB */
	serial_out(&kdb_port_info, UART_MCR, kdb_port_info.MCR);
	
	/*
	 * and set the speed of the serial port
	 * (currently hardwired to 115200 8N1
	 */

	/* baud rate is fixed to 115200 (is this sufficient?)*/
	/*t = kdb_port_info.state->baud_base / 115200;	*/
	t = kdb_port_info.state->baud_base / 115200;	
	 	/* set DLAB */
	serial_out(&kdb_port_info, UART_LCR, UART_LCR_WLEN8 | UART_LCR_DLAB);
	serial_out(&kdb_port_info, UART_DLL, t & 0xff);/* LS of divisor */
	serial_out(&kdb_port_info, UART_DLM, t >> 8);  /* MS of divisor */
	/* reset DLAB */
	serial_out(&kdb_port_info, UART_LCR, UART_LCR_WLEN8);
	clearbuffer();
}
예제 #16
0
void close_sound (void) {
	config_changed = 1;
	gui_data.sndbuf = 0;
	gui_data.sndbuf_status = 3;
	if (!have_sound)
		return;

	// SDL_PauseAudio (1);
	clearbuffer();
	if (in_callback) {
		closing_sound = 1;
		uae_sem_post (&data_available_sem);
	}

	write_comm_pipe_int (&to_sound_pipe, 1, 1);
	uae_sem_wait (&sound_init_sem);
	// SDL_CloseAudio ();
	uae_sem_destroy (&data_available_sem);
	uae_sem_destroy (&sound_init_sem);
	uae_sem_destroy (&callback_done_sem);
	have_sound = 0;
}
예제 #17
0
/*-----------------------------------------------------------------------------------*/
static void
acked(void)
{
  switch(vs->sendmsg) {
  case VNC_SEND_PFMT:
    vs->sendmsg = VNC_SEND_ENCODINGS;
    break;
  case VNC_SEND_ENCODINGS:
    vs->sendmsg = VNC_SEND_UPDATERQ;
    vs->waitmsg = VNC_WAIT_UPDATE;
    clearbuffer();
    break;
  case VNC_SEND_EVENTS:
    vs->eventptr_acked = vs->eventptr_unacked;
    vs->sendmsg = VNC_SEND_NONE;
    check_events();
    break;
  default:
    vs->sendmsg = VNC_SEND_NONE;
    break;
  }
}
예제 #18
0
파일: fbutils.c 프로젝트: noisegate/fbpy
int cleartmpbuffer()
{
    clearbuffer(tmp_buf);
    return 0;
}
예제 #19
0
/**
 * Funcao que faz parsing da mensagem
 * @param mensagem e a String que vai sofrer o parsing
 * @param localidade e uma passagem por referencia que retornara a localidade na mensagem
 * @param path e uma passagem por referencia que retornara o path na mensagem
 * @param nOi e uma passagem por referencia que retornara o nivel ou incremento na mensagem
 * @param pipeResposta e uma passagem por referencia que retornara o pipe na mensagem
 */
int parsingMensagem(char* mensagem, char **localidade, char **path, int *nOi, char **pipeResposta){
    int i=0, j=0, para=0;
    int tipo=-1, nivelOrIncr=-1;
    char *tmp=(char*)malloc(256);
    char *temp;
    
    //    TIPO|LOCALIZACAO|INCREMENTO|PIPE(aleatorio)
    //    TIPO|LOCALIZACAO|NIVEL|PATH|PIPE(aleatorio)
    
    for(i=0,j=0; i<strlen(mensagem) && !para; i++,j++){
        if(mensagem[i] != '|')
            tmp[j]=mensagem[i];
        else para=1;
    }
    tmp[j]='\0';
    tipo = atoi(tmp); //tipo
    clearbuffer(tmp, 256);
    
    for(j=0,para=0; i<strlen(mensagem) && !para; i++,j++){
        if(mensagem[i] != '|')
            tmp[j]=mensagem[i];
        else para=1;
    }
    tmp[j]='\0';
    temp=strdup(tmp); //localizacao
    (*localidade)=temp;
    clearbuffer(tmp, 256);
    
    for(j=0,para=0; i<strlen(mensagem) && !para; i++,j++){
        if(mensagem[i] != '|')
            tmp[j]=mensagem[i];
        else para=1;
    }
    tmp[j]='\0';
    
    nivelOrIncr = atoi(tmp);
    (*nOi)=nivelOrIncr;
    clearbuffer(tmp, 256);
    
    if(tipo==_AGREGAR){
        para=0;
        for(j=0; i<strlen(mensagem) && !para; i++,j++){
            if(mensagem[i] != '|')
                tmp[j]=mensagem[i];
            else para=1;
        }
        tmp[j]='\0';
        temp=strdup(tmp); //path
        (*path)=temp;
        clearbuffer(tmp, 256);
    }
    
    for(j=0,para=0; i<strlen(mensagem) && !para; i++,j++){
        if(mensagem[i] != '|' && mensagem[i] != '.')
            tmp[j]=mensagem[i];
        else para=1;
    }
    tmp[j]='\0';
    temp=strdup(tmp); //pipe de resposta
    (*pipeResposta)=temp;
    free(tmp);
    return tipo;
}
예제 #20
0
/**
 * Funcao que aglomera todo o trabalho de um processo responsavel por um distrito
 * @param distrito e a estrutura com toda as bases de um distrito
 */
int workerFilho(DistritoFluRecord *distrito){
    char* msgBuffer = (char*)malloc(256),
    *ficheiroEscrita = (char*)malloc(128),
    *localidade, *path, *pipeResposta;
    int nOi=0;
    int tamMsg=-1;
    int fdReg=-1;
    int tipo=-1;
    int fdResp=-1;
    int resp=-1;
    
    Localidades *localidades;
    
    clearbuffer(ficheiroEscrita,128);
    strcat(ficheiroEscrita, distrito->nome);
    strcat(ficheiroEscrita, ".txt");
    
    reloadFilho(ficheiroEscrita); //reler toda a informacao que ja existia no servidor relativamente a este distrito
    kill(getppid(),SIGUSR1); //enviar ao processo pai um sinal para que ele saiba que este processo esta preparado para receber qualquer mensagem
    
    close(distrito->pipe[1]);
    clearbuffer(msgBuffer, 256);
    while((tamMsg=read(distrito->pipe[0],msgBuffer,256))>0){
        if(fdReg<0){
            fdReg = open(ficheiroEscrita, O_CREAT | O_APPEND | O_WRONLY, 0666);
        }
        write(fdReg, msgBuffer, tamMsg);
        write(fdReg, "\n", 1);

        localidade=(char*)malloc(sizeof(char));
        path=(char*)malloc(sizeof(char));
        pipeResposta=(char*)malloc(sizeof(char));

        tipo = parsingMensagem(msgBuffer, &localidade, &path, &nOi, &pipeResposta);
        localidades = split(localidade,",");
        switch (tipo) {
            case _INCREMENTAR:
                incrementar(localidades->localidades, nOi);
                fdResp = open(pipeResposta,O_WRONLY);
                time_t tempoServidor = time(NULL);
                write(fdResp,ctime(&tempoServidor),strlen(ctime(&tempoServidor)));
                break;
                
            case _AGREGAR:
                    resp = agregar(localidades->localidades, nOi, path);
                    if (resp>=2000 && !(strcmp(pipeResposta, "null")==0)){ //significa que houve um erro
                        fdResp = open(pipeResposta,O_WRONLY);
                        char *tamanho=(char*)malloc(10);
                        clearbuffer(tamanho, 10);
                        sprintf(tamanho,"%d",resp);
                        write(fdResp,tamanho,strlen(tamanho));
                        free(tamanho);
                    } else if (!(strcmp(pipeResposta, "null")==0)){
                        int fdResp = open(pipeResposta,O_WRONLY);
                        time_t tempoServidor = time(NULL);
                        write(fdResp,ctime(&tempoServidor),strlen(ctime(&tempoServidor)));
                    }
                break;
            default:
                break;
        }
        if(fdResp>0)
            close(fdResp);
        clearbuffer(msgBuffer, 256);
    }
    
    return 0;
}
예제 #21
0
void reset_sound (void) {
	clearbuffer();
	return;
}
예제 #22
0
int main(int argc, const char * argv[])
{
    //DistritoFluRecord *distritos[MAX_DISTRITOS];
    const char* toServidor="./toServidor";
    
    signal(SIGCHLD, alteraSinais); //atribuir nova funcao ao SIGCHLD
    signal(SIGUSR1, alteraSinais); //atribuir nova funcao ao SIGUSR1
    
    initDistritos(); //inicializacao da estrutura que contera os distritos

    char *msgBuffer=(char*)malloc(256);
    
    int serv2Reg = pipe(pipeReg); //criar um pipe que servira de comunicacao com o processo que regista todas as mensagens
    long tamMsg=0;
    int fdListen=-1, fdResposta=-1;
    
    char* tamanho=(char*)malloc(10);
    
    unlink(toServidor); //para remover o pipe toServidor
    
    if(mkfifo(toServidor, 0777) == 0) //criar um pipe com nome para receber mensagens dos clientes
        write(1,"(B121) Server started\n",strlen("(B121) Server started\n"));
    
    char* localidade=NULL, *path=NULL, *pipeResposta=NULL;
    int nOi, tipo;
    Localidades *localidades;
    fdListen = open(toServidor,O_RDONLY); //abrir o pipe com nome que sera responsavel pela comunicacao cliente-servidor
    
    //inicia o filho que trata do registo de todas as mensagens recebidas
    pidFilhoRegisto = spawnRegWriter();
    
    write(1, "(B121) Waiting for connection\n", strlen("(B121) Waiting for connection\n"));
    while(1){
        clearbuffer(msgBuffer, 256);
        fdListen = open(toServidor,O_RDONLY);
        while((tamMsg=read(fdListen,msgBuffer,256))>0){
            write(1,"(B121) Message received\n",strlen("(B121) Message received\n"));
            write(pipeReg[1], msgBuffer, tamMsg); //enviar mensagem recebida para o pipe responsavel pelo registo
            localidade=(char*)malloc(sizeof(char));
            path=(char*)malloc(sizeof(char));
            pipeResposta=(char*)malloc(sizeof(char));
            tipo = parsingMensagem(msgBuffer, &localidade, &path, &nOi, &pipeResposta);
            if(numeroDistritos>=MAX_DISTRITOS && !(strcmp(pipeResposta, "null")==0)){ //caso nao possa ser adicionado novo distrito
                fdResposta = open(pipeResposta,O_WRONLY);
                clearbuffer(tamanho, 10);
                sprintf(tamanho,"%d",E_CAPACIDADE);
                write(fdResposta,tamanho,strlen(tamanho));
                close(fdResposta);
            } else {
                localidades = split(localidade,",");
                DistritoFluRecord *worker = getByNameDist(localidades->localidades[0]);
                if(worker!=NULL){ //se o processo relativo a este distrito existe...
                    if(worker->estado==ALIVE){
                        write(worker->pipe[1],msgBuffer,tamMsg); //se o processo esta vivo envia lhe a mensagem
                    }
                    else
                        enqueue(msgBuffer, worker); //se o processo esta a reiniciar guarda a mensagem na queue
                }
                else { //se o prococesso relativo a este distrito nao existe...
                    DistritoFluRecord *novo = criarDistrito(localidades->localidades[0]);
                    pipe(novo->pipe);
                    int pid_novoFilho=fork();
                    if(pid_novoFilho==0){ //atribuir o distrito a um novo processo
                        workerFilho(novo);
                    }
                    else{ //registar a informacao do novo processo
                        novo->pidFilho=pid_novoFilho;
                        write(novo->pipe[1],msgBuffer,strlen(msgBuffer));
                    }
                }
            }
        }
    }
    
    write(1,"(B121) Server will shutdown\n",strlen("(B121) Server will shutdown\n"));
    return 0;
}
예제 #23
0
void bw::ostreambin::flush()
{
    clearbuffer();
    out_ptr->flush();
}
예제 #24
0
/* newdata():
 *
 * Called whenever new data arrives.
 *
 * First, checks if data needs to be buffered before a previously
 * identified request can be fulfilled. If so, the incoming data is
 * buffered and the data handler is called. If no data needs to be
 * buffered, the code proceeds to identify the incoming request. If
 * the incoming request can be processed immediately (i.e., all data
 * is contained in this message) the data handler is invoked. If data
 * has to be buffered to fulfill the request, this is noted and taken
 * care of the next time this function is invoked (i.e., for the next
 * incoming data chunk).
 */
static uint8_t
newdata(void)
{
  uint16_t datalen;
  uint16_t readlen;
  uint8_t *dataptr;
  
  datalen = uip_datalen();
  dataptr = (uint8_t *)uip_appdata;

  PRINTF(("newdata: %d bytes\n", datalen));
  
  /* If we are in a "rectstate", meaning that the incoming data is
     part of a rectangle that is being incrementaly drawn on the
     screen, we handle that first. */
  if(vs->rectstate != VNC_RECTSTATE_NONE) {
    readlen = recv_rectstate(dataptr, datalen);
    PRINTF(("newdata: vs->rectstate %d, datalen %d, readlen %d\n",
	    vs->rectstate, datalen, readlen));
    datalen -= readlen;
    dataptr += readlen;
  }

  /* Next, check if we are supposed to buffer data from the incoming
     segment. */
  while(vs->bufferleft > 0 && datalen > 0) {
    if(datalen >= vs->bufferleft) {
      /* There is more data in the incoming chunk than we need to
	 buffer, so we buffer as much as we can and handle the
	 buffered data, and repeat the (identify->buffer->handle)
	 sequence for the data that is left in the incoming chunk. */
      datalen -= vs->bufferleft;
      dataptr += vs->bufferleft;
      buffer_data((uint8_t *)uip_appdata, vs->bufferleft);
      handle_data(vs->buffer, vs->buffersize);
      clearbuffer();
    } else { /* datalen < vs->bufferleft */
      /* We need to buffer more data than was received with this
         chunk, so we buffer the avaliable data and return. */
      buffer_data(dataptr, datalen);
      return 0;
    }
  }

  /* Finally, if there is data left in the segment, we handle it. */
  while(datalen > 0) {

    if(vs->rectstate != VNC_RECTSTATE_NONE) {
      readlen = recv_rectstate(dataptr, datalen);
      PRINTF(("newdata (2): vs->rectstate %d, datalen %d, readlen %d\n",
	      vs->rectstate, datalen, readlen));
      datalen -= readlen;
      dataptr += readlen;
    } else {
 
      /* We get here if there is data to be identified in the incoming
	 chunk. */
      readlen = identify_data(dataptr, datalen);

      if(readlen == 0) {
	PRINTF(("Identify returned 0\n"));
	return 0;
      }

      PRINTF(("Reading %d bytes more\n", readlen));
      /* The data has been identified and the amount of data that
	 needs to be read to be able to process the data is in the
	 "readlen" variable. If the incoming chunk contains enough
	 data, we handle it directly, otherwise we buffer the incoming
	 data and set the state so that we know that there is more
	 data to be buffered. */
      if(readlen > datalen) {
	clearbuffer(); /* Should not be needed, but just in case... */
	vs->bufferleft = readlen;
	buffer_data(dataptr, datalen);
	return 0;
      }
      if(readlen <= datalen) {
	PRINTF(("Before handle_data %d\n", readlen));
	readlen += handle_data(dataptr, readlen);
	PRINTF(("After handle_data %d\n", readlen));
	datalen -= readlen;
	dataptr += readlen;
      }

    }
    if(datalen > 0) {
      PRINTF(("newdata: there is more data left after first iteration... %d\n", datalen));
    }
    
  }
  
  return 0;
}
예제 #25
0
int svf_input()
{
	int i, j;
	int op = 0;
	int packet_size;
	int retval;
	char *p = NULL;
	char svf_name[80];
	long tdoNumBytesReturned = 0;
	int c_time = 0x10000000;
	char svfcmd[MAX_LEN];
	int byteIndex;
	long doNumBytesReturned;
	unsigned char byte;
	do
	{
		doNumBytesReturned = 0;
		len = 0;
		p = NULL;
		packet_size = MAX_LEN - 1;
		if ((retval = svf_get_packet(packet, &packet_size)) != ERROR_OK)
		{
			switch (retval)
			{
				case ERROR_ALL:
					return ERROR_OK;
				default:
					return ERROR_OK;
			}
		}
		/* terminate with zero */
		packet[packet_size] = '\0';
		strupr(packet);
		#ifdef _KENICHI_DBG
		printf("receive packet: %s \n", packet);
		#endif
	
		if (strstr("QUIT", packet) != NULL)
		{
			return ERROR_ALL;
		}
		if (strstr("EXIT", packet) != NULL)
		{
			return ERROR_ALL;
		}
		
		if (strstr("TMSRST", packet) == packet)
		{
			AMTXHAL_CMDQ_Add_jtag_tmsreset(icehandle, AMTXHAL_PORT_IO_LEVEL_0);
			AMTXHAL_CMDQ_Exe(icehandle); 
			AMTXHAL_CMDQ_Clr(icehandle);
			sprintf(info_buf, "Execute '%s' SVF command success !", packet);
			info_buf[strlen(info_buf) + 1] = '\0';
			svf_put_packet(info_buf, strlen(info_buf) + 1);

			break;
		}


		if ((strstr(packet, "SDR") == packet) || (strstr(packet, "SIR") == packet ) || \
			(strstr(packet, "SPDR") == packet) || (strstr(packet, "SPIR") == packet ))
		{
			
			// SDR 32 TDI (XXXX) TDO (XXXX) MASK (XXXX) SMASK (XXXX)
			strcpy(cmd, packet);
			stripcommandspace();
			stripcommandspace();
			// get length
			clearbuffer(svfcmdbak);
			strcpy(svfcmdbak, maincmd);
			len = svfchartohex(svfcmdbak);
		//	printf("len = 0x%x \n", len);
			
			clearbuffer(svfcmdbak);
			stripcommandspace();
			strcpy(svfcmdbak, maincmd);
			stripcommandspace();
			// get tdi data
			extractdata();
			
			clearbuffer(svfcmdbak);
			stripcommandspace();
			strcpy(svfcmdbak, maincmd);
			stripcommandspace();
			// get tdo data
			extractdata();
			
			clearbuffer(svfcmdbak);
			stripcommandspace();
			strcpy(svfcmdbak, maincmd);
			stripcommandspace();
			// get mask data
			extractdata();
		
			clearbuffer(svfcmdbak);
			stripcommandspace();
			strcpy(svfcmdbak, maincmd);
			stripcommandspace();
			// get smask data
			extractdata();

			// printf tdibuf, tdobuf, maskbuf, smaskbuf
			#ifdef _KENICHI_DBG
			printf("tdi: 0x%x \n", tdidata);
			printf("tdo: 0x%x \n", tdodata);
			printf("dr mask: 0x%x \n", drmaskdata);
			printf("ir mask: 0x%x \n", irmaskdata);
			printf("smask: 0x%x \n", smaskdata);
			#endif

	        // execute sdr & sir
			if ((strstr(packet, "SDR") == packet) || (strstr(packet, "SPDR") == packet))
			{
				AMTXHAL_CMDQ_Add_jtag_scan(
					icehandle, //long l_iceHandle,
					AMTXHAL_PORT_IO_LEVEL_0, //long l_portID,
					AMTXHAL_TARGET_ID_DEFAULT, //long l_targetID,
					AMTXHAL_SCAN_ID_DEFAULT, //long l_scanID,
					AMTXHAL_BOOLEAN_TRUE, //long l_scanInEn,
					AMTXHAL_BOOLEAN_TRUE, //long l_scanOutEn,
					AMTXHAL_BOOLEAN_TRUE, //long l_scanCheckEn,
					AMTXHAL_JTAG_STATE_DRSHIFT, //long l_scanState, <- HERE YOU SELECT DR
					len, //long l_scanLength,
					tdibuf, //char *pc_scanInTdiByteBuffer,
					tdobuf, //char *pc_scanCheckExpectedTdoByteBuffer,
					drmaskbuf, //char *pc_scanCheckMaskedTdoByteBuffer,
					AMTXHAL_JTAG_STATE_IDLE );
				AMTXHAL_CMDQ_ExeGetScanOutData(icehandle, tdobuf, &tdoNumBytesReturned);
				AMTXHAL_CMDQ_Clr(icehandle);
				
				info_buf[0] = '\0';

				if (strstr(packet, "SPDR") == packet)
				{
					for (i = 0; i < tdoNumBytesReturned - 1; i++)
					{
						byte = 0;
						byte |= ((unsigned char)tdobuf[i] & 0x1) << 7;
						byte |= ((unsigned char)tdobuf[i] & 0x2) << 5;
						byte |= ((unsigned char)tdobuf[i] & 0x4) << 3;
						byte |= ((unsigned char)tdobuf[i] & 0x8) << 1;
						byte |= ((unsigned char)tdobuf[i] & 0x10) >> 1;
						byte |= ((unsigned char)tdobuf[i] & 0x20) >> 3;
						byte |= ((unsigned char)tdobuf[i] & 0x40) >> 5;
						byte |= ((unsigned char)tdobuf[i] & 0x80) >> 7;

						tdobuf[i] = byte << 1;
						if ((unsigned char)tdobuf[i+1] & 0x01)
						{
							tdobuf[i] = ((unsigned char)tdobuf[i]) | 0x01;
						}
					}
				}
				for (byteIndex = 0; byteIndex < tdoNumBytesReturned; byteIndex++)
				{
					byte = (unsigned char) tdobuf[byteIndex]; //cast to unsigned char
				//	printf("TDO[%d]= 0x%x ", byteIndex, byte);
					
					sprintf(result_buf, "TDO[%d]= 0x%2.2x ", byteIndex, byte);
					strcat(info_buf, result_buf);
				}
				info_buf[strlen(info_buf) + 1] = '\0';
				svf_put_packet(info_buf, strlen(info_buf) + 1);

			}
			else if ((strstr(packet, "SIR") == packet) || (strstr(packet, "SPIR") == packet))
			{
				AMTXHAL_CMDQ_Add_jtag_scan(
					icehandle, //long l_iceHandle,
					AMTXHAL_PORT_IO_LEVEL_0, //long l_portID,
					AMTXHAL_TARGET_ID_DEFAULT, //long l_targetID,
					AMTXHAL_SCAN_ID_DEFAULT, //long l_scanID,
					AMTXHAL_BOOLEAN_TRUE, //long l_scanInEn,
					AMTXHAL_BOOLEAN_TRUE, //long l_scanOutEn,
					AMTXHAL_BOOLEAN_TRUE, //long l_scanCheckEn,
					AMTXHAL_JTAG_STATE_IRSHIFT, //long l_scanState, <- HERE YOU SELECT IR
					len, //long l_scanLength,
					tdibuf, //char *pc_scanInTdiByteBuffer,
					tdobuf, //char *pc_scanCheckExpectedTdoByteBuffer,
					irmaskbuf, //char *pc_scanCheckMaskedTdoByteBuffer,
					AMTXHAL_JTAG_STATE_IDLE );
				AMTXHAL_CMDQ_ExeGetScanOutData(icehandle, tdobuf, &tdoNumBytesReturned);
				AMTXHAL_CMDQ_Clr(icehandle);

				info_buf[0] = '\0';
				for (byteIndex = 0; byteIndex < tdoNumBytesReturned; byteIndex++)
				{
					byte = (unsigned char) tdobuf[byteIndex]; //cast to unsigned char
				//	printf("TDO[%d]= 0x%x ", byteIndex, byte);
					sprintf(result_buf, "TDO[%d]= 0x%2.2x ", byteIndex, byte);
					strcat(info_buf, result_buf);
				}
				info_buf[strlen(info_buf) + 1] = '\0';
				svf_put_packet(info_buf, strlen(info_buf) + 1);

			}
			break;
		}
예제 #26
0
void CJOCh264bitstream::savebufferbyte(bool bemulationprevention)
{
	bool bemulationpreventionexecuted = false;

	if (m_pOutFile == NULL)
		throw "Error: out file is NULL";

	//Check if the last bit in buffer is multiple of 8
	if ((m_nLastbitinbuffer % 8)  != 0)
		throw "Error: Save to file must be byte aligned";

	if ((m_nLastbitinbuffer / 8) <= 0)
		throw "Error: NO bytes to save";

	if (bemulationprevention == true)
	{
		//Emulation prevention will be used:
		/*As per h.264 spec,
		rbsp_data shouldn't contain
				- 0x 00 00 00
				- 0x 00 00 01
				- 0x 00 00 02
				- 0x 00 00 03

		rbsp_data shall be in the following way
				- 0x 00 00 03 00
				- 0x 00 00 03 01
				- 0x 00 00 03 02
				- 0x 00 00 03 03
		*/

		//Check if emulation prevention is needed (emulation prevention is byte align defined)
		if ((m_buffer[((m_nStartingbyte + 0) % BUFFER_SIZE_BYTES)] == 0x00)&&(m_buffer[((m_nStartingbyte + 1) % BUFFER_SIZE_BYTES)] == 0x00)&&((m_buffer[((m_nStartingbyte + 2) % BUFFER_SIZE_BYTES)] = 0x00)||(m_buffer[((m_nStartingbyte + 2) % BUFFER_SIZE_BYTES)] = 0x01)||(m_buffer[((m_nStartingbyte + 2) % BUFFER_SIZE_BYTES)] = 0x02)||(m_buffer[((m_nStartingbyte + 2) % BUFFER_SIZE_BYTES)] = 0x03)))
		{
			int nbuffersaved = 0;
			unsigned char cEmulationPreventionByte = H264_EMULATION_PREVENTION_BYTE;

			//Save 1st byte
			fwrite(&m_buffer[((m_nStartingbyte + nbuffersaved) % BUFFER_SIZE_BYTES)], 1, 1, m_pOutFile);
			nbuffersaved ++;

			//Save 2st byte
			fwrite(&m_buffer[((m_nStartingbyte + nbuffersaved) % BUFFER_SIZE_BYTES)], 1, 1, m_pOutFile);
			nbuffersaved ++;

			//Save emulation prevention byte
			fwrite(&cEmulationPreventionByte, 1, 1, m_pOutFile);

			//Save the rest of bytes (usually 1)
			while (nbuffersaved < BUFFER_SIZE_BYTES)
			{
				fwrite(&m_buffer[((m_nStartingbyte + nbuffersaved) % BUFFER_SIZE_BYTES)], 1, 1, m_pOutFile);
				nbuffersaved++;
			}

			//All bytes in buffer are saved, so clear the buffer
			clearbuffer();

			bemulationpreventionexecuted = true;
		}
	}

	if (bemulationpreventionexecuted == false)
	{
		//No emulation prevention was used

		//Save the oldest byte in buffer
		fwrite(&m_buffer[m_nStartingbyte], 1, 1, m_pOutFile);

		//Move the index
		m_buffer[m_nStartingbyte] = 0;
		m_nStartingbyte++;
		m_nStartingbyte = m_nStartingbyte % BUFFER_SIZE_BYTES;
		m_nLastbitinbuffer = m_nLastbitinbuffer - 8;
	}
}
예제 #27
0
CJOCh264bitstream::CJOCh264bitstream(FILE *pOutBinaryFile)
{
	clearbuffer();

	m_pOutFile = pOutBinaryFile;
}
예제 #28
0
파일: io.c 프로젝트: DanielMyshkin/cifer
void file2buffer(char *name, int buffer_id)
{
  int i, original_size;
  char *buf;
  FILE *file;
  struct stat filestats;

  clearbuffer(buffer_id);

  /* Grab file stats */
  if (stat(name, &filestats) == -1)
  {
    printf("file2buffer: stat failed: %s\n", strerror(errno));
    return;
  }

  /* Check if it's a regular file */
  if (!S_ISREG(filestats.st_mode))
  {
    printf("file2buffer: not a regular file; failed\n");
    return;
  }

  file = fopen(name, "r");
  if (file == NULL)
  {
    printf("file2buffer: fopen failed: %s\n", strerror(errno));
    return;
  }
  
  flock(fileno(file), LOCK_SH);

  /* Save original size incase we need to bail out */
  original_size = get_buffer_size(buffer_id);

  if (filestats.st_size > get_buffer_size(buffer_id))
  {
    printf("file2buffer: expanding buffer %i to accommodate file's %li bytes\n",
                    buffer_id, filestats.st_size);
    resizebuffer(buffer_id, filestats.st_size + 1);
  }

  i = 0;
  buf = get_buffer(buffer_id);

  while (feof(file) == 0)
  {
    *(buf + i) = fgetc(file);

    /* Detect error, convert to a null, and finish */
    if (*(buf + i) == -1)
    {
      *(buf + i) = 0;
      break;
    }
    else if (!ASCII_CH(*(buf + i)) && !XSPACE_CH(*(buf + i)))
    {
      /* trap non ascii stuff, including a null */
      printf("file2buffer: error - file is not ASCII, "
                "unknown character %2x at byte %i\n", 
                (unsigned char) *(buf + i), i);

      /* bail out, I guess. */
      printf("file2buffer: bailing out: emptying buffer\n");
      clearbuffer(buffer_id);

      /* return buffer to original size, if needed */
      if (original_size != get_buffer_size(buffer_id))
      {
        printf("file2buffer: returning buffer %i to original size %i\n",
                     buffer_id, original_size);
        resizebuffer(buffer_id, original_size);
      }

      flock(fileno(file), LOCK_UN);
      fclose(file);
      return;
    }

    i++;
  }

  *(buf + i) = 0;
  setbuffernull(buffer_id);

  printf("file2buffer: loaded %i bytes into buffer %i\n", i - 1, buffer_id);

  flock(fileno(file), LOCK_UN);
  fclose(file);
}
예제 #29
0
파일: fbutils.c 프로젝트: noisegate/fbpy
int clearscreen() 
{
    clearbuffer(fbp);
    return 0;
}
예제 #30
0
void displayfunc()
   {
   unsigned int i;

   GLuint texid;

   clearbuffer(0,0,0);

   for (i=0; i<height; i++)
      memcpy(&image[i*components*imgwidth],
             &volume[(long long)frame*components*width*height+i*components*width],components*width);

   glGenTextures(1,&texid);
   glBindTexture(GL_TEXTURE_2D,texid);

   glPixelStorei(GL_UNPACK_ALIGNMENT,1);
   if (components==1) glTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE,imgwidth,imgheight,0,GL_LUMINANCE,GL_UNSIGNED_BYTE,image);
   else if (components==3) glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,imgwidth,imgheight,0,GL_RGB,GL_UNSIGNED_BYTE,image);
   else if (components==4) glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,imgwidth,imgheight,0,GL_RGBA,GL_UNSIGNED_BYTE,image);
   else ERRORMSG();

   glDepthMask(GL_FALSE);
   glDisable(GL_DEPTH_TEST);
   glDisable(GL_DITHER);
   glDisable(GL_CULL_FACE);

   glMatrixMode(GL_TEXTURE);
   glPushMatrix();
   glLoadIdentity();
   glTranslatef(0.5f/imgwidth,0.5f/imgheight,0.0f);
   glScalef((float)(width-1)/imgwidth,(float)(height-1)/imgheight,0.0f);
   glMatrixMode(GL_PROJECTION);
   glPushMatrix();
   glLoadIdentity();
   glOrtho(0.0f,winwidth-1,0.0f,winheight-1,-1.0f,1.0f);
   glMatrixMode(GL_MODELVIEW);
   glPushMatrix();
   glLoadIdentity();

   if (width*winheight<winwidth*height)
      {
      glTranslatef((winwidth-width*winheight/height)/2.0f,0.0f,0.0f);
      glScalef(width*winheight/height,winheight,0.0f);
      }
   else
      {
      glTranslatef(0.0f,(winheight-height*winwidth/width)/2.0f,0.0f);
      glScalef(winwidth,height*winwidth/width,0.0f);
      }

   glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);

   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);

   glEnable(GL_TEXTURE_2D);

   glColor3f(1.0f,1.0f,1.0f);
   glBegin(GL_TRIANGLE_FAN);
   glTexCoord2f(0.0f,1.0f);
   glVertex3f(0.0f,0.0f,0.0f);
   glTexCoord2f(1.0f,1.0f);
   glVertex3f(1.0f,0.0f,0.0f);
   glTexCoord2f(1.0f,0.0f);
   glVertex3f(1.0f,1.0f,0.0f);
   glTexCoord2f(0.0f,0.0f);
   glVertex3f(0.0f,1.0f,0.0f);
   glEnd();

   glDisable(GL_TEXTURE_2D);
   glDeleteTextures(1,&texid);

   glDepthMask(GL_TRUE);
   glEnable(GL_DEPTH_TEST);
   glEnable(GL_DITHER);
   glEnable(GL_CULL_FACE);

   glMatrixMode(GL_TEXTURE);
   glPopMatrix();
   glMatrixMode(GL_PROJECTION);
   glPopMatrix();
   glMatrixMode(GL_MODELVIEW);
   glPopMatrix();

   glutSwapBuffers();
   waitfor(1.0/fps);

   if (!pausing)
      if (frame<depth-1) frame++;
      else frame=0;

   if (frame==depth-1) pausing=TRUE;
   }