import java.lang.*;
import java.io.*;

class Md2File {
	
	Md2FileFormat fileFormat = new Md2FileFormat();
	Head head = new Head();
	
	Md2Triangle triangles[];
	Md2Vertex vertices[][];
	Md2Frame frames[];
	
	RandomAccessFile rf;
	
	Md2File() { }
	
	Md2File(String fileName) {
		readFromFile(fileName);
	}
	
	public void readFromFile(String filename) {
		try {
			rf = new RandomAccessFile(filename,"r");
			// fileFormat.readFromRandomAccessFile(rf);

			int i;
			// Read Header
			for(i = 0;i < 17;i ++)
			{
				head.data[i] = rf.readInt();
			}
			fileFormat.readFromHead(head);
			// fileFormat.print();
			
			// Read Triangles
			
			// System.out.println("No of triangles:" + head.data[8]);
			triangles = new Md2Triangle[head.data[8]];
			for(i = 0; i < head.data[8]; i++) {
				triangles[i] = new Md2Triangle();
			}
			
			// System.out.println(head);
			// System.out.println("head data" + head.data);
			// System.out.println(head.data[0]);
			
			// System.out.println("Triangles: " + triangles);
			// System.out.println(triangles[0]);
			
			for(i = 0;i < head.data[8];i ++)
			{
				// System.out.println(i);
				
				triangles[i].index_xyz[0] = rf.readShort();
				triangles[i].index_xyz[1] = rf.readShort();
				triangles[i].index_xyz[2] = rf.readShort();
				
			}
			
			// System.out.println("reading triangles done ...");
			// read frames without name followed by the vertices 
			// without the light

			frames = new Md2Frame[head.data[10]]; //head.data[10]
			// System.out.println("frames " + frames);
			
			for(i = 0; i< head.data[10]; i++) {
				frames[i] = new Md2Frame();
			}
			
			vertices = new Md2Vertex[head.data[10]][head.data[6]];
			// System.out.println("vertices " + vertices);
			
			int j;
			for(i=0;i < head.data[10]; i++) {
				for(j=0; j < head.data[6]; j++) {
					vertices[i][j] = new Md2Vertex();
				}
			}
			
			for(i = 0;i < head.data[10];i ++)
			{
				frames[i].scale[0] = rf.readFloat();
				frames[i].scale[1] = rf.readFloat();
				frames[i].scale[2] = rf.readFloat();
				
				frames[i].translate[0] = rf.readFloat();
				frames[i].translate[1] = rf.readFloat();
				frames[i].translate[2] = rf.readFloat();
				
				
				
				// Now the vertices of the frame
				for(j = 0;j < head.data[6];j ++)
				{
					/*
					vertices[i][j].v[0] = rf.readByte();
					vertices[i][j].v[1] = rf.readByte();
					vertices[i][j].v[2] = rf.readByte();
					*/
					vertices[i][j].v[0] = rf.readShort();
					vertices[i][j].v[1] = rf.readShort();
					vertices[i][j].v[2] = rf.readShort();
				}
			}
			
			rf.close();
			
		}
		catch(Exception fn) {
			System.err.println("Caught " + fn);
		}
		
	}
	
	public void print() {
		System.out.println("FileFormat: ");
		fileFormat.print();
	}
	
}