class  Union
{

	public static Table execUnion(Table A, Table B) 
	{
		Table R = new Table(); /* output table */
		boolean format = AuxFuncs.sameFormat( A.getCol(), B.getCol() );
		//System.out.println("format="+format);
		if (format)
			R = execute(A, B);
		else
		{
			CatchErr.formatErr("UNION");
			R=A;
		}

		return R;
	}

	public static Table execute(Table A, Table B) 
	{
		/* We assume that tables A and B are of same format i.e have the same columns */

		/* sort the the two tables */
		int[] colIndex = AuxFuncs.givenIndex(A.getNoCols());
		AuxFuncs.quicksort( A, 0, A.getNoRowSet()-1, colIndex );
		AuxFuncs.quicksort( B, 0, B.getNoRowSet()-1, colIndex );

		for (int i=0; i<A.getNoRowSet(); i++)
		{
			Row row_Ai = (Row) A.getRow(i);

			int j=0; /* counter to go through rows in table B */
			boolean stop=false; /* flag to indicate if row from B is greater than row from A */
			while (j<B.getNoRowSet() && !stop)
			{
				/* the row in A is greater than the row in B, move and compare next row in B */ 
				if (AuxFuncs.compareRows(row_Ai, (Row) B.getRow(j), true, colIndex) > 0)
				{
					j++;
				}
				/* found matching rows */
				else if (AuxFuncs.compareRows(row_Ai, (Row) B.getRow(j), true, colIndex) == 0)
				{
					Object x = B.removeRow(j);
					j++;
				}
				/* found the row in A to be less than the row in B, so stop comparing further rows in B */
				else
				{
					stop=true;
					j++;
				}
			}
		}

		/* Add all rows from table B to table A */
		for (int i=0; i<B.getNoRowSet(); i++)
		{
			A.addRow( (Row) B.getRow(i) );
		}

		boolean coalFlag=UserInterface.getCoal();
		if (coalFlag)
		{
			AuxFuncs.coalesce(A);
		}

		return A;
	}
}
