CREATE OR REPLACE FUNCTION food600.semafor_vypni_stanicu(
	ip_kto character,
	OUT op_hod character)
    RETURNS character
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
DECLARE 
li_semafor INTEGER DEFAULT 0;
li_pocet INTEGER DEFAULT 0;
li_stav BOOLEAN ;
li INTEGER DEFAULT 0;
mdone INTEGER DEFAULT 0;
prep1 CURSOR FOR SELECT i_semafor FROM food600.semafor WHERE kto=ip_kto;

BEGIN
op_hod:='0';
SELECT count(*) INTO li_pocet FROM food600.semafor WHERE kto=ip_kto;

IF li_pocet=0 THEN
	op_hod:='1'; 
ELSE
	OPEN prep1;
	mdone:=0;
	WHILE (mdone<li_pocet) LOOP
		mdone:=mdone+1;
		FETCH prep1 INTO li_semafor;
		IF mdone<=li_pocet THEN
			select pg_advisory_unlock(li_semafor) into li_stav;
			IF li_stav THEN
				op_hod:= '1';
			ELSE
				op_hod:= '0';
			END IF;
			DELETE FROM food600.semafor WHERE i_semafor=li_semafor;
		END IF;
	END LOOP;
	CLOSE prep1;
END IF;
END
$BODY$;
