/*
 * @(#)Speedometer.java
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2003 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDcreator.java for details.
 */

	class Speedometer {
		long t0, t0Next;
		long counter, counterNext;
		float speed;

		public Speedometer() {
			t0 = t0Next = System.currentTimeMillis();
			counter = counterNext = 0;
			speed = 0.0f;
		}

		private void calibrate(long t) {
			if (t - t0Next > 1 * 1000) {
				t0 = t0Next;
				counter = counterNext;
				t0Next = t;
				counterNext = 0;
			}
		}

		public float getSpeed() {
			long t = System.currentTimeMillis();
			calibrate(t);
			if (t - t0 > 1 * 1000)
				speed = 1000 * counter
					/ (t - t0) / (150.0f * 1024);

			return speed;
		}

		public void inc(int n) {
			counter += n;
			counterNext += n;
		}

		public void slowDown(int maxSpeed) {
			while (true) {
				long t = System.currentTimeMillis();
				calibrate(t);
				long limit = (t - t0) * (maxSpeed * 150 * 1024)
					/ 1000;
				if (counter <= limit)
					break;
				try {
					Thread.sleep(1000 * (counter - limit)
						/ (maxSpeed * 150 * 1024));
				}
				catch (InterruptedException e) {
				}
			}
		}
	}
