int main()
{
    //showMatrix(Board, MATRIX_SIZE);
    boardToFEN();
    printf("%s", FEN_string);

    FENToBoard();
    showMatrix(Board, MATRIX_SIZE);
    
    return 0;
}
Beispiel #2
0
/**************************************************************************************

  Wait for key pressed and return its code.

  return value:
    keyCode
    0..16       ( 0-0xF )
    17: shift 7
    18: shift 8
    19: shift 9
    0xFD: HASHKEY

**************************************************************************************/
uint8_t getKeyCode()
{
  uint8_t n;
  do
  {
    showMatrix(20);
  }while(!keyPressed());

  n=getKey();

  return n;
}
Beispiel #3
0
void mexFunction( int nargout, mxArray *out[],
                  int nargin, const mxArray *in[] )
{
    jhm::cout_redirect();
    jhm::MAT mfile("data.mat");
    
    jhm::println( "Opened file with %d variables.", mfile.nfields() );
    showLogical(mfile);
    showNumeric(mfile);
    showString(mfile);
    showVector(mfile);
    showMatrix(mfile);
    showVolume(mfile);
}
void MainWindow::createActions()
{
    enterRefPointAct = new QAction(tr("Enter Reference Point"), this);
    enterRefPointAct->setShortcut(tr("Ctrl+P"));
    connect(enterRefPointAct, SIGNAL(triggered()), this, SLOT(enterRefPoint()));

    exitAct = new QAction(tr("Exit"), this);
    exitAct->setShortcut(tr("Esc, Alt+F12"));
    connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));

    normalSizeAct = new QAction(tr("&Normal Size"), this);
    normalSizeAct->setShortcut(tr("Ctrl+S"));
    normalSizeAct->setEnabled(false);
    connect(normalSizeAct, SIGNAL(triggered()), this, SLOT(normalSize()));

    openAct = new QAction(tr("&Open..."), this);
    openAct->setShortcut(tr("Ctrl+O"));
    connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

    saveTransfImgAct = new QAction(tr("Save Transformed Image"), this);
    saveTransfImgAct->setShortcut(tr("Ctrl+S"));
    saveTransfImgAct->setEnabled(false);
    connect(saveTransfImgAct, SIGNAL(triggered()), this, SLOT(saveTransfImg()));

    showMatrixAct = new QAction(tr("Show Matrix"), this);
    showMatrixAct->setShortcut(tr("Ctrl+M"));
    connect(showMatrixAct, SIGNAL(triggered()), this, SLOT(showMatrix()));

    transformAct = new QAction(tr("&Tranform"), this);
    transformAct->setShortcut(tr("Ctrl+T"));
    connect(transformAct, SIGNAL(triggered()), this, SLOT(transform()));

    testMatrixAct = new QAction(tr("Set Test Matrix"), this);
    testMatrixAct->setShortcut(tr("Ctrl+E"));
    connect(testMatrixAct, SIGNAL(triggered()), this, SLOT(setTestMatrix()));

    zoomInAct = new QAction(tr("Zoom &In (25%)"), this);
    zoomInAct->setShortcut(tr("Ctrl++"));
    zoomInAct->setEnabled(false);
    connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn()));

    zoomOutAct = new QAction(tr("Zoom &Out (25%)"), this);
    zoomOutAct->setShortcut(tr("Ctrl+-"));
    zoomOutAct->setEnabled(false);
    connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut()));
}
Beispiel #5
0
int main(){
	int n, m, i, N;
	char s[100];
	matrix origin[10000], trans[10000], multi[10000];
    scanf("%d %d ", &n, &m);
    i = 0;
    while(gets(s)){
        if(s[0]==NULL)
            break;
        sscanf(s, " (%d:%d)=%d", &origin[i].row, &origin[i].col, &origin[i].val);
        i++;
    }
    setTrans(origin, trans, i);
    N = setMulti(origin, trans, multi, n, m, i);
    showMatrix(multi, n, n, N);
    return 0;
}
Beispiel #6
0
int main(void) {
	int i,j,n,m,turn;
	int winner;

	printf("三目ならべを始めます\n");

	/*
		盤面を初期化します。
	*/
	// initialize
	for (i =0; i < MATRIX_SIZE; i++) {
		for (j = 0; j<MATRIX_SIZE; j++) {
			matrix[i][j] = NONE;
		}
	}
	
	turn = PLAYER;	// ターンを設定、先攻は人間にする。
	winner = NONE;	// 勝利者を表す変数。最初はどっちも勝ってない状態。
	while(winner == NONE) {
		showMatrix();
		switch(turn) {
		case PLAYER:
			printf("あなたの番です、○を置きたい場所の数字を入力してください\n");

			/* 入力待ちループ */
			while(turn == PLAYER) {
				scanf("%d", &n);
				if(take(n, turn) == 0) {
					turn = COMPUTER;	// COMPUTERの番にする。
					break;
				}
				printf("数値を入れなおしてください\n");
			}
			break;

		case COMPUTER:
			printf("コンピュータの番です\n");

			/* 選択処理ループ */
			while(turn == COMPUTER) {
				srand((unsigned)time(NULL));
				n = rand() % 10;
				if(take(n, turn) == 0) {
					turn = PLAYER;	// PLAYERの番にする。
				}
			}
			break;
		}
		// 勝ち負け判定
		winner = judge();
		switch(winner) {
		case PLAYER:
			printf("Player WIN!\n");
			break;
		case COMPUTER:
			printf("Computer WIN!\n");
			break;
		default:
			break;
		}
	}
	exit(0);
}
Beispiel #7
0
int main()
{

    int i;
    for(i = 0; i< 100; i++){
        if(verificaSeEhPrimo(i)){
            printf("Return true para %d\n", i);

        }
        else
        {
            printf("Return false para %d\n", i);
        }

    }



    //srand(time(NULL));

    int pares = 0, impares = 0, valueSearch = 0; // mediaImpares = 0;
    int *result;
    MatrixOfInt a, b, c, x, y, w;
    printf("RESULTADOS REFERENTES A QUESTÃO 1 DA LISTA 3. \n");
    printf("\nMatrix A:\n");
    readDimentions(&a);
    if(!allocateMatrix(&a)){
        printf("Não consegui alocar a matrix a. ");
        exit(FAIL);
    }
    //Gera vator randomico
    randomicMatrix(&a);
    //printf("\nInforme os elementos da Matrix A:\n");
    //readMatrix(&a);
    //Ordena a matriz de forma decrescente
    descendingOrderWithFlag(&a);
    //Calcula quantos numeros pares e impares tem no vetor.
    showMatrix(&a);
    calcParesImpares(&a, &pares, &impares);
    printf("O números total de pares no vetor e menores que 256 é: %d. \n", pares);
    printf("O números total de ímpares no vetor e menores que 256 é: %d. \n", impares);
    printf("A média dos números ímpares é: %f. \n", returnMediaDeImpares(&a));
    releaseMatrix(&a);
    printf("-----------------------------------------------------------------------------\n");

    printf("\nRESULTADOS REFERENTES A QUESTÃO 2 DA LISTA 3. \n");
    x.row = 1;
    y.row = 1;
    w.row = 1;
    printf("Digite o número de ELEMENTOS do vetor X:\n");
    scanf("%d", &x.col);

    if(!allocateMatrix(&x)){
        printf("Não consegui alocar a matrix X. ");
        exit(FAIL);
    }
    printf("\nInforme os elementos da Matrix X:\n");
    readMatrix(&x);

    y.col = returnNumeroColunas(&x);

    if(!allocateMatrix(&y)){
        printf("Não consegui alocar a matrix Y. ");
        exit(FAIL);
    }
    //gera vetor com valores entre 10 e 40
    geraVetor(&x, &y);
    printf("\nMATRIZ X");
    showMatrix(&x);
    printf("MATRIZ Y");
    showMatrix(&y);

    w.col = returnNumeroColunasComIndicePar(&x);

    if(!allocateMatrix(&w)){
        printf("Não consegui alocar a matrix Y. ");
        exit(FAIL);
    }
    geraVetorPartindoDeIndicePares(&x,&w);
    printf("MATRIZ W");
    showMatrix(&w);
    printf("ENTRE COM O NÚMERO PARA SER PESQUISADO NO VETOR X: ");
    scanf("%d", &valueSearch);
    result = pesquisaBinaria(&x, valueSearch);
    if (result == NULL) {
        printf("Valor não encontrado.\n");
    } else {
        printf("O valor: %d foi encontrado no vetor X.\n", *result);
    }
    printf("O menor número no vetor X é: %d.\n", *(*(x.ptr)));
    printf("O maior número no vetor X é: %d.\n", *(*(x.ptr)+(x.col-1)));

    printf("-----------------------------------------------------------------------------\n");
    printf("RESULTADOS REFERENTES A QUESTÃO 3 DA LISTA 3.\n");
    a.row = 1;
    b.row = 1;
    c.row = 1;
    printf("Digite o número de ELEMENTOS do vetores A e B:\n");
    scanf("%d", &a.col);
    b.col = a.col;
    c.col = a.col;

    if(!allocateMatrix(&a)){
        printf("Não consegui alocar a matrix A. ");
        exit(FAIL);
    }

    if(!allocateMatrix(&b)){
        printf("Não consegui alocar a matrix B. ");
        exit(FAIL);
    }

    if(!allocateMatrix(&c)){
        printf("Não consegui alocar a matrix C. ");
        exit(FAIL);
    }

    printf("\nInforme os elementos da Matrix A:\n");
    readMatrix(&a);

    printf("\nInforme os elementos da Matrix B:\n");
    readMatrix(&b);

    geraVetorPartindoDeOutrosDois(&a,&b,&c);

    printf("ENTRE COM O NÚMERO PARA SER PESQUISADO NO VETOR C: ");
    scanf("%d", &valueSearch);

    printf("MATRIX A.");
    showMatrix(&a);
    printf("MATRIX B.");
    showMatrix(&b);
    printf("MATRIX C.");
    showMatrix(&c);

    result = pesquisaSequencial(&c, valueSearch);
    if (result == NULL) {
        printf("Valor não encontrado no vetor.\n");
    } else {
        printf("O valor: %d foi encontrado no vetor C. \n", *result);
    }

    return 0;



}
Beispiel #8
0
int main()
{
	char cmd[1000]={},split[5][100]={};
	char *token;
	int cmdSpt=0,i,returnA,returnB,returnTar,returnFunc,row,col,size;
	double mul;
	FILE *fileA=NULL,*fileB=NULL,*fileTar=NULL;
	matrix matA,matB,matTar;
	
	//prints welcome messages
	system("cls");
	printf("\n\n===Matrix manipulation program===\n\n");
	printf("Type <help> for command list and usage\n\n");
	do
	{
		printf("MATRIX> ");					//command prompt
		rewind(stdin);						//rewind everything
		scanf("%[^\n]",cmd);				//get command (with spaces)
		
		cmdSpt=0;							//set sub command count to 0
		token=strtok(cmd," ");				//partition command to subcommand with spaces
		while(token!=NULL&&cmdSpt<=5)
		{
			strcpy(split[cmdSpt],token);	//save subcommands to split[]
			cmdSpt++;						//increase sub command count
			token=strtok(NULL," ");
		}
		
		for(i=0;i<strlen(split[0]);i++)			//set command to lowercase
			split[0][i]=tolower(split[0][i]);	
		
		if(strcmp(split[0],"show")==0&&cmdSpt==2)	//show command
		{
			returnA=openFile(&fileA,split[1],0);	//call openFile() to open file to show
			
			if(returnA==1)							//failed to open
				printf("Error: file %s failed to open.\n\n",split[1]);
			else
			{
				matA=readMatrix(fileA);				//read matrix and save to matA
				showMatrix(matA,split[1]);					//show matrix matA
			}
		}
		else if(strcmp(split[0],"create")==0&&cmdSpt==4)	//create command
		{
			returnA=openFile(&fileA,split[3],1);			//call openFile() to create a new file
			{
				if(returnA==1)								//failed to open
					printf("Error: file %s failed to open.\n\n",split[3]);
				else if(sscanf(split[1],"%d",&row)!=1||sscanf(split[2],"%d",&col)!=1)	//incorrect matrix size entered
					printf("Error: invalid matrix size.\n\n");
				else if(row>50||col>50)						//size too large
					printf("Error: maximum matrix size is 50x50.\n\n");
				else
				{
					createMatrix(row,col,fileA);			//create a new matrix with specified size
					printf("%dx%d matrix was successfully saved to %s.\n\n",row,col,split[3]);
				}
			}
		}
		else if(strcmp(split[0],"copy")==0&&cmdSpt==3)		//copy command
		{
			returnA=openFile(&fileA,split[1],0);			//open source and destination files
			returnB=openFile(&fileTar,split[2],1);
			
			if(returnA==1)		//failed to open source
				printf("Error: file %s failed to open.\n\n",split[1]);
			if(returnB==1)		//failed to open destination
				printf("Error: file %s failed to open.\n\n",split[2]);
			
			if(returnA==0&&returnB==0)		//passed
			{
				matA=readMatrix(fileA);		//read source file
				writeMatrix(matA,fileTar);	//write to destination file
				printf("Matrix from %s is successfully copied to %s.\n\n",split[1],split[2]);
			}
		}
		else if(strcmp(split[0],"add")==0&&cmdSpt==4)		//add command
		{
			returnA=openFile(&fileA,split[1],0);			//open source and destination files
			returnB=openFile(&fileB,split[2],0);
			returnTar=openFile(&fileTar,split[3],1);
			
			if(returnA==1)		//failed to open source A
				printf("Error: file %s failed to open.\n\n",split[1]);
			if(returnB==1)		//failed to open source B
				printf("Error: file %s failed to open.\n\n",split[2]);
			if(returnTar==1)	//failed to open destination
				printf("Error: file %s failed to open.\n\n",split[3]);
			
			if(returnA==0&&returnB==0&&returnTar==0)		//passed
			{
				matA=readMatrix(fileA);						//read both sources files
				matB=readMatrix(fileB);
				returnFunc=addMatrix(matA,matB,fileTar);	//add matrices and save to destination
				if(returnFunc==0)							//success
				{
					printf("New matrix is successfully saved to %s.\n\n",split[3]);
					matTar=readMatrix(fileTar);
					printf("===Base matrix===\n");
					showMatrix(matA,split[1]);
					printf("===Adder matrix===\n");
					showMatrix(matB,split[2]);
					printf("===Result matrix===\n");
					showMatrix(matTar,split[3]);
				}
				else										//dimensions not matched
					printf("Error: matrix dimensions unmatched.\n\n");
			}
		}
		else if((strcmp(split[0],"subtract")==0||strcmp(split[0],"sub")==0)&&cmdSpt==4)		//subtract command
		{
			returnA=openFile(&fileA,split[1],0);			//open source and destination files
			returnB=openFile(&fileB,split[2],0);
			returnTar=openFile(&fileTar,split[3],1);
			
			if(returnA==1)		//failed to open source A
				printf("Error: file %s failed to open.\n\n",split[1]);
			if(returnB==1)		//failed to open source B
				printf("Error: file %s failed to open.\n\n",split[2]);
			if(returnTar==1)	//failed to open destination	
				printf("Error: file %s failed to open.\n\n",split[3]);
			
			if(returnA==0&&returnB==0&&returnTar==0)		//passed
			{
				matA=readMatrix(fileA);						//read both sources files
				matB=readMatrix(fileB);
				returnFunc=subMatrix(matA,matB,fileTar);	//subtract matrices and save to destination
				if(returnFunc==0)							//success
				{
					printf("New matrix is successfully saved to %s.\n\n",split[3]);
					matTar=readMatrix(fileTar);
					printf("===Base matrix===\n");
					showMatrix(matA,split[1]);
					printf("===Subtractor matrix===\n");
					showMatrix(matB,split[2]);
					printf("===Result matrix===\n");
					showMatrix(matTar,split[3]);
				}
				else										//dimensions not matched
					printf("Error: matrix dimensions unmatched.\n\n");
			}			
		}
		else if((strcmp(split[0],"multiply")==0||strcmp(split[0],"mul")==0)&&cmdSpt==4)		//multiply command
		{
			returnA=openFile(&fileA,split[1],0);			//open source and destination files
			returnB=openFile(&fileB,split[2],0);
			returnTar=openFile(&fileTar,split[3],1);
			
			if(returnA==1)		//failed to open source A
				printf("Error: file %s failed to open.\n\n",split[1]);
			if(returnB==1)		//failed to open source B
				printf("Error: file %s failed to open.\n\n",split[2]);
			if(returnTar==1)	//failed to open destination	
				printf("Error: file %s failed to open.\n\n",split[3]);
			
			if(returnA==0&&returnB==0&&returnTar==0)		//passed
			{
				matA=readMatrix(fileA);						//read both sources files
				matB=readMatrix(fileB);
				returnFunc=mulMatrix(matA,matB,fileTar);	//multiply matrices and save to destination
				if(returnFunc==0)							//success
				{
					printf("New matrix is successfully saved to %s.\n\n",split[3]);
					matTar=readMatrix(fileTar);
					printf("===Base matrix===\n");
					showMatrix(matA,split[1]);
					printf("===Multiplier matrix===\n");
					showMatrix(matB,split[2]);
					printf("===Result matrix===\n");
					showMatrix(matTar,split[3]);
				}
				else										//dimensions not matched
					printf("Error: matrix dimensions unmatched.\n\n");
			}			
		}
		else if((strcmp(split[0],"mulscalar")==0||strcmp(split[0],"muls")==0)&&cmdSpt==4)	//multiply scalar command
		{
			returnA=openFile(&fileA,split[2],0);			//open source and destination files
			returnTar=openFile(&fileTar,split[3],1);
			returnFunc=sscanf(split[1],"%lf",&mul);			//convert multiplier to double
			
			if(returnA==1)		//failed to open source A					
				printf("Error: file %s failed to open.\n\n",split[2]);
			if(returnTar==1)	//failed to open destination
				printf("Error: file %s failed to open.\n\n",split[3]);
			if(returnFunc!=1)	//cannot convert multiplier to double (invalid)
				printf("Error: invalid multiplier.\n\n");
			
			if(returnA==0&&returnB==0&&returnFunc==1)		//passed
			{
				matA=readMatrix(fileA);						//read source file
				mulScaMatrix(matA,mul,fileTar);				//multiply with scalar and save to destination
				
				printf("New matrix is successfully saved to %s.\n\n",split[3]);	
				matTar=readMatrix(fileTar);
				printf("===Base matrix===\n");
				showMatrix(matA,split[2]);
				printf("Multiply with %g\n\n",mul);
				printf("===Result matrix===\n");
				showMatrix(matTar,split[3]);				
			}
		}
		else if((strcmp(split[0],"transpose")==0||strcmp(split[0],"trans")==0)&&cmdSpt==3)	//transpose command
		{
			returnA=openFile(&fileA,split[1],0);			//open source and destination files
			returnTar=openFile(&fileTar,split[2],1);	

			if(returnA==1)		//failed to open source A
				printf("Error: file %s failed to open.\n\n",split[1]);
			if(returnTar==1)	//failed to open destination
				printf("Error: file %s failed to open.\n\n",split[2]);	

			if(returnA==0&&returnTar==0)					//passed
			{
				matA=readMatrix(fileA);						//read source file
				transMatrix(matA,fileTar);					//transpose matrix and save to destination
				
				printf("New matrix is successfully saved to %s.\n\n",split[2]);	
			}
		}
		else if((strcmp(split[0],"identity")==0||strcmp(split[0],"iden")==0)&&cmdSpt==3)	//identity matrix command
		{
			returnTar=openFile(&fileTar,split[2],1);		//open destination file
			returnFunc=sscanf(split[1],"%d",&size);			//convert size to integer
			
			if(returnTar==1)			//failed to open destination
				printf("Error: file %s failed to open.\n\n",split[2]);
			else if(returnFunc!=1)		//failed to convert size to integer (invalid)
				printf("Error: invalid matrix size.\n\n");
			else if(size>50)			//size too large
				printf("Error: maximum matrix size is 50x50.\n\n");
			else
			{
				idenMatrix(size,fileTar);		//create identity matrix with specified size and save to destination
				
				printf("Identity matrix of size %d is successfully saved to %s.\n\n",size,split[2]);	
			}
		}
		else if(strcmp(split[0],"help")==0&&cmdSpt==1)		//help command
		{
			displayHelp();		//display help
		}
		else if((strcmp(split[0],"clear")==0||strcmp(split[0],"cls")==0)&&cmdSpt==1)	//clear screen command
		{
			system("cls");		//clear screen
		}
		else if((strcmp(split[0],"exit")==0||strcmp(split[0],"end")==0)&&cmdSpt==1)		//exit command
		{
			printf("Exit\n");	//display exit message
		}
		else					//invalid command
		{
			printf("Invalid command or incorrect command syntax, type <help> for command list and usage.\n\n");
		}
		
		if(fileA!=NULL)			//close all file pointers in case they weren't closed by functions
			fclose(fileA);
		if(fileB!=NULL)
			fclose(fileB);
		if(fileTar!=NULL)
			fclose(fileTar);
		
	} while(strcmp(cmd,"exit")!=0&&strcmp(cmd,"end")!=0);	//loop until exit
	return 0;
}
Beispiel #9
0
void executeVm(Cpu_t *cpu)
{
	uint8_t temp;
	uint8_t command;
	//SYSTEMOUTHEX("adr",cpu->Pc);
	//SYSTEMOUTHEX("flag",cpu->flag);
	command=cpu->M[cpu->Pc];
	cpu->Pc++;
	switch(command)
	{
		// KA 	K->Ar 	 0, 1 	The pressed key from the hex keypad is saved to the A register.
		// If a key is not pressed, the Flag is set to 1, otherwise it is 0.
		case KA:{
		  DISASM("KA   ");
		  if(KEYHIT())
          {
            cpu->M[AR]=GETKEY();
            cpu->flag=0;
            SYSTEMOUTHEX("Key:",cpu->M[AR]);
          }else {
            SYSTEMOUT("nokey");
            cpu->flag=1;
          }
		}break;
		// AO 	Ar->Op 		1 	The 7-segment readout displays the value currently contained in the A register.
		case AO:{
			DISASM("AO   ");
			//show7Segment(cpu->M[AR]);
			DISPLAYOUTHEX(cpu->M[AR]);
			 //PRINT7SEGMENT(x);
			cpu->flag=1;
		}break;
		// CH 	Ar<=>Br
        // Yr<=>Zr 	1 	Exchange the contents of the A and B registers, and the Y and Z registers.
		case CH:{
			DISASM("CH   ");

			temp=cpu->M[AR];
			cpu->M[AR]=cpu->M[BR];
			cpu->M[BR]=temp;
			temp=cpu->M[YR];
			cpu->M[YR]=cpu->M[ZR];
			cpu->M[ZR]=temp;
			cpu->flag=1;
		}break;
		// CY 	Ar<=>Yr 	1 	Exchange the contents of the A and Y registers.
		case CY:{
			DISASM("CY   ");

			temp=cpu->M[AR];
			cpu->M[AR]=cpu->M[YR];
			cpu->M[YR]=temp;
			cpu->flag=1;
		}break;
		// AM 	Ar->M 		1 	Write the contents of the A register to data memory (memory address is 50 + Y register).
		case AM:{
			DISASM("AM   ");

			cpu->M[((cpu->M[YR])&0xF)+M_OFFSET]=cpu->M[AR];
			cpu->flag=1;
		}break;
		// MA 	M->Ar 		1 	Write the contents of data memory (50 + Y register) to the A register.
		case MA:{
			DISASM("MA   ");

			cpu->M[AR]=cpu->M[((cpu->M[YR])&0xF)+M_OFFSET];
			cpu->flag=1;
		}break;
		// M+ 	M+Ar->Ar 	0, 1 	Add the contents of data memory (50 + Y register) to the A register. If there is overflow, the Flag is set to 1, otherwise 0.
		case MPLUS:{
			DISASM("M+   ");

			cpu->M[AR]+=cpu->M[((cpu->M[YR])&0xF)+M_OFFSET];
			if(((cpu->M[AR])&0x10)!=0)cpu->flag=1;
			else cpu->flag=0;
			cpu->M[AR]&=0x0F;
		}break;
		// M- 	M-Ar->Ar 	0, 1 	Subtract the contents of data memory (50 + Y register) from the A register. If the result is negative, the Flag is set to 1, otherwise 0.
		case MMINUS:{
			DISASM("M-   ");

			cpu->M[AR]-=cpu->M[((cpu->M[YR])&0xF)+M_OFFSET];
			if(((cpu->M[AR])&0x10)!=0)cpu->flag=1;
			else cpu->flag=0;
			cpu->M[AR]&=0x0F;
		}break;
		// TIA [ ] 	[ ] -> Ar 	1 	Transfer immediate to the A register.
		case TIA:{
			DISASM("TIA  ");

			cpu->M[AR]=cpu->M[cpu->Pc];
			cpu->Pc++;
			cpu->flag=1;
		}break;
		// AIA [ ] 	Ar + [ ] -> Ar 	0, 1 	Add immediate to the A register. If there is overflow, the Flag is set to 1, otherwise 0.
		case AIA:{
			DISASM("AIA  ");

			cpu->M[AR]+=cpu->M[cpu->Pc];
			if(((cpu->M[AR])&0x10)!=0)cpu->flag=1;
			else cpu->flag=0;
			cpu->M[AR]&=0x0F;
			cpu->Pc++;
		}break;
		// TIY [ ] 	[ ] -> Yr 	1 	Transfer immediate to the Y register.
		case TIY:{
			DISASM("TIA  ");

			cpu->M[YR]=cpu->M[cpu->Pc];
			cpu->Pc++;
			cpu->flag=1;
		}break;
		// AIY [ ] 	Yr + [ ] -> Yr 	0, 1 	Add immediate to the Y register. If there is overflow, the Flag is set to 1, otherwise 0.
		case AIY:{
			DISASM("AIY  ");

			cpu->M[YR]+=cpu->M[cpu->Pc];
			if(((cpu->M[YR])&0x10)!=0)cpu->flag=1;
			else cpu->flag=0;
			cpu->M[YR]&=0x0F;
			cpu->Pc++;
		}break;
		// CIA [ ] 	Ar != [ ] ? 	0, 1 	Compare immediate to the A register. If equal, Flag reset to 0, otherwise set to 1.
		case CIA:{
			DISASM("CIA  ");

			if(cpu->M[AR]!=cpu->M[cpu->Pc])cpu->flag=0;
			else cpu->flag=1;
			cpu->Pc++;
		}break;
		// CIY [ ] 	Yr != [ ] ? 	0, 1 	Compare immediate to the Y register. If equal, Flag reset to 0, otherwise set to 1.
		case CIY:{
			DISASM("CIY  ");

			if(cpu->M[YR]!=cpu->M[cpu->Pc])cpu->flag=0;
			else cpu->flag=1;
			cpu->Pc++;
		}break;
		//JUMP [ ] [ ] 		1 	Jump to the immediate address if the Flag is 1, otherwise just increment the program counter.
		//The Flag is then set to 1. Note that this is an absolute address. That is, JUMP [0] [2] will change the address pointer to hex address 0x02.
		//You can jump both forward and backward in program space.
		case JUMP:{
			DISASM("JUMP ");

			if((cpu->flag)==1)
			{
				temp=cpu->M[cpu->Pc]<<4;
				cpu->Pc++;
				temp+=cpu->M[cpu->Pc]<<4;
				cpu->Pc=temp;
			}else{
				cpu->Pc++;
				cpu->flag=1;
			}
		}break;
		//      --- 	--- 	--- 	Extended code. See table below.
		case EXTENDED:{
			command=(cpu->M[cpu->Pc])|0xE0;
			SYSTEMOUTHEX("com:",command);
			cpu->Pc++;
			if(cpu->flag==1)switch(command)
			{
				case CAL_RSTO:{
					DISASM("CAL_RSTO  ");
					SYSTEMOUTCHAR(' ');
					//SYSTEMOUT("clear 7 seg");
				}break;
				case CAL_SETR:{
					DISASM("CAL_SETR  ");
					cpu->leds|=(1<<(cpu->M[YR]));
					SHOWLEDS(cpu->leds);
					//SYSTEMOUT("led on");
				}break;
				case CAL_RSTR:{
					DISASM("CAL_RSTR  ");
                    cpu->leds&=~(1<<(cpu->M[YR]));
                    SHOWLEDS(cpu->leds);
					//SYSTEMOUT("led off");
				}break;
				// 0xE4 // 	CAL CMPL 	1 	Complement the A register (1 <=> 0).
				case CAL_CMPL:{
					DISASM("CAL_CMPL  ");

					cpu->M[AR]=(~cpu->M[AR])&0x0F;
					cpu->flag=1;
				}break;
				//0xE5 // 	CAL CHNG 	1 	Swap the A/B/Y/Z registers with A'/B'/Y'/Z'
				case CAL_CHNG:{
					DISASM("CAL_CHNG  ");

					temp=cpu->M[AR];
					cpu->M[AR]=cpu->M[AR_];
					cpu->M[AR_]=temp;

					temp=cpu->M[BR];
					cpu->M[BR]=cpu->M[BR_];
					cpu->M[BR_]=temp;

					temp=cpu->M[YR];
					cpu->M[YR]=cpu->M[YR_];
					cpu->M[YR_]=temp;

					temp=cpu->M[ZR];
					cpu->M[ZR]=cpu->M[ZR_];
					cpu->M[ZR_]=temp;

					cpu->flag=1;

				}break;
				// 0xE6 //	CAL SIFT 	0, 1 	Shift the A register right 1 bit. If the starting value is even (bit 0 = 0), set the Flag to 1, otherwise 0.
				case CAL_SIFT:{
					DISASM("CAL_SIFT  ");

					if((cpu->M[AR])&1)cpu->flag=1;
					else cpu->flag=0;
					cpu->M[AR]=(~cpu->M[AR])>>1;
				}break;
				//0xE7 //	CAL ENDS 	1 	Play the End sound.
				case CAL_ENDS:{
					DISASM("CAL_ENDS  ");
					SOUND(NOTE_D6,80);
					SOUND(NOTE_E6,80);
					SOUND(NOTE_F6,80);
					SOUND(NOTE_G6,80);
					SOUND(NOTE_A6,80);
					SOUND(NOTE_B6,80);
				    //soundf(0);
					//SOUND(440,500);
					SYSTEMOUT("end sound");
					cpu->flag=1;
				}break;
				//0xE8 //	CAL ERRS 	1 	Play the Error sound.
				case CAL_ERRS:{
					DISASM("CAL_ERRS  ");
				    for(int n = 0; n < 6; n++)
				    {
				        SOUND(NOTE_G5,20);
				        SOUND(NOTE_A5,20);
				        SOUND(NOTE_B5,20);
				        SOUND(NOTE_C6,20);
				        SOUND(NOTE_D6,20);
				        SOUND(NOTE_E6,20);
				    }
					//SOUND(200,500);
					SYSTEMOUT("play error sound");
					cpu->flag=1;
				}break;
				//0xE9 //	CAL SHTS 	1 	Play a short "pi" sound.
				case CAL_SHTS:{
					DISASM("CAL_SHTS  ");
					SOUND(NOTE_C5,150);
					SYSTEMOUT("play short peep sound");
					cpu->flag=1;
				}break;
				//0xEA //	CAL LONS 	1 	Play a longer "pi-" sound.
				case CAL_LONS:{
					DISASM("CAL_LONS  ");
					SOUND(NOTE_C5,450);
					SYSTEMOUT("play longer peep sound");
					cpu->flag=1;
				}break;
				//0xEB //	CAL SUND 	1 	Play a note based on the value of the A register
				//(allowed values are 1 - E).
				case CAL_SUND:{

					DISASM("CAL_SUND  ");
					//SOUND(cpu->M[AR],500);
					gmcSound(cpu->M[AR],300);

					SYSTEMOUT("play A reg");
					cpu->flag=1;
				}break;
				//0xEC // 	CAL TIMR 	1
				//Pause for the time calculated by (value of A register +1) * 0.1 seconds.
				case CAL_TIMR:{
					DISASM("CAL_TIMR  ");

					showMatrix(((cpu->M[AR])*100+1));

					cpu->flag=1;
				}break;

				//0xED //	CAL DSPR 	1 	Set the 2-pin LEDs with the value from data memory. The data to display is as follows: the upper three bits come from memory address 5F (bits 0-2), and the lower four from memory address 5E (bits 0-3).
				case CAL_DSPR:{
					DISASM("CAL_DSPR  ");

					SYSTEMOUT("set LED");
					cpu->flag=1;
				}break;
				//0xEE // 	CAL DEM- 	1
				//Subtract the value of the A register from the value in data memory.
				//The new value is stored in data memory as a decimal.
				//Afterwards, the Y register is decremented by 1.
				case CAL_DEMMINUS:{
					DISASM("CAL_DEM-  ");

					//SYSTEMOUT("dem-");
					cpu->M[YR]=cpu->M[YR]-cpu->M[AR];
					cpu->M[YR]++;
					cpu->M[YR]&=0xF;
					cpu->flag=1;
				}break;

				//0xEF //	CAL DEM+ 	1
				//Add the value of the A register to the value in data memory.
				//The new value is stored in memory as a decimal.
				//If the result is overflow, data memory will be automatically adjusted.
				//Afterwards, the Y register is decremented.
				case CAL_DEMPLUS:{
					DISASM("CAL_DEM+  ");

					cpu->M[YR]=cpu->M[YR]+cpu->M[AR];
					cpu->M[YR]--;
					cpu->M[YR]&=0xF;
					cpu->flag=1;
				}break;
			}
		}break;

	}
}
void loop() {

    static int8_t value=0;
    uint8_t n;

    // blink LED
    for(n=0; n<3; n++)
    {
        ledOn();
        delay(200);
        ledOff();
        delay(200);
    }
    uint8_t row,col;

    // display row an colun test
    initDisplay();
    for(row=0; row<5; row++)
    {
        for(col=0; col<7; col++)
        {

            setRow(row);
            setCol(col);
            delay(100);
        }
    }

    // show hello
    _putchar('H');
    showMatrix(200);
    _putchar('E');
    showMatrix(200);
    _putchar('L');
    showMatrix(400);
    _putchar('O');
    showMatrix(200);


    //**************** key display example ***************************
    do
    {
        n=_getchar();
        value=getKey();
        _putchar(n);
        showLeds(value);
    }
    while(n!='i');

    //**************** key sound display example ***************************
    tone(CH2_SPEAKERPIN, frequencyTable[0],50);
    do
    {
        n=_getchar();
        value=getKey();
        tone(CH2_SPEAKERPIN, frequencyTable[value],50);
        delay(50);
        _putchar(n);
        showLeds(value);
    }
    while(n!='i');

    // key code test
    do
    {
        n=scanKey();
        //initDisplay();
        //setCol(0);
        //setRowPattern(n);
        if(n<0x10)	hex1(n);
        else _putchar('n');
        showLeds(n);
        showMatrix(100);
        //delay(1000);
    } while(n!=HASHKEY);

}
Beispiel #11
0
AUD_Int32s train_keyword_hmm( const AUD_Int8s *pKeywordFile, AUD_Int8s *pHmmName )
{
	AUD_Error  error = AUD_ERROR_NONE;

	// step 1: read garbage model from file
	void *hGarbageGmm = NULL;
	FILE *fpGarbage = fopen( (char*)WOV_UBM_GMMHMMMODEL_FILE, "rb" );
	if ( fpGarbage == NULL )
	{
		AUDLOG( "cannot open gmm model file: [%s]\n", WOV_UBM_GMMHMMMODEL_FILE );
		return AUD_ERROR_IOFAILED;
	}

	error = gmm_import( &hGarbageGmm, fpGarbage );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	fclose( fpGarbage );
	fpGarbage = NULL;

	// AUDLOG( "garbage GMM as:\n" );
	// gmm_show( hGarbageGmm );

	// step 2: read template stream & extract MFCC feature vector
	AUD_Int32s sampleNum = 0;
	AUD_Int32s bufLen    = SAMPLE_RATE * BYTES_PER_SAMPLE * 10;
	AUD_Int16s *pBuf     = (AUD_Int16s*)calloc( bufLen, 1 );
	AUD_ASSERT( pBuf );

	AUD_Int32s ret;

	// read stream from file
	sampleNum = readWavFromFile( (AUD_Int8s*)pKeywordFile, pBuf, bufLen );
	AUD_ASSERT( sampleNum > 0 );

	AUD_Int32s i = 0, j = 0, k = 0, m = 0;

	// front end processing

	 // pre-emphasis
	sig_preemphasis( pBuf, pBuf, sampleNum );


	// calc frame number
	for ( j = 0; j * FRAME_STRIDE + FRAME_LEN <= sampleNum; j++ )
	{
		;
	}

	AUD_Feature feature;
	feature.featureMatrix.rows     = j - MFCC_DELAY;
	feature.featureMatrix.cols     = MFCC_FEATDIM;
	feature.featureMatrix.dataType = AUD_DATATYPE_INT32S;
	ret = createMatrix( &(feature.featureMatrix) );
	AUD_ASSERT( ret == 0 );

	feature.featureNorm.len      = j - MFCC_DELAY;
	feature.featureNorm.dataType = AUD_DATATYPE_INT64S;
	ret = createVector( &(feature.featureNorm) );
	AUD_ASSERT( ret == 0 );

	// init mfcc handle
	void *hMfccHandle = NULL;
	error = mfcc16s32s_init( &hMfccHandle, FRAME_LEN, WINDOW_TYPE, MFCC_ORDER, FRAME_STRIDE, SAMPLE_RATE, COMPRESS_TYPE );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	// calc MFCC feature
	error = mfcc16s32s_calc( hMfccHandle, pBuf, sampleNum, &feature );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	free( pBuf );
	pBuf = NULL;

	// step 3: for each feature vector, get the bestN most likelihood component indices from GMM
	AUD_Vector componentLLR;
	componentLLR.len      = gmm_getmixnum( hGarbageGmm );
	componentLLR.dataType = AUD_DATATYPE_DOUBLE;
	ret = createVector( &componentLLR );
	AUD_ASSERT( ret == 0 );

	AUD_Matrix indexTable;
	indexTable.rows     = feature.featureMatrix.rows ;
	indexTable.cols     = WOV_KEYWORD_GMMMODEL_ORDER;
	indexTable.dataType = AUD_DATATYPE_INT32S;
	ret = createMatrix( &indexTable );
	AUD_ASSERT( ret == 0 );

	AUD_Matrix llrTable;
	llrTable.rows     = feature.featureMatrix.rows;
	llrTable.cols     = WOV_KEYWORD_GMMMODEL_ORDER;
	llrTable.dataType = AUD_DATATYPE_DOUBLE;
	ret = createMatrix( &llrTable );
	AUD_ASSERT( ret == 0 );

	AUD_Double totalLLR;

	for ( i = 0; i < feature.featureMatrix.rows; i++ )
	{
		totalLLR = gmm_llr( hGarbageGmm, &(feature.featureMatrix), i, &componentLLR );

#if 0
		showVector( &componentLLR );
#endif

		// sort the bestN likelihood
		AUD_Int32s *pIndex = indexTable.pInt32s + i * indexTable.cols;
		AUD_Double *pLLR   = llrTable.pDouble + i * llrTable.cols;

		for ( j = 0; j < WOV_KEYWORD_GMMMODEL_ORDER; j++ )
		{
			pIndex[j] = -1;
			pLLR[j]   = 0.;
		}

		for ( j = 0; j < componentLLR.len; j++ )
		{
			for ( k = 0; k < WOV_KEYWORD_GMMMODEL_ORDER; k++ )
			{
				if ( pIndex[k] == -1 )
				{
					pIndex[k] = j;
					pLLR[k]   = componentLLR.pDouble[j];
					break;
				}
				else if ( componentLLR.pDouble[j] > pLLR[k] )
				{
					for ( m = WOV_KEYWORD_GMMMODEL_ORDER - 1; m > k ; m-- )
					{
						pIndex[m] = pIndex[m - 1];
						pLLR[m]   = pLLR[m - 1];
					}
					pIndex[k] = j;
					pLLR[k]   = componentLLR.pDouble[j];
					break;
				}
			}
		}
	}

#if 0
	AUDLOG( "index table( %s, %s, %d ):\n", __FILE__, __FUNCTION__, __LINE__ );
	showMatrix( &indexTable );
	AUDLOG( "llr table( %s, %s, %d ):\n", __FILE__, __FUNCTION__, __LINE__ );
	showMatrix( &llrTable );
#endif

	ret = destroyVector( &componentLLR );
	AUD_ASSERT( ret == 0 );

	// step 4: cluster GMM
	AUD_Int32s *pClusterLabel = (AUD_Int32s*)calloc( sizeof(AUD_Int32s) * feature.featureMatrix.rows, 1 );
	AUD_ASSERT( pClusterLabel );

	error = gmm_cluster( hGarbageGmm, &indexTable, WOV_GMM_CLUSTER_THRESHOLD, pClusterLabel );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	AUD_Int32s stateNum = pClusterLabel[feature.featureMatrix.rows - 1];
	AUD_ASSERT( stateNum >= 5 );

	// step 5: select and build state GMM
	void **phKeywordGmms = (void**)calloc( sizeof(void*) * stateNum, 1 );
	AUD_ASSERT( phKeywordGmms );

	AUD_Vector indexVector;
	indexVector.len      = WOV_KEYWORD_GMMMODEL_ORDER;
	indexVector.dataType = AUD_DATATYPE_INT32S;
	ret = createVector( &indexVector );
	AUD_ASSERT( ret == 0 );

	AUD_Vector llrVector;
	llrVector.len      = WOV_KEYWORD_GMMMODEL_ORDER;
	llrVector.dataType = AUD_DATATYPE_DOUBLE;
	ret = createVector( &llrVector );
	AUD_ASSERT( ret == 0 );

	int start = 0, end = 0;
	for ( i = 0; i < stateNum; i++ )
	{
		for ( j = 0; j < indexVector.len; j++ )
		{
			indexVector.pInt32s[j] = -1;
			llrVector.pInt32s[j]   = 1.;
		}

		for ( j = start; j < feature.featureMatrix.rows; j++ )
		{
			if ( pClusterLabel[j] != i )
			{
				break;
			}
		}
		end = j;

		for ( k = start * llrTable.cols; k < end * llrTable.cols; k++ )
		{
			for ( m = 0; m < indexVector.len; m++ )
			{
				if ( llrTable.pDouble[k] == llrVector.pDouble[m] &&
				     indexTable.pInt32s[k] == indexVector.pInt32s[m] )
				{
					break;
				}
				else if ( indexVector.pInt32s[m] == -1 || llrTable.pDouble[k] > llrVector.pDouble[m] )
				{
					for ( int n = indexVector.len - 1; n > m ; n-- )
					{
						indexVector.pInt32s[n] = indexVector.pInt32s[n - 1];
						llrVector.pDouble[n]   = llrVector.pDouble[n - 1];
					}
					indexVector.pInt32s[m] = indexTable.pInt32s[k];
					llrVector.pDouble[m]   = llrTable.pDouble[k];
					break;
				}
			}
		}

		// AUDLOG( "Final GMM indices for state[%d]:\n", i );
		// showVector( &indexVector );

		AUD_Int8s gmmName[256] = { 0, };
		sprintf( (char*)gmmName, "state%d", i );
		error = gmm_select( &phKeywordGmms[i], hGarbageGmm, &indexVector, 0, gmmName );
		AUD_ASSERT( error == AUD_ERROR_NONE );

		start = end;
	}

	ret = destroyMatrix( &indexTable );
	AUD_ASSERT( ret == 0 );

	ret = destroyMatrix( &llrTable );
	AUD_ASSERT( ret == 0 );

	ret = destroyVector( &indexVector );
	AUD_ASSERT( ret == 0 );

	ret = destroyVector( &llrVector );
	AUD_ASSERT( ret == 0 );

	free( pClusterLabel );
	pClusterLabel = NULL;

	// step 6: generate keyword model by Baum-Welch algorithm
	AUD_Vector pi;
	pi.len      = stateNum;
	pi.dataType = AUD_DATATYPE_DOUBLE;
	ret = createVector( &pi );
	AUD_ASSERT( ret == 0 );

	pi.pDouble[0] = 1.0f;
	void *hKeywordHmm   = NULL;
	error = gmmhmm_init( &hKeywordHmm, stateNum, &pi, phKeywordGmms );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	error = gmmhmm_learn( hKeywordHmm, &feature, 1, 0.001 );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	// step 8: write model to file
	error = gmmhmm_export( hKeywordHmm, pHmmName );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	// gmmhmm_show( hKeywordHmm );

	// clean field
	error = mfcc16s32s_deinit( &hMfccHandle );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	error = gmm_free( &hGarbageGmm );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	ret = destroyMatrix( &(feature.featureMatrix) );
	AUD_ASSERT( ret == 0 );

	ret = destroyVector( &(feature.featureNorm) );
	AUD_ASSERT( ret == 0 );

	ret = destroyVector( &pi );
	AUD_ASSERT( ret == 0 );


	for ( i = 0; i < stateNum; i++ )
	{
		error = gmm_free( &phKeywordGmms[i] );
		AUD_ASSERT( error == AUD_ERROR_NONE );
	}
	free( phKeywordGmms );
	phKeywordGmms = NULL;

	error = gmmhmm_free( &hKeywordHmm );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	return 0;
}
int main(void)
{
	//PORTS A,C,E,D are dedicated to matrix display
	DDRD = 0xFF;
	DDRE = 0xFF;
	DDRA = 0xFF;
	DDRC = 0xFF;
	
	//button port is for input
	BUTTON_DIR = 0x00;
	//pullups for PINB0 and PINB1 (button X and Z)
	BUTTON_PORT = 0x03;
	//just make sure pullups are NOT disabled
	MCUCR |= (0 << PUD);
	
	//A0-A3 : are the negative row 1-4
	//C4-C7 : are the negative row 5-8
	
	XDIV = 0x00;

	init_timer2_OVF();
	init_timer0_OVF();
	
	//DS1302 is plugged on the G port	
	setupDS1302();
			
	wormInit();
	rainInit();
	
	while (1){
		//refresh display
		showMatrix();
		
		if (mShowMode != MODE_SETTIME){
			//check if BUTTON_X is pressed (back board button)
			if ((~BUTTON_INPUT & (1 << BUTTON_X)) != 0){
				matrixClearAll();
				mShowMode = (mShowMode + 1) % MODE_COUNT;
				//debounce
				_delay_ms(500);
			}

			//Z : go set time
			if ((~BUTTON_INPUT & (1 << BUTTON_Z)) != 0){
				mShowMode = MODE_SETTIME;
				mSubModeSetTimeStep = 0;
				//debounce
				_delay_ms(500);
			}
		}		
		else {
			//mode set time

			//X : hour or minute +1
			if ((~BUTTON_INPUT & (1 << BUTTON_X)) != 0){
				if (mSubModeSetTimeStep == 0){
					//hours +=1
					uint8_t vHours = rtc.h24.Hour10 * 10 + rtc.h24.Hour;
					vHours = (vHours +1) % 24;
					rtc.h24.Hour10 = vHours / 10;
					rtc.h24.Hour = vHours % 10;
					
					//write and read just after to see the result
					DS1302_clock_burst_write((uint8_t *) &rtc);
					DS1302_clock_burst_read( (uint8_t *) &rtc);
				}
				if (mSubModeSetTimeStep == 1){
					//minutes +=1
					uint8_t vMin = rtc.Minutes10 * 10 + rtc.Minutes;
					vMin = (vMin +1) % 60;
					rtc.Minutes10 = vMin / 10;
					rtc.Minutes = vMin % 10;
					
					//write and read just after to see the result
					DS1302_clock_burst_write((uint8_t *) &rtc);
					DS1302_clock_burst_read( (uint8_t *) &rtc);			
				}
				//debounce
				_delay_ms(500);
			}

			//Z : go set time
			if ((~BUTTON_INPUT & (1 << BUTTON_Z)) != 0){
				mSubModeSetTimeStep++;
				if (mSubModeSetTimeStep > 1){
					//finished
					matrixClearAll();
					mShowMode = MODE_TIME_RND;
					mSubModeAnimId = rand() % 3;
				}
				//debounce
				_delay_ms(500);
			}
		}

	}
	
}
Beispiel #13
0
AUD_Int32s denoise_aud( AUD_Int16s *pInBuf, AUD_Int16s *pOutBuf, AUD_Int32s inLen )
{
    Fft_16s        *hFft        = NULL;
    Ifft_16s       *hIfft       = NULL;
    AUD_Window16s  *hWin        = NULL;

    AUD_Int32s     frameSize    = 512;
    AUD_Int32s     frameStride  = 256;
    AUD_Int32s     frameOverlap = 256;
    AUD_Int32s     nFFT         = frameSize;
    AUD_Int32s     nSpecLen     = nFFT / 2 + 1;
    AUD_Int32s     nNoiseFrame  = 6; // (AUD_Int32s)( ( 0.25 * SAMPLE_RATE - frameSize ) / frameStride + 1 );

    AUD_Int32s     i, j, k, m, n, ret;

    AUD_Int32s     cleanLen     = 0;

    // pre-emphasis
    // sig_preemphasis( pInBuf, pInBuf, inLen );

    // init hamming module
    win16s_init( &hWin, AUD_WIN_HAMM, frameSize, 14 );
    AUD_ASSERT( hWin );

    // init fft handle
    fft_init( &hFft, nFFT, 15 );
    AUD_ASSERT( hFft );

    // init ifft handle
    ifft_init( &hIfft, nFFT, 15 );
    AUD_ASSERT( hIfft );

    AUD_Int16s *pFrame  = (AUD_Int16s*)calloc( frameSize * sizeof(AUD_Int16s), 1 );
    AUD_ASSERT( pFrame );

    // FFT
    AUD_Int32s *pFFTMag  = (AUD_Int32s*)calloc( nFFT * sizeof(AUD_Int32s), 1 );
    AUD_ASSERT( pFFTMag );
    AUD_Int32s *pFFTRe   = (AUD_Int32s*)calloc( nFFT * sizeof(AUD_Int32s), 1 );
    AUD_ASSERT( pFFTRe );
    AUD_Int32s *pFFTIm   = (AUD_Int32s*)calloc( nFFT * sizeof(AUD_Int32s), 1 );
    AUD_ASSERT( pFFTIm );

    AUD_Int32s *pFFTCleanRe = (AUD_Int32s*)calloc( nFFT * sizeof(AUD_Int32s), 1 );
    AUD_ASSERT( pFFTCleanRe );
    AUD_Int32s *pFFTCleanIm = (AUD_Int32s*)calloc( nFFT * sizeof(AUD_Int32s), 1 );
    AUD_ASSERT( pFFTCleanIm );

    // noise spectrum
    AUD_Double *pNoiseEn = (AUD_Double*)calloc( nSpecLen * sizeof(AUD_Double), 1 );
    AUD_ASSERT( pNoiseEn );

    AUD_Double *pNoiseB = (AUD_Double*)calloc( nSpecLen * sizeof(AUD_Double), 1 );
    AUD_ASSERT( pNoiseB );

    AUD_Double *pXPrev = (AUD_Double*)calloc( nSpecLen * sizeof(AUD_Double), 1 );
    AUD_ASSERT( pXPrev );

    AUD_Double *pAb = (AUD_Double*)calloc( nSpecLen * sizeof(AUD_Double), 1 );
    AUD_ASSERT( pAb );

    AUD_Double *pH = (AUD_Double*)calloc( nSpecLen * sizeof(AUD_Double), 1 );
    AUD_ASSERT( pH );

    AUD_Double *pGammak = (AUD_Double*)calloc( nSpecLen * sizeof(AUD_Double), 1 );
    AUD_ASSERT( pGammak );

    AUD_Double *pKsi = (AUD_Double*)calloc( nSpecLen * sizeof(AUD_Double), 1 );
    AUD_ASSERT( pKsi );

    AUD_Double *pLogSigmak = (AUD_Double*)calloc( nSpecLen * sizeof(AUD_Double), 1 );
    AUD_ASSERT( pLogSigmak );

    AUD_Double *pAlpha = (AUD_Double*)calloc( nSpecLen * sizeof(AUD_Double), 1 );
    AUD_ASSERT( pAlpha );

    AUD_Int32s *pLinToBark = (AUD_Int32s*)calloc( nSpecLen * sizeof(AUD_Int32s), 1 );
    AUD_ASSERT( pLinToBark );

    AUD_Int16s *pxOld   = (AUD_Int16s*)calloc( frameOverlap * sizeof(AUD_Int16s), 1 );
    AUD_ASSERT( pxOld );
    AUD_Int16s *pxClean = (AUD_Int16s*)calloc( nFFT * sizeof(AUD_Int16s), 1 );
    AUD_ASSERT( pxClean );

    /*
    AUD_Int32s critBandEnds[22] = { 0, 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270,
                                    1480, 1720, 2000, 2320, 2700, 3150, 3700, 4400, 5300, 6400, 7700 };
    */
    AUD_Int32s critFFTEnds[CRITICAL_BAND_NUM + 1]  = { 0, 4, 7, 10, 13, 17, 21, 25, 30, 35, 41, 48, 56, 64,
                                                       75, 87, 101, 119, 141, 170, 205, 247, 257 };

    // generate linear->bark transform mapping
    k = 0;
    for ( i = 0; i < CRITICAL_BAND_NUM; i++ )
    {
        while ( k >= critFFTEnds[i] &&  k < critFFTEnds[i + 1] )
        {
            pLinToBark[k] = i;
            k++;
        }
    }

    AUD_Double absThr[CRITICAL_BAND_NUM] = { 38, 31, 22, 18.5, 15.5, 13, 11, 9.5, 8.75, 7.25, 4.75, 2.75,
                                             1.5, 0.5, 0, 0, 0, 0, 2, 7, 12, 15.5 };

    AUD_Double dbOffset[CRITICAL_BAND_NUM];
    AUD_Double sumn[CRITICAL_BAND_NUM];
    AUD_Double spread[CRITICAL_BAND_NUM];

    for ( i = 0; i < CRITICAL_BAND_NUM; i++ )
    {
        absThr[i]   = pow( 10., absThr[i] / 10. ) / nFFT / ( 65535. * 65535. );
        dbOffset[i] = 10. + i;

        sumn[i]   = 0.474 + i;
        spread[i] = pow( 10., ( 15.81 + 7.5 * sumn[i] - 17.5 * sqrt( 1. + sumn[i] * sumn[i] ) ) / 10. );
    }

    AUD_Double dcGain[CRITICAL_BAND_NUM];
    for ( i = 0; i < CRITICAL_BAND_NUM; i++ )
    {
        dcGain[i] = 0.;
        for ( j = 0; j < CRITICAL_BAND_NUM; j++ )
        {
            dcGain[i] += spread[MABS( i - j )];
        }
    }

    AUD_Matrix exPatMatrix;
    exPatMatrix.rows     = CRITICAL_BAND_NUM;
    exPatMatrix.cols     = nSpecLen;
    exPatMatrix.dataType = AUD_DATATYPE_DOUBLE;
    ret = createMatrix( &exPatMatrix );
    AUD_ASSERT( ret == 0 );

    // excitation pattern
    AUD_Int32s index = 0;
    for ( i = 0; i < exPatMatrix.rows; i++ )
    {
        AUD_Double *pExpatRow = exPatMatrix.pDouble + i * exPatMatrix.cols;

        for ( j = 0; j < exPatMatrix.cols; j++ )
        {
            index = MABS( i - pLinToBark[j] );
            pExpatRow[j] = spread[index];
        }
    }

    AUD_Int32s frameNum = (inLen - frameSize) / frameStride + 1;
    AUD_ASSERT( frameNum > nNoiseFrame );

    // compute noise mean
    for ( i = 0; i < nNoiseFrame; i++ )
    {
        win16s_calc( hWin, pInBuf + i * frameSize, pFrame );

        fft_mag( hFft, pFrame, frameSize, pFFTMag );

        for ( j = 0; j < nSpecLen; j++ )
        {
            pNoiseEn[j] += pFFTMag[j] / 32768. * pFFTMag[j] / 32768.;
        }
    }
    for ( j = 0; j < nSpecLen; j++ )
    {
        pNoiseEn[j] /= nNoiseFrame;
    }

    // get cirtical band mean filtered noise power
    AUD_Int32s k1 = 0, k2 = 0;
    for ( i = 0; i < CRITICAL_BAND_NUM; i++ )
    {
        k1 = k2;
        AUD_Double segSum = 0.;
        while ( k2 >= critFFTEnds[i] &&  k2 < critFFTEnds[i + 1] )
        {
            segSum += pNoiseEn[k2];
            k2++;
        }
        segSum /= ( k2 - k1 );

        for ( m = k1; m < k2; m++ )
        {
            pNoiseB[m] = segSum;
        }
    }

#if 0
    AUDLOG( "noise band spectrum:\n" );
    for ( j = 0; j < nSpecLen; j++ )
    {
        AUDLOG( "%.2f, ", pNoiseB[j] );
    }
    AUDLOG( "\n" );
#endif

    AUD_Matrix frameMatrix;
    frameMatrix.rows     = nSpecLen;
    frameMatrix.cols     = 1;
    frameMatrix.dataType = AUD_DATATYPE_DOUBLE;
    ret = createMatrix( &frameMatrix );
    AUD_ASSERT( ret == 0 );
    AUD_Double *pFrameEn = frameMatrix.pDouble;

    AUD_Matrix xMatrix;
    xMatrix.rows     = nSpecLen;
    xMatrix.cols     = 1;
    xMatrix.dataType = AUD_DATATYPE_DOUBLE;
    ret = createMatrix( &xMatrix );
    AUD_ASSERT( ret == 0 );
    AUD_Double *pX = xMatrix.pDouble;

    AUD_Matrix cMatrix;
    cMatrix.rows     = CRITICAL_BAND_NUM;
    cMatrix.cols     = 1;
    cMatrix.dataType = AUD_DATATYPE_DOUBLE;
    ret = createMatrix( &cMatrix );
    AUD_ASSERT( ret == 0 );
    AUD_Double *pC = cMatrix.pDouble;

    AUD_Matrix tMatrix;
    tMatrix.rows     = 1;
    tMatrix.cols     = CRITICAL_BAND_NUM;
    tMatrix.dataType = AUD_DATATYPE_DOUBLE;
    ret = createMatrix( &tMatrix );
    AUD_ASSERT( ret == 0 );
    AUD_Double *pT = tMatrix.pDouble;

    AUD_Matrix tkMatrix;
    tkMatrix.rows     = 1;
    tkMatrix.cols     = nSpecLen;
    tkMatrix.dataType = AUD_DATATYPE_DOUBLE;
    ret = createMatrix( &tkMatrix );
    AUD_ASSERT( ret == 0 );
    AUD_Double *pTk = tkMatrix.pDouble;

    AUD_Double dB0[CRITICAL_BAND_NUM];
    AUD_Double epsilon = pow( 2, -52 );

    #define ESTIMATE_MASKTHRESH( sigMatrix, tkMatrix )\
    do {\
        AUD_Double *pSig = sigMatrix.pDouble; \
        for ( m = 0; m < exPatMatrix.rows; m++ ) \
        { \
            AUD_Double suma = 0.; \
            AUD_Double *pExpatRow = exPatMatrix.pDouble + m * exPatMatrix.cols; \
            for ( n = 0; n < exPatMatrix.cols; n++ ) \
            { \
                suma += pExpatRow[n] * pSig[n]; \
            } \
            pC[m] = suma; \
        } \
        AUD_Double product = 1.; \
        AUD_Double sum     = 0.; \
        for ( m = 0; m < sigMatrix.rows; m++ ) \
        { \
            product *= pSig[m]; \
            sum     += pSig[m]; \
        } \
        AUD_Double power = 1. / sigMatrix.rows;\
        AUD_Double sfmDB = 10. * log10( pow( product, power ) / sum / sigMatrix.rows + epsilon ); \
        AUD_Double alpha = AUD_MIN( 1., sfmDB / (-60.) ); \
        for ( m = 0; m < tMatrix.cols; m++ ) \
        { \
            dB0[m] = dbOffset[m] * alpha + 5.5; \
            pT[m]  = pC[m] / pow( 10., dB0[m] / 10. ) / dcGain[m]; \
            pT[m]  = AUD_MAX( pT[m], absThr[m] ); \
        } \
        for ( m = 0; m < tkMatrix.cols; m++ ) \
        { \
            pTk[m] = pT[pLinToBark[m]]; \
        } \
       } while ( 0 )

    AUD_Double aa    = 0.98;
    AUD_Double mu    = 0.98;
    AUD_Double eta   = 0.15;
    AUD_Double vadDecision;

    k = 0;
    // start processing
    for ( i = 0; i < frameNum; i++ )
    {
        win16s_calc( hWin, pInBuf + i * frameStride, pFrame );

        fft_calc( hFft, pFrame, frameSize, pFFTRe, pFFTIm );

        // compute SNR
        vadDecision = 0.;
        for ( j = 0; j < nSpecLen; j++ )
        {
            pFrameEn[j] = pFFTRe[j] / 32768. * pFFTRe[j] / 32768. + pFFTIm[j] / 32768. * pFFTIm[j] / 32768.;

            pGammak[j]  = AUD_MIN( pFrameEn[j] / pNoiseEn[j], 40. );

            if ( i > 0 )
            {
                pKsi[j] = aa * pXPrev[j] / pNoiseEn[j] + ( 1 - aa ) * AUD_MAX( pGammak[j] - 1., 0. );
            }
            else
            {
                pKsi[j] = aa + ( 1. - aa ) * AUD_MAX( pGammak[j] - 1., 0. );
            }

            pLogSigmak[j] = pGammak[j] * pKsi[j] / ( 1. + pKsi[j] ) - log( 1. + pKsi[j] );

            vadDecision += ( j > 0 ? 2 : 1 ) * pLogSigmak[j];
        }
        vadDecision /= nFFT;

#if 0
        AUDLOG( "X prev:\n" );
        for ( j = 0; j < nSpecLen; j++ )
        {
            AUDLOG( "%.2f, ", pXPrev[j] );
        }
        AUDLOG( "\n" );
#endif

#if 0
        AUDLOG( "gamma k:\n" );
        for ( j = 0; j < nSpecLen; j++ )
        {
            AUDLOG( "%.2f, ", pGammak[j] );
        }
        AUDLOG( "\n" );
#endif

#if 0
        AUDLOG( "ksi:\n" );
        for ( j = 0; j < nSpecLen; j++ )
        {
            AUDLOG( "%.2f, ", pKsi[j] );
        }
        AUDLOG( "\n" );
#endif

#if 0
        AUDLOG( "log sigma k:\n" );
        for ( j = 0; j < nSpecLen; j++ )
        {
            AUDLOG( "%.2f, ", pLogSigmak[j] );
        }
        AUDLOG( "\n" );
#endif

        // AUDLOG( "vadDecision: %.2f\n", vadDecision );
        // re-estimate noise
        if ( vadDecision < eta )
        {
            for ( j = 0; j < nSpecLen; j++ )
            {
                pNoiseEn[j] = mu * pNoiseEn[j] + ( 1. - mu ) * pFrameEn[j];
            }

            // re-estimate crital band based noise
            AUD_Int32s k1 = 0, k2 = 0;
            for ( int band = 0; band < CRITICAL_BAND_NUM; band++ )
            {
                k1 = k2;
                AUD_Double segSum = 0.;
                while ( k2 >= critFFTEnds[band] &&  k2 < critFFTEnds[band + 1] )
                {
                    segSum += pNoiseEn[k2];
                    k2++;
                }
                segSum /= ( k2 - k1 );

                for ( m = k1; m < k2; m++ )
                {
                    pNoiseB[m] = segSum;
                }
            }

#if 0
            AUDLOG( "noise band spectrum:\n" );
            for ( j = 0; j < nSpecLen; j++ )
            {
                AUDLOG( "%.2f, ", pNoiseB[j] );
            }
            AUDLOG( "\n" );
#endif
        }

        for ( j = 0; j < nSpecLen; j++ )
        {
            pX[j]     = AUD_MAX( pFrameEn[j] - pNoiseEn[j], 0.001 );
            pXPrev[j] = pFrameEn[j];
        }

        ESTIMATE_MASKTHRESH( xMatrix, tkMatrix );
        for ( int iter = 0; iter < 2; iter++ )
        {
            for ( j = 0; j < nSpecLen; j++ )
            {
                pAb[j]      = pNoiseB[j] + pNoiseB[j] * pNoiseB[j] / pTk[j];
                pFrameEn[j] = pFrameEn[j] * pFrameEn[j] / ( pFrameEn[j] + pAb[j] );
                ESTIMATE_MASKTHRESH( frameMatrix, tkMatrix );

#if 0
                showMatrix( &tMatrix );
#endif
            }
        }

#if 0
        AUDLOG( "tk:\n" );
        for ( j = 0; j < nSpecLen; j++ )
        {
            AUDLOG( "%.2f, ", pTk[j] );
        }
        AUDLOG( "\n" );
#endif

        pAlpha[0]      = ( pNoiseB[0] + pTk[0] ) * ( pNoiseB[0] / pTk[0] );
        pH[0]          = pFrameEn[0] / ( pFrameEn[0] + pAlpha[0] );
        pXPrev[0]     *= pH[0] * pH[0];
        pFFTCleanRe[0] = 0;
        pFFTCleanIm[0] = 0;
        for ( j = 1; j < nSpecLen; j++ )
        {
            pAlpha[j] = ( pNoiseB[j] + pTk[j] ) * ( pNoiseB[j] / pTk[j] );

            pH[j]     = pFrameEn[j] / ( pFrameEn[j] + pAlpha[j] );

            pFFTCleanRe[j] = pFFTCleanRe[nFFT - j] = (AUD_Int32s)round( pH[j] * pFFTRe[j] );
            pFFTCleanIm[j]        = (AUD_Int32s)round( pH[j] * pFFTIm[j] );
            pFFTCleanIm[nFFT - j] = -pFFTCleanIm[j];

            pXPrev[j] *= pH[j] * pH[j];
        }

#if 0
        AUDLOG( "denoise transfer function:\n" );
        for ( j = 0; j < nSpecLen; j++ )
        {
            AUDLOG( "%.2f, ", pH[j] );
        }
        AUDLOG( "\n" );
#endif

#if 0
        AUDLOG( "clean FFT with phase:\n" );
        for ( j = 0; j < nFFT; j++ )
        {
            AUDLOG( "%d + j%d, ", pFFTCleanRe[j], pFFTCleanIm[j] );
        }
        AUDLOG( "\n" );
#endif

        ifft_real( hIfft, pFFTCleanRe, pFFTCleanIm, nFFT, pxClean );

#if 0
        AUDLOG( "clean speech:\n" );
        for ( j = 0; j < nFFT; j++ )
        {
            AUDLOG( "%d, ", pxClean[j] );
        }
        AUDLOG( "\n" );
#endif

        for ( j = 0; j < frameStride; j++ )
        {
            if ( j < frameOverlap )
            {
                pOutBuf[k + j] = pxOld[j] + pxClean[j];
                pxOld[j] = pxClean[frameStride + j];
            }
            else
            {
                pOutBuf[k + j] = pxClean[j];
            }
        }

        k        += frameStride;
        cleanLen += frameStride;
    }

    // de-emphasis
    // sig_deemphasis( pOutBuf, pOutBuf, cleanLen );

    win16s_free( &hWin );
    fft_free( &hFft );
    ifft_free( &hIfft );

    free( pFrame );
    free( pNoiseEn );
    free( pNoiseB );

    free( pFFTMag );
    free( pFFTRe );
    free( pFFTIm );
    free( pXPrev );
    free( pAb );
    free( pH );

    free( pFFTCleanRe );
    free( pFFTCleanIm );

    free( pxOld );
    free( pxClean );

    free( pGammak );
    free( pKsi );
    free( pLogSigmak );
    free( pAlpha );
    free( pLinToBark );

    ret = createMatrix( &xMatrix );
    AUD_ASSERT( ret == 0 );

    ret = destroyMatrix( &exPatMatrix );
    AUD_ASSERT( ret == 0 );

    ret = destroyMatrix( &frameMatrix );
    AUD_ASSERT( ret == 0 );

    ret = destroyMatrix( &cMatrix );
    AUD_ASSERT( ret == 0 );

    ret = destroyMatrix( &tMatrix );
    AUD_ASSERT( ret == 0 );

    ret = destroyMatrix( &tkMatrix );
    AUD_ASSERT( ret == 0 );

    return cleanLen;
}