use strict;
use warnings;


########################
######################## main ########################
########################

package main;

sub printToJson {
    my $mode = $_[0];

    open(my $file, ">>", "mirRNA.json") # open for update
    or die "Can't open 'mirRNA.json' for update: $!";

    if ($mode == 1) { #start file
        close($file);
        open(my $file, ">", "mirRNA.json") # open for update
        or die "Can't open 'mirRNA.json' for update: $!";
        print $file "[\n{\n";
    }
    elsif ($mode == 2) { #add mirRNA
        my $mipf = qx(grep -w $_[1] miFam.1line.dat | awk '{print \$1}');
        my $mir = qx(grep -w $_[1] miFam.1line.dat | awk '{print \$2}');

        print $file "\"value\": \"$_[2]\",\n";
        print $file "\"text\": \"$_[1]\",\n";

        chomp $mipf;
        chomp $mir;
        my @valuesMipf = split('\n', $mipf);
        if ($#valuesMipf+1) {
            print $file "\"mipf\": \"@valuesMipf\",\n";
        }
        else {
            print $file "\"mipf\": \"$mipf\",\n";
        }
        my @valuesMir = split('\n', $mir);
        if ($#valuesMir+1) {
            print $file "\"mir\": \"@valuesMir\"\n";
        }
        else {
            @valuesMir = split('_', $_[1]);
            print $file "\"mir\": \"$valuesMir[0]\"\n";

        }
    }
    elsif ($mode == 3) { #add next

        print $file "},\n{\n";
    }
    elsif ($mode == 4) { #add end
        print $file "}\n]\n";
    }

    close($file);
}

########################

open(my $fileIn, "<", "index.pattern") # open for read
    or die "Can't open 'index.pattern' for read: $!";

open(my $fileOut, ">", "index.pattern.mipf") # open for update
    or die "Can't open 'index.pattern.mipf' for update: $!";

while (my $row = <$fileIn>) {
    my @values = split('\t', $row);
    chomp $values[1];
    my $mirRNA = $values[0];
    my $pattern = $values[1];

    my $mir = qx(grep -w $mirRNA miFam.1line.dat | awk '{print \$2}');
    chomp $mir;
    @values = split('\n', $mir);
    if ($#values+1) {
        $mir = $values[0];
    }
    else {
        @values = split('_', $mirRNA);
        $mir = $values[0];
    }

    print $fileOut "$mirRNA\t$pattern\t$mir\n";
}
close($fileOut);

close($fileIn);


system("sort -k 3,3 index.pattern.mipf > index.pattern.mipf.sort");
system("mv index.pattern.mipf.sort index.pattern.mipf");

my $i = 1;

open(my $file, "<", "index.pattern.mipf") # open for read
    or die "Can't open 'index.pattern.mipf' for read: $!";

printToJson(1);

while (my $row = <$file>) {
    if ($i) {
        $i = 0;
    }
    else {
        printToJson(3);
    }

    my @values = split('\t', $row);
    chomp $values[1];

    printToJson(2, $values[0], $values[1]);
}
printToJson(4);

close($file);
printf ("The program is complete.\n");
