#!/usr/bin/env python2

"""Convert ROI mask files from MATLAB format to ASCII."""

import os
import sys

import scipy.io

def line_to_text(line):
    return ''.join(map(str, line))

def mask_to_text(mask):
    return '\n'.join(map(line_to_text, mask))


infile = sys.argv[1]
mat = scipy.io.loadmat(infile, struct_as_record=False)

roislices = map(int, mat['ROIslices'][0])
rois = mat['ROIs'][0]

for roi in rois:
    struct = roi[0,0]
    name = struct.name[0]
    #vol = struct.vol[0,0]
    outfile = '%s_%s.mask' % (os.path.basename(infile), name)
    with open(outfile, 'wb') as f:
        f.write('slice: %i\n' % roislices[0])
        f.write(mask_to_text(struct.mask))

@@ -253,16 +253,17 @@
 %0A%0Ainfile
+s
  = sys.a
@@ -267,18 +267,46 @@
 s.argv%5B1
+:
 %5D%0A
+for infile in infiles:%0A    
 mat = sc
@@ -352,17 +352,20 @@
 =False)%0A
-%0A
+    
 roislice
@@ -398,16 +398,20 @@
 s'%5D%5B0%5D)%0A
+    
 rois = m
@@ -428,20 +428,26 @@
 %5B0%5D%0A
-%0A
+    
 for
+ i,
  roi in 
 rois
@@ -446,14 +446,141 @@
  in 
+enumerate(
 rois
+)
 :%0A
+        try:%0A            roislice = roislices%5Bi%5D%0A        except IndexError:%0A            roislice = roislices%5B0%5D%0A    
     
@@ -593,24 +593,28 @@
  = roi%5B0,0%5D%0A
+    
     name = s
@@ -631,16 +631,20 @@
 %5B0%5D%0A    
+ 
+   
 #vol = s
@@ -654,24 +654,28 @@
 ct.vol%5B0,0%5D%0A
+    
     outfile 
@@ -681,16 +681,19 @@
  = '%25s_%25
+i_%25
 s.mask' 
@@ -724,15 +724,61 @@
 le),
+ i+1,
  name)%0A
+        print 'Writing %25s' %25 outfile%0A    
     
@@ -808,16 +808,20 @@
 ) as f:%0A
+    
         
@@ -856,14 +856,14 @@
 lice
-s%5B0%5D)%0A
+)%0A    
     

Handle multiple files, put mask number in filename