 $$
 LANGUAGE PLPGSQL;
 
+CREATE OR REPLACE FUNCTION GET_NEXT_EXPERIMENT_FOR_GROUP(PARAM_EXPERIMENT_GROUP_ID BIGINT) RETURNS BIGINT
+AS 
+$$
+DECLARE EXPERIMENT_ID BIGINT;
+BEGIN
+	-- This query seems icky. Redo?
+	UPDATE EXPERIMENT AS E 
+	SET NEXT_RUN = NOW() + interval '1 second' * ES.ALLOWED_DURATION_SECONDS
+	FROM EXPERIMENT_GROUP EG
+	JOIN EXPERIMENT_SCRIPT ES
+	ON ES.ID = EG.EXPERIMENT_SCRIPT_ID
+	WHERE E.ID =
+	(
+		SELECT ID
+		FROM EXPERIMENT 	
+		WHERE TOTAL_TRIALS = 0
+		AND NOW() > NEXT_RUN
+		ORDER BY NEXT_RUN
+		LIMIT 1
+		FOR UPDATE OF EXPERIMENT
+	
+	)
+	AND EG.ID = E.EXPERIMENT_GROUP_ID
+	RETURNING E.ID INTO EXPERIMENT_ID;
+
+	RETURN EXPERIMENT_ID;
+END
+$$
+LANGUAGE PLPGSQL;
 
 CREATE OR REPLACE FUNCTION GET_PARENTS_FROM_GENE_POOL(PARAM_EXPERIMENT_GROUP_ID BIGINT) RETURNS TABLE (EXPERIMENT_PARENT_ALPHA BIGINT, EXPERIMENT_PARENT_BETA BIGINT)
 AS

DECLARE EXPERIMENT_GROUP_ID BIGINT;
DECLARE EXPERIMENT_ID BIGINT;
BEGIN
	SELECT EXPERIMENT_GROUP_ID = GET_ACTIVE_EXPERIMENT_GROUP();
	SELECT EXPERIMENT_ID = GET_NEXT_EXPERIMENT_FOR_GROUP(EXPERIMENT_GROUP_ID);
	IF EXPERIMENT_ID IS NULL THEN
		EXPERIMENT_ID = GENERATE_NEW_EXPERIMENT(EXPERIMENT_GROUP_ID);
	END IF;

-- 		====
-- 
-- 		';
		
		CURRENT_EXPERIMENT = GET_NEXT_EXPERIMENT(EXPERIMENT_GROUP_ID);

--		CURRENT_EXPERIMENT = GENERATE_NEW_EXPERIMENT(EXPERIMENT_GROUP_ID);
		
		SELECT
			HCPRTC.W,HCPRTC.X,HCPRTC.Y,HCPRTC.Z
