#!/usr/bin/perl
#$Id: format_jdata.pl,v 1.4 2014/07/30 06:40:00 sofc Exp $
# Script for reformatting jdata files if changes in configuration durring test resulted in 
# changes in number and/or position of fields in the raw data files (and thus the jdata file)
use strict;
use warnings;
use File::Copy;
use RFC::Rig;
use RFC::Header;
use SemaforeFile;
my $rig = RFC::Rig->new(shift);
$rig->check_run;
my $test = $rig->session();
if (@ARGV)
{
    $test = shift;
    die "No test specified!" unless (defined($test) && $test =~ /\d+/);
    $test += 0;
    $test = $rig->session() if ($test > $rig->session());
}
my $homedir = $RFC::Header::publicdir . 'rig' . $rig->name . "/" . $rig->name . 'test' . $test.'/';
my $jdata = $homedir.'jdata';
my $out = $homedir.'jdata_2';

my %fields = ();
my $j = SemaforeFile->new($jdata);
$j->lock_sh;
$j->open_read;
while (my $line = $j->readline)
{
    my @l = split(/[\s\t]+/,$line);
    for (my $x = 2; $x < @l; $x+=2)
    {
	$fields{$l[$x]} = 1;
    }
}
$j->close;
$j->open_read;
my @tags = ();
foreach my $item (sort keys %fields)
{
    next unless ($item =~ /^[a-zA-Z][\w\d\+\-\.]+$/);
    push @tags,$item;
}
open MYOUT,'>',$out or die "Could not open file $out for writing $!\n";
while (my $line = $j->readline)
{
    ### Set values to 0 ##
    foreach my $tag (@tags)
    {
	$fields{$tag} = 0;
    }
    my @l = split(/[\s\t]+/,$line);
    for (my $x = 2; $x < @l; $x+=2)
    {
	$fields{$l[$x]} = $l[$x+1];
    }
    my @list = ();
    foreach my $tag (@tags)
    {
        $fields{$tag} = -32768 unless (defined($fields{$tag}));
	push @list,$tag,$fields{$tag};
    }
    print MYOUT join(' ',$l[0],$l[1],@list),"\n" unless ($l[0] < 0);
}
close MYOUT;
$j->close;
$j->lock_ex;
move($out,$jdata);
$j->lock_un;
