/*
	[ply.c]		<サンプル>
			beep音で音楽再生
*/

#include <stdio.h>
#include <stdusr.h>

#define _C	0
#define _Cs	1
#define _Df	1
#define _D	2
#define _Ds 3
#define _Ef 3
#define _E	4
#define _F	5
#define _Fs	6
#define _Gf	6
#define _G	7
#define _Gs	8
#define _Af	8
#define _A	9
#define _As	10
#define _Bf	10
#define _B	11

#ifndef	_R
#define _R 0040
#endif

#define OCT( n )	n+50
#define TMP( n )	n+100

int play( int *melo , int len ){
	const int tone[12]={
		262 , 277 , 294 , 311 , 330 , 350 , 370 , 392 , 415 , 440 , 466 , 493
		};
	static count=0;
	static oct=4;
	static tmp=100;
	int hz;
	
	if( melo[count] >= 100 ){		/* テンポ変更 */
		tmp = melo[count] - 100 ;
		count++;
		if( count == len )	count=0;
	}
	
	if( melo[count] >= 50 ){		/* オクターブ変更 */
		oct = melo[count] - 50 ;
		count++;
		if( count == len )	count=0;
	}
	
	if( !isbeep() ){				/* 音発生中？ */
		if( melo[count] == 0040 ){	/* 休符 ちと強引？ (^^; */
			_hzbeep( tmp , 19200 );
			count++;
		}
		else{						/* 通常音 */
			hz = tone[ melo[count] ];
			if( oct > 4 )	hz = hz<<(oct-4);
			if( oct < 4 )	hz = hz>>(4-oct);
			
			_hzbeep( tmp , hz );
			count++;
		}
		if( count == len )	count = 0;
	}
	
	return( count );
}

void main( void ){
	int i,j;
	/* 音楽設定 */
	int melo[] = {
			TMP(50) ,
			OCT(5) , _C , _C , _D , _D , _C , _D , _E ,
			_R ,
			OCT(6) , _C , _D , _E , _F , _G , _A , _B ,
			TMP(25),
			OCT(7) , _C
		};
	
	while( play( melo , sizeof(melo)>>1 ) );
	
	fputs( "このように､この関数に戻るまでに他の処理を入れる事が可能です\n"
		, stderr );
	hitany();
	
	while( play( melo , sizeof(melo)>>1 ) ){
		for(i=0;i<20;i++){
			for(j=0;j<79;j++)	fputc( '.' , stderr );
			fputc( '\n' , stderr );
		}
		txt_cls();
	}
	
	fputs(	"この場合、そのループなどの処理が重くならないように"
			"注意してください\n" , stderr );
	
	hitany();
	
	fputs( "終わり\n" , stderr );
	
	stkclear();
}
