# General Python Libraries
import os

# Setting the working directory
os.chdir('workingdirectory') 

# Data Science Specific Libraries
import pandas as pd 
import numpy as np

#function that handles the conversion
#outputdir is the output were the bicluster are going to go
#name is a prefix for the bicluster generated csv files
#data is the original dataset
#file is the file generated by BicPAMS
def bicpamsconverter(outputdir, name, data,file):
    FileObject = open(file, "r")
    lines = FileObject.readlines(0)
    nbic = int(lines[0].replace("FOUND BICS:#",""))
    line = []
    for i in range(nbic):
        line.append(lines[i+1])
    Biclusters = []
    for i in range(nbic):
        y = []
        x = []
        ytrue = False
        xtrue = False
        for j in range(len(line[i])):
            if line[i][j] == 'Y':
                ytrue = True
            if ytrue == True and line[i][j] == ']':
                ytrue = False
            if line[i][j] == 'X':
                xtrue = True
            if xtrue == True and line[i][j] == ']':
                xtrue = False    
            if ytrue:
                y.append(line[i][j])
            if xtrue:
                x.append(line[i][j])
                
        y = y[3:len(y)]
        x = x[3:len(x)]
        
        bicluster_y = []
        temp = ''
        for i in y:
            if i != ',':
                temp += i
            else:
                bicluster_y.append(temp)
                temp = ''
        bicluster_y.append(temp)
        
        bicluster_x = []
        temp = ''
        for j in x:
            if j != ',':
                temp += j
            else:
                bicluster_x.append(temp)
                temp = ''
        bicluster_x.append(temp)        
        Biclusters.append([bicluster_x,bicluster_y])
        
    FullBicluster = []
        
    for b in range(len(Biclusters)):
        FullBicluster.append(data.loc[ Biclusters[b][1] , Biclusters[b][0] ])
    
    for i in range(len(FullBicluster)):
        FullBicluster[i].to_csv(outputdir + name + str(i+1) + ".csv")  


data = pd.read_csv("originalDatasetLocation/dataset.csv", index_col = 0)

name = "bicpam_Bicluster_"

bicpamsconverter("OutputFolder/", "prefix", data, "BicPAMfile.txt")
