package crush.apex;

import nom.tam.fits.*;

import java.io.*;

public class ESORename {

	public static void main(String[] args) {
		if(args.length == 0) {
			usage();
			System.exit(0);
		}
		
		for(int i=0; i<args.length; i++) {
			try { rename(args[i]); }
			catch(Exception e) { 
				System.err.println(" WARNING! " + args[i] + ": " + e.getMessage());				
			}
		}
	}
	
	public static void rename(String fileName) throws Exception {
		File file = new File(fileName);
	
		boolean isCompressed = fileName.endsWith(".gz") || fileName.endsWith(".Z");
		String ext = ".fits";
		if(isCompressed) ext += fileName.substring(fileName.lastIndexOf("."));
	
		Fits fits = new Fits(file, isCompressed);
		Header header = fits.getHDU(0).getHeader();
		
		String origName = header.getStringValue("ORIGFILE") + ext;
		String stem = "";
		if(fileName.contains(File.separator)) stem += fileName.substring(0, 1 + fileName.lastIndexOf(File.separator));
		File origFile = new File(stem + origName);
		
		System.err.println(" --> " + origName);
		
		file.renameTo(origFile);
	}
	
	public static void usage() {
		System.err.println();
		System.err.println("  -------------------------------------------------------------------");
		System.err.println("  esorename -- Rename ESO archive files to their original file names.");
		System.err.println("               Copyright (C)2010 Attila Kovacs");
		System.err.println("  -------------------------------------------------------------------");
		System.err.println();
		System.err.println("  Usage: esorename <filenames>");
		System.err.println();	
	}
	
}
