import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

class FileRen extends Frame implements WindowListener {
	Vector extension = new Vector();
	TextArea tf;
	boolean finished;

	public static void main(String args[]) {
		FileRen p = new FileRen(args);
	}

	public FileRen(String args[]) {
	        for (int i = 1; i < args.length; i++)
        	    extension.addElement(args[i]);
		
		setTitle("Kengs' File Renamer");
		tf = new TextArea();
		add(tf);
		setSize(560, 420);
		addWindowListener(this);
		setVisible(true);

		finished = false;
		recurse_files(args[0]);
		finished = true;
	}

	void recurse_files(String dir) {
		File f;
		int i, j;
		try {
			f = new File(dir);
			String l[] = f.list();
			for (i=0; i < l.length; i++) {
				String file_n = dir+"/"+l[i];
				file_n = file_n.toLowerCase();
				tf.append(file_n+"\n");
				int leng = extension.size();
				for (j=0; j<leng; j++) {
				   String ext = extension.elementAt(j).toString().toLowerCase();
        	                   if ( file_n.endsWith("."+ext ) ) {
					 rename_file(file_n, ext);
				   }
				}
				if ((new File(file_n)).isDirectory() == true)
					recurse_files(file_n);
			}
		} catch(Exception ex) {
			tf.append("NO DIRECTORY : "+dir);
		}
	}

	void rename_file(String name, String ext) {
		int i;
	        int len_e = ext.length();
		int len = name.length();
		StringBuffer newname = new StringBuffer();

		// remove the extension from old name
		// ..by finding the dot.
		int dotPlace = name.lastIndexOf(".");
		newname.append(name.substring(0, dotPlace)+".");

		// Reverse the extension
	        for (i = (len_e - 1); i >= 0; i--)
        	    newname.append(ext.charAt(i));
//		System.out.println(newname);

		File oldFile = new File(name);
		File newFile = new File(newname.toString());
		oldFile.renameTo(newFile);
		tf.append("RENAMED "+name+" TO "+newname+"\n");
	}

	public void windowClosing(WindowEvent e) {
		if (!finished) {
			String message = "WARNING: Renaming process terminated inbetween!";
			tf.append(message);
			System.out.println(message);
		}
		System.exit(0);
	}

	public void windowClosed(WindowEvent e) {}
	public void windowOpened(WindowEvent e) {}
	public void windowIconified(WindowEvent e) {}
	public void windowDeiconified(WindowEvent e) {}
	public void windowActivated(WindowEvent e) {}
	public void windowDeactivated(WindowEvent e) {}

}
