DECLARE

	CURSOR dependancy_cur IS
		SELECT run_trigs.RUN_NUMBER Run, runs.TRIG_CONFIG_VERS Version, run_trigs.Bit_Name TrigName, run_trigs.Depend_Bit DepBit
		FROM   runs.runs runs, runs.run_trigs run_trigs
		WHERE  runs.TRIG_CONFIG_NAME like '%/global%'
                AND    runs.RUN_NUMBER=run_trigs.RUN_NUMBER
		AND    run_trigs.Bit_Name like 'MUH1_TK12_TLM12' 
		AND    run_trigs.Trg_Type = 'L3bit';

	CURSOR prescale_cur (run_number_in IN runs.RUN_NUMBER%TYPE,
			     dep_bit_in    IN run_trigs.Depend_Bit%TYPE)
	IS
		SELECT run_trigs.Prescale PS
		FROM   runs.run_trigs run_trigs
		WHERE  run_trigs.Trg_Type = 'L1bit'
		AND    run_trigs.RUN_NUMBER = run_number_in
		AND    run_trigs.Bit_Num = dep_bit_in ;

	dependancy_rec dependancy_cur%ROWTYPE;
	prescale_rec prescale_cur%ROWTYPE;

BEGIN
	IF NOT dependancy_cur%ISOPEN
	THEN
		OPEN dependancy_cur;
	END IF;

	LOOP
		FETCH dependancy_cur INTO dependancy_rec;
		EXIT WHEN dependancy_cur%NOTFOUND;
		
		OPEN prescale_cur (dependancy_rec.Run, dependancy_rec.DepBit);
		FETCH prescale_cur INTO prescale_rec;
		DBMS_OUTPUT.PUT_LINE 
			( TO_CHAR(dependancy_rec.Run) || ' ' || 
			  TO_CHAR(dependancy_rec.Version) || ' ' || 
			  TO_CHAR(dependancy_rec.TrigName) || ' ' || 
			  TO_CHAR(prescale_rec.PS) ); 
		CLOSE prescale_cur;
	END LOOP;
END;
.
set serverout on size 1000000 
SPOOL MUH1_TK12_TLM12.txt
run;
SPOOL OFF
