#!/usr/bin/perl -w

use strict;

my $line;
my $title;
my $size;
my %sizes;
my %records;
my @cds;
my $name;
my $capacity = 74;

open(CLIPS, "<$ARGV[0]") || die "Couldn't open $ARGV[0]\n";

# Read in the file of film clips
while($line = <CLIPS>) {
  chomp $line;
  if($line !~ /^(.*)\s+(\d+)$/ ) {  #I covered this, but you may want to review
    print "Error in input format\n";
    exit;
  } else {
    $size = $2;
    $title = $1;
  
    $sizes{$title} = $size;       # I basically did this, but I didn't
    $records{$title} = $line;     # talk about how we were going to print 
	                              # things out.
  }
}

# I didn't touch anything after this...


# Produce a list of titles orders by size
my @ordered_sizes = sort { $sizes{$b}<=>$sizes{$a} } keys %sizes;

foreach $name (@ordered_sizes) {
  my $cdnum = 0;
  my $placed = 0;

  # If a clip is too big, set its disk label to "not archived"
  if($sizes{$name} > $capacity) {
    $records{$name} .= " not archived";
    next;
  }

  while(!$placed ) {
    # If we have run out of partially full CDs to put this clip on
    # then create a new CD
    if(!defined($cds[$cdnum])) {
      $cds[$cdnum] = $capacity;
    }

    # If there is room on the current CD, add the clip to the CD
    # and set a disk label for the CD
    if($cds[$cdnum] > $sizes{$name}) {
      $cds[$cdnum] -= $sizes{$name};
      $records{$name} .= " disk" . $cdnum;
      $placed = 1;
    }
    $cdnum++;
  }
}

# Print the catalog
foreach $name (sort keys %records) {
  print "$records{$name}\n";
}


