import java.awt.*;
import java.awt.geom.*;
import java.text.*;
import javax.swing.*;
import javax.swing.border.*;


public class Ruler extends JPanel {
    Scale scale;
    Font font = new Font("Monospaced", Font.PLAIN, 10);
    
    int width = 50;

    public Ruler() {
	scale = new Scale();
	setPreferredSize(new Dimension(width, 1));
	setBackground(Color.WHITE);

	//Border border = BorderFactory.createEtchedBorder();
	//setBorder(border);
    }

    public void setScale(double min, double max) {
	setRuler(new Scale(min, max));
    }

    public void setRuler(Scale setscale) {
	scale=setscale;
	repaint();
    }

    public void paintComponent(Graphics g){
	//AffineTransform upright = new AffineTransform();
	//upright.rotate(Math.PI/2.0);
	//font = font.deriveFont(upright);
	
	super.paintComponent(g);

	FontMetrics fm = g.getFontMetrics(font);
	int fontheight=fm.getHeight();
	setFont(font);

	int height = getHeight();
	int width = getWidth();

	double a = height/(scale.max-scale.min);

	int smalldivs=10;
	double smalldiv=(height/(10*(scale.max-scale.min)/scale.div));
	if(smalldiv < 5 && smalldiv > 2.5) smalldivs/=2; 
	if(smalldiv <= 2.5 ) smalldivs/=5;
	
	for(double level=scale.lo-scale.div; level<=scale.hi+scale.div; level+=scale.div/smalldivs) {
	    int y=(int) (height-a*(level-scale.min));
	    g.drawLine(0, y, 2, y);
	}

	for(double level=scale.lo; level<=scale.hi; level+=scale.div) {
	    int y=(int) (height-a*(level-scale.min));
	    g.drawLine(0, y, 8, y);
	    g.drawString(format(level), 10, y + fontheight / 2);
	}	
	 
    }

    public String format(double level) {
	double L = Math.abs(level);
	if(L == 0.0) return i1.format(level);
	if(L < 10000.0 && L >= 10.0) return i1.format(level);
	if(L >= 10000.0) e2.format(level);
	if(L < 10.0 && L >= 0.1) return f1.format(level);
	if(L < 0.1 && L >= 0.01) return f2.format(level);
	if(L < 0.01 && L >= 0.001) return f3.format(level);
	else return e1.format(level);
    }


    final static DecimalFormat e1 = new DecimalFormat("0.0E0");
    final static DecimalFormat e2 = new DecimalFormat("0.00E0");
    final static DecimalFormat i1 = new DecimalFormat("0");
    final static DecimalFormat f1 = new DecimalFormat("0.0");    
    final static DecimalFormat f2 = new DecimalFormat("0.00");
    final static DecimalFormat f3 = new DecimalFormat("0.000");
}
