CREATE OR REPLACE FUNCTION insert_results (
  boolean,     -- cexperience
  boolean,     -- wexperience
  integer,     -- agegroupid
  boolean[],   -- headtracking
  boolean[],   -- stereo
  boolean[],   -- shadow
  integer[],   -- boxsizeid
  time[][],    -- elapsedtime
  integer[][], -- holeposition
  integer[][]  -- blockid
) RETURNS integer AS $$
DECLARE
  par_cexperience  ALIAS FOR $1;
  par_wexperience  ALIAS FOR $2;
  par_agegroupid   ALIAS FOR $3;
  par_headtracking ALIAS FOR $4;
  par_stereo       ALIAS FOR $5;
  par_shadow       ALIAS FOR $6;
  par_boxsizeid    ALIAS FOR $7;
  par_elapsedtime  ALIAS FOR $8;
  par_holeposition ALIAS FOR $9;
  par_blockid      ALIAS FOR $10;

  i                integer;
  j                integer;
  var_ntests       integer;
  var_nturns       integer;
  var_personid     integer;
  var_testid       integer;
BEGIN
  i := 0;

  SELECT INTO var_personid insert_person(par_cexperience,
                                         par_wexperience,
                                         par_agegroupid);

  var_ntests = array_upper(par_headtracking, 1);

  WHILE i < var_ntests LOOP
    SELECT INTO var_testid insert_test(var_personid,
                                       par_headtracking,
                                       par_stereo,
                                       par_shadow,
                                       par_boxsizeid);
    
    var_nturns = array_upper(elapsedtime[i], 1);
    j := 0;

    WHILE j < var_nturns LOOP
      PERFORM insert_turn(var_testid,
                          par_elapsedtime,
                          par_holeposition,
                          par_blockid);
    END LOOP;

  END LOOP;

  RETURN var_ntests * var_nturns;
END;
$$ LANGUAGE plpgsql;