#!/usr/local/bin/perl

#############################################################################
# Script to expand IPI .dat file with minimal IPRND entries at the end      # 
#############################################################################
 use strict;

# print usage information if no arguments supplied  
  unless ($ARGV[0]) {
    print "The .dat database to expand should be given as argument";
    exit 1;
  }

my($infile);
$infile = $ARGV[0];

open (INFILE,  "+<$infile")          || die "Error: cannot open input file";
open (OUTFILE, "+>$infile" . ".tmp") || die "Error: cannot create temp file";

# use the same EOL for the output as found in the input file
  binmode INFILE;
  binmode OUTFILE;
  $/ = "\012ID";
  my $eol;
  while (<INFILE>) {
    if (length($_) > 1) {
      if (/\015\012/) {
        $eol = "\015\012"; #DOS
      } else {
        $eol = "\012"; #Unix
      }
      last;
    } else {
      next;
    }
  }

# read a complete sequence entry at a time
  $/ = $eol."ID";

# set the cursor to start of file + 2 characters, skip first "ID"
  seek(INFILE, 2, 0);

# loop through input file and create the output file
  while (<INFILE>) {
    my($idline, $accline, $rest) = split(/$eol/o, $_, 3);
    $idline =~ s/IPI/IPRND/;
    $accline =~ s/IPI/IPRND/; 
    print OUTFILE "ID" . $idline . $eol;
    print OUTFILE $accline . $eol;
    print OUTFILE "DE    Random sequence".$eol;		
  }

#now write everything to the end of old file 
  seek(OUTFILE, 0, 0);
  while (<OUTFILE>) {
     print INFILE $_;      
  }
  close OUTFILE;
  unlink "$infile" . ".tmp";
  
  exit 0;


