/*******************************************************************************
 * Copyright (c) 2010 Attila Kovacs <attila_kovacs@post.harvard.edu>.
 * All rights reserved. 
 * 
 * This file is part of crush.
 * 
 *     crush is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     crush is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with crush.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Attila Kovacs <attila_kovacs@post.harvard.edu> - initial API and implementation
 ******************************************************************************/
package crush.fits;

import java.util.*;

import crush.CRUSH;
import crush.Integration;
import nom.tam.fits.*;
import nom.tam.util.*;

public class HDUManager {
	Integration<?,?> integration;
	private final Vector<Thread> queue = new Vector<Thread>();
	private FitsException fitsException = null;
	
	public HDUManager(Integration<?,?> integration) {
		this.integration = integration;
	}
	
	protected synchronized void queue(Thread thread) {
		queue.add(thread);
	}
	
	protected synchronized void checkout(Thread thread) {
		queue.remove(thread);
		notifyAll();
	}
	
	protected synchronized void readException(FitsException e) {
		fitsException = e;
		for(Thread thread : queue) thread.interrupt();
		notifyAll();
	}
	
	public synchronized Vector<HDUReader> read(TableHDU hdu, HDUReader readerTemplate) throws FitsException {
		int frames = hdu.getNRows();
		
		// Do not split less than 100 rows of data into threads...
		int threads = Math.min(CRUSH.useCPUs, (int)Math.ceil(frames/100.0)); 
		
		Vector<HDUReader> readers = new Vector<HDUReader>(threads);
		
		// Make sure that the integration is filled with elements than can be
		// replaced during the reading...
		if(integration.size() < frames);
		for(int i=integration.size(); i<frames; i++) integration.add(null);
			
		ColumnTable table = (ColumnTable) hdu.getData().getData();
		
		int step = (int)Math.ceil((double) frames / threads);
		int from = 0;
		for(int i=0; i<threads; i++, from += step) {
			int to = Math.min(from + step, frames);
			final HDUReader reader = (HDUReader) readerTemplate.clone(); 
			reader.setManager(this);
			reader.setData(hdu, table, from, to);
			reader.start();
			readers.add(reader);	
		}
		
		while(!queue.isEmpty() && fitsException == null) {
			try { wait(); }
			catch(InterruptedException e) {}
		}
		
		if(fitsException != null) throw fitsException;	
	
		return readers;
	}
	
}
