// File: Tape.java
// Time-stamp: "2005-12-27 21:14:35 calvanese"
// Scopo: Tape: solution part 1

class Node {
  String name;
  int    length;
  Node   next;
}


public class Tape {

  // representation of the objects
  private int  residualCapacity;   // space left on time in minutes
  private int  numberOfPrograms;   // how many programs are stored on the tape
  private Node programListing;     // reference to linked list of nodes

  // public methods
  public Tape (int k) {
    residualCapacity  = k;
    numberOfPrograms  = 0;
    programListing = null;
  }

  public int getResidualCapacity() {
    return residualCapacity;
  }

  public int getNumberOfPrograms() {
    return numberOfPrograms;
  }

  public void record(String name, int length) {
    if (residualCapacity < length) {
      throw new RuntimeException(
        "cannot record: not enough space left on tape");
    } else {

      // insert program to top of linked list
      // (we store the programs in inverse order for simplicity)
      Node aux = new Node();
      aux.name = name;
      aux.length = length;
      aux.next = programListing;
      programListing = aux;

      numberOfPrograms++;
      residualCapacity = residualCapacity - length;
    }
  }

  public String getProgram(int n) {
    return findNode(programListing, numberOfPrograms - 1 - n).name;
  }

  public int getLength(int n) {
    return findNode(programListing, numberOfPrograms - 1 - n).length;
  }

  // helper method
  private static Node findNode(Node lis, int pos) {
    if (pos < 0 || lis == null)
      throw new RuntimeException("could not find program");
    else if (pos == 0)
      return lis;
    else
      return findNode(lis.next, pos - 1);
  }
}
