from pyscescbm import CBSolver as slv

work_dir = os.path.join(cDir, work_dir)
if not os.path.exists(work_dir):
    os.mkdir(work_dir)

if sbml_level == 3:
    print('Trying level 3')
    cmod = CBRead.readSBML3FBC(model_file, work_dir=model_dir)
else:
    cmod = CBRead.readSBML2FBA(model_file, work_dir=model_dir)
cmod.id = model_name

slv.analyzeModel(cmod, lpFname=os.path.join(work_dir, 'raw_({0:s})'.format(cmod.id)))

# scan for duplicates
print('\nScan for duplicates')
dup_C = CBTools.scanForReactionDuplicates(cmod, ignore_coefficients=False)
print('\nReaction pairs with matching reagents and coefficients: {0:d}'.format( len(dup_C) ))
for d in dup_C:
    print('{0:s} == {1:s} ({2:s})'.format(d[0],d[1],d[2]))

# write duplicate reactions to file
F = open(os.path.join(model_dir,'{0:s}.duplicates.csv'.format(model_file)),'w')
F.write('Model file: {0:s},,,,\n'.format( model_file) )
F.write('Duplicate reactions pairs: {0:d},,,,\n'.format( len(dup_C) ) )
for d in dup_C:
    F.write('\"{0:s}\",\"{1:s}\",\"{2:s}\",\"{3:s}\",\"{4:s}\"\n'.format(d[0],d[1],d[2],d[3],d[4]))
F.write('\n')
F.close()
if sbml_level == 3:
    print('Trying level 3')
    cmod = CBRead.readSBML3FBC(model_file, work_dir=model_dir)
else:
    cmod = CBRead.readSBML2FBA(model_file, work_dir=model_dir)

cmod.id = model_name
print('\nAttempting to delete bounds for biomass reaction,', cmod.getActiveObjective().getFluxObjectiveReactions()[0])
cmod.deleteBoundsForReactionId(cmod.getActiveObjective().getFluxObjectiveReactions()[0])

mLP = slv.analyzeModel(cmod, return_lp_obj=True)
CBWrite.printFBASolution(cmod)
tmp_mid = cmod.id+'_cplex'

CBTools.countedPause(1)

cmod.id = tmp_mid

print('\n{0:d}\n'.format(len(cmod.flux_bounds)) )
cmod.changeAllFluxBoundsWithValue(inf_bound, 'Infinity')
cmod.changeAllFluxBoundsWithValue(-inf_bound, '-Infinity')
cmod.changeAllFluxBoundsWithValue(numpy.inf, 'Infinity')
cmod.changeAllFluxBoundsWithValue(-numpy.inf, '-Infinity')

print('\n{0:d}\n'.format(len(cmod.flux_bounds)) )
slv.analyzeModel(cmod, lpFname=os.path.join(work_dir2, cmod.id), oldlpgen=False)

cmod.id = cmod.id.replace('_cplex','')+'.noinf'
print('\n{0:d}\n'.format(len(cmod.flux_bounds)) )
cmod.deleteAllFluxBoundsWithValue('Infinity')
for file_in in os.listdir(work_dir):       
    if file_in.endswith('noinf_r.ine.all'):
        subnetwork_name = file_in.replace('.noinf_r.ine.all','') 
        model_file = "{0:s}.xml".format(subnetwork_name)
        vertex_file = os.path.join(work_dir, '{0:s}.noinf_r.ine.all'.format(subnetwork_name) )
        rfva_file = os.path.join(work_dir, '{0:s}.noinf_r.ine.opt.fva'.format(subnetwork_name) )   
        if sbml_level == 3:
            try:
                cmod = CBRead.readSBML3FBC(model_file, work_dir=model_dir)  
            except:        
                cmod = CBRead.readSBML2FBA(model_file, work_dir=model_dir)      
        else:    
            cmod = CBRead.readSBML2FBA(model_file, work_dir=model_dir)        
        cmod.id = subnetwork_name
        CBTools.addStoichToFBAModel(cmod)
        CBTools.processBiGGchemFormula(cmod)
        
        if USE_COLUMN_CROSSCHECK:
            mismatch = []                        
            F = open(os.path.join(H_format_dir, '{0:s}.noinf_r.columns.txt'.format(subnetwork_name) ), 'r')
            indx_lst = []
            for L in F:
                l = [i.strip() for i in L.split(',')]
                if len(l) == 2:
                    indx_lst.append(l[1])
            F.close()
            for r in range(len(indx_lst)):
                match = bool(indx_lst[r] == cmod.N.col[r])
                print('{0} == {1}: {2}'.format(indx_lst[r], cmod.N.col[r], match))
                if not match: mismatch.append((indx_lst[r], cmod.N.col[r]))