#!/free/bin/perl

# Purpose: Reformats a RNODC/SOC data file.  In brief, every
#          station in the file is shifted two characters to
#          the right of the previous station.  The file format
#          should be NODC's Oceanographic Station Data (SD2)
#          format.  Use the -help option for usage information.
# Written: Steven Rutz 08 May 1999 in Perl.

# Print help info if asked or if no arguments.
if(!@ARGV | $ARGV[0]=~"-help") {
 @pathprg = split(/\//, $0); $prg = pop @pathprg; # Get the program name.
 die "Purpose: Reformats a RNODC/SOC data file.  In brief, every,\n",
     "         station in the file is shifted two characters to\n",
     "         the right of the previous station.  The file format\n",
     "         should be NODC's Oceanographic Station Data (SD2)\n",
     "         format.\n",
     "Usage:   $prg input_file > output_file\n",
     "Written: Steven Rutz 08 May 1999 in Perl.\n";
} elsif(!(-e $ARGV[0]) & $ARGV[0] ne "-") { # Test if file exists.
 die "Error: Input file doesn't exist!\n";
}

open(INFILE, $ARGV[0]); # Open input file.

chomp($line1 = <INFILE>); # Read 1st record and chomp newline character.
$offset = 80 - length($line1); # Set offset.

# Loop through file.
while(chomp($line2 = <INFILE>)) { # Read 2nd record and chomp newline character.
 $line = $line1 . $line2; # Append last two records read.
 $len = length($line); # Length of the appended records.

# Depending on the length of the appended records, and the offset,
# print out one record of 80 characters from the appended records.
 if($len == 160) {
  print substr($line, $offset, 80), "\n";
 } elsif($len > 80) {
  print substr($line, 0 + $offset, 80 + $offset), "\n";
  $offset = 80 - length($line1); # Reset the offset.
 } elsif(length($line1) == 80) {
  print substr($line, 0, 80), "\n";
 }

 $line1 = $line2; # Record 2 becomes record 1.
}

close(INFILE); # Close input file.
