package util;

import java.util.Vector ;
import java.awt.Point;
import java.io.*;

import Targa.*;

/**
* Given that all of our mask files were created in Paint Shop Pro 5.01 (c) Jasc
* some method of converting them to .msk files was needed. This simply loads a tga
* mask file, makes any non-zero pixels 1, and saves it to a .msk
*/

public class PSPMaskToMask {
	static void convert(String file) {
System.out.println("CONVERT: "+file);
		if (file.lastIndexOf(".tga") == -1) {
System.out.println(file + " is not a valid targa file. Action:RETURNING");
			return;
		}

		TargaPicture tp = null;
	 	try {
		  	tp = new TargaPicture(file) ;
			tp.read() ;
		} catch (IOException e) {
System.out.println("Convert Error " +e);
System.exit(1) ;
		}

	 	RGBPoint pt = null;
		for (int i = 0; i < tp.w*tp.h; i++) {
			pt = new RGBPoint(tp.getImageData(i)) ;
			if ((pt.r > 0) || (pt.g > 0) || (pt.b > 0)) {
				tp.setMaskData(i,true);
			} else tp.setMaskData(i,false);
		}
		tp.writeMask(file.substring(0,file.lastIndexOf(".tga"))+".msk");
	}

	/**
	* Main. 
	* This method either operates on  a directory or a single file.
	* If args[0] is a directory, all valid tga files are interpreted as mask files,
	* and a binary .msk format file is produced for each tga file.
	* If args[0] is a single file, that a .msk file is produced for that file.
	* If directory techniques is used, then it is a really good idea to have
	* only mask files in it!
	*/

	public static void main(String[] args) {
		File f = new File(args[0]) ;
		if (f.exists() == true) {
			if (f.isDirectory() != true) {
				PSPMaskToMask.convert(args[0]);
			} else { // file is a directory so process all .tga files
				String[] directory = f.list() ; // get list of all files in directory
				for (int i =0; i < directory.length; i++) {
					PSPMaskToMask.convert(args[0]+directory[i]);
				}
			}
		} else {
System.out.println("Cant find file " + args[0] + ". Does it exist?");
		}
	}
}





