/**
 * 
 */
package jp.mydns.masahase.sdes.common;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.xml.bind.JAXBException;

import jp.mydns.masahase.InherentStrain.ElementType;
import jp.mydns.masahase.InherentStrain.NodeType;
import jp.mydns.masahase.operateXML.InherentStrain;

/**
 * 保存された固有ひずみ分布をPostScriptとして図示する.
 * 
 * @author hasegawa
 *
 */
public class Pe2Ps {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			InherentStrain is=new InherentStrain();
			is.setInput(new FileInputStream(args[0]));
			is.readXML();
			Pe2Ps p2p=new Pe2Ps(args[1]);
			p2p.draw(is);
			p2p.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	OutputStream os;
	PrintStream ps;
	public Pe2Ps(String fname){
		try {
			os=new BufferedOutputStream(new FileOutputStream(fname));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			os=System.out;
		}
		ps=new PrintStream(os);
		ps.println("%!PS-Adobe-2.0");
		ps.println("100 dict begin");
		ps.println("gsave");
		ps.println("mark");
		ps.println("300 300 translate");
		ps.println("2 2 scale");
	}
	public void close(){
		ps.println("cleartomark");
		ps.println("end");
		ps.println("grestore");
		ps.println("showpage");
		ps.close();
	}
	
	void drawLine(double x1,double y1,double x2,double y2){
		ps.printf("%f %f moveto\n",x1,y1);
		ps.printf("%f %f lineto\n", x2,y2);
		ps.println("stroke");
	}
	
	void printString(String str,double x,double y){
		ps.printf("%f %f moveto\n",x,y);
		ps.print("/Times-Roman findfont 10 scalefont setfont\n");
		ps.printf("(%s)", str);
		ps.println("show");
	}
	public void draw(InherentStrain ist){
		for(ElementType et:ist.getElements().getElement()){
			NodeType pnd=null;
			for(int nid:et.getNodeId()){
				if(pnd==null){
					pnd=ist.getNode(nid);
				}else{
					NodeType tmp=ist.getNode(nid);
					drawLine(pnd.getX(), pnd.getY(), tmp.getX(), tmp.getY());
					pnd=tmp;
				}
				printString(Integer.valueOf(pnd.getId()).toString(), pnd.getX(), pnd.getY());
			}
		}
	}
}
