#!/usr/local/bin/perl -w
#
# Used to join a directory of dctc created parts to one file
#
# Perl script by: Tobias

use Fcntl;
use strict;

# Name of the directory that should be joined
my $GDLdir = "./";
# name of the file that will be the result
my $outputfilename = "joinedfile";
# verbose output enabled
my $verbose = 1;

my @files = qw//;
opendir(DIR, $GDLdir) || die "can't opendir $GDLdir $!, stopped";
@files = grep { /^[0-9A-F]+-[0-9A-F]+$/ } readdir(DIR); # stuff all files matching into the array
closedir(DIR);

my ($realPos, $startingPos, $buffer, $bytesRead, $offset, $file) = 0;
sysopen(OUTPUT, $outputfilename, O_TRUNC|O_CREAT|O_WRONLY) or
  die ("can't open file $outputfilename: $!, stopped");

foreach (sort(@files)) {
  $file = $_; # set $file
  /^([0-9A-F]+)/; $startingPos = hex($1); # convert the file's starting position from hex string to int
  $verbose and print "filename: $file, starting position of file: $startingPos, next byte to write: $realPos \n";

  if ($startingPos > $realPos) {
    die ("parts missing: $file begins at $startingPos, which is after $realPos, stopped");
  } elsif ($startingPos < $realPos) {
    print "anomaly detected and dealt with, size: ".($realPos - $startingPos).", file where data is skipped: $file\n";
  }

  open(INPUT, $GDLdir.$file) or die ("can't open input $GDLdir$file : $!, stopped");
  $bytesRead = read(INPUT, $buffer, 8192, $realPos - $startingPos);
  while ($bytesRead) {
    if (syswrite(OUTPUT, $buffer, $bytesRead) != $bytesRead) {
      die ("error writing to disk. disk full?: $!, stopped");
    }
    $realPos += $bytesRead;
    $bytesRead = read(INPUT, $buffer, 8192);
  }
  close INPUT;
}
close OUTPUT;

