import java.io.*;
import java.lang.Long;
import java.util.*;
import java.text.*;

class renamechronologic{

    static long numfiles=0;
    static long numwriteprotected=0;

    public static void main(String[] args){
	long diff = 0;
	File path;

	if(args.length!=1){//Not enough arguments
	    System.out.println("Usage:");
	    System.out.println("renamechronologic path");
	    System.out.println("will only rename files recursively (directory names unchanged).");
	    System.exit(1);
	}

	//Parse path
	path = new File(args[0]);
	if(!(path.isDirectory()||path.isFile())){
	    System.err.println("ERROR: the specified path \"" + args[0] +"\" is not an existing directory or file!");
	    System.exit(1);
	}
	

	//We got here if path is valid...
	
	//recursively rename:
	numfiles=0;
	numwriteprotected=0;
	change(path, true); //Just fake the change, won't modify anything
	if(numwriteprotected!=0){
	    System.err.println("ERROR: Aborting operation without performing any changes, since " + numwriteprotected + " files not writable.");
	    System.exit(2);
	}

	numfiles=0;
	numwriteprotected=0;
		
	change(path, false); //Performs the change
	System.out.println("Number of files changed: " + numfiles);
	System.out.println("Write protected files: " + numwriteprotected);
	System.exit(0);
	
    }

    static void change(File path, boolean justfaking){
	long time;
	if(path.isFile()){
	    if(path.canWrite()){
		//System.out.println("change(" + diff + ", \"" + path+"\")");
		time = path.lastModified();
		GregorianCalendar c = new GregorianCalendar();
		c.setTimeInMillis(time);
		//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
		SimpleDateFormat sdf = new SimpleDateFormat("HH.mm.ss");
		String formattedtime = sdf.format(c.getTime());
		File newname = new File(path.getParent() + File.separator + formattedtime + "_" + path.getName());
		System.out.println(newname);
		if(!justfaking){
		    if(!path.renameTo(newname)){
			System.err.println("ERROR: unknown error renaming \""
					   + path + "\"");
		    }else{
			System.out.println("change(\"" + path+"\") --> " + newname + "\"");
		    }
		    
		}
		numfiles++;
	    }else{ //!canWrite()
		System.err.println("ERROR: Write Protected: \"" + path + "\"");
		numwriteprotected++;
	    }
	    
	}
	
	if(path.isDirectory()){
	    File[] additional = path.listFiles();
	    if(additional==null){
		System.err.println("ERROR: ?");
	    }else {
		for(int i=0; i<additional.length; i++){
		    change(additional[i],justfaking);
		}
	    }
	}
    }
    
}
