import sys, getopt

def main(argv):
  staticN=''
  dynamicN=''
  outputfile=''
  try:
    opts, args = getopt.getopt(argv,"s:d:o:",["sfile=","dfile=","ofile="])
  except getopt.GetoptError:
    print 'static-vs-dynamic-gdvs.py -s <static gdvs> -d <dynamic gdvs> -o <output file>'
    sys.exit(2)
  for opt, arg in opts:
    if opt in ("-s","--sfile"):
      staticN=arg
    elif opt in ("-d", "--dfile"):
      dynamicN = arg
    elif opt in ("-o", "--ofile"):
      outputfile = arg
  sF1=open(staticN,'r')
  staticF=sF1.readlines()
  dF1=open(dynamicN,'r')
  dynamicF=dF1.readlines()
  
  sdF=open(outputfile,'w')

  print 'static file: ',staticN
  print 'dynamic file: ',dynamicN
  print 'output file: ',outputfile
  print 'reading the static gdvs file now'
  ## read the static gdvs
  node_dict=dict()
  s_firstLine=staticF.pop(0)
  s_nodeNames=s_firstLine.split(' ')
  row=0
  for line in staticF:
    lineArr=line.split()
    ##create keys (node1-node2) for dict
    node1=lineArr[0].strip('\n')
    column=0
    #print 'node1-'+node1
    for node2 in s_nodeNames[row+3:]:  
      ikey=node1+"-"+node2.strip('\n')
      ivalue=lineArr[column+2+row]
      xyArr=ivalue+'-0'
      node_dict.update({ikey:xyArr})
      #print 'key-'+ikey+' value-'+xyArr
      #print 'column-'+str(column)+' : key-'+ikey+' : value-'+ivalue
      column+=1
    row+=1 
  sF1.close()
  print 'reading the dynamic gdvs file now'
  ## read the dynamic gdvs
  d_firstLine=dynamicF.pop(0)
  d_nodeNames=d_firstLine.split(' ')
 
  row=0
  for line in dynamicF:
    lineArr=line.split()
    ## create keys (node1-node2)
    node1=lineArr[0].strip('\n').strip('node-')
    column=0
    for node2 in d_nodeNames[row+3:]:
      node2=node2.strip('\n').strip('node-')
      ikey1=node1+'-'+node2
      ikey2=node2+'-'+node1
      ivalue=lineArr[column+2+row]
     # print 'key-'+ikey1+' ivalue-'+ivalue
      if(node_dict.has_key(ikey1)):
        #node_dict[ikey1]=ivalue
        node_dict[ikey1]=node_dict[ikey1].split('-')[0]+'-'+ivalue
        #print 'column-'+str(column)+' : key-'+ikey1+' : value-'+ivalue
      elif(node_dict.has_key(ikey2)):
        #node_dict[ikey2][1]=ivalue
        node_dict[ikey2]=node_dict[ikey2].split('-')[0]+'-'+ivalue
        #print 'column-'+str(column)+' : key-'+ikey2+' : value-'+ivalue
      else:
        print 'cannot find '+ikey1+' in the static file'
      column+=1
    row+=1
  dF1.close()
  
  ## ouput the results to the output file
  print 'writing the results to the ouputfile file now'
  for k in sorted(node_dict.keys()):
    #print k+'\t'+v[0]+'\t'+v[1]
    iv=node_dict[k]
    v=iv.split('-')
    #sdF.write(k+'\t'+iv+'\n')
    #v=iv.split('-')
    
    #if(v[1]!='0'):
    sdF.write(k+'\t'+v[0]+'\t'+v[1]+'\n')
 

if __name__ == "__main__":
   main(sys.argv[1:])
  
