#!/usr/bin/perl
#
# Filename: separate_cips_pan.pl

use XML::Simple;
use strict;
use Switch;
use Data::Dumper;


# Purpose:
#   This script takes in a single argument that points to a cips pan file,
# which is structured as a concatenation of <PRODUCT> xml documents.  This
# script searches each of the products and sorts them based upon the 'TITLE'
# value.  Currently, they are separated into three sections: level 2a, level 3a,
# 3a and level 4.  Each of these products are then concatenated into a file 
# based upon their title value.  The three files are local, and their names are
# declared here:

my $level2file = "cips_pan_2a.txt";
my $level3file = "cips_pan_3a.txt";
my $level4file = "cips_pan_4.txt";


my $numArgs = scalar @ARGV;
my $xml_simple;

if ($numArgs ne 1) {
   print "Usage: separate_cips_pan.pl <cips_pan_filename>\n";
   exit;
}

open(IFILE, $ARGV[0]) || die("Could not open file!");
open(OFILE2, ">>$level2file") || die("Could not open level 2a file for writing!");
open(OFILE3, ">>$level3file") || die("Could not open level 3 file for writing!");
open(OFILE4, ">>$level4file") || die("Could not open level 4 file for writing!");

my @arrayName = <IFILE>;
my $inProduct = 0;
my $product = "";

foreach my $line (@arrayName) {
  if ($inProduct == 0) {
    if ($line =~ /^\<PRODUCT\>$/) {
      $inProduct = 1;
      $product = $line;
    }
  } else {
    if ($line =~ /^\<\/PRODUCT\>$/) {
      $inProduct = 0;
      $product .= $line;
      
      $xml_simple = new XML::Simple ( RootName=>'PRODUCT');
      my $xmlProd = $xml_simple->XMLin($product);
      my %product_hash = map { %{$_} } @{$xmlProd};
      
      switch ($product_hash{'TITLE'}) {
	case "CIPS Level2A" { print OFILE2 $product; }
	case "CIPS Level3A" { print OFILE3 $product; }
	case "CIPS Level4"  { print OFILE4 $product; }
	else { print "Unrecognized title, $product_hash{'TITLE'}\n" }
    }
      
      
    } else { $product .= $line }
  } 
}


close(IFILE);
close(OFILE2);
close(OFILE3);
close(OFILE4);
