DROP PROCEDURE IF EXISTS `CALCUPGARDE`;
delimiter ;;
CREATE PROCEDURE `CALCUPGARDE`(IN `PLAYER` INT)
BEGIN
	DECLARE
		MLAYER,
		MCOUNT,
		MCOUNT1,
		MCOUNT2 INT;
	
	SET MLAYER := PLAYER;
	SELECT
		COUNT(*) INTO MCOUNT 
	FROM
		AR_BS_BONUS_103_CALC T 
	WHERE
		T.LAYER = MLAYER 
		AND USER_TYPE10 = 10 
		AND USER_TYPE = 0;
	IF
		( MCOUNT > 0 ) THEN
			BREAKLABLE :
		WHILE
				MLAYER > 0 DO
			SELECT
				COUNT(*) INTO MCOUNT1 
			FROM
				AR_BS_BONUS_103_CALC T1 
			WHERE
				T1.USER_TYPE10 = 10 
				AND T1.LAYER = MLAYER - 1;
			UPDATE AR_BS_BONUS_103_CALC T1
			INNER JOIN ( SELECT INTRODUCER_ID FROM AR_BS_BONUS_103_CALC WHERE LAYER = MLAYER AND USER_TYPE10 = 10 GROUP BY INTRODUCER_ID ) T2 ON T1.USER_ID = T2.INTRODUCER_ID 
			AND T1.USER_TYPE10 = 0 
			AND T1.LAYER = MLAYER - 1 
			SET T1.USER_TYPE10 = 10,
			T1.USER_TYPE = 10;
			SELECT
				COUNT(*) INTO MCOUNT2 
			FROM
				AR_BS_BONUS_103_CALC T1 
			WHERE
				T1.USER_TYPE10 = 10 
				AND T1.LAYER = MLAYER - 1;
			IF
				( MCOUNT1 = MCOUNT2 ) THEN
					LEAVE BREAKLABLE;
				
			END IF;
			
			SET MLAYER := MLAYER - 1;
			
		END WHILE;
		
	END IF;

END
;;