#!/bin/sh

val=$1

atg_clk_setting () {
	reg=$1
	#SLCR reg for unlock
	devmem 0xf8000008 16 0xDF0D

	#update the FCLK1 clock [13-8] 6bits for Divisor0
	devmem 0xf8000180 32 $reg

	#SLCR reg for lock
	devmem 0xf8000004 16 0x767B
}

start_atg () {
	var=$1
	# read the GPIO bank2 direction register
	dirm="$(devmem 0xE000A284)"
	# read the GPIO bank2 output enable register
	oen="$(devmem 0xE000A048)"
	# read the GPIO bank2 data register
	data="$(devmem 0xE000A010)"

	val1=$dirm
	val2=$oen
	val3=$data
	if [ $var -eq 1 ]
	then
		# enable the EMIO pin2 to start the ATG1
		dirm=$((dirm|0x4))
		oen=$((oen|0x4))
		data=$((data|0x4))
	elif [ $var -eq 2 ]
	then
		# enable the EMIO pin4 to start the ATG2
		dirm=$((dirm|0x10))
		oen=$((oen|0x10))
		data=$((data|0x10))
	fi
	devmem 0xE000A284 32 $dirm
	devmem 0xE000A048 32 $oen
	devmem 0xE000A010 32 $data
	devmem 0xE000A284 32 $val1
	devmem 0xE000A048 32 $val2
	devmem 0xE000A010 32 $val3
}

stop_atg () {
	var=$1
	# read the GPIO bank2 direction register
	dirm="$(devmem 0xE000A284)"
	# read the GPIO bank2 output enable register
	oen="$(devmem 0xE000A048)"
	# read the GPIO bank2 data register
	data="$(devmem 0xE000A010)"

	val1=$dirm
	val2=$oen
	val3=$data
	if [ $var -eq 1 ]
	then
		# enable the EMIO pin3 to stop the ATG1
		dirm=$((dirm|0x8))
		oen=$((oen|0x8))
		data=$((data|0x8))
	elif [ $var -eq 2 ]
	then
		# enable the EMIO pin5 to stop the ATG2
		dirm=$((dirm|0x20))
		oen=$((oen|0x20))
		data=$((data|0x20))
	fi
	devmem 0xE000A284 32 $dirm
	devmem 0xE000A048 32 $oen
	devmem 0xE000A010 32 $data
	devmem 0xE000A284 32 $val1
	devmem 0xE000A048 32 $val2
	devmem 0xE000A010 32 $val3
}

if [ $val -eq 1 ]
then
	atg_clk_setting 0x00100A00

	atg_clk_setting 0x00100900

	atg_clk_setting 0x00100800

	atg_clk_setting 0x00100700

	atg_clk_setting 0x00100600
	echo ATG Clock set to 167Mhz

	#start the two ATG core IP's
	#echo Trigger ATG controllers
	var=$((0+1))
	while [  $var -le 2 ]
	do
		#echo start Pulse to ATG$var
		#/bin/sh /media/card/bin/start_atg.sh $var
		start_atg $var
		var=$((var+1))
	done
	#echo Trigger ATG controllers Done
elif [ $val -eq 0 ]
then
	#stop the two ATG core IP's
	atg_clk_setting 0x00100700
	
	atg_clk_setting 0x00100800
	
	atg_clk_setting 0x00100900
	
	atg_clk_setting 0x00100A00
	#echo Stop ATG controllers
	var=$((0+1))
	while [  $var -le 2 ]
	do
		#echo stop Pulse to ATG$var
		#/bin/sh /media/card/bin/stop_atg.sh $var
		stop_atg $var
		var=$((var+1))
	done
	#echo Stop ATG controllers Done
fi