import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class BoxOffice {
	
	/** Constants **/
	public static final int BILLIONS = 1000000000;
	public static final int MILLIONS = 1000000;
	public static final int THOUSANDS = 1000;
	
	/** Class Variables **/
	public static int[] years;  		// read from file
	public static int[] grossSales;		// read from file
	public static String[] movies;		// read from file
	
	/** Methods **/
	public static int numLines(String fname) throws FileNotFoundException {
		Scanner file = new Scanner(new File(fname));
		int cnt = 0;
		while (file.hasNextLine()) {
			file.nextLine();
			cnt++;
		}
		file.close();
		return cnt;
	}
	
	public static void readGrossSalesFile(String fname) throws FileNotFoundException {
		int numLines = numLines(fname);
		years = new int[numLines];
		grossSales = new int[numLines];
		movies = new String[numLines];
	
		Scanner file = new Scanner(new File(fname));
		int cnt = 0;
		while (file.hasNextLine()) {
			years[cnt] = file.nextInt();
			grossSales[cnt] = file.nextInt();
			movies[cnt] = file.nextLine();
			movies[cnt] = movies[cnt].trim();
			cnt++;
		}
		file.close();
	}
	
	public static String formatSales(int sales) {
		String ret;
		if (sales >= BILLIONS) {
			ret = String.format("$%.3fB", (double)sales/BILLIONS);
		} else if (sales >= MILLIONS) {
			ret = String.format("$%.0fM", (double)sales/MILLIONS);
		} else {
			ret = String.format("$%.0fK", (double)sales/THOUSANDS);
		}
		return ret;
	}
	
	public static void printMovie(int idx) {
		System.out.printf("%d   %7s   %s\n", years[idx], formatSales(grossSales[idx]), movies[idx]);
	}
	
	public static void printAllMovies() {
		System.out.printf("\n%s   %-7s   %s\n", "YEAR", "GROSS", "MOVIE");
		System.out.printf("%s   %7s   %s\n", "----", "-------", "--------------------------------------------------");
		for (int i = 0; i < movies.length; i++) {
			printMovie(i);
		}
	}
	
	public static void printTopMovie() {
		System.out.println("\nTOP GROSSING MOVIE (ADJUSTED FOR INFLATION)");
		System.out.println("-------------------------------------------");
		int max = Integer.MIN_VALUE;
		int maxIdx = 0;
		for (int x=0; x < grossSales.length; x++) {
			if (grossSales[x] > max) {
				max = grossSales[x];
				maxIdx = x;
			}
		}
		printMovie(maxIdx);
	}
	
	public static void main(String[] args) throws FileNotFoundException {
		readGrossSalesFile("GrossSales.txt");
		printAllMovies();
		printTopMovie();	
	}
}