#!/usr/bin/python
import os, sys
from numpy import *

def loadFSPatchASCII(filename=None):

    #from numpy import *
    f = open(filename)
    #ignore first line
    comment_line = f.readline()
    #line 2 has vert and triangle count
    cnts =  f.readline().strip().split()
    nVerts, nPolys = int(cnts[0]), int(cnts[1])

    #matrices to hold vertices and triangles
    coords = zeros((nVerts,5),'f')
    polys = zeros((nPolys,5),'i')

    #loop through vert lines and populate a matrix
    compare_vert = 0
    skipped_vert_count = 0
    skipped_verts = ones((1000000,1),'i')*-1
    used_verts = [999999999]
    for i in range(nVerts):
        extracted_val = f.readline().strip().split()[0]
        #print extracted_val
        curr_index = abs(float(extracted_val))-1
        #print curr_index
        #if curr_index in used_verts:
        #    print ' at ', i, ' got ', curr_index, ' dup'
        #    break    
        #used_verts.append(curr_index)
        
        num_skipped = curr_index - compare_vert
        if num_skipped != 0:
            for j in range(int(num_skipped)):
                #print 'at ', curr_index, ' compared to ',compare_vert,' skipping ', curr_index-(j+1)
                skipped_verts[skipped_vert_count] = int(curr_index-(j+1))
                skipped_vert_count+=1
        compare_vert = curr_index + 1
        curr_coord = array(f.readline().strip().split(),'f')
        coords[i,0] = curr_index
        coords[i,1:4] = curr_coord
        coords[i,4] = i

    #create new coords list where unused coords are 0,0,0
    #first create the skipped portion
    skipped_verts = skipped_verts[skipped_verts!=-1] #strip out unused vals

    #now because of the odd fs file format we need to remap the 
    # coordinates so that all (even unused) are represented in 
    # the coords array

    #reshape to correct size to combine
    new_coords = zeros((len(coords)+len(skipped_verts),5),'f')
    new_coords[:len(coords),:] = coords
    new_coords[len(coords):len(coords)+len(skipped_verts),0] = skipped_verts
    new_coords = new_coords[new_coords[:,0].argsort(),]    

    polys[:,0] = 3

    #loop through polygon lines and populate a matrix    
    for i in range(nPolys):
        curr_index = int(f.readline().strip().split()[0])
        curr_coord = array(f.readline().strip().split(),'i')
        polys[i,1] = curr_index
        polys[i,2:5] = curr_coord

    #now just pass back the required values
    vtk_coords = new_coords[:,1:4]
    vtk_polys = polys[:,2:5]

    print vtk_coords, vtk_polys
    
    return vtk_coords, vtk_polys

