#include<stdio.h>
#include<signal.h>
#include<sys/types.h>
#include<X11/Intrinsic.h>
#include<X11/StringDefs.h>

int play( void );

/* ウィジット（クラス) */

int ErrLin = 1;
int ErrCol = 0;

FILE* Fp;
Display *Disp;

static XKeyboardState State; /* キーボードコントロールの保存 */

static XtAppContext App;   /* アプリケーションコンテクスト */

static Widget
       Top;              /* 最上位                        */


static void timi( XtPointer c, XtIntervalId id );

static void save_state( void )
{
  XGetKeyboardControl( Disp,&State );
}

static recover_state( void )
{
  XKeyboardControl v;

  v.bell_pitch = State.bell_pitch;
  v.bell_duration = State.bell_duration;

  XChangeKeyboardControl( Disp,KBBellPitch|KBBellDuration,&v );
  XFlush( Disp );
}


/* シグナルハンドラ */

static void sighandler( void )
{
  recover_state();
  exit(0);
}


static void timi( XtPointer c,XtIntervalId id )
{
  int l;

  l = play();
  if( l == 0 ){
    recover_state();
    exit(0);
  }
  if( l == -1 ){
    fprintf(stderr,"Error in Line %d  Column %d\n",ErrLin,ErrCol );
    recover_state();
    exit(1);
  }
  XtAppAddTimeOut( App, l,(XtTimerCallbackProc)timi,NULL );
}


int main(int argc,char **argv)
{

  XtSetLanguageProc(NULL,NULL,NULL);

  Top = XtVaAppInitialize(&App,"Music",NULL,0,
			&argc,argv,NULL,NULL);

  if( argc < 2 )
    Fp = stdin;
  else if( ( Fp = fopen( argv[1],"r" ) ) == NULL ){
    fprintf(stderr,"can't open file: %s\n",argv[1] );
    exit(1);
  }

  Disp = XtDisplay( Top );

  save_state();

  signal( SIGTERM,sighandler );
  signal( SIGINT,sighandler );

  XtAppAddTimeOut( App, 0,(XtTimerCallbackProc)timi,NULL );
  XtAppMainLoop(App);

  return 0;
}
