import java.io.*;

public class DelimitedFileTransformer {

	public static void main(String[] args) throws Throwable {

		if (args.length < 4) {
			System.out.println("Usage: java DelimitedFileTransformer <input file> "
				+ "<#columns to repeat for each line> <label for header column> "
				+ "<label for value column>"
			);
			System.out.println("Example: java DelimitedFileTransformer input.txt 5 Sample Genotype");
			System.out.println("Note: Two last label arguments should not contain any spaces");

			return;
		}


		String inputFile = args[0];
		int prefixColumns = Integer.parseInt(args[1]);
		String columnHeaderLabel = args[2];
		String columnValueLabel = args[3];

		String outputFile;
		if (inputFile.indexOf('.') != -1) {
			outputFile = inputFile.substring(0, inputFile.indexOf('.')) + ".out";
		} else {
			outputFile = inputFile + ".out";
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(inputFile))));
		PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(outputFile))));

		int inputLines = 0;
		int outputLines = 0;

		try {


			// Read header line of input file.
			String headerLine = reader.readLine();
			String[] headers = headerLine.split("\t");
			int expansionFactor = headers.length - prefixColumns;

			System.out.println("There is a total of " + headers.length
				+ " columns in the input file. Each input line will be split into "
				+ expansionFactor + " lines in the output file."
			);

			// Write header line of output file.
			for (int j = 0; j < prefixColumns; j++) {
				writer.print(headers[j]);
				writer.print('\t');
			}
			writer.print(columnHeaderLabel);
			writer.print('\t');
			writer.print(columnValueLabel);
			writer.println();

			// Process input file.
			String inputLine;
			while ((inputLine = reader.readLine()) != null) {

				inputLines++;

				String[] columns = inputLine.split("\t");
				for (int i = 0; i < expansionFactor; i++) {
					for (int j = 0; j < prefixColumns; j++) {
						writer.print(columns[j]);
						writer.print('\t');
					}
					writer.print(headers[prefixColumns + i]);
					writer.print('\t');
					writer.print(columns[prefixColumns + i]);
					writer.println();
					outputLines++;
				}

			}

			System.out.println("Read " + inputLines + " lines from " + inputFile
				+ " and wrote " + outputLines + " lines to " + outputFile
			);

		} catch (Throwable th) {
			System.err.println("Error occured at line " + (inputLines + 1) + " of input file");
			throw th;

		} finally {
			reader.close();
			writer.close();
		}


	}

}
