
/**
 */

import java.io.*;
import java.util.*;

public class RandomAccessFileDemo {


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

    new RandomAccessFileDemo().process(args[0]);

  }

  // simple "shell" for manipulating a file of ints
  public void process(String fileName) throws Exception {
  
    RandomAccessFile file = new RandomAccessFile(fileName,"rwd");

    System.out.println("opened " + fileName + " mode rwd : " + file);

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line = null;
    int point = 0;
    // make sure file is large enough
    if (file.length() <= 4*point) file.setLength(4*(point+1));

    while ((line = in.readLine()) != null) {
      String[] tokens = line.split(" ");

      // Process command
      if ("q".equals(tokens[0])) {
	// Quit command
	file.close();
	return;

      } else if ("g".equals(tokens[0])) {
	// Go to position command
	int newPoint = point;
	try {
	  newPoint = Integer.parseInt(tokens[1]);
	} catch (Exception e) {
	  e.printStackTrace();
	  System.out.println("go command: g <position> e.g. g 17");
	}
	point = newPoint;
	// make sure file is large enough
	if (file.length() <= 4*point) file.setLength(4*(point+1));

      } else if ("c".equals(tokens[0])) {
	// Change value at position command
	try {
	  int newValue = Integer.parseInt(tokens[1]);
	  // make sure we are at the correct position
	  file.seek(4*point);
	  file.writeInt(newValue);
	} catch (Exception e) {
	  e.printStackTrace();
	  System.out.println("change command: c <newValue> e.g. c 42");
	}

      } else if ("p".equals(tokens[0])) {
	// Print file contents command
	for(int i = 0; i < file.length(); i+=4) {
	  showPoint(i/4,file);
	}
	System.out.println("");

      } else {
	// Show all commands
	System.out.println("Unknown command: " + line);
	System.out.println("List of commands:");
	System.out.println("go command: g <position> e.g. g 17");
	System.out.println("change command: c <newValue> e.g. c 42");
	System.out.println("printAll command: p");
	System.out.println("quit command: q");
      }

      // output current position and value
      showPoint(point,file);
    }
  }

  // output integer value found at POINT in FILE
  public void showPoint(int point, RandomAccessFile file) throws Exception {
    file.seek(4*point);
    int value = file.readInt();
    System.out.println("> " + point + " " + value);
  }
}
