CREATE OR REPLACE FUNCTION food600.semafor_stav(
	ip_hod character,
	OUT p_kto 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;
lkto  character(50);
lkedy  timestamp;
lhod  integer;

BEGIN
lkto:='';
lkedy:=null;
lhod:= 0; 

select count(*) into li_pocet from food600.semafor where n_semafor=ip_hod;

IF li_pocet=0 THEN
 --insert into food600.semafor(n_semafor) values (ip_hod);	
 p_kto:='';
ELSE
select min(i_semafor) into li_semafor from food600.semafor where n_semafor=ip_hod;

select pg_try_advisory_lock(li_semafor) into li_stav;

if li_stav THEN
 lhod = 1;
 p_kto:= '' ;
 --update food600.semafor set kedy = now() where i_semafor = li_semafor;
  li_stav = false;
  WHILE (li_stav) LOOP /*REPEAT*/
   li:=li+1;
   lhod:=12;
   select pg_advisory_unlock(li_semafor) into li_stav;
   IF li > 10000 THEN
    li_stav:= true;
    lhod:=13;
   END IF;
    	
  END LOOP; 
else
 lhod = 0;
 select kto into lkto from food600.semafor where i_semafor=li_semafor;
 p_kto:= ':' || lkto;
 --p_kto:= ':';
END IF;

END IF;

END
$BODY$;
