#!/usr/bin/perl -Wall

use strict;
use Data::Dumper;

# LOAD CGDB->RegulonDb ID mapping
my $map;
my $rids;
open(F,'regulondb.cgdb.map');
while (<F>) {
	chomp; # removes "\n" at end of line
	my ($r,$c) = split '\t';
	$map->{$r} = $c; # map regulonDb ID $r to CGDB ID $c
	$rids->{uc($r)} = $r; # needed because TF are capitalized, e.g. AcrR for acrR, so we can map all genes (AcrR and acrR) to acrR version
}
close(F);

# LOAD Ids having profile
my $exprs;
open(F,'EcolA.GPL3154.rma.cgdb.txt');
while (<F>) {
	chomp;
	next if $. == 1; # skip 1st line
	my ($gene) = split '\t';
	$exprs->{$gene} = 1; # we use a hash the genes we have seen
}
close(F);

# ids in network RegDb file
open(F,'RegulonDB--network_tf_operon.txt'); # change the file name if different from what I have
my $ids;
while (<F>) {
	next if $_ =~ /^#/; # skip comments
	chomp;
	my ($tf, $ut, $reg) = split '\t';
	next if ! defined $rids->{uc($tf)}; # we did not map this gene between RegulonDb and CGDB

	$tf = $rids->{uc($tf)}; # the AcrR/acrR stuff of above

	# if we have an expression profile for that gene
	# we define a key formed by the triplet: TfRegulonDbGeneId--CgdbGeneId--RegulonDb[OperonId|Tf]Id
	$ids->{$tf."\t".$map->{$tf}."\t".$tf} = 1 if defined $exprs->{ $map->{$tf} };

	# parse operon field formed by operonId[gene1, gene2, ...]
	my ($utid, $utgenes) = $ut =~ /(\w+)\[([\w\s\,]+)\]/;
	# then for each gene in the operon, if we have a profile for that gene:
	# generate a key of the form: RegulonDbGeneId--CgdbId--RegulonDbOperonId
	foreach (split ',',$utgenes) {
		$ids->{$_."\t".$map->{$_}."\t".$utid} = 1 if defined $map->{$_} && defined $exprs->{ $map->{$_} };
	}
}
close(F);

# output keys previously formed
foreach (sort keys %$ids) { print $_; }
