/*  This program is free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*  You should have received a copy of the GNU General Public License
*  along with this program; if not, write to the Free Software
*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
// (C) PicoPeta Simputers Pvt. Ltd. 


#include <stdio.h>
#include <stdlib.h>
#include "tk.h"
#include <fcntl.h>
#include <sys/stat.h> 
#include <sys/types.h>
#include <unistd.h>
#include <sys/ioctl.h>


#include <linux/sound.h>
#include <linux/soundcard.h>

int volume_cntl(ClientData cd, Tcl_Interp *interp,
                    int objc, Tcl_Obj *CONST objv[])
{

	Tcl_Obj *optr;
	int fd;
	int value;

	fd = open("/dev/mixer", O_RDWR);

	if(fd < 0) {
		perror("open : ");
		value = -1;
		goto END;
	}

	if(objc < 2) {

		if(ioctl(fd, SOUND_MIXER_READ_VOLUME, &value) < 0) {
			perror("ioctl : ");
			value = -1;
			goto END;
		}

		value >>= 8;
		goto END;
	}


	if(Tcl_GetIntFromObj(interp,objv[1], &value) != TCL_OK ) {
		value = -1;
		goto END;
	}
	
	if(value < 0) {
		value = 0;
	}

	if(value > 100) {
		value = 100;
	}

	value = value +  (value << 8);

	printf("%04x \n",value);

	if(ioctl(fd, SOUND_MIXER_WRITE_VOLUME, &value ) < 0) {
		perror("ioctl : ");
		value = -1;
		goto END;
	}

	value >>= 8;

	END :

	if(fd >= 0) {
		close(fd);
	}

	optr = Tcl_GetObjResult(interp);

	/*
	 * stops the crackling noise ... 
	 */

	fd = open("/dev/dsp", O_RDWR);
	close(fd);

	if(value < 0) {
		Tcl_SetIntObj(optr, -1);
		return TCL_ERROR;
	} else {
		Tcl_SetIntObj(optr, value);
		return TCL_OK;
	}
}
