Skip to content
util.c 80.4 KiB
Newer Older
Fabio Roberto Vitello's avatar
Fabio Roberto Vitello committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
   int j;
   long k;
   static long idum2=123456789;
   static long iy=0;
   static long iv[NTAB];
   double temp;
   
   if (*idum <= 0) {                 // Initialize.
       if (-(*idum) < 1) *idum=1;     // Be sure to prevent idum = 0.
       else *idum = -(*idum);
       idum2=(*idum);
       for (j=NTAB+7;j>=0;j--) {      // Load the shu.e table (after 8 warm-ups).
           k=(*idum)/IQ1;
           *idum=IA1*(*idum-k*IQ1)-k*IR1;
           if (*idum < 0) *idum += IM1;
           if (j < NTAB) iv[j] = *idum;
       }
       iy=iv[0];
   }
   k=(*idum)/IQ1;                    // Start here when not initializing.
   *idum=IA1*(*idum-k*IQ1)-k*IR1;    // Compute idum=(IA1*idum) % IM1 without
                                     // over ows by Schrage's method.
   if (*idum < 0) *idum += IM1;
   k=idum2/IQ2;
   idum2=IA2*(idum2-k*IQ2)-k*IR2;    // Compute idum2=(IA2*idum) % IM2 likewise.
   if (idum2 < 0) idum2 += IM2;
   j=iy/NDIV;                        // Will be in the range 0..NTAB-1.
   iy=iv[j]-idum2;                   // Here idum is shu.ed, idum and idum2 are
                                     // combined to generate output.
   iv[j] = *idum;
   if (iy < 1) iy += IMM1;
   if ((temp=AM*iy) > RNMX) return RNMX;  // Because users don't expect endpoint values.
   else return temp;
}


void ByteSwap(unsigned char * b, int n)
{
   register int i = 0;
   register int j = n-1;
   char temp;
   while (i<j)
   {
 		 temp = b[i];
         b[i] = b[j];
 		 b[j] = temp;
                 /* std::swap(b[i], b[j]); */
      i++, j--;
   }
}

int invMap(int nAstroPSolved,int *inv){
//inv[0] Row of Long
//inv[1] Row of Lat
//inv[2] Row of MuLong
//inv[3] Row of MuLat
    
    for(int i=0;i<4;i++)
        inv[i]=-1;
    if(nAstroPSolved<1 || nAstroPSolved>5)
        return 1;
    if(nAstroPSolved==2){
        inv[0]=0;
        inv[1]=1;
    }
    if(nAstroPSolved==3){
        inv[0]=1;
        inv[1]=2;
    }
    if(nAstroPSolved==4){
        inv[0]=0;
        inv[1]=1;
        inv[2]=2;
        inv[3]=3;
    }
    if(nAstroPSolved==5){
        inv[0]=1;
        inv[1]=2;
        inv[2]=3;
        inv[3]=4;
    }
    return 0;
}

void writeBinFiles(double* systemMatrix,long* matrixIndex,int* instrCol,double* knownTerms,char* wrfileDir,char* wpath, struct comData comlsqr, int debugMode){
    
    int nproc,myid;
    FILE *fpSM,*fpMI,*fpII,*fpKT,*fpBar;
    int nparam;
    
    MPI_Status status;
    char actpath[1024];
    size_t sizePath=1020;
    int extConstraint;
    int barConstraint;

    
    MPI_Comm_size(MPI_COMM_WORLD, &nproc);
    MPI_Comm_rank(MPI_COMM_WORLD, &myid);
    
    nparam=comlsqr.nAstroPSolved+comlsqr.nAttP+comlsqr.nInstrPSolved+comlsqr.nGlobP;
    getcwd(actpath,sizePath);
    chdir(wpath);
    if(!(chdir(wrfileDir)==0))  {
        printf("wrfile directory does not exist. Aborting\n");
        MPI_Abort(MPI_COMM_WORLD,1);
        exit(EXIT_FAILURE);
    }

    
    long int rowCounter=1;
    long int rowWritten=0;
    long int stillOpen=-1;
    int nOfFile=1;  // file numerati da 1 in avanti. Il corrente file da scrivere è nOfFile
    int lastStargsrId=-1;
    rowWritten=0;
	rowCounter=0;
	long rowCounterPrev=0;
    extConstraint=comlsqr.extConstraint;
    barConstraint=comlsqr.barConstraint;
	
    if(myid>0){
        MPI_Recv(&lastStargsrId, 1, MPI_INT, myid-1, 0, MPI_COMM_WORLD, &status);
        MPI_Recv(&rowCounterPrev, 1, MPI_LONG, myid-1, 1, MPI_COMM_WORLD, &status); //righe scritte nell'ultimo file
        MPI_Recv(&nOfFile, 1, MPI_INT, myid-1, 2, MPI_COMM_WORLD, &status);
//        printf("TP0 PE=%d ricevo da %d  lastStargsrId=%d rowCounterPrev=%ld nOfFile=%ld\n",myid,myid-1,lastStargsrId,rowCounterPrev,nOfFile);
    }
    if(lastStargsrId==1000*nOfFile-1)  // sono in fase di chiusura file
    {
        if(lastStargsrId!=matrixIndex[0]/comlsqr.nAstroPSolved ){ //rinomino il file precedente era alla fine, io sono in stella successiva!
            char filenameCoeffBinMatrixIndex[512];
            strcpy(filenameCoeffBinMatrixIndex,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
            char tmp1[20],tmp2[20],tmp3[20];
            sprintf(tmp1,"%09d",1000*(nOfFile-1));
            sprintf(tmp2,"%09d",lastStargsrId);
            sprintf(tmp3,"%07ld",rowCounterPrev);
            rowCounterPrev=0;
            
            strcat(filenameCoeffBinMatrixIndex, tmp1);
            strcat(filenameCoeffBinMatrixIndex, "_");
            strcat(filenameCoeffBinMatrixIndex, tmp2);
            strcat(filenameCoeffBinMatrixIndex, "_000000_nrows-");
            strcat(filenameCoeffBinMatrixIndex, tmp3);
            strcat(filenameCoeffBinMatrixIndex, "_MI.bin");

            char filenameCoeffBinSystemMatrix[512];
            strcpy(filenameCoeffBinSystemMatrix,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
            strcat(filenameCoeffBinSystemMatrix, tmp1);
            strcat(filenameCoeffBinSystemMatrix, "_");
            strcat(filenameCoeffBinSystemMatrix, tmp2);
            strcat(filenameCoeffBinSystemMatrix, "_000000_nrows-");
            strcat(filenameCoeffBinSystemMatrix, tmp3);
            strcat(filenameCoeffBinSystemMatrix, "_SM.bin");
            
            char filenameCoeffBinIstrIndex[512];
            strcpy(filenameCoeffBinIstrIndex,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
            strcat(filenameCoeffBinIstrIndex, tmp1);
            strcat(filenameCoeffBinIstrIndex, "_");
            strcat(filenameCoeffBinIstrIndex, tmp2);
            strcat(filenameCoeffBinIstrIndex, "_000000_nrows-");
            strcat(filenameCoeffBinIstrIndex, tmp3);
            strcat(filenameCoeffBinIstrIndex, "_II.bin");
            
            char filenameCoeffBinKnownTerms[512];
            strcpy(filenameCoeffBinKnownTerms,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
            strcat(filenameCoeffBinKnownTerms, tmp1);
            strcat(filenameCoeffBinKnownTerms, "_");
            strcat(filenameCoeffBinKnownTerms, tmp2);
            strcat(filenameCoeffBinKnownTerms, "_000000_nrows-");
            strcat(filenameCoeffBinKnownTerms, tmp3);
            strcat(filenameCoeffBinKnownTerms, "_KT.bin");
            stillOpen=0;
            rename("MI.bin", filenameCoeffBinMatrixIndex);
            rename("SM.bin", filenameCoeffBinSystemMatrix);
            rename("II.bin", filenameCoeffBinIstrIndex);
            rename("KT.bin", filenameCoeffBinKnownTerms);
            nOfFile++;
//            printf("TP3 PE=%d rinominati file %s %s %s %s\n",myid,filenameCoeffBinMatrixIndex, filenameCoeffBinSystemMatrix,filenameCoeffBinIstrIndex,filenameCoeffBinKnownTerms);

        }  // if(lastStargsrId!=matrixIndex[0]/comlsqr.nAstroPSolved
    } // if(lastStargsrId==1000*nOfFile-1
 
       
    fpMI=fopen("MI.bin","ab");
    fpSM=fopen("SM.bin","ab");
    fpII=fopen("II.bin","ab");
    fpKT=fopen("KT.bin","ab");
//    printf("TP4 PE=%d aperti in append  files MI.bin ecc\n",myid);
    for(long int i=0;i<comlsqr.mapNoss[myid];i++){
       if(i==comlsqr.mapNoss[myid]-1 ){ //  sono all'ultima osservazione dell'attuale pe
//           printf("TP5 PE=%d  i=%ld\n",myid,i);
			rowCounter++;
			fwrite(&matrixIndex[rowWritten*comlsqr.multMI],sizeof(long int),rowCounter*comlsqr.multMI,fpMI);
                     
			for(int q=0;q<nparam;q++) {
					fwrite(&systemMatrix[rowWritten*nparam+rowCounter*q],sizeof(double),rowCounter,fpSM);
			}
           
			if(comlsqr.nInstrPSolved>0) fwrite(&instrCol[rowWritten*comlsqr.nInstrPSolved],sizeof(int),rowCounter*comlsqr.nInstrPSolved,fpII);
					
			fwrite(&knownTerms[rowWritten],sizeof(double),rowCounter,fpKT);
			fclose(fpMI);
			fclose(fpSM);
			fclose(fpII);
			fclose(fpKT);
//            printf("TP6 PE=%d  i=%ld, rowCounter=%ld rowWritten=%ld rowCounterPrev=%ld\n",myid,i,rowCounter,rowWritten,rowCounterPrev);

            if(myid==nproc-1){
                 lastStargsrId=matrixIndex[comlsqr.mapNoss[myid]*2-comlsqr.multMI]/comlsqr.nAstroPSolved;
//                printf("TP7 PE=%d  i=%ld lastStargsrId=%d\n",myid,i,lastStargsrId);
               char filenameCoeffBinMatrixIndex[512];
               strcpy(filenameCoeffBinMatrixIndex,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
               char tmp1[20],tmp2[20],tmp3[20];
               sprintf(tmp1,"%09d",1000*(nOfFile-1));
               sprintf(tmp2,"%09d",lastStargsrId);
               sprintf(tmp3,"%07ld",rowCounter+rowCounterPrev);
               strcat(filenameCoeffBinMatrixIndex, tmp1);
               strcat(filenameCoeffBinMatrixIndex, "_");
               strcat(filenameCoeffBinMatrixIndex, tmp2);
               strcat(filenameCoeffBinMatrixIndex, "_000000_nrows-");
               strcat(filenameCoeffBinMatrixIndex, tmp3);
               strcat(filenameCoeffBinMatrixIndex, "_MI.bin");

               char filenameCoeffBinSystemMatrix[512];
               strcpy(filenameCoeffBinSystemMatrix,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
               strcat(filenameCoeffBinSystemMatrix, tmp1);
               strcat(filenameCoeffBinSystemMatrix, "_");
               strcat(filenameCoeffBinSystemMatrix, tmp2);
               strcat(filenameCoeffBinSystemMatrix, "_000000_nrows-");
               strcat(filenameCoeffBinSystemMatrix, tmp3);
               strcat(filenameCoeffBinSystemMatrix, "_SM.bin");
               char filenameCoeffBinIstrIndex[512];
               strcpy(filenameCoeffBinIstrIndex,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
               strcat(filenameCoeffBinIstrIndex, tmp1);
               strcat(filenameCoeffBinIstrIndex, "_");
               strcat(filenameCoeffBinIstrIndex, tmp2);
               strcat(filenameCoeffBinIstrIndex, "_000000_nrows-");
               strcat(filenameCoeffBinIstrIndex, tmp3);
               strcat(filenameCoeffBinIstrIndex, "_II.bin");
               char filenameCoeffBinKnownTerms[512];
               strcpy(filenameCoeffBinKnownTerms,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
               strcat(filenameCoeffBinKnownTerms, tmp1);
               strcat(filenameCoeffBinKnownTerms, "_");
               strcat(filenameCoeffBinKnownTerms, tmp2);
               strcat(filenameCoeffBinKnownTerms, "_000000_nrows-");
               strcat(filenameCoeffBinKnownTerms, tmp3);
               strcat(filenameCoeffBinKnownTerms, "_KT.bin");
               rename("MI.bin", filenameCoeffBinMatrixIndex);
               rename("SM.bin", filenameCoeffBinSystemMatrix);
               rename("II.bin", filenameCoeffBinIstrIndex);
               rename("KT.bin", filenameCoeffBinKnownTerms);
                rowCounterPrev=rowCounter;  //inutile
//               printf("TP7.1 PE=%d  i=%ld, rowCounter=%ld rowWritten=%ld  rinominati i files MI.bin ecc FINITO!!\n",myid,i,rowCounter,rowWritten);
                break; 
           } //if(myid==nproc-1)
           rowCounterPrev+=rowCounter;
//           printf("TP7.2 PE=%d  i=%ld, rowCounter=%ld rowWritten=%ld rowCounterPrev=%ld PROX PE!!\n",myid,i,rowCounter,rowWritten,rowCounterPrev);
           break;  //esce dal ciclo for
			
        }//if(i==comlsqr.mapNoss[myid]-1 )
			
       if ( (matrixIndex[i*comlsqr.multMI]/comlsqr.nAstroPSolved) < 1000*nOfFile ) {
					rowCounter++;
					continue;
		} else
        {
            fwrite(&matrixIndex[rowWritten*comlsqr.multMI],sizeof(long int),rowCounter*comlsqr.multMI,fpMI);
            fclose(fpMI);
            
            for(int q=0;q<nparam;q++){
                fwrite(&systemMatrix[rowWritten*nparam+rowCounter*q],sizeof(double),rowCounter,fpSM);
            }

            fclose(fpSM);
            
            if(comlsqr.nInstrPSolved>0) fwrite(&instrCol[rowWritten*comlsqr.nInstrPSolved],sizeof(int),rowCounter*comlsqr.nInstrPSolved,fpII);
            fclose(fpII);
            
            fwrite(&knownTerms[rowWritten],sizeof(double),rowCounter,fpKT);
            fclose(fpKT);
            char filenameCoeffBinMatrixIndex[512];
			char filenameCoeffBinSystemMatrix[512];
			char filenameCoeffBinInstrIndex[512];
			char filenameCoeffBinKnownTerms[512];
			strcpy(filenameCoeffBinMatrixIndex,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
			strcpy(filenameCoeffBinSystemMatrix,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
			strcpy(filenameCoeffBinInstrIndex,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
			strcpy(filenameCoeffBinKnownTerms,"Gsr_dpccu3dpctavugsrgsrsystemrow_0000_");
			
            char tmp1[20],tmp2[20],tmp3[20];
			sprintf(tmp1,"%09d",1000*(nOfFile-1));
			
            sprintf(tmp2,"%09d",1000*nOfFile-1);
			sprintf(tmp3,"%07ld",rowCounter+rowCounterPrev);
			strcat(filenameCoeffBinMatrixIndex, tmp1);
			strcat(filenameCoeffBinMatrixIndex, "_");
			strcat(filenameCoeffBinMatrixIndex, tmp2);
			strcat(filenameCoeffBinMatrixIndex, "_000000_nrows-");
			strcat(filenameCoeffBinMatrixIndex, tmp3);
			strcat(filenameCoeffBinMatrixIndex, "_MI.bin");

			strcat(filenameCoeffBinSystemMatrix, tmp1);
			strcat(filenameCoeffBinSystemMatrix, "_");
			strcat(filenameCoeffBinSystemMatrix, tmp2);
			strcat(filenameCoeffBinSystemMatrix, "_000000_nrows-");
			strcat(filenameCoeffBinSystemMatrix, tmp3);
			strcat(filenameCoeffBinSystemMatrix, "_SM.bin");
			strcat(filenameCoeffBinInstrIndex, tmp1);
			strcat(filenameCoeffBinInstrIndex, "_");
			strcat(filenameCoeffBinInstrIndex, tmp2);
			strcat(filenameCoeffBinInstrIndex, "_000000_nrows-");
			strcat(filenameCoeffBinInstrIndex, tmp3);
			strcat(filenameCoeffBinInstrIndex, "_II.bin");
			strcat(filenameCoeffBinKnownTerms, tmp1);
            strcat(filenameCoeffBinKnownTerms, "_");
            strcat(filenameCoeffBinKnownTerms, tmp2);
            strcat(filenameCoeffBinKnownTerms, "_000000_nrows-");
            strcat(filenameCoeffBinKnownTerms, tmp3);
            strcat(filenameCoeffBinKnownTerms, "_KT.bin");
            rename("MI.bin", filenameCoeffBinMatrixIndex);
            rename("SM.bin", filenameCoeffBinSystemMatrix);
            rename("II.bin", filenameCoeffBinInstrIndex);
            rename("KT.bin", filenameCoeffBinKnownTerms);
//            printf("TP9 PE=%d  i=%ld Rinominati sui file GSR_... MI.bin ecc %s \n",myid,i,filenameCoeffBinMatrixIndex );
            fpMI=fopen("MI.bin","wb");
            fpSM=fopen("SM.bin","wb");
            fpII=fopen("II.bin","wb");
            fpKT=fopen("KT.bin","wb");
            rowWritten+=rowCounter;
			rowCounter=1;  // sono già sulla successiva stella
//            printf("TP10 PE=%d aperti in wb  files MI.bin ecc\n",myid);
            rowCounterPrev=0;
			
            nOfFile++;
        }//else //Scrivere su file
    }
    if(myid<nproc-1){
        lastStargsrId=matrixIndex[comlsqr.mapNoss[myid]*2-comlsqr.multMI]/comlsqr.nAstroPSolved;
        
        MPI_Send(&lastStargsrId, 1, MPI_INT, myid+1, 0, MPI_COMM_WORLD);
        MPI_Send(&rowCounterPrev, 1, MPI_LONG, myid+1, 1, MPI_COMM_WORLD);
        MPI_Send(&nOfFile, 1, MPI_INT, myid+1, 2, MPI_COMM_WORLD);


    }

    if(extConstraint && myid==0){
        /// write extConstr for stars
        long nStar=comlsqr.nStar;
        int nEqExtConstr=comlsqr.nEqExtConstr;
        long nDegFreedomAtt=comlsqr.nDegFreedomAtt;
        int startStar=0;
        int endStar=0;
        int numOfExtStarinFile=1000000;
        int numOfExtStartoWrite;
        double randVal;
        short nAstroPSolved=comlsqr.nAstroPSolved;
        for(int nwr=0;nwr<nStar;nwr+=numOfExtStarinFile){   
           int localCounter=0;
           if(nStar>numOfExtStarinFile+nwr)numOfExtStartoWrite=numOfExtStarinFile;
            else numOfExtStartoWrite=nStar-nwr;
            startStar=nwr;
            endStar=startStar+numOfExtStartoWrite-1;
            double *buffArray;
            buffArray=(double *)calloc(numOfExtStartoWrite*nAstroPSolved*nEqExtConstr,sizeof(double));
 
            for(int j=0;j<nEqExtConstr;j++)
                for(int i=0;i<numOfExtStartoWrite*nAstroPSolved;i++){
                    randVal=(((double)rand())/RAND_MAX)*2 - 1.0;
                    if(nAstroPSolved==3 && i%nAstroPSolved==0) randVal=0.;
                    if(nAstroPSolved==4 && i%nAstroPSolved>=2) randVal=0.;
                    if(nAstroPSolved==5 && i%nAstroPSolved==0) randVal=0.;
                    if(nAstroPSolved==5 && i%nAstroPSolved>2 && j<3) randVal=0.;
                    buffArray[localCounter]=randVal;
                    localCounter++;
                }
            
            
            char filenameExtConstrAstro[512];
            char tmp1[20],tmp2[20],tmp3[20];
            sprintf(tmp1,"%09d",startStar);
            sprintf(tmp2,"%09d",endStar);
            sprintf(tmp3,"%09d",nEqExtConstr);
            strcpy(filenameExtConstrAstro,"Gsr_nullspaceastrofit_0000_");
            strcat(filenameExtConstrAstro, tmp1);
            strcat(filenameExtConstrAstro, "_");
            strcat(filenameExtConstrAstro, tmp2);
            strcat(filenameExtConstrAstro, "_000000_nrows-");
            strcat(filenameExtConstrAstro, tmp3);
            strcat(filenameExtConstrAstro,".bin");
            fpSM=fopen(filenameExtConstrAstro,"wb");
            fwrite(buffArray,sizeof(double),nEqExtConstr*numOfExtStartoWrite*nAstroPSolved,fpSM);
            fclose(fpSM);
            free(buffArray);
        } // for(in nwr=..
        /// write extConstr for Att
        double *buffArray;
        buffArray=(double *)calloc(nDegFreedomAtt,sizeof(double));
        for(int i=0;i<nDegFreedomAtt;i++){
            randVal=(((double)rand())/RAND_MAX)*2 - 1.0;
            buffArray[i]=randVal;
        }
        char filenameExtConstrAtt[512];
        strcpy(filenameExtConstrAtt,"Gsr_nullspaceattitudefit_0000_000000_nrows-0660601_EC.bin");
        fpSM=fopen(filenameExtConstrAtt,"wb");
        fwrite(buffArray,sizeof(double),nDegFreedomAtt,fpSM);
        fclose(fpSM);
        free(buffArray);

    }//if (extConstraint

    if(barConstraint && myid==0){
        /// write extConstr for stars
        long nStar=comlsqr.nStar;
        int nEqBarConstr=comlsqr.nEqBarConstr;
        int startStar=0;
        int endStar=0;
        int numOfBarStarinFile=1000000;
        int numOfBarStartoWrite;
        double randVal;
        short nAstroPSolved=comlsqr.nAstroPSolved;
        for(int nwr=0;nwr<nStar;nwr+=numOfBarStarinFile){
            int localCounter=0;
            if(nStar>numOfBarStarinFile+nwr)numOfBarStartoWrite=numOfBarStarinFile;
            else numOfBarStartoWrite=nStar-nwr;
            startStar=nwr;
            endStar=startStar+numOfBarStartoWrite-1;
            double *buffArray;
            buffArray=(double *)calloc(numOfBarStartoWrite*nAstroPSolved*nEqBarConstr,sizeof(double));
            
            for(int j=0;j<nEqBarConstr;j++)
            for(int i=0;i<numOfBarStartoWrite*nAstroPSolved;i++){
                randVal=(((double)rand())/RAND_MAX)*2 - 1.0;
                if(nAstroPSolved==3 && i%nAstroPSolved==0) randVal=0.;
                if(nAstroPSolved==4 && i%nAstroPSolved>=2) randVal=0.;
                if(nAstroPSolved==5 && i%nAstroPSolved==0) randVal=0.;
                if(nAstroPSolved==5 && i%nAstroPSolved>2 && j<3) randVal=0.;
                buffArray[localCounter]=randVal;
                localCounter++;
            }
            
            
            char filenameBarConstrAstro[512];
            char tmp1[20],tmp2[20],tmp3[20];
            sprintf(tmp1,"%09d",startStar);
            sprintf(tmp2,"%09d",endStar);
            sprintf(tmp3,"%09d",nEqBarConstr);
            strcpy(filenameBarConstrAstro,"Gsr_barconstrastrofit_0000_");
            strcat(filenameBarConstrAstro, tmp1);
            strcat(filenameBarConstrAstro, "_");
            strcat(filenameBarConstrAstro, tmp2);
            strcat(filenameBarConstrAstro, "_000000_nrows-");
            strcat(filenameBarConstrAstro, tmp3);
            strcat(filenameBarConstrAstro,".bin");
            fpBar=fopen(filenameBarConstrAstro,"wb");
            fwrite(buffArray,sizeof(double),nEqBarConstr*numOfBarStartoWrite*nAstroPSolved,fpBar);
            fclose(fpBar);
            free(buffArray);
        } // for(in nwr=..
        
    }//if (barConstraint

    MPI_Barrier(MPI_COMM_WORLD);
    chdir(wpath);
    chdir(actpath);
}

int cmpfunc (const void * a, const void * b)
{
    return ( *(int*)a - *(int*)b );
}

int randint(int max) {
    return (int) (max*(rand()/(RAND_MAX+1.0)));
}

// This function generates a psuedo-random integer n, where min <= n <= max
int randint1(int min, int max) {
    if (min>max) {
        return max+(int)((min-max+1)*(rand()/(RAND_MAX+1.0)));
    } else {
        return min+(int)((max-min+1)*(rand()/(RAND_MAX+1.0)));
    }
}

// This function generates a psuedo-random long integer n, where 0 <= n < max
long randlong(long max) {
    return (long) (max*(rand()/(RAND_MAX+1.0)));
}

// This function generates a psuedo-random long integer n, where min <= n <= max
long randlong1(long min, long max) {
    if (min>max) {
        return max+(long)((min-max+1)*(rand()/(RAND_MAX+1.0)));
    } else {
        return min+(long)((max-min+1)*(rand()/(RAND_MAX+1.0)));
    }
}

// This function computes the instrument hash given the number of FoV, CCD, PixelColumn and TimeInterval.
// Since these numbers must fill in 1, 8, 11, and 11 bits respectively, they are checked against appropriate
// maximum values, and if their values are greater, the function returns -1.
// If the function is called with FoV, CCD, PixelColumn and TimeInterval it returns the instrId hash,
// if it is called with nFoVs, nCCDs, nPixelColumns and nTimeIntervals it returns the instrSetUp hash.
// NB: the FoV is treated differently since it can be 1 or 2, so what is actually hashed is nFoVs-1 to keep it into 1 bit.
long instr_hash(int FoV, int CCD, int PixelColumn, int TimeInterval) {
    short CCDOffset = 1;
    short PixelOffset = 9;
    short TimeOffset = 20;
    short FoVMaxValue = ((short) pow(2.0, CCDOffset));
    short CCDMaxValue = ((short) pow(2.0, PixelOffset-CCDOffset));
    short PixelMaxValue = ((short) pow(2.0, TimeOffset-PixelOffset));
    short TimeMaxValue = ((short) pow(2.0, TimeOffset-PixelOffset));
    
    if(FoV>FoVMaxValue || CCD>CCDMaxValue || PixelColumn>PixelMaxValue || TimeInterval>TimeMaxValue)
        return -1; // Some parameter is greater than its maximum possible value. The hash cannot be calculated.
    else
        return (((long) FoV-1)
                | (((long) CCD) << (CCDOffset))
                | (((long) PixelColumn) << (PixelOffset))
                | (((long) TimeInterval) << (TimeOffset)));
}


// This function extracts an integer in the range pos_min..pos_max which points to a position of the array <values>.
// This implies that values is an array with pos_max+1 positions.
void swap(long *i, long *j) {
    long t = *i;
    *i = *j;
    *j = t;
}

int fill_extract(long *values, long *pos_min, long pos_max, long *number) {
    long position;
    
    if(*pos_min==pos_max-1)
        position=*pos_min;
    else
        position=randlong1(*pos_min, pos_max-1);
    *number=values[position];
    swap(&values[*pos_min], &values[position]);
    (*pos_min)++;
    if(*pos_min>=pos_max) 
        return 1;
    return 0;
}

struct nullSpace cknullSpace(double * systemMatrix,long * matrixIndex,double *attNS,struct comData  comlsqr){
    struct nullSpace results;
    int nproc, myid;
    long nunkSplitNS;
    double * nullSpaceVect;
    double * prodNS;
    long nElements, nStar;
    int nEqExtConstr;
    int nparam;
    int nLocalStar;
    int firstStarConstr,lastStarConstr;
    int nOfElextObs,numOfExtStar,numOfExtAttCol,startingAttColExtConstr;
    short nAstroPSolved,nAttParAxis,nAttAxes;
    double *nullSpaceFPN;
    double *productNS;
    int npeSend,npeRecv;
    double sum,extConstrW;
    long sumVer;
    int setBound[4];
    long int l1,k,l,j;
    long int nDegFreedomAtt,localAstroMax,offsetAttParam;
    long int *mapNoss, *mapNcoeff;
    time_t seconds[2], tot_sec;

    int **mapStar;
    
    MPI_Status status;
    MPI_Request req1;

    MPI_Comm_size(MPI_COMM_WORLD, &nproc);
    MPI_Comm_rank(MPI_COMM_WORLD, &myid);
    
    
    nEqExtConstr=comlsqr.nEqExtConstr;
    firstStarConstr=comlsqr.firstStarConstr;
    lastStarConstr=comlsqr.lastStarConstr;
    nAstroPSolved=comlsqr.nAstroPSolved;
    nOfElextObs=comlsqr.nOfElextObs;
    nDegFreedomAtt=comlsqr.nDegFreedomAtt;
    nAttParAxis=comlsqr.nAttParAxis;
    localAstroMax=comlsqr.VrIdAstroPDimMax*nAstroPSolved;
    offsetAttParam=comlsqr.offsetAttParam;
    numOfExtStar=comlsqr.numOfExtStar;
    nAttAxes=comlsqr.nAttAxes;
    mapNcoeff=comlsqr.mapNcoeff;
    mapNoss=comlsqr.mapNoss;
    numOfExtAttCol=comlsqr.numOfExtAttCol;
    startingAttColExtConstr=comlsqr.startingAttColExtConstr;
    setBound[0]=comlsqr.setBound[0];
    setBound[1]=comlsqr.setBound[1];
    setBound[2]=comlsqr.setBound[2];
    setBound[3]=comlsqr.setBound[3];
    extConstrW=comlsqr.extConstrW;
    int multMI=comlsqr.multMI;
    mapStar=comlsqr.mapStar;
    nStar=comlsqr.nStar;
    int nAttParam=comlsqr.nAttParam;
    int nInstrParam=comlsqr.nInstrParam;
    int nGlobalParam=comlsqr.nGlobalParam;
    
// errore ==>    nparam=nAstroPSolved+comlsqr.nAttP+comlsqr.nInstrP+comlsqr.nGlobP;
    nparam=nAstroPSolved+comlsqr.nAttP+comlsqr.nInstrPSolved+comlsqr.nGlobP;
    nLocalStar=comlsqr.mapStar[myid][1]-comlsqr.mapStar[myid][0]+1;
    
    nElements = mapNoss[myid]+nEqExtConstr;
    
    nullSpaceFPN = (double *) calloc(nAstroPSolved*nEqExtConstr, sizeof(double));
    if (!nullSpaceFPN)
        exit(err_malloc("nullSpaceFPN",myid));
     
    productNS = (double *) calloc(nElements, sizeof(double));
    if (!productNS)
        exit(err_malloc("productNS",myid));

     
       
    npeSend=myid-1;
    npeRecv=myid+1;
        
    for(int i=0; i<nEqExtConstr;i++){
        if(myid>0){
        MPI_Isend(&systemMatrix[mapNoss[myid]*nparam+i*nOfElextObs],nAstroPSolved, MPI_DOUBLE, npeSend, 1,MPI_COMM_WORLD, &req1);
        }
        if(myid<nproc-1){
            MPI_Recv(&nullSpaceFPN[nAstroPSolved*i], nAstroPSolved, MPI_DOUBLE, npeRecv, 1,MPI_COMM_WORLD, &status);
        }
         if(myid>0) MPI_Wait(&req1,&status);
        
        MPI_Barrier(MPI_COMM_WORLD);
    }
        
        
        
    prodNS = (double *) calloc(nElements, sizeof(double));
    if (!prodNS)
            exit(err_malloc("prodNS",myid));

    
    
    nunkSplitNS=localAstroMax + nAttParam+nInstrParam+nGlobalParam;
    
   
    nullSpaceVect = (double *) calloc(nunkSplitNS, sizeof(double));
    if (!nullSpaceVect) exit(err_malloc("nullSpaceVect",myid));
    
    for(int ic=0; ic<nEqExtConstr;ic++){
        seconds[0]=time(NULL);
        for(int j1=localAstroMax;j1<nunkSplitNS;j1++)
            nullSpaceVect[j1]=0.0;
            for(int j1=0;j1<nElements;j1++)
                productNS[j1]=0.0;
        for(int j1=0;j1<(lastStarConstr-firstStarConstr+1)*nAstroPSolved;j1++){
            nullSpaceVect[j1]= systemMatrix[mapNoss[myid]*nparam+j1+ic*comlsqr.nOfElextObs]/extConstrW;
        }
        if(comlsqr.mapStar[myid][1]>lastStarConstr){
            for(int j=0;j<nAstroPSolved;j++)
                nullSpaceVect[(lastStarConstr-firstStarConstr+1)*nAstroPSolved+j]=nullSpaceFPN[ic*nAstroPSolved+j]/extConstrW;
        }

        if(ic<3)
        {
            for (int m=0;m<nDegFreedomAtt;m++)
                    nullSpaceVect[localAstroMax+ic*nDegFreedomAtt+m]=comlsqr.nullSpaceAttfact/extConstrW;
        } else{
            for (int m=0;m<nDegFreedomAtt;m++)
                nullSpaceVect[localAstroMax+(ic-3)*nDegFreedomAtt+m]=attNS[m]/extConstrW;
            
        }
////#pragma omp parallel private(myid, sum, sumVer  k, l1, l2, l, j,tid,nthreads) shared(mapNoss,comlsqr,nullSpaceVect,systemMatrix,matrixIndex,productNS)
{
////#ifdef OMP
///            tid = omp_get_thread_num();
///            nthreads = omp_get_num_threads();
//            if(myid==39) printf("TP00.1 PE=%d tid=%d nthreads=%d mapNoss[myid]=%ld, nElements=%ld, multMI=%d\n",myid,tid,nthreads,mapNoss[myid],nElements,multMI);
//            if(myid==39) printf("TP00.1 PE=%d  mapNoss[myid]=%ld\n",myid,mapNoss[myid]);
////#endif
///#pragma omp for
        for(int i=0;i<mapNoss[myid];i++){
                sum=0.0;
                sumVer=0;
                k=0;
                l1=nparam*i;
                int lset=0;

            // sumAstro=(nAstroPSolved*nAstroPSolved*((j-1)*nStar+(multMI*i)/nAstroPSolved)+nAstroPSolved*(nAstroPSolved+1)/2)
            // sumAtt  =4*((j-1)*nDegFreedomAtt+(multMI*i+1))+6
            // sumVer  = sumAstro + sumAtt

            long chkSumVer=(nAstroPSolved*nAstroPSolved*(ic*nStar+matrixIndex[multMI*i]/nAstroPSolved)+(nAstroPSolved*(nAstroPSolved-1))/2)+4*(ic*nDegFreedomAtt+matrixIndex[multMI*i+1]-nStar*nAstroPSolved)+6;
            
            
                for(l=l1;l<l1+setBound[2];l++){
                        if(lset<setBound[1])
                        {
                            if(lset==0)
                            {
/*                                 if(multMI*i>=mapNoss[myid]*multMI){
                                    printf("ERROR: PE=%d i=%d lset=%d multMI*i=%d greather than mapNoss[myid]*multMI=%ld\n",myid,i,lset,multMI*i,mapNoss[myid]*multMI);
                                    continue;
			        }*/
                               long numOfStarPos=matrixIndex[multMI*i]/nAstroPSolved;
                                j=(numOfStarPos-comlsqr.mapStar[myid][0])*nAstroPSolved;
                            }
                            else
                                j++;
                        }
                        if(lset>=setBound[1] && lset<setBound[2])
                        {
                            if(((lset-setBound[1]) % nAttParAxis)==0) {
/*                                if(multMI*i>=mapNoss[myid]*multMI){
                                    printf("ERROR: PE=%d i=%d lset=%d multMI*i+(multMI-1)=%d greather than mapNoss[myid]*multMI=%ld\n",myid,i,lset,multMI*i+(multMI-1),mapNoss[myid]*multMI);
                                    continue;
                                }*/
                                j=matrixIndex[multMI*i+(multMI-1)]+((lset-setBound[1])/nAttParAxis)*nDegFreedomAtt+(localAstroMax-offsetAttParam);
                            }
                            else
                                j++;
                        }
                    sum=sum+systemMatrix[l]*nullSpaceVect[j];
                    
                    double NSVal;
                    if(lset<setBound[1]){
                            NSVal=(matrixIndex[multMI*i]+lset)+ic*nStar*nAstroPSolved;
                            sumVer=sumVer+1.0*NSVal;
                    }
                    else{
                                if(ic==0 || ic==3){
                                
                                if(lset<setBound[1]+4)
                                    NSVal=(matrixIndex[multMI*i+1]-nStar*nAstroPSolved)+lset-setBound[1]+ic*nDegFreedomAtt;
                                else
                                    NSVal=0;
                                }
                               
                            if(ic==1 || ic==4){
                                if(lset>=setBound[1]+4 && lset<setBound[1]+8)
                                    NSVal=(matrixIndex[multMI*i+1]-nStar*nAstroPSolved)+ic*nDegFreedomAtt+lset-(setBound[1]+4);
                                else
                                    NSVal=0;
                            }
                            if(ic==2 || ic==5){
                                if(lset>=setBound[1]+8)
                                    NSVal=(matrixIndex[multMI*i+1]-nStar*nAstroPSolved)+ic*nDegFreedomAtt+lset-(setBound[1]+8);
                                else
                                    NSVal=0;
                            }
                            sumVer=sumVer+1.0*NSVal;
                    }
                     lset++;
                }//for(l
/*                    if(i>=nElements){
                            printf("ERROR: PE=%d i=%d   greather than nElements=%ld\n",myid,i ,nElements);
                            continue;
                    }*/
               if(sumVer != chkSumVer){
                   printf("ERROR: PE=%d NullSapce Equation ic=%d, sumVer[%d]=%d and chkSumVer=%ld are not equal\n",myid,ic,i,sumVer,    chkSumVer);
                   MPI_Abort(MPI_COMM_WORLD, 0);
                   exit(1);
               }
                productNS[i]=sum;
        }//for i
        ////////////   in case of ExtConstr
/*  TO BE DECIDED orthogonalty of nullspace base vectors
         for(i2=0;i2<nEqExtConstr;i2++ ){
         sum=0.0;
         for(j2=0;j2<numOfExtStar*nAstroPSolved;j2++){
         sum+=(systemMatrix[mapNcoeff[myid]+j2+i2*nOfElextObs]/extConstrW)*nullSpaceVect[j2];
         }
         for(na=0;na<nAttAxes;na++)
         for(j2=0;j2<numOfExtAttCol;j2++){
         sum+=(systemMatrix[mapNcoeff[myid]+numOfExtStar*nAstroPSolved+j2+i2*nOfElextObs+na*numOfExtAttCol]/extConstrW)*nullSpaceVect[localAstroMax+startingAttColExtConstr+na*nDegFreedomAtt+j2];
         }
         productNS[mapNoss[myid]+i2]+=sum;
         }//for i2
         
         double *kcopy;
         kcopy=(double *) calloc(nEqExtConstr, sizeof(double));
         MPI_Allreduce(&productNS[mapNoss[myid]],kcopy,nEqExtConstr,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
         for(int i3=0;i3<nEqExtConstr;i3++)
         {
         productNS[mapNoss[myid]+i3]=kcopy[i3];
         }
         free(kcopy);
         ////////////   in case of ExtConstr
         */
}//pragma
        double normLoc;
        normLoc=cblas_dnrm2(mapNoss[myid],productNS,1);
        double normLoc2=normLoc*normLoc;
        double nrmGlob;
        MPI_Allreduce(&normLoc2, &nrmGlob,1,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
        results.vectNorm[ic]=sqrt(nrmGlob);
        double localMin=productNS[0];
        double localMax=productNS[0];
        double globalSum=0.0;
        double localSum=0.0;
        for(int j=0;j<comlsqr.mapNoss[myid];j++){
//            if(myid==39 && j==1456748) printf("TP0.1 PE=%d   localSum=%lf localMin=%lf localMax=%lf productNS[1456748]=%lf\n",myid,localSum,localMin,localMax,productNS[1456748]);
           if(localMin>productNS[j]) localMin=productNS[j];
            if(localMax<productNS[j]) localMax=productNS[j];
            localSum+=productNS[j];
//                if(myid==39 && j==1456748) printf("TP0.2 PE=%d   localSum=%lf localMin=%lf localMax=%lf productNS[1456748]=%lf\n",myid,localSum,localMin,localMax,productNS[1456748]);
        }
//       if(myid==39) printf("TP1 PE=%d   localSum=%lf localMin=%lf localMax=%lf productNS[1456748]=%lf\n",myid,localSum,localMin,localMax,productNS[1456748]);
       MPI_Allreduce(&localMin,&results.compMin[ic], 1, MPI_DOUBLE, MPI_MIN,MPI_COMM_WORLD );
       MPI_Allreduce(&localMax,&results.compMax[ic], 1, MPI_DOUBLE, MPI_MAX,MPI_COMM_WORLD );
       MPI_Allreduce(&localSum,&globalSum, 1, MPI_DOUBLE, MPI_SUM,MPI_COMM_WORLD );
       double avg=globalSum/comlsqr.nobs;
       results.compAvg[ic]=avg;

       double localsqrsum=0;
       double globalsqrsum=0;
       for(int j=0;j<comlsqr.mapNoss[myid];j++)
               localsqrsum+=productNS[j]*productNS[j];
               
        MPI_Allreduce(&localsqrsum,&globalsqrsum, 1, MPI_DOUBLE, MPI_SUM,MPI_COMM_WORLD );
        results.compVar[ic]=sqrt((globalsqrsum/comlsqr.nobs)-avg*avg);
 
        if(myid==0){
               FILE *fpNS;
               char icstr[10];
               char *fileName;
               fileName=(char *) malloc(512);
               sprintf(icstr,"%1d",ic);
               strcpy(fileName, "Gsr_NullSpaceProduct_");
               strcat(fileName, icstr);
               strcat(fileName, ".dat");
               fpNS=fopen(fileName,"w");
               if (!fpNS)
               {
                   printf("PE=%d Error while open %s\n",myid,fileName);
                   MPI_Abort(MPI_COMM_WORLD,1);
                   exit(EXIT_FAILURE);
               }
               long t1=comlsqr.nobs/100;
               int bins=MIN(1000,t1);
               int *isto;
               double binWidth=(results.compMax[ic]-results.compMin[ic])/bins;
                 int ix;
                isto=(int *) calloc(bins, sizeof(int));
                 for( int j=0;j<mapNoss[myid];j++){
                     if(productNS[j]==results.compMax[ic]){
                         ix=bins-1;
                         isto[ix]++;
                         continue;
                     }
                     ix=(productNS[j]-results.compMin[ic])/binWidth;
                     if(ix >=bins){
                         printf("Error while computing local myid=0 ix=%d on cknullSpace at element %d on equation %d. prodNS=%lf greater than max=%lf\n",ix,j,ic,productNS[j],results.compMax[ic]);
                         MPI_Abort(MPI_COMM_WORLD,1);
                         exit(EXIT_FAILURE);
                        
                     }
                     isto[ix]++;
                 }
              for(int k=1;k<nproc;k++){
                   MPI_Recv(productNS, mapNoss[k], MPI_DOUBLE, k, 0, MPI_COMM_WORLD,&status);
//                  if(k==39) printf("TP2 from PE=%k  productNS[1456748]=%lf\n",k,productNS[1456748]);
                  for( int j=0;j<mapNoss[k];j++){
                      if(productNS[j]==results.compMax[ic]){
                          ix=bins-1;
                          isto[ix]++;
                          continue;
                      }
                      ix=(productNS[j]-results.compMin[ic])/binWidth;
                      if(ix >=bins){
                          printf("Error while computing remote peid=%d ix=%d on cknullSpace at element %d on equation %d. prodNS=%lf greater than max=%lf\n",k,ix,j,ic,productNS[j],results.compMax[ic]);
                          MPI_Abort(MPI_COMM_WORLD,1);
                          exit(EXIT_FAILURE);
                          
                      }
                      isto[ix]++;
                  }

               }
              fprintf(fpNS, "%le\n%le\n%le\n%le\n%le\n%d\n%le\n",results.compMin[ic],results.compMax[ic],results.compAvg[ic],results.compVar[ic],
                      results.vectNorm[ic],bins,binWidth);
            for(int j=0;j<bins;j++)
                fprintf(fpNS, "%d\n",isto[j]);
               fclose(fpNS);
               free(fileName);
                free(isto);
                seconds[1] = time(NULL);
                tot_sec = seconds[1] - seconds[0];
                 printf("Istogram nullSpace file for Nullspace row %d, in %ld sec\n",ic,tot_sec);

             } else{
//                 if(myid==39) printf("TP3 PE=%d  productNS[1456748]=%lf\n",myid,productNS[1456748]);

               MPI_Send(productNS, mapNoss[myid], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
        }//if myid==0
        
        } //for ic
    free(nullSpaceFPN);
    free(productNS);
    free(prodNS);
    free(nullSpaceVect);
    return results;
}
char* subString (const char* input, int offset, int len, char* dest)
{
    int input_len = strlen (input);
    
    if (offset + len > input_len)
    {
        return NULL;
    }
    
    strncpy (dest, input + offset, len);
    return dest;
}

/*--------------------------------------------------------------------------*/
// Compute the value of the shifted Legendre polinomial of degree deg. Here we
// just need deg<3.
double legendre(int deg, double x) {
	double res;
	
	switch(deg) {
	case 0:
		res = 1.0;
		break;
	case 1:
		res = 2.0*(x-0.5);
		break;
	case 2:
		res = 6.0*(x-0.5)*(x-0.5)-0.5;
		break;
	default:
		res = -1.0;
		break;
}
	
	return res;
}

//void computeInstrContr (int lsInstrFlag, int ssInstrFlag, long nFoVs,long nCCDs, long nPixelColumns,long nTimeIntervals,double * instrCoeffConstr,int * instrColsConstr,int * instrConstrIlung)
int computeInstrConstr (struct comData comlsqr,double * instrCoeffConstr,int * instrColsConstr,int * instrConstrIlung)
{
    ////////////////// Writing instrConstrRows_xxxx.bin file
// There are 1 AL + 2 AC constraint equations for each time interval for the large scale parameters (total=3*nTimeIntervals)
// There are 1 AL + 1 AC constraint equations for each CCD and Legendre polinomial degree (total=2*nCCDs*3)
// The equations are described by three arrays: instrCoeffConstr, instrColsConstr, instrConstrIlung, which contain the
// coefficients, the column indexes and the length of the non-zero coefficients of each equation respectively.
// MUST BE ALLOCATED THE FOLLOWING VECTORS:
//instrCoeffConstr=(double *) calloc(nElemIC, sizeof(double));
//instrColsConstr=(int *) calloc(nElemIC, sizeof(int));
//instrConstrIlung=(int *) calloc(nOfInstrConstr, sizeof(int));

    int lsInstrFlag=comlsqr.lsInstrFlag;
    int ssInstrFlag=comlsqr.ssInstrFlag;
    long nFoVs=1+comlsqr.instrConst[0];
    long nCCDs=comlsqr.instrConst[1];
    long nPixelColumns=comlsqr.instrConst[2];
    long nTimeIntervals=comlsqr.instrConst[3];
    long cCDLSAACZP=comlsqr.cCDLSAACZP;
    
int nElemICLSAL =comlsqr.nElemICLSAL;
int nElemICLSAC =comlsqr.nElemICLSAC;
int nElemICSS = comlsqr.nElemICSS;
int nOfInstrConstr = comlsqr.nOfInstrConstr;
int nElemIC = comlsqr.nElemIC;
int counterElem=0;
int counterEqs=0;
int elemAcc=0;

if(lsInstrFlag){
    // generate large scale constraint eq. AL
    for(int i=0; i<nTimeIntervals; i++) {
        instrConstrIlung[counterEqs] = nElemICLSAL;
        elemAcc+=nElemICLSAL;
        counterEqs++;
        for(int j=0; j<nFoVs; j++) {
            for(int k=0; k<nCCDs; k++) {
                instrCoeffConstr[counterElem] = 1.0;
                instrColsConstr[counterElem] = comlsqr.offsetCdelta_eta + j*nCCDs*nTimeIntervals+k*nTimeIntervals+i;
                counterElem++;
            }
        }
    }
    // generate large scale constraint eq. AC
    for(int i=0; i<nTimeIntervals; i++) {
        for(int j=0; j<nFoVs; j++) {
            instrConstrIlung[counterEqs] = nElemICLSAC;
            elemAcc+=nElemICLSAC;
            counterEqs++;
            for(int k=0; k<nCCDs; k++) {
                instrCoeffConstr[counterElem] = 1.0;
                instrColsConstr[counterElem] = comlsqr.offsetCdelta_zeta + j*nCCDs*nTimeIntervals+k*nTimeIntervals+i;
                counterElem++;
            }
        }
    }